Skip to main content

rustc_mir_transform/
pass_manager.rs

1use std::cell::RefCell;
2use std::collections::hash_map::Entry;
3
4use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
5use rustc_middle::mir::{Body, MirDumper, MirPhase, RuntimePhase};
6use rustc_middle::ty::TyCtxt;
7use rustc_session::Session;
8use tracing::trace;
9
10use crate::lint::lint_body;
11use crate::{errors, validate};
12
13#[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! {
14    /// Maps MIR pass names to a snake case form to match profiling naming style
15    static PASS_TO_PROFILER_NAMES: RefCell<FxHashMap<&'static str, &'static str>> = {
16        RefCell::new(FxHashMap::default())
17    };
18}
19
20/// Converts a MIR pass name into a snake case form to match the profiling naming style.
21fn to_profiler_name(type_name: &'static str) -> &'static str {
22    PASS_TO_PROFILER_NAMES.with(|names| match names.borrow_mut().entry(type_name) {
23        Entry::Occupied(e) => *e.get(),
24        Entry::Vacant(e) => {
25            let snake_case: String = type_name
26                .chars()
27                .flat_map(|c| {
28                    if c.is_ascii_uppercase() {
29                        <[_]>::into_vec(::alloc::boxed::box_new(['_', c.to_ascii_lowercase()]))vec!['_', c.to_ascii_lowercase()]
30                    } else if c == '-' {
31                        <[_]>::into_vec(::alloc::boxed::box_new(['_']))vec!['_']
32                    } else {
33                        <[_]>::into_vec(::alloc::boxed::box_new([c]))vec![c]
34                    }
35                })
36                .collect();
37            let result = &*String::leak(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("mir_pass{0}", snake_case))
    })format!("mir_pass{}", snake_case));
38            e.insert(result);
39            result
40        }
41    })
42}
43
44// A function that simplifies a pass's type_name. E.g. `Baz`, `Baz<'_>`,
45// `foo::bar::Baz`, and `foo::bar::Baz<'a, 'b>` all become `Baz`.
46//
47// It's `const` for perf reasons: it's called a lot, and doing the string
48// operations at runtime causes a non-trivial slowdown. If
49// `split_once`/`rsplit_once` become `const` its body could be simplified to
50// this:
51// ```ignore (fragment)
52// let name = if let Some((_, tail)) = name.rsplit_once(':') { tail } else { name };
53// let name = if let Some((head, _)) = name.split_once('<') { head } else { name };
54// name
55// ```
56const fn simplify_pass_type_name(name: &'static str) -> &'static str {
57    // FIXME(const-hack) Simplify the implementation once more `str` methods get const-stable.
58
59    // Work backwards from the end. If a ':' is hit, strip it and everything before it.
60    let bytes = name.as_bytes();
61    let mut i = bytes.len();
62    while i > 0 && bytes[i - 1] != b':' {
63        i -= 1;
64    }
65    let (_, bytes) = bytes.split_at(i);
66
67    // Work forwards from the start of what's left. If a '<' is hit, strip it and everything after
68    // it.
69    let mut i = 0;
70    while i < bytes.len() && bytes[i] != b'<' {
71        i += 1;
72    }
73    let (bytes, _) = bytes.split_at(i);
74
75    match std::str::from_utf8(bytes) {
76        Ok(name) => name,
77        Err(_) => ::core::panicking::panic("explicit panic")panic!(),
78    }
79}
80
81/// A streamlined trait that you can implement to create a pass; the
82/// pass will be named after the type, and it will consist of a main
83/// loop that goes over each available MIR and applies `run_pass`.
84pub(super) trait MirPass<'tcx> {
85    fn name(&self) -> &'static str {
86        const { simplify_pass_type_name(std::any::type_name::<Self>()) }
87    }
88
89    fn profiler_name(&self) -> &'static str {
90        to_profiler_name(self.name())
91    }
92
93    /// Returns `true` if this pass is enabled with the current combination of compiler flags.
94    fn is_enabled(&self, _sess: &Session) -> bool {
95        true
96    }
97
98    /// Returns `true` if this pass can be overridden by `-Zenable-mir-passes`. This should be
99    /// true for basically every pass other than those that are necessary for correctness.
100    fn can_be_overridden(&self) -> bool {
101        true
102    }
103
104    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
105
106    fn is_mir_dump_enabled(&self) -> bool {
107        true
108    }
109
110    /// Returns `true` if this pass must be run (i.e. it is required for soundness).
111    /// For passes which are strictly optimizations, this should return `false`.
112    /// If this is `false`, `#[optimize(none)]` will disable the pass.
113    fn is_required(&self) -> bool;
114}
115
116/// Just like `MirPass`, except it cannot mutate `Body`, and MIR dumping is
117/// disabled (via the `Lint` adapter).
118pub(super) trait MirLint<'tcx> {
119    fn name(&self) -> &'static str {
120        const { simplify_pass_type_name(std::any::type_name::<Self>()) }
121    }
122
123    fn is_enabled(&self, _sess: &Session) -> bool {
124        true
125    }
126
127    fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>);
128}
129
130/// An adapter for `MirLint`s that implements `MirPass`.
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)]
132pub(super) struct Lint<T>(pub T);
133
134impl<'tcx, T> MirPass<'tcx> for Lint<T>
135where
136    T: MirLint<'tcx>,
137{
138    fn name(&self) -> &'static str {
139        self.0.name()
140    }
141
142    fn is_enabled(&self, sess: &Session) -> bool {
143        self.0.is_enabled(sess)
144    }
145
146    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
147        self.0.run_lint(tcx, body)
148    }
149
150    fn is_mir_dump_enabled(&self) -> bool {
151        false
152    }
153
154    fn is_required(&self) -> bool {
155        true
156    }
157}
158
159pub(super) struct WithMinOptLevel<T>(pub u32, pub T);
160
161impl<'tcx, T> MirPass<'tcx> for WithMinOptLevel<T>
162where
163    T: MirPass<'tcx>,
164{
165    fn name(&self) -> &'static str {
166        self.1.name()
167    }
168
169    fn is_enabled(&self, sess: &Session) -> bool {
170        sess.mir_opt_level() >= self.0 as usize
171    }
172
173    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
174        self.1.run_pass(tcx, body)
175    }
176
177    fn is_required(&self) -> bool {
178        self.1.is_required()
179    }
180}
181
182/// Whether to allow non-[required] optimizations
183///
184/// [required]: MirPass::is_required
185#[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)]
186pub(crate) enum Optimizations {
187    Suppressed,
188    Allowed,
189}
190
191/// Run the sequence of passes without validating the MIR after each pass. The MIR is still
192/// validated at the end.
193pub(super) fn run_passes_no_validate<'tcx>(
194    tcx: TyCtxt<'tcx>,
195    body: &mut Body<'tcx>,
196    passes: &[&dyn MirPass<'tcx>],
197    phase_change: Option<MirPhase>,
198) {
199    run_passes_inner(tcx, body, passes, phase_change, false, Optimizations::Allowed);
200}
201
202/// The optional `phase_change` is applied after executing all the passes, if present
203pub(super) fn run_passes<'tcx>(
204    tcx: TyCtxt<'tcx>,
205    body: &mut Body<'tcx>,
206    passes: &[&dyn MirPass<'tcx>],
207    phase_change: Option<MirPhase>,
208    optimizations: Optimizations,
209) {
210    run_passes_inner(tcx, body, passes, phase_change, true, optimizations);
211}
212
213pub(super) fn should_run_pass<'tcx, P>(
214    tcx: TyCtxt<'tcx>,
215    pass: &P,
216    optimizations: Optimizations,
217) -> bool
218where
219    P: MirPass<'tcx> + ?Sized,
220{
221    let name = pass.name();
222
223    if !pass.can_be_overridden() {
224        return pass.is_enabled(tcx.sess);
225    }
226
227    let overridden_passes = &tcx.sess.opts.unstable_opts.mir_enable_passes;
228    let overridden =
229        overridden_passes.iter().rev().find(|(s, _)| s == &*name).map(|(_name, polarity)| {
230            {
    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:230",
                        "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(230u32),
                        ::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!(
231                pass = %name,
232                "{} as requested by flag",
233                if *polarity { "Running" } else { "Not running" },
234            );
235            *polarity
236        });
237    let suppressed = !pass.is_required() && #[allow(non_exhaustive_omitted_patterns)] match optimizations {
    Optimizations::Suppressed => true,
    _ => false,
}matches!(optimizations, Optimizations::Suppressed);
238    overridden.unwrap_or_else(|| !suppressed && pass.is_enabled(tcx.sess))
239}
240
241fn run_passes_inner<'tcx>(
242    tcx: TyCtxt<'tcx>,
243    body: &mut Body<'tcx>,
244    passes: &[&dyn MirPass<'tcx>],
245    phase_change: Option<MirPhase>,
246    validate_each: bool,
247    optimizations: Optimizations,
248) {
249    let overridden_passes = &tcx.sess.opts.unstable_opts.mir_enable_passes;
250    {
    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:250",
                        "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(250u32),
                        ::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);
251
252    let named_passes: FxIndexSet<_> =
253        overridden_passes.iter().map(|(name, _)| name.as_str()).collect();
254
255    for &name in named_passes.difference(&*crate::PASS_NAMES) {
256        tcx.dcx().emit_warn(errors::UnknownPassName { name });
257    }
258
259    // Verify that no passes are missing from the `declare_passes` invocation
260    #[cfg(debug_assertions)]
261    {
262        let used_passes: FxIndexSet<_> = passes.iter().map(|p| p.name()).collect();
263
264        let undeclared = used_passes.difference(&*crate::PASS_NAMES).collect::<Vec<_>>();
265        if let Some((name, rest)) = undeclared.split_first() {
266            let mut err =
267                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`"));
268            for name in rest {
269                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`"));
270            }
271            err.emit();
272        }
273    }
274
275    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()));
276
277    if !body.should_skip() {
278        let validate = validate_each & tcx.sess.opts.unstable_opts.validate_mir;
279        let lint = tcx.sess.opts.unstable_opts.lint_mir;
280
281        for pass in passes {
282            let pass_name = pass.name();
283
284            if !should_run_pass(tcx, *pass, optimizations) {
285                continue;
286            };
287
288            let dumper = if pass.is_mir_dump_enabled()
289                && let Some(dumper) = MirDumper::new(tcx, pass_name, body)
290            {
291                Some(dumper.set_show_pass_num().set_disambiguator(&"before"))
292            } else {
293                None
294            };
295
296            if let Some(dumper) = dumper.as_ref() {
297                dumper.dump_mir(body);
298            }
299
300            if let Some(prof_arg) = &prof_arg {
301                tcx.sess
302                    .prof
303                    .generic_activity_with_arg(pass.profiler_name(), &**prof_arg)
304                    .run(|| pass.run_pass(tcx, body));
305            } else {
306                pass.run_pass(tcx, body);
307            }
308
309            if let Some(dumper) = dumper {
310                dumper.set_disambiguator(&"after").dump_mir(body);
311            }
312
313            if validate {
314                validate_body(tcx, body, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("after pass {0}", pass_name))
    })format!("after pass {pass_name}"));
315            }
316            if lint {
317                lint_body(tcx, body, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("after pass {0}", pass_name))
    })format!("after pass {pass_name}"));
318            }
319
320            body.pass_count += 1;
321        }
322    }
323
324    if let Some(new_phase) = phase_change {
325        if body.phase >= new_phase {
326            {
    ::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);
327        }
328
329        body.phase = new_phase;
330        body.pass_count = 0;
331
332        dump_mir_for_phase_change(tcx, body);
333
334        let validate =
335            (validate_each & tcx.sess.opts.unstable_opts.validate_mir & !body.should_skip())
336                || new_phase == MirPhase::Runtime(RuntimePhase::Optimized);
337        let lint = tcx.sess.opts.unstable_opts.lint_mir & !body.should_skip();
338        if validate {
339            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()));
340        }
341        if lint {
342            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()));
343        }
344
345        body.pass_count = 1;
346    }
347}
348
349pub(super) fn validate_body<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>, when: String) {
350    validate::Validator { when }.run_pass(tcx, body);
351}
352
353pub(super) fn dump_mir_for_phase_change<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
354    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);
355    if let Some(dumper) = MirDumper::new(tcx, body.phase.name(), body) {
356        dumper.set_show_pass_num().set_disambiguator(&"after").dump_mir(body)
357    }
358}