1#![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)]
15use 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
60macro_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 #[allow(unused_imports)]
93 use $mod_name::$pass_name as _;
94 )+
95 )*
96
97 static PASS_NAMES: LazyLock<FxIndexSet<&str>> = LazyLock::new(|| [
98 "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 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 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 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 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
311fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet<LocalDefId> {
314 let mut set: FxIndexSet<_> = tcx.hir_body_owners().collect();
316
317 set.retain(|&def_id| !matches!(tcx.def_kind(def_id), DefKind::GlobalAsm));
320
321 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 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 let body = &tcx.mir_built(def).borrow();
352 let ccx = check_consts::ConstCx::new(tcx, body);
353 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 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 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 &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 &simplify::SimplifyCfg::Initial,
393 &Lint(sanity_check::SanityCheck),
394 ],
395 None,
396 pm::Optimizations::Allowed,
397 );
398 tcx.alloc_steal_mir(body)
399}
400
401fn mir_promoted(
403 tcx: TyCtxt<'_>,
404 def: LocalDefId,
405) -> (&Steal<Body<'_>>, &Steal<IndexVec<Promoted, Body<'_>>>) {
406 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 tcx.ensure_done().has_ffi_unwind_calls(def);
427
428 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 RequiredConstsVisitor::compute_required_consts(&mut body);
441
442 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
458fn 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 if tcx.is_constructor(def.to_def_id()) {
466 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 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
488fn 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 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 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 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
543pub 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 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
577fn 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
598fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
600 let passes: &[&dyn MirPass<'tcx>] = &[
601 &add_call_guards::CriticalCallEdges,
603 &post_analysis_normalize::PostAnalysisNormalize,
605 &add_subtyping_projections::Subtyper,
607 &elaborate_drops::ElaborateDrops,
608 &Lint(check_call_recursion::CheckDropRecursion),
610 &abort_unwinding_calls::AbortUnwindingCalls,
614 &add_moves_for_packed_drops::AddMovesForPackedDrops,
617 &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
627fn 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 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 pm::run_passes(
666 tcx,
667 body,
668 &[
669 &check_alignment::CheckAlignment,
671 &check_null::CheckNull,
672 &lower_slice_len::LowerSliceLenCalls,
677 &instsimplify::InstSimplify::BeforeInline,
680 &inline::ForceInline,
682 &inline::Inline,
684 &remove_storage_markers::RemoveStorageMarkers,
687 &remove_zsts::RemoveZsts,
689 &remove_unneeded_drops::RemoveUnneededDrops,
690 &unreachable_enum_branching::UnreachableEnumBranching,
693 &unreachable_prop::UnreachablePropagation,
694 &o1(simplify::SimplifyCfg::AfterUnreachableEnumBranching),
695 &ref_prop::ReferencePropagation,
698 &sroa::ScalarReplacementOfAggregates,
699 &multiple_return_terminators::MultipleReturnTerminators,
700 &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 &strip_debuginfo::StripDebugInfo,
720 ©_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 &add_call_guards::CriticalCallEdges,
728 &prettify::ReorderBasicBlocks,
730 &prettify::ReorderLocals,
731 &dump_mir::Marker("PreCodegen"),
733 ],
734 Some(MirPhase::Runtime(RuntimePhase::Optimized)),
735 optimizations,
736 );
737}
738
739fn 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 return shim::build_adt_ctor(tcx, did.to_def_id());
751 }
752
753 match tcx.hir_body_const_context(did) {
754 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 mentioned_items::MentionedItems.run_pass(tcx, &mut body);
773
774 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
788fn 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}