1#![cfg_attr(doc, recursion_limit = "256")] #![feature(array_windows)]
4#![feature(assert_matches)]
5#![feature(box_patterns)]
6#![feature(const_type_name)]
7#![feature(cow_is_borrowed)]
8#![feature(file_buffered)]
9#![feature(if_let_guard)]
10#![feature(impl_trait_in_assoc_type)]
11#![feature(let_chains)]
12#![feature(map_try_insert)]
13#![feature(never_type)]
14#![feature(try_blocks)]
15#![feature(yeet_expr)]
16use hir::ConstContext;
19use required_consts::RequiredConstsVisitor;
20use rustc_const_eval::check_consts::{self, ConstCx};
21use rustc_const_eval::util;
22use rustc_data_structures::fx::FxIndexSet;
23use rustc_data_structures::steal::Steal;
24use rustc_hir as hir;
25use rustc_hir::def::{CtorKind, DefKind};
26use rustc_hir::def_id::LocalDefId;
27use rustc_index::IndexVec;
28use rustc_middle::mir::{
29 AnalysisPhase, Body, CallSource, ClearCrossCrate, ConstOperand, ConstQualifs, LocalDecl,
30 MirPhase, Operand, Place, ProjectionElem, Promoted, RuntimePhase, Rvalue, START_BLOCK,
31 SourceInfo, Statement, StatementKind, TerminatorKind,
32};
33use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
34use rustc_middle::util::Providers;
35use rustc_middle::{bug, query, span_bug};
36use rustc_mir_build::builder::build_mir;
37use rustc_span::source_map::Spanned;
38use rustc_span::{DUMMY_SP, sym};
39use tracing::debug;
40
41#[macro_use]
42mod pass_manager;
43
44use std::sync::LazyLock;
45
46use pass_manager::{self as pm, Lint, MirLint, MirPass, WithMinOptLevel};
47
48mod check_pointers;
49mod cost_checker;
50mod cross_crate_inline;
51mod deduce_param_attrs;
52mod elaborate_drop;
53mod errors;
54mod ffi_unwind_calls;
55mod lint;
56mod lint_tail_expr_drop_order;
57mod patch;
58mod shim;
59mod ssa;
60
61macro_rules! declare_passes {
84 (
85 $(
86 $vis:vis mod $mod_name:ident : $($pass_name:ident $( { $($ident:ident),* } )?),+ $(,)?;
87 )*
88 ) => {
89 $(
90 $vis mod $mod_name;
91 $(
92 #[allow(unused_imports)]
94 use $mod_name::$pass_name as _;
95 )+
96 )*
97
98 static PASS_NAMES: LazyLock<FxIndexSet<&str>> = LazyLock::new(|| [
99 "PreCodegen",
101 $(
102 $(
103 stringify!($pass_name),
104 $(
105 $(
106 $mod_name::$pass_name::$ident.name(),
107 )*
108 )?
109 )+
110 )*
111 ].into_iter().collect());
112 };
113}
114
115declare_passes! {
116 mod abort_unwinding_calls : AbortUnwindingCalls;
117 mod add_call_guards : AddCallGuards { AllCallEdges, CriticalCallEdges };
118 mod add_moves_for_packed_drops : AddMovesForPackedDrops;
119 mod add_retag : AddRetag;
120 mod add_subtyping_projections : Subtyper;
121 mod check_inline : CheckForceInline;
122 mod check_call_recursion : CheckCallRecursion, CheckDropRecursion;
123 mod check_alignment : CheckAlignment;
124 mod check_const_item_mutation : CheckConstItemMutation;
125 mod check_null : CheckNull;
126 mod check_packed_ref : CheckPackedRef;
127 mod check_undefined_transmutes : CheckUndefinedTransmutes;
128 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 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 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 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
313fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet<LocalDefId> {
316 let mut set: FxIndexSet<_> = tcx.hir_body_owners().collect();
318
319 set.retain(|&def_id| !matches!(tcx.def_kind(def_id), DefKind::GlobalAsm));
322
323 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 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 let body = &tcx.mir_built(def).borrow();
354 let ccx = check_consts::ConstCx::new(tcx, body);
355 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 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 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 &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 &simplify::SimplifyCfg::Initial,
396 &Lint(sanity_check::SanityCheck),
397 ],
398 None,
399 pm::Optimizations::Allowed,
400 );
401 tcx.alloc_steal_mir(body)
402}
403
404fn mir_promoted(
406 tcx: TyCtxt<'_>,
407 def: LocalDefId,
408) -> (&Steal<Body<'_>>, &Steal<IndexVec<Promoted, Body<'_>>>) {
409 let const_qualifs = match tcx.def_kind(def) {
414 DefKind::Fn | DefKind::AssocFn | DefKind::Closure
415 if tcx.constness(def) == hir::Constness::Const
416 || tcx.is_const_default_method(def.to_def_id()) =>
417 {
418 tcx.mir_const_qualif(def)
419 }
420 DefKind::AssocConst
421 | DefKind::Const
422 | DefKind::Static { .. }
423 | DefKind::InlineConst
424 | DefKind::AnonConst => tcx.mir_const_qualif(def),
425 _ => ConstQualifs::default(),
426 };
427
428 tcx.ensure_done().has_ffi_unwind_calls(def);
430
431 if tcx.needs_coroutine_by_move_body_def_id(def.to_def_id()) {
433 tcx.ensure_done().coroutine_by_move_body_def_id(def);
434 }
435
436 let mut body = tcx.mir_built(def).steal();
437 if let Some(error_reported) = const_qualifs.tainted_by_errors {
438 body.tainted_by_errors = Some(error_reported);
439 }
440
441 RequiredConstsVisitor::compute_required_consts(&mut body);
444
445 let promote_pass = promote_consts::PromoteTemps::default();
447 pm::run_passes(
448 tcx,
449 &mut body,
450 &[&promote_pass, &simplify::SimplifyCfg::PromoteConsts, &coverage::InstrumentCoverage],
451 Some(MirPhase::Analysis(AnalysisPhase::Initial)),
452 pm::Optimizations::Allowed,
453 );
454
455 lint_tail_expr_drop_order::run_lint(tcx, def, &body);
456
457 let promoted = promote_pass.promoted_fragments.into_inner();
458 (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
459}
460
461fn mir_for_ctfe(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &Body<'_> {
463 tcx.arena.alloc(inner_mir_for_ctfe(tcx, def_id))
464}
465
466fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: LocalDefId) -> Body<'_> {
467 if tcx.is_constructor(def.to_def_id()) {
469 return shim::build_adt_ctor(tcx, def.to_def_id());
474 }
475
476 let body = tcx.mir_drops_elaborated_and_const_checked(def);
477 let body = match tcx.hir_body_const_context(def) {
478 Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => body.steal(),
481 Some(hir::ConstContext::ConstFn) => body.borrow().clone(),
482 None => bug!("`mir_for_ctfe` called on non-const {def:?}"),
483 };
484
485 let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::Const);
486 pm::run_passes(tcx, &mut body, &[&ctfe_limit::CtfeLimit], None, pm::Optimizations::Allowed);
487
488 body
489}
490
491fn mir_drops_elaborated_and_const_checked(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
495 if tcx.is_coroutine(def.to_def_id()) {
496 tcx.ensure_done().mir_coroutine_witnesses(def);
497 }
498
499 let tainted_by_errors =
501 if !tcx.is_synthetic_mir(def) { tcx.mir_borrowck(def).tainted_by_errors } else { None };
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.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
650fn 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 &match_branches::MatchBranchSimplification,
700 &multiple_return_terminators::MultipleReturnTerminators,
702 &instsimplify::InstSimplify::AfterSimplifyCfg,
705 &simplify::SimplifyLocals::BeforeConstProp,
706 &dead_store_elimination::DeadStoreElimination::Initial,
707 &gvn::GVN,
708 &simplify::SimplifyLocals::AfterGVN,
709 &dataflow_const_prop::DataflowConstProp,
710 &single_use_consts::SingleUseConsts,
711 &o1(simplify_branches::SimplifyConstCondition::AfterConstProp),
712 &jump_threading::JumpThreading,
713 &early_otherwise_branch::EarlyOtherwiseBranch,
714 &simplify_comparison_integral::SimplifyComparisonIntegral,
715 &dest_prop::DestinationPropagation,
716 &o1(simplify_branches::SimplifyConstCondition::Final),
717 &o1(remove_noop_landing_pads::RemoveNoopLandingPads),
718 &o1(simplify::SimplifyCfg::Final),
719 &strip_debuginfo::StripDebugInfo,
721 ©_prop::CopyProp,
722 &dead_store_elimination::DeadStoreElimination::Final,
723 &nrvo::RenameReturnPlace,
724 &simplify::SimplifyLocals::Final,
725 &multiple_return_terminators::MultipleReturnTerminators,
726 &large_enums::EnumSizeOpt { discrepancy: 128 },
727 &add_call_guards::CriticalCallEdges,
729 &prettify::ReorderBasicBlocks,
731 &prettify::ReorderLocals,
732 &dump_mir::Marker("PreCodegen"),
734 ],
735 Some(MirPhase::Runtime(RuntimePhase::Optimized)),
736 optimizations,
737 );
738}
739
740fn optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> &Body<'_> {
742 tcx.arena.alloc(inner_optimized_mir(tcx, did))
743}
744
745fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
746 if tcx.is_constructor(did.to_def_id()) {
747 return shim::build_adt_ctor(tcx, did.to_def_id());
752 }
753
754 match tcx.hir_body_const_context(did) {
755 Some(hir::ConstContext::ConstFn) => tcx.ensure_done().mir_for_ctfe(did),
759 None => {}
760 Some(other) => panic!("do not use `optimized_mir` for constants: {other:?}"),
761 }
762 debug!("about to call mir_drops_elaborated...");
763 let body = tcx.mir_drops_elaborated_and_const_checked(did).steal();
764 let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::NotConst);
765
766 if body.tainted_by_errors.is_some() {
767 return body;
768 }
769
770 mentioned_items::MentionedItems.run_pass(tcx, &mut body);
774
775 if let TerminatorKind::Unreachable = body.basic_blocks[START_BLOCK].terminator().kind
779 && body.basic_blocks[START_BLOCK].statements.is_empty()
780 {
781 return body;
782 }
783
784 run_optimization_passes(tcx, &mut body);
785
786 body
787}
788
789fn promoted_mir(tcx: TyCtxt<'_>, def: LocalDefId) -> &IndexVec<Promoted, Body<'_>> {
792 if tcx.is_constructor(def.to_def_id()) {
793 return tcx.arena.alloc(IndexVec::new());
794 }
795
796 if !tcx.is_synthetic_mir(def) {
797 tcx.ensure_done().mir_borrowck(def);
798 }
799 let mut promoted = tcx.mir_promoted(def).1.steal();
800
801 for body in &mut promoted {
802 run_analysis_to_runtime_passes(tcx, body);
803 }
804
805 tcx.arena.alloc(promoted)
806}