Skip to main content

rustc_mir_transform/
pass_manager.rs

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::{diagnostics, 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    /// Maps MIR pass names to a snake case form to match profiling naming style
16    static PASS_TO_PROFILER_NAMES: RefCell<FxHashMap<&'static str, &'static str>> = {
17        RefCell::new(FxHashMap::default())
18    };
19}
20
21/// Converts a MIR pass name into a snake case form to match the profiling naming style.
22fn 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
45// A function that simplifies a pass's type_name. E.g. `Baz`, `Baz<'_>`,
46// `foo::bar::Baz`, and `foo::bar::Baz<'a, 'b>` all become `Baz`.
47//
48// It's `const` for perf reasons: it's called a lot, and doing the string
49// operations at runtime causes a non-trivial slowdown. If
50// `split_once`/`rsplit_once` become `const` its body could be simplified to
51// this:
52// ```ignore (fragment)
53// let name = if let Some((_, tail)) = name.rsplit_once(':') { tail } else { name };
54// let name = if let Some((head, _)) = name.split_once('<') { head } else { name };
55// name
56// ```
57const fn simplify_pass_type_name(name: &'static str) -> &'static str {
58    // FIXME(const-hack) Simplify the implementation once more `str` methods get const-stable.
59
60    // Work backwards from the end. If a ':' is hit, strip it and everything before it.
61    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    // Work forwards from the start of what's left. If a '<' is hit, strip it and everything after
69    // it.
70    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
82/// Rules outlining when this pass may be overridden or suppressed.
83#[derive(#[automatically_derived]
impl ::core::marker::Copy for PassPolicy { }Copy, #[automatically_derived]
impl ::core::clone::Clone for PassPolicy {
    #[inline]
    fn clone(&self) -> PassPolicy {
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for PassPolicy {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            PassPolicy::Required =>
                ::core::fmt::Formatter::write_str(f, "Required"),
            PassPolicy::Optional {
                generally_enabled: __self_0, optimization: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Optional", "generally_enabled", __self_0, "optimization",
                    &__self_1),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for PassPolicy {
    #[inline]
    fn eq(&self, other: &PassPolicy) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (PassPolicy::Optional {
                    generally_enabled: __self_0, optimization: __self_1 },
                    PassPolicy::Optional {
                    generally_enabled: __arg1_0, optimization: __arg1_1 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for PassPolicy {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq)]
84pub(crate) enum PassPolicy {
85    /// This pass implements a mandatory lowering step, either to implement parts of the MIR semantics
86    /// or to bring MIR into a shape that is easier to deal with for later passes/codegen.
87    /// Passes using this cannot be disabled via any means. They must not remove any UB, as they will
88    /// run in Miri. They must also come with a comment justifying why they must always run.
89    Required,
90    /// An optional pass that may be configured by `-Zmir-enable-passes`.
91    Optional {
92        /// Whether this pass should be enabled by default in this session in the absence of
93        /// an explicit `-Zmir-enable-passes` or `#[optimize(none)]`.
94        generally_enabled: bool,
95        /// Whether this is an optimization pass. `#[optimize(none)]` only disables optimization
96        /// passes.
97        /// A pass may be optional without being an optimization pass,
98        /// e.g. if it just adds extra debug checks that one can turn off.
99        optimization: bool,
100    },
101}
102
103impl PassPolicy {
104    fn and_enabled(self, enabled: bool) -> Self {
105        match self {
106            PassPolicy::Required => PassPolicy::Required,
107            PassPolicy::Optional { generally_enabled: enabled_by_default, optimization } => {
108                PassPolicy::Optional {
109                    generally_enabled: enabled_by_default && enabled,
110                    optimization,
111                }
112            }
113        }
114    }
115
116    /// Create a [`PassPolicy::Optional`] that is not an optimization,
117    /// enabled by default under the given condition.
118    pub(crate) fn optional_non_optimization(condition: bool) -> Self {
119        Self::Optional { generally_enabled: condition, optimization: false }
120    }
121
122    /// Create a [`PassPolicy::Optional`] optimization, enabled by default under the given condition.
123    pub(crate) fn optimization(condition: bool) -> Self {
124        Self::Optional { generally_enabled: condition, optimization: true }
125    }
126}
127
128/// A streamlined trait that you can implement to create a pass; the
129/// pass will be named after the type, and it will consist of a main
130/// loop that goes over each available MIR and applies `run_pass`.
131pub(super) trait MirPass<'tcx> {
132    fn name(&self) -> &'static str {
133        const { simplify_pass_type_name(std::any::type_name::<Self>()) }
134    }
135
136    fn profiler_name(&self) -> &'static str {
137        to_profiler_name(self.name())
138    }
139
140    /// Describes how this pass is enabled and which mechanisms may disable it.
141    fn policy(&self, sess: &Session) -> PassPolicy;
142
143    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
144
145    fn is_mir_dump_enabled(&self) -> bool {
146        true
147    }
148}
149
150/// Just like `MirPass`, except it cannot mutate `Body`, and MIR dumping is
151/// disabled (via the `Lint` adapter).
152pub(super) trait MirLint<'tcx> {
153    fn name(&self) -> &'static str {
154        const { simplify_pass_type_name(std::any::type_name::<Self>()) }
155    }
156
157    fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>);
158}
159
160/// An adapter for `MirLint`s that implements `MirPass`.
161#[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)]
162pub(super) struct Lint<T>(pub T);
163
164impl<'tcx, T> MirPass<'tcx> for Lint<T>
165where
166    T: MirLint<'tcx>,
167{
168    fn name(&self) -> &'static str {
169        self.0.name()
170    }
171
172    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
173        self.0.run_lint(tcx, body)
174    }
175
176    fn is_mir_dump_enabled(&self) -> bool {
177        false
178    }
179
180    fn policy(&self, _sess: &Session) -> PassPolicy {
181        PassPolicy::optional_non_optimization(true)
182    }
183}
184
185pub(super) struct WithMinOptLevel<T>(pub u32, pub T);
186
187impl<'tcx, T> MirPass<'tcx> for WithMinOptLevel<T>
188where
189    T: MirPass<'tcx>,
190{
191    fn name(&self) -> &'static str {
192        self.1.name()
193    }
194
195    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
196        self.1.run_pass(tcx, body)
197    }
198
199    fn policy(&self, sess: &Session) -> PassPolicy {
200        self.1.policy(sess).and_enabled(sess.mir_opt_level() >= self.0 as usize)
201    }
202}
203
204/// Whether to allow [optimization passes].
205///
206/// [optimization passes]: PassPolicy::Optional::optimization
207#[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_fields_are_eq(&self) {}
}Eq)]
208pub(crate) enum Optimizations {
209    /// The current function has `#[optimize(none)]`.
210    Suppressed,
211    /// Normal optimizations may run.
212    Allowed,
213}
214
215/// Run the sequence of passes without validating the MIR after each pass. The MIR is still
216/// validated at the end.
217pub(super) fn run_passes_no_validate<'tcx>(
218    tcx: TyCtxt<'tcx>,
219    body: &mut Body<'tcx>,
220    passes: &[&dyn MirPass<'tcx>],
221    phase_change: Option<MirPhase>,
222) {
223    run_passes_inner(tcx, body, passes, phase_change, false);
224}
225
226/// The optional `phase_change` is applied after executing all the passes, if present
227pub(super) fn run_passes<'tcx>(
228    tcx: TyCtxt<'tcx>,
229    body: &mut Body<'tcx>,
230    passes: &[&dyn MirPass<'tcx>],
231    phase_change: Option<MirPhase>,
232) {
233    run_passes_inner(tcx, body, passes, phase_change, true);
234}
235
236pub(super) fn should_run_pass<'tcx, P>(
237    tcx: TyCtxt<'tcx>,
238    pass: &P,
239    optimizations: Optimizations,
240) -> bool
241where
242    P: MirPass<'tcx> + ?Sized,
243{
244    let name = pass.name();
245    let pass_override = || {
246        tcx.sess
247            .opts
248            .unstable_opts
249            .mir_enable_passes
250            .iter()
251            .rev()
252            .find_map(|(name_, polarity)| if name == name_ { Some(*polarity) } else { None })
253    };
254
255    match pass.policy(tcx.sess) {
256        PassPolicy::Required => true,
257        PassPolicy::Optional { generally_enabled: enabled_by_default, optimization } => {
258            if let Some(o) = pass_override() {
259                {
    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:259",
                        "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(259u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::pass_manager"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("pass")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("pass");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0} as requested by flag",
                                                    if o { "Running" } else { "Not running" }) as
                                            &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::display(&name)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!(
260                    pass = %name,
261                    "{} as requested by flag",
262                    if o { "Running" } else { "Not running" }
263                );
264                o
265            } else if optimization && optimizations == Optimizations::Suppressed {
266                {
    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:266",
                        "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(266u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::pass_manager"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("pass")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("pass");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Not running as requested by `#[optimize(none)]`")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::display(&name)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!(pass = %name, "Not running as requested by `#[optimize(none)]`");
267                false
268            } else {
269                enabled_by_default
270            }
271        }
272    }
273}
274
275fn run_passes_inner<'tcx>(
276    tcx: TyCtxt<'tcx>,
277    body: &mut Body<'tcx>,
278    passes: &[&dyn MirPass<'tcx>],
279    phase_change: Option<MirPhase>,
280    validate_each: bool,
281) {
282    let overridden_passes = &tcx.sess.opts.unstable_opts.mir_enable_passes;
283    {
    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:283",
                        "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(283u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::pass_manager"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("overridden_passes")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("overridden_passes");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&overridden_passes)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!(?overridden_passes);
284
285    let named_passes: FxIndexSet<_> =
286        overridden_passes.iter().map(|(name, _)| name.as_str()).collect();
287
288    let mut unknown_found = false;
289    for &name in named_passes.difference(&*crate::PASS_NAMES) {
290        tcx.dcx().emit_warn(diagnostics::UnknownPassName { name });
291        unknown_found = true;
292    }
293
294    if unknown_found {
295        let mut valid_pass_names = crate::PASS_NAMES.iter().copied().collect::<Vec<_>>();
296        valid_pass_names.sort();
297        tcx.dcx().emit_note(diagnostics::ValidPassNames { valid_passes: valid_pass_names.into() });
298    }
299
300    // Verify that no passes are missing from the `declare_passes` invocation
301    #[cfg(debug_assertions)]
302    {
303        let used_passes: FxIndexSet<_> = passes.iter().map(|p| p.name()).collect();
304
305        let undeclared = used_passes.difference(&*crate::PASS_NAMES).collect::<Vec<_>>();
306        if let Some((name, rest)) = undeclared.split_first() {
307            let mut err =
308                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`"));
309            for name in rest {
310                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`"));
311            }
312            err.emit();
313        }
314    }
315
316    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()));
317
318    if !body.should_skip() {
319        let validate = validate_each & tcx.sess.opts.unstable_opts.validate_mir;
320        let lint = tcx.sess.opts.unstable_opts.lint_mir;
321
322        let def_id = body.source.def_id();
323        let optimizations = if tcx.def_kind(def_id).has_codegen_attrs()
324            && tcx.codegen_fn_attrs(def_id).optimize.do_not_optimize()
325        {
326            Optimizations::Suppressed
327        } else {
328            Optimizations::Allowed
329        };
330
331        for pass in passes {
332            let pass_name = pass.name();
333
334            if !should_run_pass(tcx, *pass, optimizations) {
335                continue;
336            };
337
338            if is_optimization_stage(body, phase_change, optimizations)
339                && let Some(limit) = &tcx.sess.opts.unstable_opts.mir_opt_bisect_limit
340                && limited_by_opt_bisect(
341                    tcx,
342                    tcx.def_path_debug_str(body.source.def_id()),
343                    *limit,
344                    *pass,
345                )
346            {
347                continue;
348            }
349
350            let dumper = if pass.is_mir_dump_enabled()
351                && let Some(dumper) = MirDumper::new(tcx, pass_name, body)
352            {
353                Some(dumper.set_show_pass_num().set_disambiguator(&"before"))
354            } else {
355                None
356            };
357
358            if let Some(dumper) = dumper.as_ref() {
359                dumper.dump_mir(body);
360            }
361
362            if let Some(prof_arg) = &prof_arg {
363                tcx.sess
364                    .prof
365                    .generic_activity_with_arg(pass.profiler_name(), &**prof_arg)
366                    .run(|| pass.run_pass(tcx, body));
367            } else {
368                pass.run_pass(tcx, body);
369            }
370
371            if let Some(dumper) = dumper {
372                dumper.set_disambiguator(&"after").dump_mir(body);
373            }
374
375            if validate {
376                validate_body(tcx, body, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("after pass {0}", pass_name))
    })format!("after pass {pass_name}"));
377            }
378            if lint {
379                lint_body(tcx, body, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("after pass {0}", pass_name))
    })format!("after pass {pass_name}"));
380            }
381
382            body.pass_count += 1;
383        }
384    }
385
386    if let Some(new_phase) = phase_change {
387        if body.phase >= new_phase {
388            {
    ::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);
389        }
390
391        body.phase = new_phase;
392        body.pass_count = 0;
393
394        dump_mir_for_phase_change(tcx, body);
395
396        let validate =
397            (validate_each & tcx.sess.opts.unstable_opts.validate_mir & !body.should_skip())
398                || new_phase == MirPhase::Runtime(RuntimePhase::Optimized);
399        let lint = tcx.sess.opts.unstable_opts.lint_mir & !body.should_skip();
400        if validate {
401            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()));
402        }
403        if lint {
404            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()));
405        }
406
407        body.pass_count = 1;
408    }
409}
410
411pub(super) fn validate_body<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>, when: String) {
412    validate::Validator { when }.run_pass(tcx, body);
413}
414
415pub(super) fn dump_mir_for_phase_change<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
416    {
    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);
417    if let Some(dumper) = MirDumper::new(tcx, body.phase.name(), body) {
418        dumper.set_show_pass_num().set_disambiguator(&"after").dump_mir(body)
419    }
420}
421
422fn is_optimization_stage(
423    body: &Body<'_>,
424    phase_change: Option<MirPhase>,
425    optimizations: Optimizations,
426) -> bool {
427    optimizations == Optimizations::Allowed
428        && body.phase == MirPhase::Runtime(RuntimePhase::PostCleanup)
429        && phase_change == Some(MirPhase::Runtime(RuntimePhase::Optimized))
430}
431
432fn limited_by_opt_bisect<'tcx, P>(
433    tcx: TyCtxt<'tcx>,
434    def_path: String,
435    limit: usize,
436    pass: &P,
437) -> bool
438where
439    P: MirPass<'tcx> + ?Sized,
440{
441    let current_opt_bisect_count =
442        tcx.sess.mir_opt_bisect_eval_count.fetch_add(1, Ordering::Relaxed);
443
444    let can_run = current_opt_bisect_count < limit;
445
446    if can_run {
447        {
    ::std::io::_eprint(format_args!("BISECT: running pass ({0}) {1} on {2}\n",
            current_opt_bisect_count + 1, pass.name(), def_path));
};eprintln!(
448            "BISECT: running pass ({}) {} on {}",
449            current_opt_bisect_count + 1,
450            pass.name(),
451            def_path
452        );
453    } else {
454        {
    ::std::io::_eprint(format_args!("BISECT: NOT running pass ({0}) {1} on {2}\n",
            current_opt_bisect_count + 1, pass.name(), def_path));
};eprintln!(
455            "BISECT: NOT running pass ({}) {} on {}",
456            current_opt_bisect_count + 1,
457            pass.name(),
458            def_path
459        );
460    }
461
462    !can_run
463}