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