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
13thread_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                        vec!['_', c.to_ascii_lowercase()]
30                    } else if c == '-' {
31                        vec!['_']
32                    } else {
33                        vec![c]
34                    }
35                })
36                .collect();
37            let result = &*String::leak(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(_) => 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(Debug, 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(Copy, Clone, Debug, PartialEq, 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            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() && 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    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    #[allow(rustc::diagnostic_outside_of_impl)]
262    #[allow(rustc::untranslatable_diagnostic)]
263    {
264        let used_passes: FxIndexSet<_> = passes.iter().map(|p| p.name()).collect();
265
266        let undeclared = used_passes.difference(&*crate::PASS_NAMES).collect::<Vec<_>>();
267        if let Some((name, rest)) = undeclared.split_first() {
268            let mut err =
269                tcx.dcx().struct_bug(format!("pass `{name}` is not declared in `PASS_NAMES`"));
270            for name in rest {
271                err.note(format!("pass `{name}` is also not declared in `PASS_NAMES`"));
272            }
273            err.emit();
274        }
275    }
276
277    let prof_arg = tcx.sess.prof.enabled().then(|| format!("{:?}", body.source.def_id()));
278
279    if !body.should_skip() {
280        let validate = validate_each & tcx.sess.opts.unstable_opts.validate_mir;
281        let lint = tcx.sess.opts.unstable_opts.lint_mir;
282
283        for pass in passes {
284            let pass_name = pass.name();
285
286            if !should_run_pass(tcx, *pass, optimizations) {
287                continue;
288            };
289
290            let dumper = if pass.is_mir_dump_enabled()
291                && let Some(dumper) = MirDumper::new(tcx, pass_name, body)
292            {
293                Some(dumper.set_show_pass_num().set_disambiguator(&"before"))
294            } else {
295                None
296            };
297
298            if let Some(dumper) = dumper.as_ref() {
299                dumper.dump_mir(body);
300            }
301
302            if let Some(prof_arg) = &prof_arg {
303                tcx.sess
304                    .prof
305                    .generic_activity_with_arg(pass.profiler_name(), &**prof_arg)
306                    .run(|| pass.run_pass(tcx, body));
307            } else {
308                pass.run_pass(tcx, body);
309            }
310
311            if let Some(dumper) = dumper {
312                dumper.set_disambiguator(&"after").dump_mir(body);
313            }
314
315            if validate {
316                validate_body(tcx, body, format!("after pass {pass_name}"));
317            }
318            if lint {
319                lint_body(tcx, body, format!("after pass {pass_name}"));
320            }
321
322            body.pass_count += 1;
323        }
324    }
325
326    if let Some(new_phase) = phase_change {
327        if body.phase >= new_phase {
328            panic!("Invalid MIR phase transition from {:?} to {:?}", body.phase, new_phase);
329        }
330
331        body.phase = new_phase;
332        body.pass_count = 0;
333
334        dump_mir_for_phase_change(tcx, body);
335
336        let validate =
337            (validate_each & tcx.sess.opts.unstable_opts.validate_mir & !body.should_skip())
338                || new_phase == MirPhase::Runtime(RuntimePhase::Optimized);
339        let lint = tcx.sess.opts.unstable_opts.lint_mir & !body.should_skip();
340        if validate {
341            validate_body(tcx, body, format!("after phase change to {}", new_phase.name()));
342        }
343        if lint {
344            lint_body(tcx, body, format!("after phase change to {}", new_phase.name()));
345        }
346
347        body.pass_count = 1;
348    }
349}
350
351pub(super) fn validate_body<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>, when: String) {
352    validate::Validator { when }.run_pass(tcx, body);
353}
354
355pub(super) fn dump_mir_for_phase_change<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
356    assert_eq!(body.pass_count, 0);
357    if let Some(dumper) = MirDumper::new(tcx, body.phase.name(), body) {
358        dumper.set_show_pass_num().set_disambiguator(&"after").dump_mir(body)
359    }
360}