1use std::cell::RefCell;
2use std::collections::hash_map::Entry;
3use std::sync::atomic::Ordering;
4
5use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
6use rustc_middle::mir::{Body, MirDumper, MirPhase, RuntimePhase};
7use rustc_middle::ty::TyCtxt;
8use rustc_session::Session;
9use tracing::trace;
10
11use crate::lint::lint_body;
12use crate::{errors, validate};
13
14#[doc =
r" Maps MIR pass names to a snake case form to match profiling naming style"]
const PASS_TO_PROFILER_NAMES:
::std::thread::LocalKey<RefCell<FxHashMap<&'static str, &'static str>>> =
{
#[inline]
fn __rust_std_internal_init_fn()
-> RefCell<FxHashMap<&'static str, &'static str>> {
{ RefCell::new(FxHashMap::default()) }
}
unsafe {
::std::thread::LocalKey::new(const {
if ::std::mem::needs_drop::<RefCell<FxHashMap<&'static str,
&'static str>>>() {
|__rust_std_internal_init|
{
#[thread_local]
static __RUST_STD_INTERNAL_VAL:
::std::thread::local_impl::LazyStorage<RefCell<FxHashMap<&'static str,
&'static str>>, ()> =
::std::thread::local_impl::LazyStorage::new();
__RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
__rust_std_internal_init_fn)
}
} else {
|__rust_std_internal_init|
{
#[thread_local]
static __RUST_STD_INTERNAL_VAL:
::std::thread::local_impl::LazyStorage<RefCell<FxHashMap<&'static str,
&'static str>>, !> =
::std::thread::local_impl::LazyStorage::new();
__RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
__rust_std_internal_init_fn)
}
}
})
}
};thread_local! {
15 static PASS_TO_PROFILER_NAMES: RefCell<FxHashMap<&'static str, &'static str>> = {
17 RefCell::new(FxHashMap::default())
18 };
19}
20
21fn to_profiler_name(type_name: &'static str) -> &'static str {
23 PASS_TO_PROFILER_NAMES.with(|names| match names.borrow_mut().entry(type_name) {
24 Entry::Occupied(e) => *e.get(),
25 Entry::Vacant(e) => {
26 let snake_case: String = type_name
27 .chars()
28 .flat_map(|c| {
29 if c.is_ascii_uppercase() {
30 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
['_', c.to_ascii_lowercase()]))vec!['_', c.to_ascii_lowercase()]
31 } else if c == '-' {
32 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
['_']))vec!['_']
33 } else {
34 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[c]))vec![c]
35 }
36 })
37 .collect();
38 let result = &*String::leak(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("mir_pass{0}", snake_case))
})format!("mir_pass{}", snake_case));
39 e.insert(result);
40 result
41 }
42 })
43}
44
45const fn simplify_pass_type_name(name: &'static str) -> &'static str {
58 let bytes = name.as_bytes();
62 let mut i = bytes.len();
63 while i > 0 && bytes[i - 1] != b':' {
64 i -= 1;
65 }
66 let (_, bytes) = bytes.split_at(i);
67
68 let mut i = 0;
71 while i < bytes.len() && bytes[i] != b'<' {
72 i += 1;
73 }
74 let (bytes, _) = bytes.split_at(i);
75
76 match std::str::from_utf8(bytes) {
77 Ok(name) => name,
78 Err(_) => ::core::panicking::panic("explicit panic")panic!(),
79 }
80}
81
82pub(super) trait MirPass<'tcx> {
86 fn name(&self) -> &'static str {
87 const { simplify_pass_type_name(std::any::type_name::<Self>()) }
88 }
89
90 fn profiler_name(&self) -> &'static str {
91 to_profiler_name(self.name())
92 }
93
94 fn is_enabled(&self, _sess: &Session) -> bool {
96 true
97 }
98
99 fn can_be_overridden(&self) -> bool {
102 true
103 }
104
105 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
106
107 fn is_mir_dump_enabled(&self) -> bool {
108 true
109 }
110
111 fn is_required(&self) -> bool;
115}
116
117pub(super) trait MirLint<'tcx> {
120 fn name(&self) -> &'static str {
121 const { simplify_pass_type_name(std::any::type_name::<Self>()) }
122 }
123
124 fn is_enabled(&self, _sess: &Session) -> bool {
125 true
126 }
127
128 fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>);
129}
130
131#[derive(#[automatically_derived]
impl<T: ::core::fmt::Debug> ::core::fmt::Debug for Lint<T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Lint", &&self.0)
}
}Debug, #[automatically_derived]
impl<T: ::core::clone::Clone> ::core::clone::Clone for Lint<T> {
#[inline]
fn clone(&self) -> Lint<T> { Lint(::core::clone::Clone::clone(&self.0)) }
}Clone)]
133pub(super) struct Lint<T>(pub T);
134
135impl<'tcx, T> MirPass<'tcx> for Lint<T>
136where
137 T: MirLint<'tcx>,
138{
139 fn name(&self) -> &'static str {
140 self.0.name()
141 }
142
143 fn is_enabled(&self, sess: &Session) -> bool {
144 self.0.is_enabled(sess)
145 }
146
147 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
148 self.0.run_lint(tcx, body)
149 }
150
151 fn is_mir_dump_enabled(&self) -> bool {
152 false
153 }
154
155 fn is_required(&self) -> bool {
156 true
157 }
158}
159
160pub(super) struct WithMinOptLevel<T>(pub u32, pub T);
161
162impl<'tcx, T> MirPass<'tcx> for WithMinOptLevel<T>
163where
164 T: MirPass<'tcx>,
165{
166 fn name(&self) -> &'static str {
167 self.1.name()
168 }
169
170 fn is_enabled(&self, sess: &Session) -> bool {
171 sess.mir_opt_level() >= self.0 as usize
172 }
173
174 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
175 self.1.run_pass(tcx, body)
176 }
177
178 fn is_required(&self) -> bool {
179 self.1.is_required()
180 }
181}
182
183#[derive(#[automatically_derived]
impl ::core::marker::Copy for Optimizations { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Optimizations {
#[inline]
fn clone(&self) -> Optimizations { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Optimizations {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Optimizations::Suppressed => "Suppressed",
Optimizations::Allowed => "Allowed",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for Optimizations {
#[inline]
fn eq(&self, other: &Optimizations) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Optimizations {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq)]
187pub(crate) enum Optimizations {
188 Suppressed,
189 Allowed,
190}
191
192pub(super) fn run_passes_no_validate<'tcx>(
195 tcx: TyCtxt<'tcx>,
196 body: &mut Body<'tcx>,
197 passes: &[&dyn MirPass<'tcx>],
198 phase_change: Option<MirPhase>,
199) {
200 run_passes_inner(tcx, body, passes, phase_change, false, Optimizations::Allowed);
201}
202
203pub(super) fn run_passes<'tcx>(
205 tcx: TyCtxt<'tcx>,
206 body: &mut Body<'tcx>,
207 passes: &[&dyn MirPass<'tcx>],
208 phase_change: Option<MirPhase>,
209 optimizations: Optimizations,
210) {
211 run_passes_inner(tcx, body, passes, phase_change, true, optimizations);
212}
213
214pub(super) fn should_run_pass<'tcx, P>(
215 tcx: TyCtxt<'tcx>,
216 pass: &P,
217 optimizations: Optimizations,
218) -> bool
219where
220 P: MirPass<'tcx> + ?Sized,
221{
222 let name = pass.name();
223
224 if !pass.can_be_overridden() {
225 return pass.is_enabled(tcx.sess);
226 }
227
228 let overridden_passes = &tcx.sess.opts.unstable_opts.mir_enable_passes;
229 let overridden =
230 overridden_passes.iter().rev().find(|(s, _)| s == &*name).map(|(_name, polarity)| {
231 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_transform/src/pass_manager.rs:231",
"rustc_mir_transform::pass_manager",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/pass_manager.rs"),
::tracing_core::__macro_support::Option::Some(231u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_transform::pass_manager"),
::tracing_core::field::FieldSet::new(&["message", "pass"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("{0} as requested by flag",
if *polarity { "Running" } else { "Not running" }) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&display(&name) as
&dyn Value))])
});
} else { ; }
};trace!(
232 pass = %name,
233 "{} as requested by flag",
234 if *polarity { "Running" } else { "Not running" },
235 );
236 *polarity
237 });
238 let suppressed = !pass.is_required() && #[allow(non_exhaustive_omitted_patterns)] match optimizations {
Optimizations::Suppressed => true,
_ => false,
}matches!(optimizations, Optimizations::Suppressed);
239 overridden.unwrap_or_else(|| !suppressed && pass.is_enabled(tcx.sess))
240}
241
242fn run_passes_inner<'tcx>(
243 tcx: TyCtxt<'tcx>,
244 body: &mut Body<'tcx>,
245 passes: &[&dyn MirPass<'tcx>],
246 phase_change: Option<MirPhase>,
247 validate_each: bool,
248 optimizations: Optimizations,
249) {
250 let overridden_passes = &tcx.sess.opts.unstable_opts.mir_enable_passes;
251 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_transform/src/pass_manager.rs:251",
"rustc_mir_transform::pass_manager",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/pass_manager.rs"),
::tracing_core::__macro_support::Option::Some(251u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_transform::pass_manager"),
::tracing_core::field::FieldSet::new(&["overridden_passes"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&overridden_passes)
as &dyn Value))])
});
} else { ; }
};trace!(?overridden_passes);
252
253 let named_passes: FxIndexSet<_> =
254 overridden_passes.iter().map(|(name, _)| name.as_str()).collect();
255
256 for &name in named_passes.difference(&*crate::PASS_NAMES) {
257 tcx.dcx().emit_warn(errors::UnknownPassName { name });
258 }
259
260 #[cfg(debug_assertions)]
262 {
263 let used_passes: FxIndexSet<_> = passes.iter().map(|p| p.name()).collect();
264
265 let undeclared = used_passes.difference(&*crate::PASS_NAMES).collect::<Vec<_>>();
266 if let Some((name, rest)) = undeclared.split_first() {
267 let mut err =
268 tcx.dcx().struct_bug(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("pass `{0}` is not declared in `PASS_NAMES`",
name))
})format!("pass `{name}` is not declared in `PASS_NAMES`"));
269 for name in rest {
270 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("pass `{0}` is also not declared in `PASS_NAMES`",
name))
})format!("pass `{name}` is also not declared in `PASS_NAMES`"));
271 }
272 err.emit();
273 }
274 }
275
276 let prof_arg = tcx.sess.prof.enabled().then(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", body.source.def_id()))
})format!("{:?}", body.source.def_id()));
277
278 if !body.should_skip() {
279 let validate = validate_each & tcx.sess.opts.unstable_opts.validate_mir;
280 let lint = tcx.sess.opts.unstable_opts.lint_mir;
281
282 for pass in passes {
283 let pass_name = pass.name();
284
285 if !should_run_pass(tcx, *pass, optimizations) {
286 continue;
287 };
288
289 if is_optimization_stage(body, phase_change, optimizations)
290 && let Some(limit) = &tcx.sess.opts.unstable_opts.mir_opt_bisect_limit
291 {
292 if limited_by_opt_bisect(
293 tcx,
294 tcx.def_path_debug_str(body.source.def_id()),
295 *limit,
296 *pass,
297 ) {
298 continue;
299 }
300 }
301
302 let dumper = if pass.is_mir_dump_enabled()
303 && let Some(dumper) = MirDumper::new(tcx, pass_name, body)
304 {
305 Some(dumper.set_show_pass_num().set_disambiguator(&"before"))
306 } else {
307 None
308 };
309
310 if let Some(dumper) = dumper.as_ref() {
311 dumper.dump_mir(body);
312 }
313
314 if let Some(prof_arg) = &prof_arg {
315 tcx.sess
316 .prof
317 .generic_activity_with_arg(pass.profiler_name(), &**prof_arg)
318 .run(|| pass.run_pass(tcx, body));
319 } else {
320 pass.run_pass(tcx, body);
321 }
322
323 if let Some(dumper) = dumper {
324 dumper.set_disambiguator(&"after").dump_mir(body);
325 }
326
327 if validate {
328 validate_body(tcx, body, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("after pass {0}", pass_name))
})format!("after pass {pass_name}"));
329 }
330 if lint {
331 lint_body(tcx, body, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("after pass {0}", pass_name))
})format!("after pass {pass_name}"));
332 }
333
334 body.pass_count += 1;
335 }
336 }
337
338 if let Some(new_phase) = phase_change {
339 if body.phase >= new_phase {
340 {
::core::panicking::panic_fmt(format_args!("Invalid MIR phase transition from {0:?} to {1:?}",
body.phase, new_phase));
};panic!("Invalid MIR phase transition from {:?} to {:?}", body.phase, new_phase);
341 }
342
343 body.phase = new_phase;
344 body.pass_count = 0;
345
346 dump_mir_for_phase_change(tcx, body);
347
348 let validate =
349 (validate_each & tcx.sess.opts.unstable_opts.validate_mir & !body.should_skip())
350 || new_phase == MirPhase::Runtime(RuntimePhase::Optimized);
351 let lint = tcx.sess.opts.unstable_opts.lint_mir & !body.should_skip();
352 if validate {
353 validate_body(tcx, body, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("after phase change to {0}",
new_phase.name()))
})format!("after phase change to {}", new_phase.name()));
354 }
355 if lint {
356 lint_body(tcx, body, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("after phase change to {0}",
new_phase.name()))
})format!("after phase change to {}", new_phase.name()));
357 }
358
359 body.pass_count = 1;
360 }
361}
362
363pub(super) fn validate_body<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>, when: String) {
364 validate::Validator { when }.run_pass(tcx, body);
365}
366
367pub(super) fn dump_mir_for_phase_change<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
368 match (&body.pass_count, &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(body.pass_count, 0);
369 if let Some(dumper) = MirDumper::new(tcx, body.phase.name(), body) {
370 dumper.set_show_pass_num().set_disambiguator(&"after").dump_mir(body)
371 }
372}
373
374fn is_optimization_stage(
375 body: &Body<'_>,
376 phase_change: Option<MirPhase>,
377 optimizations: Optimizations,
378) -> bool {
379 optimizations == Optimizations::Allowed
380 && body.phase == MirPhase::Runtime(RuntimePhase::PostCleanup)
381 && phase_change == Some(MirPhase::Runtime(RuntimePhase::Optimized))
382}
383
384fn limited_by_opt_bisect<'tcx, P>(
385 tcx: TyCtxt<'tcx>,
386 def_path: String,
387 limit: usize,
388 pass: &P,
389) -> bool
390where
391 P: MirPass<'tcx> + ?Sized,
392{
393 let current_opt_bisect_count =
394 tcx.sess.mir_opt_bisect_eval_count.fetch_add(1, Ordering::Relaxed);
395
396 let can_run = current_opt_bisect_count < limit;
397
398 if can_run {
399 {
::std::io::_eprint(format_args!("BISECT: running pass ({0}) {1} on {2}\n",
current_opt_bisect_count + 1, pass.name(), def_path));
};eprintln!(
400 "BISECT: running pass ({}) {} on {}",
401 current_opt_bisect_count + 1,
402 pass.name(),
403 def_path
404 );
405 } else {
406 {
::std::io::_eprint(format_args!("BISECT: NOT running pass ({0}) {1} on {2}\n",
current_opt_bisect_count + 1, pass.name(), def_path));
};eprintln!(
407 "BISECT: NOT running pass ({}) {} on {}",
408 current_opt_bisect_count + 1,
409 pass.name(),
410 def_path
411 );
412 }
413
414 !can_run
415}