rustc_mir_transform/
lib.rs

1// tidy-alphabetical-start
2#![feature(array_windows)]
3#![feature(assert_matches)]
4#![feature(box_patterns)]
5#![feature(const_type_name)]
6#![feature(cow_is_borrowed)]
7#![feature(file_buffered)]
8#![feature(gen_blocks)]
9#![feature(if_let_guard)]
10#![feature(impl_trait_in_assoc_type)]
11#![feature(try_blocks)]
12#![feature(yeet_expr)]
13// tidy-alphabetical-end
14
15use hir::ConstContext;
16use required_consts::RequiredConstsVisitor;
17use rustc_const_eval::check_consts::{self, ConstCx};
18use rustc_const_eval::util;
19use rustc_data_structures::fx::FxIndexSet;
20use rustc_data_structures::steal::Steal;
21use rustc_hir as hir;
22use rustc_hir::def::{CtorKind, DefKind};
23use rustc_hir::def_id::LocalDefId;
24use rustc_index::IndexVec;
25use rustc_middle::mir::{
26    AnalysisPhase, Body, CallSource, ClearCrossCrate, ConstOperand, ConstQualifs, LocalDecl,
27    MirPhase, Operand, Place, ProjectionElem, Promoted, RuntimePhase, Rvalue, START_BLOCK,
28    SourceInfo, Statement, StatementKind, TerminatorKind,
29};
30use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
31use rustc_middle::util::Providers;
32use rustc_middle::{bug, query, span_bug};
33use rustc_mir_build::builder::build_mir;
34use rustc_span::source_map::Spanned;
35use rustc_span::{DUMMY_SP, sym};
36use tracing::debug;
37
38#[macro_use]
39mod pass_manager;
40
41use std::sync::LazyLock;
42
43use pass_manager::{self as pm, Lint, MirLint, MirPass, WithMinOptLevel};
44
45mod check_pointers;
46mod cost_checker;
47mod cross_crate_inline;
48mod deduce_param_attrs;
49mod elaborate_drop;
50mod errors;
51mod ffi_unwind_calls;
52mod lint;
53mod lint_tail_expr_drop_order;
54mod liveness;
55mod patch;
56mod shim;
57mod ssa;
58mod trivial_const;
59
60/// We import passes via this macro so that we can have a static list of pass names
61/// (used to verify CLI arguments). It takes a list of modules, followed by the passes
62/// declared within them.
63/// ```ignore,macro-test
64/// declare_passes! {
65///     // Declare a single pass from the module `abort_unwinding_calls`
66///     mod abort_unwinding_calls : AbortUnwindingCalls;
67///     // When passes are grouped together as an enum, declare the two constituent passes
68///     mod add_call_guards : AddCallGuards {
69///         AllCallEdges,
70///         CriticalCallEdges
71///     };
72///     // Declares multiple pass groups, each containing their own constituent passes
73///     mod simplify : SimplifyCfg {
74///         Initial,
75///         /* omitted */
76///     }, SimplifyLocals {
77///         BeforeConstProp,
78///         /* omitted */
79///     };
80/// }
81/// ```
82macro_rules! declare_passes {
83    (
84        $(
85            $vis:vis mod $mod_name:ident : $($pass_name:ident $( { $($ident:ident),* } )?),+ $(,)?;
86        )*
87    ) => {
88        $(
89            $vis mod $mod_name;
90            $(
91                // Make sure the type name is correct
92                #[allow(unused_imports)]
93                use $mod_name::$pass_name as _;
94            )+
95        )*
96
97        static PASS_NAMES: LazyLock<FxIndexSet<&str>> = LazyLock::new(|| [
98            // Fake marker pass
99            "PreCodegen",
100            $(
101                $(
102                    stringify!($pass_name),
103                    $(
104                        $(
105                            $mod_name::$pass_name::$ident.name(),
106                        )*
107                    )?
108                )+
109            )*
110        ].into_iter().collect());
111    };
112}
113
114declare_passes! {
115    mod abort_unwinding_calls : AbortUnwindingCalls;
116    mod add_call_guards : AddCallGuards { AllCallEdges, CriticalCallEdges };
117    mod add_moves_for_packed_drops : AddMovesForPackedDrops;
118    mod add_retag : AddRetag;
119    mod add_subtyping_projections : Subtyper;
120    mod check_inline : CheckForceInline;
121    mod check_call_recursion : CheckCallRecursion, CheckDropRecursion;
122    mod check_inline_always_target_features: CheckInlineAlwaysTargetFeature;
123    mod check_alignment : CheckAlignment;
124    mod check_enums : CheckEnums;
125    mod check_const_item_mutation : CheckConstItemMutation;
126    mod check_null : CheckNull;
127    mod check_packed_ref : CheckPackedRef;
128    // This pass is public to allow external drivers to perform MIR cleanup
129    pub mod cleanup_post_borrowck : CleanupPostBorrowck;
130
131    mod copy_prop : CopyProp;
132    mod coroutine : StateTransform;
133    mod coverage : InstrumentCoverage;
134    mod ctfe_limit : CtfeLimit;
135    mod dataflow_const_prop : DataflowConstProp;
136    mod dead_store_elimination : DeadStoreElimination {
137        Initial,
138        Final
139    };
140    mod deref_separator : Derefer;
141    mod dest_prop : DestinationPropagation;
142    pub mod dump_mir : Marker;
143    mod early_otherwise_branch : EarlyOtherwiseBranch;
144    mod erase_deref_temps : EraseDerefTemps;
145    mod elaborate_box_derefs : ElaborateBoxDerefs;
146    mod elaborate_drops : ElaborateDrops;
147    mod function_item_references : FunctionItemReferences;
148    mod gvn : GVN;
149    // Made public so that `mir_drops_elaborated_and_const_checked` can be overridden
150    // by custom rustc drivers, running all the steps by themselves. See #114628.
151    pub mod inline : Inline, ForceInline;
152    mod impossible_predicates : ImpossiblePredicates;
153    mod instsimplify : InstSimplify { BeforeInline, AfterSimplifyCfg };
154    mod jump_threading : JumpThreading;
155    mod known_panics_lint : KnownPanicsLint;
156    mod large_enums : EnumSizeOpt;
157    mod lower_intrinsics : LowerIntrinsics;
158    mod lower_slice_len : LowerSliceLenCalls;
159    mod match_branches : MatchBranchSimplification;
160    mod mentioned_items : MentionedItems;
161    mod multiple_return_terminators : MultipleReturnTerminators;
162    mod post_drop_elaboration : CheckLiveDrops;
163    mod prettify : ReorderBasicBlocks, ReorderLocals;
164    mod promote_consts : PromoteTemps;
165    mod ref_prop : ReferencePropagation;
166    mod remove_noop_landing_pads : RemoveNoopLandingPads;
167    mod remove_place_mention : RemovePlaceMention;
168    mod remove_storage_markers : RemoveStorageMarkers;
169    mod remove_uninit_drops : RemoveUninitDrops;
170    mod remove_unneeded_drops : RemoveUnneededDrops;
171    mod remove_zsts : RemoveZsts;
172    mod required_consts : RequiredConstsVisitor;
173    mod post_analysis_normalize : PostAnalysisNormalize;
174    mod sanity_check : SanityCheck;
175    // This pass is public to allow external drivers to perform MIR cleanup
176    pub mod simplify :
177        SimplifyCfg {
178            Initial,
179            PromoteConsts,
180            RemoveFalseEdges,
181            PostAnalysis,
182            PreOptimizations,
183            Final,
184            MakeShim,
185            AfterUnreachableEnumBranching
186        },
187        SimplifyLocals {
188            BeforeConstProp,
189            AfterGVN,
190            Final
191        };
192    mod simplify_branches : SimplifyConstCondition {
193        AfterInstSimplify,
194        AfterConstProp,
195        Final
196    };
197    mod simplify_comparison_integral : SimplifyComparisonIntegral;
198    mod single_use_consts : SingleUseConsts;
199    mod sroa : ScalarReplacementOfAggregates;
200    mod strip_debuginfo : StripDebugInfo;
201    mod unreachable_enum_branching : UnreachableEnumBranching;
202    mod unreachable_prop : UnreachablePropagation;
203    mod validate : Validator;
204}
205
206rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
207
208pub fn provide(providers: &mut Providers) {
209    coverage::query::provide(providers);
210    ffi_unwind_calls::provide(providers);
211    shim::provide(providers);
212    cross_crate_inline::provide(providers);
213    providers.queries = query::Providers {
214        mir_keys,
215        mir_built,
216        mir_const_qualif,
217        mir_promoted,
218        mir_drops_elaborated_and_const_checked,
219        mir_for_ctfe,
220        mir_coroutine_witnesses: coroutine::mir_coroutine_witnesses,
221        optimized_mir,
222        check_liveness: liveness::check_liveness,
223        is_mir_available,
224        is_ctfe_mir_available: is_mir_available,
225        mir_callgraph_cyclic: inline::cycle::mir_callgraph_cyclic,
226        mir_inliner_callees: inline::cycle::mir_inliner_callees,
227        promoted_mir,
228        deduced_param_attrs: deduce_param_attrs::deduced_param_attrs,
229        coroutine_by_move_body_def_id: coroutine::coroutine_by_move_body_def_id,
230        trivial_const: trivial_const::trivial_const_provider,
231        ..providers.queries
232    };
233}
234
235fn remap_mir_for_const_eval_select<'tcx>(
236    tcx: TyCtxt<'tcx>,
237    mut body: Body<'tcx>,
238    context: hir::Constness,
239) -> Body<'tcx> {
240    for bb in body.basic_blocks.as_mut().iter_mut() {
241        let terminator = bb.terminator.as_mut().expect("invalid terminator");
242        match terminator.kind {
243            TerminatorKind::Call {
244                func: Operand::Constant(box ConstOperand { ref const_, .. }),
245                ref mut args,
246                destination,
247                target,
248                unwind,
249                fn_span,
250                ..
251            } if let ty::FnDef(def_id, _) = *const_.ty().kind()
252                && tcx.is_intrinsic(def_id, sym::const_eval_select) =>
253            {
254                let Ok([tupled_args, called_in_const, called_at_rt]) = take_array(args) else {
255                    unreachable!()
256                };
257                let ty = tupled_args.node.ty(&body.local_decls, tcx);
258                let fields = ty.tuple_fields();
259                let num_args = fields.len();
260                let func =
261                    if context == hir::Constness::Const { called_in_const } else { called_at_rt };
262                let (method, place): (fn(Place<'tcx>) -> Operand<'tcx>, Place<'tcx>) =
263                    match tupled_args.node {
264                        Operand::Constant(_) => {
265                            // There is no good way of extracting a tuple arg from a constant
266                            // (const generic stuff) so we just create a temporary and deconstruct
267                            // that.
268                            let local = body.local_decls.push(LocalDecl::new(ty, fn_span));
269                            bb.statements.push(Statement::new(
270                                SourceInfo::outermost(fn_span),
271                                StatementKind::Assign(Box::new((
272                                    local.into(),
273                                    Rvalue::Use(tupled_args.node.clone()),
274                                ))),
275                            ));
276                            (Operand::Move, local.into())
277                        }
278                        Operand::Move(place) => (Operand::Move, place),
279                        Operand::Copy(place) => (Operand::Copy, place),
280                    };
281                let place_elems = place.projection;
282                let arguments = (0..num_args)
283                    .map(|x| {
284                        let mut place_elems = place_elems.to_vec();
285                        place_elems.push(ProjectionElem::Field(x.into(), fields[x]));
286                        let projection = tcx.mk_place_elems(&place_elems);
287                        let place = Place { local: place.local, projection };
288                        Spanned { node: method(place), span: DUMMY_SP }
289                    })
290                    .collect();
291                terminator.kind = TerminatorKind::Call {
292                    func: func.node,
293                    args: arguments,
294                    destination,
295                    target,
296                    unwind,
297                    call_source: CallSource::Misc,
298                    fn_span,
299                };
300            }
301            _ => {}
302        }
303    }
304    body
305}
306
307fn take_array<T, const N: usize>(b: &mut Box<[T]>) -> Result<[T; N], Box<[T]>> {
308    let b: Box<[T; N]> = std::mem::take(b).try_into()?;
309    Ok(*b)
310}
311
312fn is_mir_available(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
313    tcx.mir_keys(()).contains(&def_id)
314}
315
316/// Finds the full set of `DefId`s within the current crate that have
317/// MIR associated with them.
318fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet<LocalDefId> {
319    // All body-owners have MIR associated with them.
320    let mut set: FxIndexSet<_> = tcx.hir_body_owners().collect();
321
322    // Remove the fake bodies for `global_asm!`, since they're not useful
323    // to be emitted (`--emit=mir`) or encoded (in metadata).
324    set.retain(|&def_id| !matches!(tcx.def_kind(def_id), DefKind::GlobalAsm));
325
326    // Coroutine-closures (e.g. async closures) have an additional by-move MIR
327    // body that isn't in the HIR.
328    for body_owner in tcx.hir_body_owners() {
329        if let DefKind::Closure = tcx.def_kind(body_owner)
330            && tcx.needs_coroutine_by_move_body_def_id(body_owner.to_def_id())
331        {
332            set.insert(tcx.coroutine_by_move_body_def_id(body_owner).expect_local());
333        }
334    }
335
336    // tuple struct/variant constructors have MIR, but they don't have a BodyId,
337    // so we need to build them separately.
338    for item in tcx.hir_crate_items(()).free_items() {
339        if let DefKind::Struct | DefKind::Enum = tcx.def_kind(item.owner_id) {
340            for variant in tcx.adt_def(item.owner_id).variants() {
341                if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
342                    set.insert(ctor_def_id.expect_local());
343                }
344            }
345        }
346    }
347
348    set
349}
350
351fn mir_const_qualif(tcx: TyCtxt<'_>, def: LocalDefId) -> ConstQualifs {
352    // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
353    // cannot yet be stolen), because `mir_promoted()`, which steals
354    // from `mir_built()`, forces this query to execute before
355    // performing the steal.
356    let body = &tcx.mir_built(def).borrow();
357    let ccx = check_consts::ConstCx::new(tcx, body);
358    // No need to const-check a non-const `fn`.
359    match ccx.const_kind {
360        Some(ConstContext::Const { .. } | ConstContext::Static(_) | ConstContext::ConstFn) => {}
361        None => span_bug!(
362            tcx.def_span(def),
363            "`mir_const_qualif` should only be called on const fns and const items"
364        ),
365    }
366
367    if body.return_ty().references_error() {
368        // It's possible to reach here without an error being emitted (#121103).
369        tcx.dcx().span_delayed_bug(body.span, "mir_const_qualif: MIR had errors");
370        return Default::default();
371    }
372
373    let mut validator = check_consts::check::Checker::new(&ccx);
374    validator.check_body();
375
376    // We return the qualifs in the return place for every MIR body, even though it is only used
377    // when deciding to promote a reference to a `const` for now.
378    validator.qualifs_in_return_place()
379}
380
381fn mir_built(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
382    let mut body = build_mir(tcx, def);
383
384    // Identifying trivial consts based on their mir_built is easy, but a little wasteful.
385    // Trying to push this logic earlier in the compiler and never even produce the Body would
386    // probably improve compile time.
387    if trivial_const::trivial_const(tcx, def, || &body).is_some() {
388        // Skip all the passes below for trivial consts.
389        let body = tcx.alloc_steal_mir(body);
390        pass_manager::dump_mir_for_phase_change(tcx, &body.borrow());
391        return body;
392    }
393
394    pass_manager::dump_mir_for_phase_change(tcx, &body);
395
396    pm::run_passes(
397        tcx,
398        &mut body,
399        &[
400            // MIR-level lints.
401            &Lint(check_inline::CheckForceInline),
402            &Lint(check_call_recursion::CheckCallRecursion),
403            // Check callee's target features match callers target features when
404            // using `#[inline(always)]`
405            &Lint(check_inline_always_target_features::CheckInlineAlwaysTargetFeature),
406            &Lint(check_packed_ref::CheckPackedRef),
407            &Lint(check_const_item_mutation::CheckConstItemMutation),
408            &Lint(function_item_references::FunctionItemReferences),
409            // What we need to do constant evaluation.
410            &simplify::SimplifyCfg::Initial,
411            &Lint(sanity_check::SanityCheck),
412        ],
413        None,
414        pm::Optimizations::Allowed,
415    );
416    tcx.alloc_steal_mir(body)
417}
418
419/// Compute the main MIR body and the list of MIR bodies of the promoteds.
420fn mir_promoted(
421    tcx: TyCtxt<'_>,
422    def: LocalDefId,
423) -> (&Steal<Body<'_>>, &Steal<IndexVec<Promoted, Body<'_>>>) {
424    debug_assert!(!tcx.is_trivial_const(def), "Tried to get mir_promoted of a trivial const");
425
426    // Ensure that we compute the `mir_const_qualif` for constants at
427    // this point, before we steal the mir-const result.
428    // Also this means promotion can rely on all const checks having been done.
429
430    let const_qualifs = match tcx.def_kind(def) {
431        DefKind::Fn | DefKind::AssocFn | DefKind::Closure
432            if tcx.constness(def) == hir::Constness::Const
433                || tcx.is_const_default_method(def.to_def_id()) =>
434        {
435            tcx.mir_const_qualif(def)
436        }
437        DefKind::AssocConst
438        | DefKind::Const
439        | DefKind::Static { .. }
440        | DefKind::InlineConst
441        | DefKind::AnonConst => tcx.mir_const_qualif(def),
442        _ => ConstQualifs::default(),
443    };
444
445    // the `has_ffi_unwind_calls` query uses the raw mir, so make sure it is run.
446    tcx.ensure_done().has_ffi_unwind_calls(def);
447
448    // the `by_move_body` query uses the raw mir, so make sure it is run.
449    if tcx.needs_coroutine_by_move_body_def_id(def.to_def_id()) {
450        tcx.ensure_done().coroutine_by_move_body_def_id(def);
451    }
452
453    // the `trivial_const` query uses mir_built, so make sure it is run.
454    tcx.ensure_done().trivial_const(def);
455
456    let mut body = tcx.mir_built(def).steal();
457    if let Some(error_reported) = const_qualifs.tainted_by_errors {
458        body.tainted_by_errors = Some(error_reported);
459    }
460
461    // Collect `required_consts` *before* promotion, so if there are any consts being promoted
462    // we still add them to the list in the outer MIR body.
463    RequiredConstsVisitor::compute_required_consts(&mut body);
464
465    // What we need to run borrowck etc.
466    let promote_pass = promote_consts::PromoteTemps::default();
467    pm::run_passes(
468        tcx,
469        &mut body,
470        &[&promote_pass, &simplify::SimplifyCfg::PromoteConsts, &coverage::InstrumentCoverage],
471        Some(MirPhase::Analysis(AnalysisPhase::Initial)),
472        pm::Optimizations::Allowed,
473    );
474
475    lint_tail_expr_drop_order::run_lint(tcx, def, &body);
476
477    let promoted = promote_pass.promoted_fragments.into_inner();
478    (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
479}
480
481/// Compute the MIR that is used during CTFE (and thus has no optimizations run on it)
482fn mir_for_ctfe(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &Body<'_> {
483    debug_assert!(!tcx.is_trivial_const(def_id), "Tried to get mir_for_ctfe of a trivial const");
484    tcx.arena.alloc(inner_mir_for_ctfe(tcx, def_id))
485}
486
487fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: LocalDefId) -> Body<'_> {
488    // FIXME: don't duplicate this between the optimized_mir/mir_for_ctfe queries
489    if tcx.is_constructor(def.to_def_id()) {
490        // There's no reason to run all of the MIR passes on constructors when
491        // we can just output the MIR we want directly. This also saves const
492        // qualification and borrow checking the trouble of special casing
493        // constructors.
494        return shim::build_adt_ctor(tcx, def.to_def_id());
495    }
496
497    let body = tcx.mir_drops_elaborated_and_const_checked(def);
498    let body = match tcx.hir_body_const_context(def) {
499        // consts and statics do not have `optimized_mir`, so we can steal the body instead of
500        // cloning it.
501        Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => body.steal(),
502        Some(hir::ConstContext::ConstFn) => body.borrow().clone(),
503        None => bug!("`mir_for_ctfe` called on non-const {def:?}"),
504    };
505
506    let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::Const);
507    pm::run_passes(tcx, &mut body, &[&ctfe_limit::CtfeLimit], None, pm::Optimizations::Allowed);
508
509    body
510}
511
512/// Obtain just the main MIR (no promoteds) and run some cleanups on it. This also runs
513/// mir borrowck *before* doing so in order to ensure that borrowck can be run and doesn't
514/// end up missing the source MIR due to stealing happening.
515fn mir_drops_elaborated_and_const_checked(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
516    if tcx.is_coroutine(def.to_def_id()) {
517        tcx.ensure_done().mir_coroutine_witnesses(def);
518    }
519
520    // We only need to borrowck non-synthetic MIR.
521    let tainted_by_errors = if !tcx.is_synthetic_mir(def) {
522        tcx.mir_borrowck(tcx.typeck_root_def_id(def.to_def_id()).expect_local()).err()
523    } else {
524        None
525    };
526
527    let is_fn_like = tcx.def_kind(def).is_fn_like();
528    if is_fn_like {
529        // Do not compute the mir call graph without said call graph actually being used.
530        if pm::should_run_pass(tcx, &inline::Inline, pm::Optimizations::Allowed)
531            || inline::ForceInline::should_run_pass_for_callee(tcx, def.to_def_id())
532        {
533            tcx.ensure_done().mir_inliner_callees(ty::InstanceKind::Item(def.to_def_id()));
534        }
535    }
536
537    tcx.ensure_done().check_liveness(def);
538
539    let (body, _) = tcx.mir_promoted(def);
540    let mut body = body.steal();
541
542    if let Some(error_reported) = tainted_by_errors {
543        body.tainted_by_errors = Some(error_reported);
544    }
545
546    // Also taint the body if it's within a top-level item that is not well formed.
547    //
548    // We do this check here and not during `mir_promoted` because that may result
549    // in borrowck cycles if WF requires looking into an opaque hidden type.
550    let root = tcx.typeck_root_def_id(def.to_def_id());
551    match tcx.def_kind(root) {
552        DefKind::Fn
553        | DefKind::AssocFn
554        | DefKind::Static { .. }
555        | DefKind::Const
556        | DefKind::AssocConst => {
557            if let Err(guar) = tcx.ensure_ok().check_well_formed(root.expect_local()) {
558                body.tainted_by_errors = Some(guar);
559            }
560        }
561        _ => {}
562    }
563
564    run_analysis_to_runtime_passes(tcx, &mut body);
565
566    tcx.alloc_steal_mir(body)
567}
568
569// Made public so that `mir_drops_elaborated_and_const_checked` can be overridden
570// by custom rustc drivers, running all the steps by themselves. See #114628.
571pub fn run_analysis_to_runtime_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
572    assert!(body.phase == MirPhase::Analysis(AnalysisPhase::Initial));
573    let did = body.source.def_id();
574
575    debug!("analysis_mir_cleanup({:?})", did);
576    run_analysis_cleanup_passes(tcx, body);
577    assert!(body.phase == MirPhase::Analysis(AnalysisPhase::PostCleanup));
578
579    // Do a little drop elaboration before const-checking if `const_precise_live_drops` is enabled.
580    if check_consts::post_drop_elaboration::checking_enabled(&ConstCx::new(tcx, body)) {
581        pm::run_passes(
582            tcx,
583            body,
584            &[
585                &remove_uninit_drops::RemoveUninitDrops,
586                &simplify::SimplifyCfg::RemoveFalseEdges,
587                &Lint(post_drop_elaboration::CheckLiveDrops),
588            ],
589            None,
590            pm::Optimizations::Allowed,
591        );
592    }
593
594    debug!("runtime_mir_lowering({:?})", did);
595    run_runtime_lowering_passes(tcx, body);
596    assert!(body.phase == MirPhase::Runtime(RuntimePhase::Initial));
597
598    debug!("runtime_mir_cleanup({:?})", did);
599    run_runtime_cleanup_passes(tcx, body);
600    assert!(body.phase == MirPhase::Runtime(RuntimePhase::PostCleanup));
601}
602
603// FIXME(JakobDegen): Can we make these lists of passes consts?
604
605/// After this series of passes, no lifetime analysis based on borrowing can be done.
606fn run_analysis_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
607    let passes: &[&dyn MirPass<'tcx>] = &[
608        &impossible_predicates::ImpossiblePredicates,
609        &cleanup_post_borrowck::CleanupPostBorrowck,
610        &remove_noop_landing_pads::RemoveNoopLandingPads,
611        &simplify::SimplifyCfg::PostAnalysis,
612        &deref_separator::Derefer,
613    ];
614
615    pm::run_passes(
616        tcx,
617        body,
618        passes,
619        Some(MirPhase::Analysis(AnalysisPhase::PostCleanup)),
620        pm::Optimizations::Allowed,
621    );
622}
623
624/// Returns the sequence of passes that lowers analysis to runtime MIR.
625fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
626    let passes: &[&dyn MirPass<'tcx>] = &[
627        // These next passes must be executed together.
628        &add_call_guards::CriticalCallEdges,
629        // Must be done before drop elaboration because we need to drop opaque types, too.
630        &post_analysis_normalize::PostAnalysisNormalize,
631        // Calling this after `PostAnalysisNormalize` ensures that we don't deal with opaque types.
632        &add_subtyping_projections::Subtyper,
633        &elaborate_drops::ElaborateDrops,
634        // Needs to happen after drop elaboration.
635        &Lint(check_call_recursion::CheckDropRecursion),
636        // This will remove extraneous landing pads which are no longer
637        // necessary as well as forcing any call in a non-unwinding
638        // function calling a possibly-unwinding function to abort the process.
639        &abort_unwinding_calls::AbortUnwindingCalls,
640        // AddMovesForPackedDrops needs to run after drop
641        // elaboration.
642        &add_moves_for_packed_drops::AddMovesForPackedDrops,
643        // `AddRetag` needs to run after `ElaborateDrops` but before `ElaborateBoxDerefs`.
644        // Otherwise it should run fairly late, but before optimizations begin.
645        &add_retag::AddRetag,
646        &erase_deref_temps::EraseDerefTemps,
647        &elaborate_box_derefs::ElaborateBoxDerefs,
648        &coroutine::StateTransform,
649        &Lint(known_panics_lint::KnownPanicsLint),
650    ];
651    pm::run_passes_no_validate(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::Initial)));
652}
653
654/// Returns the sequence of passes that do the initial cleanup of runtime MIR.
655fn run_runtime_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
656    let passes: &[&dyn MirPass<'tcx>] = &[
657        &lower_intrinsics::LowerIntrinsics,
658        &remove_place_mention::RemovePlaceMention,
659        &simplify::SimplifyCfg::PreOptimizations,
660    ];
661
662    pm::run_passes(
663        tcx,
664        body,
665        passes,
666        Some(MirPhase::Runtime(RuntimePhase::PostCleanup)),
667        pm::Optimizations::Allowed,
668    );
669
670    // Clear this by anticipation. Optimizations and runtime MIR have no reason to look
671    // into this information, which is meant for borrowck diagnostics.
672    for decl in &mut body.local_decls {
673        decl.local_info = ClearCrossCrate::Clear;
674    }
675}
676
677pub(crate) fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
678    fn o1<T>(x: T) -> WithMinOptLevel<T> {
679        WithMinOptLevel(1, x)
680    }
681
682    let def_id = body.source.def_id();
683    let optimizations = if tcx.def_kind(def_id).has_codegen_attrs()
684        && tcx.codegen_fn_attrs(def_id).optimize.do_not_optimize()
685    {
686        pm::Optimizations::Suppressed
687    } else {
688        pm::Optimizations::Allowed
689    };
690
691    // The main optimizations that we do on MIR.
692    pm::run_passes(
693        tcx,
694        body,
695        &[
696            // Add some UB checks before any UB gets optimized away.
697            &check_alignment::CheckAlignment,
698            &check_null::CheckNull,
699            &check_enums::CheckEnums,
700            // Before inlining: trim down MIR with passes to reduce inlining work.
701
702            // Has to be done before inlining, otherwise actual call will be almost always inlined.
703            // Also simple, so can just do first.
704            &lower_slice_len::LowerSliceLenCalls,
705            // Perform instsimplify before inline to eliminate some trivial calls (like clone
706            // shims).
707            &instsimplify::InstSimplify::BeforeInline,
708            // Perform inlining of `#[rustc_force_inline]`-annotated callees.
709            &inline::ForceInline,
710            // Perform inlining, which may add a lot of code.
711            &inline::Inline,
712            // Inlining may have introduced a lot of redundant code and a large move pattern.
713            // Now, we need to shrink the generated MIR.
714            // Code from other crates may have storage markers, so this needs to happen after
715            // inlining.
716            &remove_storage_markers::RemoveStorageMarkers,
717            // Inlining and instantiation may introduce ZST and useless drops.
718            &remove_zsts::RemoveZsts,
719            &remove_unneeded_drops::RemoveUnneededDrops,
720            // Type instantiation may create uninhabited enums.
721            // Also eliminates some unreachable branches based on variants of enums.
722            &unreachable_enum_branching::UnreachableEnumBranching,
723            &unreachable_prop::UnreachablePropagation,
724            &o1(simplify::SimplifyCfg::AfterUnreachableEnumBranching),
725            &multiple_return_terminators::MultipleReturnTerminators,
726            // After simplifycfg, it allows us to discover new opportunities for peephole
727            // optimizations. This invalidates CFG caches, so avoid putting between
728            // `ReferencePropagation` and `GVN` which both use the dominator tree.
729            &instsimplify::InstSimplify::AfterSimplifyCfg,
730            // After `InstSimplify-after-simplifycfg` with `-Zub_checks=false`, simplify
731            // ```
732            // _13 = const false;
733            // assume(copy _13);
734            // Call(precondition_check);
735            // ```
736            // to unreachable to eliminate the call to help later passes.
737            // This invalidates CFG caches also.
738            &o1(simplify_branches::SimplifyConstCondition::AfterInstSimplify),
739            &ref_prop::ReferencePropagation,
740            &sroa::ScalarReplacementOfAggregates,
741            &simplify::SimplifyLocals::BeforeConstProp,
742            &dead_store_elimination::DeadStoreElimination::Initial,
743            &gvn::GVN,
744            &simplify::SimplifyLocals::AfterGVN,
745            &match_branches::MatchBranchSimplification,
746            &dataflow_const_prop::DataflowConstProp,
747            &single_use_consts::SingleUseConsts,
748            &o1(simplify_branches::SimplifyConstCondition::AfterConstProp),
749            &jump_threading::JumpThreading,
750            &early_otherwise_branch::EarlyOtherwiseBranch,
751            &simplify_comparison_integral::SimplifyComparisonIntegral,
752            &o1(simplify_branches::SimplifyConstCondition::Final),
753            &o1(remove_noop_landing_pads::RemoveNoopLandingPads),
754            &o1(simplify::SimplifyCfg::Final),
755            // After the last SimplifyCfg, because this wants one-block functions.
756            &strip_debuginfo::StripDebugInfo,
757            &copy_prop::CopyProp,
758            &dead_store_elimination::DeadStoreElimination::Final,
759            &dest_prop::DestinationPropagation,
760            &simplify::SimplifyLocals::Final,
761            &multiple_return_terminators::MultipleReturnTerminators,
762            &large_enums::EnumSizeOpt { discrepancy: 128 },
763            // Some cleanup necessary at least for LLVM and potentially other codegen backends.
764            &add_call_guards::CriticalCallEdges,
765            // Cleanup for human readability, off by default.
766            &prettify::ReorderBasicBlocks,
767            &prettify::ReorderLocals,
768            // Dump the end result for testing and debugging purposes.
769            &dump_mir::Marker("PreCodegen"),
770        ],
771        Some(MirPhase::Runtime(RuntimePhase::Optimized)),
772        optimizations,
773    );
774}
775
776/// Optimize the MIR and prepare it for codegen.
777fn optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> &Body<'_> {
778    tcx.arena.alloc(inner_optimized_mir(tcx, did))
779}
780
781fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
782    if tcx.is_constructor(did.to_def_id()) {
783        // There's no reason to run all of the MIR passes on constructors when
784        // we can just output the MIR we want directly. This also saves const
785        // qualification and borrow checking the trouble of special casing
786        // constructors.
787        return shim::build_adt_ctor(tcx, did.to_def_id());
788    }
789
790    match tcx.hir_body_const_context(did) {
791        // Run the `mir_for_ctfe` query, which depends on `mir_drops_elaborated_and_const_checked`
792        // which we are going to steal below. Thus we need to run `mir_for_ctfe` first, so it
793        // computes and caches its result.
794        Some(hir::ConstContext::ConstFn) => tcx.ensure_done().mir_for_ctfe(did),
795        None => {}
796        Some(other) => panic!("do not use `optimized_mir` for constants: {other:?}"),
797    }
798    debug!("about to call mir_drops_elaborated...");
799    let body = tcx.mir_drops_elaborated_and_const_checked(did).steal();
800    let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::NotConst);
801
802    if body.tainted_by_errors.is_some() {
803        return body;
804    }
805
806    // Before doing anything, remember which items are being mentioned so that the set of items
807    // visited does not depend on the optimization level.
808    // We do not use `run_passes` for this as that might skip the pass if `injection_phase` is set.
809    mentioned_items::MentionedItems.run_pass(tcx, &mut body);
810
811    // If `mir_drops_elaborated_and_const_checked` found that the current body has unsatisfiable
812    // predicates, it will shrink the MIR to a single `unreachable` terminator.
813    // More generally, if MIR is a lone `unreachable`, there is nothing to optimize.
814    if let TerminatorKind::Unreachable = body.basic_blocks[START_BLOCK].terminator().kind
815        && body.basic_blocks[START_BLOCK].statements.is_empty()
816    {
817        return body;
818    }
819
820    run_optimization_passes(tcx, &mut body);
821
822    body
823}
824
825/// Fetch all the promoteds of an item and prepare their MIR bodies to be ready for
826/// constant evaluation once all generic parameters become known.
827fn promoted_mir(tcx: TyCtxt<'_>, def: LocalDefId) -> &IndexVec<Promoted, Body<'_>> {
828    if tcx.is_constructor(def.to_def_id()) {
829        return tcx.arena.alloc(IndexVec::new());
830    }
831
832    if !tcx.is_synthetic_mir(def) {
833        tcx.ensure_done().mir_borrowck(tcx.typeck_root_def_id(def.to_def_id()).expect_local());
834    }
835    let mut promoted = tcx.mir_promoted(def).1.steal();
836
837    for body in &mut promoted {
838        run_analysis_to_runtime_passes(tcx, body);
839    }
840
841    tcx.arena.alloc(promoted)
842}