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(if_let_guard)]
9#![feature(impl_trait_in_assoc_type)]
10#![feature(map_try_insert)]
11#![feature(never_type)]
12#![feature(try_blocks)]
13#![feature(vec_deque_pop_if)]
14#![feature(yeet_expr)]
15// tidy-alphabetical-end
16
17use hir::ConstContext;
18use required_consts::RequiredConstsVisitor;
19use rustc_const_eval::check_consts::{self, ConstCx};
20use rustc_const_eval::util;
21use rustc_data_structures::fx::FxIndexSet;
22use rustc_data_structures::steal::Steal;
23use rustc_hir as hir;
24use rustc_hir::def::{CtorKind, DefKind};
25use rustc_hir::def_id::LocalDefId;
26use rustc_index::IndexVec;
27use rustc_middle::mir::{
28    AnalysisPhase, Body, CallSource, ClearCrossCrate, ConstOperand, ConstQualifs, LocalDecl,
29    MirPhase, Operand, Place, ProjectionElem, Promoted, RuntimePhase, Rvalue, START_BLOCK,
30    SourceInfo, Statement, StatementKind, TerminatorKind,
31};
32use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
33use rustc_middle::util::Providers;
34use rustc_middle::{bug, query, span_bug};
35use rustc_mir_build::builder::build_mir;
36use rustc_span::source_map::Spanned;
37use rustc_span::{DUMMY_SP, sym};
38use tracing::debug;
39
40#[macro_use]
41mod pass_manager;
42
43use std::sync::LazyLock;
44
45use pass_manager::{self as pm, Lint, MirLint, MirPass, WithMinOptLevel};
46
47mod check_pointers;
48mod cost_checker;
49mod cross_crate_inline;
50mod deduce_param_attrs;
51mod elaborate_drop;
52mod errors;
53mod ffi_unwind_calls;
54mod lint;
55mod lint_tail_expr_drop_order;
56mod patch;
57mod shim;
58mod ssa;
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_alignment : CheckAlignment;
123    mod check_const_item_mutation : CheckConstItemMutation;
124    mod check_null : CheckNull;
125    mod check_packed_ref : CheckPackedRef;
126    // This pass is public to allow external drivers to perform MIR cleanup
127    pub mod cleanup_post_borrowck : CleanupPostBorrowck;
128
129    mod copy_prop : CopyProp;
130    mod coroutine : StateTransform;
131    mod coverage : InstrumentCoverage;
132    mod ctfe_limit : CtfeLimit;
133    mod dataflow_const_prop : DataflowConstProp;
134    mod dead_store_elimination : DeadStoreElimination {
135        Initial,
136        Final
137    };
138    mod deref_separator : Derefer;
139    mod dest_prop : DestinationPropagation;
140    pub mod dump_mir : Marker;
141    mod early_otherwise_branch : EarlyOtherwiseBranch;
142    mod elaborate_box_derefs : ElaborateBoxDerefs;
143    mod elaborate_drops : ElaborateDrops;
144    mod function_item_references : FunctionItemReferences;
145    mod gvn : GVN;
146    // Made public so that `mir_drops_elaborated_and_const_checked` can be overridden
147    // by custom rustc drivers, running all the steps by themselves. See #114628.
148    pub mod inline : Inline, ForceInline;
149    mod impossible_predicates : ImpossiblePredicates;
150    mod instsimplify : InstSimplify { BeforeInline, AfterSimplifyCfg };
151    mod jump_threading : JumpThreading;
152    mod known_panics_lint : KnownPanicsLint;
153    mod large_enums : EnumSizeOpt;
154    mod lower_intrinsics : LowerIntrinsics;
155    mod lower_slice_len : LowerSliceLenCalls;
156    mod match_branches : MatchBranchSimplification;
157    mod mentioned_items : MentionedItems;
158    mod multiple_return_terminators : MultipleReturnTerminators;
159    mod nrvo : RenameReturnPlace;
160    mod post_drop_elaboration : CheckLiveDrops;
161    mod prettify : ReorderBasicBlocks, ReorderLocals;
162    mod promote_consts : PromoteTemps;
163    mod ref_prop : ReferencePropagation;
164    mod remove_noop_landing_pads : RemoveNoopLandingPads;
165    mod remove_place_mention : RemovePlaceMention;
166    mod remove_storage_markers : RemoveStorageMarkers;
167    mod remove_uninit_drops : RemoveUninitDrops;
168    mod remove_unneeded_drops : RemoveUnneededDrops;
169    mod remove_zsts : RemoveZsts;
170    mod required_consts : RequiredConstsVisitor;
171    mod post_analysis_normalize : PostAnalysisNormalize;
172    mod sanity_check : SanityCheck;
173    // This pass is public to allow external drivers to perform MIR cleanup
174    pub mod simplify :
175        SimplifyCfg {
176            Initial,
177            PromoteConsts,
178            RemoveFalseEdges,
179            PostAnalysis,
180            PreOptimizations,
181            Final,
182            MakeShim,
183            AfterUnreachableEnumBranching
184        },
185        SimplifyLocals {
186            BeforeConstProp,
187            AfterGVN,
188            Final
189        };
190    mod simplify_branches : SimplifyConstCondition {
191        AfterConstProp,
192        Final
193    };
194    mod simplify_comparison_integral : SimplifyComparisonIntegral;
195    mod single_use_consts : SingleUseConsts;
196    mod sroa : ScalarReplacementOfAggregates;
197    mod strip_debuginfo : StripDebugInfo;
198    mod unreachable_enum_branching : UnreachableEnumBranching;
199    mod unreachable_prop : UnreachablePropagation;
200    mod validate : Validator;
201}
202
203rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
204
205pub fn provide(providers: &mut Providers) {
206    coverage::query::provide(providers);
207    ffi_unwind_calls::provide(providers);
208    shim::provide(providers);
209    cross_crate_inline::provide(providers);
210    providers.queries = query::Providers {
211        mir_keys,
212        mir_built,
213        mir_const_qualif,
214        mir_promoted,
215        mir_drops_elaborated_and_const_checked,
216        mir_for_ctfe,
217        mir_coroutine_witnesses: coroutine::mir_coroutine_witnesses,
218        optimized_mir,
219        is_mir_available,
220        is_ctfe_mir_available: is_mir_available,
221        mir_callgraph_reachable: inline::cycle::mir_callgraph_reachable,
222        mir_inliner_callees: inline::cycle::mir_inliner_callees,
223        promoted_mir,
224        deduced_param_attrs: deduce_param_attrs::deduced_param_attrs,
225        coroutine_by_move_body_def_id: coroutine::coroutine_by_move_body_def_id,
226        ..providers.queries
227    };
228}
229
230fn remap_mir_for_const_eval_select<'tcx>(
231    tcx: TyCtxt<'tcx>,
232    mut body: Body<'tcx>,
233    context: hir::Constness,
234) -> Body<'tcx> {
235    for bb in body.basic_blocks.as_mut().iter_mut() {
236        let terminator = bb.terminator.as_mut().expect("invalid terminator");
237        match terminator.kind {
238            TerminatorKind::Call {
239                func: Operand::Constant(box ConstOperand { ref const_, .. }),
240                ref mut args,
241                destination,
242                target,
243                unwind,
244                fn_span,
245                ..
246            } if let ty::FnDef(def_id, _) = *const_.ty().kind()
247                && tcx.is_intrinsic(def_id, sym::const_eval_select) =>
248            {
249                let Ok([tupled_args, called_in_const, called_at_rt]) = take_array(args) else {
250                    unreachable!()
251                };
252                let ty = tupled_args.node.ty(&body.local_decls, tcx);
253                let fields = ty.tuple_fields();
254                let num_args = fields.len();
255                let func =
256                    if context == hir::Constness::Const { called_in_const } else { called_at_rt };
257                let (method, place): (fn(Place<'tcx>) -> Operand<'tcx>, Place<'tcx>) =
258                    match tupled_args.node {
259                        Operand::Constant(_) => {
260                            // There is no good way of extracting a tuple arg from a constant
261                            // (const generic stuff) so we just create a temporary and deconstruct
262                            // that.
263                            let local = body.local_decls.push(LocalDecl::new(ty, fn_span));
264                            bb.statements.push(Statement {
265                                source_info: SourceInfo::outermost(fn_span),
266                                kind: StatementKind::Assign(Box::new((
267                                    local.into(),
268                                    Rvalue::Use(tupled_args.node.clone()),
269                                ))),
270                            });
271                            (Operand::Move, local.into())
272                        }
273                        Operand::Move(place) => (Operand::Move, place),
274                        Operand::Copy(place) => (Operand::Copy, place),
275                    };
276                let place_elems = place.projection;
277                let arguments = (0..num_args)
278                    .map(|x| {
279                        let mut place_elems = place_elems.to_vec();
280                        place_elems.push(ProjectionElem::Field(x.into(), fields[x]));
281                        let projection = tcx.mk_place_elems(&place_elems);
282                        let place = Place { local: place.local, projection };
283                        Spanned { node: method(place), span: DUMMY_SP }
284                    })
285                    .collect();
286                terminator.kind = TerminatorKind::Call {
287                    func: func.node,
288                    args: arguments,
289                    destination,
290                    target,
291                    unwind,
292                    call_source: CallSource::Misc,
293                    fn_span,
294                };
295            }
296            _ => {}
297        }
298    }
299    body
300}
301
302fn take_array<T, const N: usize>(b: &mut Box<[T]>) -> Result<[T; N], Box<[T]>> {
303    let b: Box<[T; N]> = std::mem::take(b).try_into()?;
304    Ok(*b)
305}
306
307fn is_mir_available(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
308    tcx.mir_keys(()).contains(&def_id)
309}
310
311/// Finds the full set of `DefId`s within the current crate that have
312/// MIR associated with them.
313fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet<LocalDefId> {
314    // All body-owners have MIR associated with them.
315    let mut set: FxIndexSet<_> = tcx.hir_body_owners().collect();
316
317    // Remove the fake bodies for `global_asm!`, since they're not useful
318    // to be emitted (`--emit=mir`) or encoded (in metadata).
319    set.retain(|&def_id| !matches!(tcx.def_kind(def_id), DefKind::GlobalAsm));
320
321    // Coroutine-closures (e.g. async closures) have an additional by-move MIR
322    // body that isn't in the HIR.
323    for body_owner in tcx.hir_body_owners() {
324        if let DefKind::Closure = tcx.def_kind(body_owner)
325            && tcx.needs_coroutine_by_move_body_def_id(body_owner.to_def_id())
326        {
327            set.insert(tcx.coroutine_by_move_body_def_id(body_owner).expect_local());
328        }
329    }
330
331    // tuple struct/variant constructors have MIR, but they don't have a BodyId,
332    // so we need to build them separately.
333    for item in tcx.hir_crate_items(()).free_items() {
334        if let DefKind::Struct | DefKind::Enum = tcx.def_kind(item.owner_id) {
335            for variant in tcx.adt_def(item.owner_id).variants() {
336                if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
337                    set.insert(ctor_def_id.expect_local());
338                }
339            }
340        }
341    }
342
343    set
344}
345
346fn mir_const_qualif(tcx: TyCtxt<'_>, def: LocalDefId) -> ConstQualifs {
347    // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
348    // cannot yet be stolen), because `mir_promoted()`, which steals
349    // from `mir_built()`, forces this query to execute before
350    // performing the steal.
351    let body = &tcx.mir_built(def).borrow();
352    let ccx = check_consts::ConstCx::new(tcx, body);
353    // No need to const-check a non-const `fn`.
354    match ccx.const_kind {
355        Some(ConstContext::Const { .. } | ConstContext::Static(_) | ConstContext::ConstFn) => {}
356        None => span_bug!(
357            tcx.def_span(def),
358            "`mir_const_qualif` should only be called on const fns and const items"
359        ),
360    }
361
362    if body.return_ty().references_error() {
363        // It's possible to reach here without an error being emitted (#121103).
364        tcx.dcx().span_delayed_bug(body.span, "mir_const_qualif: MIR had errors");
365        return Default::default();
366    }
367
368    let mut validator = check_consts::check::Checker::new(&ccx);
369    validator.check_body();
370
371    // We return the qualifs in the return place for every MIR body, even though it is only used
372    // when deciding to promote a reference to a `const` for now.
373    validator.qualifs_in_return_place()
374}
375
376fn mir_built(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
377    let mut body = build_mir(tcx, def);
378
379    pass_manager::dump_mir_for_phase_change(tcx, &body);
380
381    pm::run_passes(
382        tcx,
383        &mut body,
384        &[
385            // MIR-level lints.
386            &Lint(check_inline::CheckForceInline),
387            &Lint(check_call_recursion::CheckCallRecursion),
388            &Lint(check_packed_ref::CheckPackedRef),
389            &Lint(check_const_item_mutation::CheckConstItemMutation),
390            &Lint(function_item_references::FunctionItemReferences),
391            // What we need to do constant evaluation.
392            &simplify::SimplifyCfg::Initial,
393            &Lint(sanity_check::SanityCheck),
394        ],
395        None,
396        pm::Optimizations::Allowed,
397    );
398    tcx.alloc_steal_mir(body)
399}
400
401/// Compute the main MIR body and the list of MIR bodies of the promoteds.
402fn mir_promoted(
403    tcx: TyCtxt<'_>,
404    def: LocalDefId,
405) -> (&Steal<Body<'_>>, &Steal<IndexVec<Promoted, Body<'_>>>) {
406    // Ensure that we compute the `mir_const_qualif` for constants at
407    // this point, before we steal the mir-const result.
408    // Also this means promotion can rely on all const checks having been done.
409
410    let const_qualifs = match tcx.def_kind(def) {
411        DefKind::Fn | DefKind::AssocFn | DefKind::Closure
412            if tcx.constness(def) == hir::Constness::Const
413                || tcx.is_const_default_method(def.to_def_id()) =>
414        {
415            tcx.mir_const_qualif(def)
416        }
417        DefKind::AssocConst
418        | DefKind::Const
419        | DefKind::Static { .. }
420        | DefKind::InlineConst
421        | DefKind::AnonConst => tcx.mir_const_qualif(def),
422        _ => ConstQualifs::default(),
423    };
424
425    // the `has_ffi_unwind_calls` query uses the raw mir, so make sure it is run.
426    tcx.ensure_done().has_ffi_unwind_calls(def);
427
428    // the `by_move_body` query uses the raw mir, so make sure it is run.
429    if tcx.needs_coroutine_by_move_body_def_id(def.to_def_id()) {
430        tcx.ensure_done().coroutine_by_move_body_def_id(def);
431    }
432
433    let mut body = tcx.mir_built(def).steal();
434    if let Some(error_reported) = const_qualifs.tainted_by_errors {
435        body.tainted_by_errors = Some(error_reported);
436    }
437
438    // Collect `required_consts` *before* promotion, so if there are any consts being promoted
439    // we still add them to the list in the outer MIR body.
440    RequiredConstsVisitor::compute_required_consts(&mut body);
441
442    // What we need to run borrowck etc.
443    let promote_pass = promote_consts::PromoteTemps::default();
444    pm::run_passes(
445        tcx,
446        &mut body,
447        &[&promote_pass, &simplify::SimplifyCfg::PromoteConsts, &coverage::InstrumentCoverage],
448        Some(MirPhase::Analysis(AnalysisPhase::Initial)),
449        pm::Optimizations::Allowed,
450    );
451
452    lint_tail_expr_drop_order::run_lint(tcx, def, &body);
453
454    let promoted = promote_pass.promoted_fragments.into_inner();
455    (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
456}
457
458/// Compute the MIR that is used during CTFE (and thus has no optimizations run on it)
459fn mir_for_ctfe(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &Body<'_> {
460    tcx.arena.alloc(inner_mir_for_ctfe(tcx, def_id))
461}
462
463fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: LocalDefId) -> Body<'_> {
464    // FIXME: don't duplicate this between the optimized_mir/mir_for_ctfe queries
465    if tcx.is_constructor(def.to_def_id()) {
466        // There's no reason to run all of the MIR passes on constructors when
467        // we can just output the MIR we want directly. This also saves const
468        // qualification and borrow checking the trouble of special casing
469        // constructors.
470        return shim::build_adt_ctor(tcx, def.to_def_id());
471    }
472
473    let body = tcx.mir_drops_elaborated_and_const_checked(def);
474    let body = match tcx.hir_body_const_context(def) {
475        // consts and statics do not have `optimized_mir`, so we can steal the body instead of
476        // cloning it.
477        Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => body.steal(),
478        Some(hir::ConstContext::ConstFn) => body.borrow().clone(),
479        None => bug!("`mir_for_ctfe` called on non-const {def:?}"),
480    };
481
482    let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::Const);
483    pm::run_passes(tcx, &mut body, &[&ctfe_limit::CtfeLimit], None, pm::Optimizations::Allowed);
484
485    body
486}
487
488/// Obtain just the main MIR (no promoteds) and run some cleanups on it. This also runs
489/// mir borrowck *before* doing so in order to ensure that borrowck can be run and doesn't
490/// end up missing the source MIR due to stealing happening.
491fn mir_drops_elaborated_and_const_checked(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
492    if tcx.is_coroutine(def.to_def_id()) {
493        tcx.ensure_done().mir_coroutine_witnesses(def);
494    }
495
496    // We only need to borrowck non-synthetic MIR.
497    let tainted_by_errors = if !tcx.is_synthetic_mir(def) {
498        tcx.mir_borrowck(tcx.typeck_root_def_id(def.to_def_id()).expect_local()).err()
499    } else {
500        None
501    };
502
503    let is_fn_like = tcx.def_kind(def).is_fn_like();
504    if is_fn_like {
505        // Do not compute the mir call graph without said call graph actually being used.
506        if pm::should_run_pass(tcx, &inline::Inline, pm::Optimizations::Allowed)
507            || inline::ForceInline::should_run_pass_for_callee(tcx, def.to_def_id())
508        {
509            tcx.ensure_done().mir_inliner_callees(ty::InstanceKind::Item(def.to_def_id()));
510        }
511    }
512
513    let (body, _) = tcx.mir_promoted(def);
514    let mut body = body.steal();
515
516    if let Some(error_reported) = tainted_by_errors {
517        body.tainted_by_errors = Some(error_reported);
518    }
519
520    // Also taint the body if it's within a top-level item that is not well formed.
521    //
522    // We do this check here and not during `mir_promoted` because that may result
523    // in borrowck cycles if WF requires looking into an opaque hidden type.
524    let root = tcx.typeck_root_def_id(def.to_def_id());
525    match tcx.def_kind(root) {
526        DefKind::Fn
527        | DefKind::AssocFn
528        | DefKind::Static { .. }
529        | DefKind::Const
530        | DefKind::AssocConst => {
531            if let Err(guar) = tcx.ensure_ok().check_well_formed(root.expect_local()) {
532                body.tainted_by_errors = Some(guar);
533            }
534        }
535        _ => {}
536    }
537
538    run_analysis_to_runtime_passes(tcx, &mut body);
539
540    tcx.alloc_steal_mir(body)
541}
542
543// Made public so that `mir_drops_elaborated_and_const_checked` can be overridden
544// by custom rustc drivers, running all the steps by themselves. See #114628.
545pub fn run_analysis_to_runtime_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
546    assert!(body.phase == MirPhase::Analysis(AnalysisPhase::Initial));
547    let did = body.source.def_id();
548
549    debug!("analysis_mir_cleanup({:?})", did);
550    run_analysis_cleanup_passes(tcx, body);
551    assert!(body.phase == MirPhase::Analysis(AnalysisPhase::PostCleanup));
552
553    // Do a little drop elaboration before const-checking if `const_precise_live_drops` is enabled.
554    if check_consts::post_drop_elaboration::checking_enabled(&ConstCx::new(tcx, body)) {
555        pm::run_passes(
556            tcx,
557            body,
558            &[
559                &remove_uninit_drops::RemoveUninitDrops,
560                &simplify::SimplifyCfg::RemoveFalseEdges,
561                &Lint(post_drop_elaboration::CheckLiveDrops),
562            ],
563            None,
564            pm::Optimizations::Allowed,
565        );
566    }
567
568    debug!("runtime_mir_lowering({:?})", did);
569    run_runtime_lowering_passes(tcx, body);
570    assert!(body.phase == MirPhase::Runtime(RuntimePhase::Initial));
571
572    debug!("runtime_mir_cleanup({:?})", did);
573    run_runtime_cleanup_passes(tcx, body);
574    assert!(body.phase == MirPhase::Runtime(RuntimePhase::PostCleanup));
575}
576
577// FIXME(JakobDegen): Can we make these lists of passes consts?
578
579/// After this series of passes, no lifetime analysis based on borrowing can be done.
580fn run_analysis_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
581    let passes: &[&dyn MirPass<'tcx>] = &[
582        &impossible_predicates::ImpossiblePredicates,
583        &cleanup_post_borrowck::CleanupPostBorrowck,
584        &remove_noop_landing_pads::RemoveNoopLandingPads,
585        &simplify::SimplifyCfg::PostAnalysis,
586        &deref_separator::Derefer,
587    ];
588
589    pm::run_passes(
590        tcx,
591        body,
592        passes,
593        Some(MirPhase::Analysis(AnalysisPhase::PostCleanup)),
594        pm::Optimizations::Allowed,
595    );
596}
597
598/// Returns the sequence of passes that lowers analysis to runtime MIR.
599fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
600    let passes: &[&dyn MirPass<'tcx>] = &[
601        // These next passes must be executed together.
602        &add_call_guards::CriticalCallEdges,
603        // Must be done before drop elaboration because we need to drop opaque types, too.
604        &post_analysis_normalize::PostAnalysisNormalize,
605        // Calling this after `PostAnalysisNormalize` ensures that we don't deal with opaque types.
606        &add_subtyping_projections::Subtyper,
607        &elaborate_drops::ElaborateDrops,
608        // Needs to happen after drop elaboration.
609        &Lint(check_call_recursion::CheckDropRecursion),
610        // This will remove extraneous landing pads which are no longer
611        // necessary as well as forcing any call in a non-unwinding
612        // function calling a possibly-unwinding function to abort the process.
613        &abort_unwinding_calls::AbortUnwindingCalls,
614        // AddMovesForPackedDrops needs to run after drop
615        // elaboration.
616        &add_moves_for_packed_drops::AddMovesForPackedDrops,
617        // `AddRetag` needs to run after `ElaborateDrops` but before `ElaborateBoxDerefs`.
618        // Otherwise it should run fairly late, but before optimizations begin.
619        &add_retag::AddRetag,
620        &elaborate_box_derefs::ElaborateBoxDerefs,
621        &coroutine::StateTransform,
622        &Lint(known_panics_lint::KnownPanicsLint),
623    ];
624    pm::run_passes_no_validate(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::Initial)));
625}
626
627/// Returns the sequence of passes that do the initial cleanup of runtime MIR.
628fn run_runtime_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
629    let passes: &[&dyn MirPass<'tcx>] = &[
630        &lower_intrinsics::LowerIntrinsics,
631        &remove_place_mention::RemovePlaceMention,
632        &simplify::SimplifyCfg::PreOptimizations,
633    ];
634
635    pm::run_passes(
636        tcx,
637        body,
638        passes,
639        Some(MirPhase::Runtime(RuntimePhase::PostCleanup)),
640        pm::Optimizations::Allowed,
641    );
642
643    // Clear this by anticipation. Optimizations and runtime MIR have no reason to look
644    // into this information, which is meant for borrowck diagnostics.
645    for decl in &mut body.local_decls {
646        decl.local_info = ClearCrossCrate::Clear;
647    }
648}
649
650pub(crate) fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
651    fn o1<T>(x: T) -> WithMinOptLevel<T> {
652        WithMinOptLevel(1, x)
653    }
654
655    let def_id = body.source.def_id();
656    let optimizations = if tcx.def_kind(def_id).has_codegen_attrs()
657        && tcx.codegen_fn_attrs(def_id).optimize.do_not_optimize()
658    {
659        pm::Optimizations::Suppressed
660    } else {
661        pm::Optimizations::Allowed
662    };
663
664    // The main optimizations that we do on MIR.
665    pm::run_passes(
666        tcx,
667        body,
668        &[
669            // Add some UB checks before any UB gets optimized away.
670            &check_alignment::CheckAlignment,
671            &check_null::CheckNull,
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}