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