1#![cfg_attr(bootstrap, feature(let_chains))]
3#![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(map_try_insert)]
12#![feature(never_type)]
13#![feature(try_blocks)]
14#![feature(vec_deque_pop_if)]
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 mod check_unnecessary_transmutes: CheckUnnecessaryTransmutes;
129 pub mod cleanup_post_borrowck : CleanupPostBorrowck;
131
132 mod copy_prop : CopyProp;
133 mod coroutine : StateTransform;
134 mod coverage : InstrumentCoverage;
135 mod ctfe_limit : CtfeLimit;
136 mod dataflow_const_prop : DataflowConstProp;
137 mod dead_store_elimination : DeadStoreElimination {
138 Initial,
139 Final
140 };
141 mod deref_separator : Derefer;
142 mod dest_prop : DestinationPropagation;
143 pub mod dump_mir : Marker;
144 mod early_otherwise_branch : EarlyOtherwiseBranch;
145 mod elaborate_box_derefs : ElaborateBoxDerefs;
146 mod elaborate_drops : ElaborateDrops;
147 mod function_item_references : FunctionItemReferences;
148 mod gvn : GVN;
149 pub mod inline : Inline, ForceInline;
152 mod impossible_predicates : ImpossiblePredicates;
153 mod instsimplify : InstSimplify { BeforeInline, AfterSimplifyCfg };
154 mod jump_threading : JumpThreading;
155 mod known_panics_lint : KnownPanicsLint;
156 mod large_enums : EnumSizeOpt;
157 mod lower_intrinsics : LowerIntrinsics;
158 mod lower_slice_len : LowerSliceLenCalls;
159 mod match_branches : MatchBranchSimplification;
160 mod mentioned_items : MentionedItems;
161 mod multiple_return_terminators : MultipleReturnTerminators;
162 mod nrvo : RenameReturnPlace;
163 mod post_drop_elaboration : CheckLiveDrops;
164 mod prettify : ReorderBasicBlocks, ReorderLocals;
165 mod promote_consts : PromoteTemps;
166 mod ref_prop : ReferencePropagation;
167 mod remove_noop_landing_pads : RemoveNoopLandingPads;
168 mod remove_place_mention : RemovePlaceMention;
169 mod remove_storage_markers : RemoveStorageMarkers;
170 mod remove_uninit_drops : RemoveUninitDrops;
171 mod remove_unneeded_drops : RemoveUnneededDrops;
172 mod remove_zsts : RemoveZsts;
173 mod required_consts : RequiredConstsVisitor;
174 mod post_analysis_normalize : PostAnalysisNormalize;
175 mod sanity_check : SanityCheck;
176 pub mod simplify :
178 SimplifyCfg {
179 Initial,
180 PromoteConsts,
181 RemoveFalseEdges,
182 PostAnalysis,
183 PreOptimizations,
184 Final,
185 MakeShim,
186 AfterUnreachableEnumBranching
187 },
188 SimplifyLocals {
189 BeforeConstProp,
190 AfterGVN,
191 Final
192 };
193 mod simplify_branches : SimplifyConstCondition {
194 AfterConstProp,
195 Final
196 };
197 mod simplify_comparison_integral : SimplifyComparisonIntegral;
198 mod single_use_consts : SingleUseConsts;
199 mod sroa : ScalarReplacementOfAggregates;
200 mod strip_debuginfo : StripDebugInfo;
201 mod unreachable_enum_branching : UnreachableEnumBranching;
202 mod unreachable_prop : UnreachablePropagation;
203 mod validate : Validator;
204}
205
206rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
207
208pub fn provide(providers: &mut Providers) {
209 coverage::query::provide(providers);
210 ffi_unwind_calls::provide(providers);
211 shim::provide(providers);
212 cross_crate_inline::provide(providers);
213 providers.queries = query::Providers {
214 mir_keys,
215 mir_built,
216 mir_const_qualif,
217 mir_promoted,
218 mir_drops_elaborated_and_const_checked,
219 mir_for_ctfe,
220 mir_coroutine_witnesses: coroutine::mir_coroutine_witnesses,
221 optimized_mir,
222 is_mir_available,
223 is_ctfe_mir_available: is_mir_available,
224 mir_callgraph_reachable: inline::cycle::mir_callgraph_reachable,
225 mir_inliner_callees: inline::cycle::mir_inliner_callees,
226 promoted_mir,
227 deduced_param_attrs: deduce_param_attrs::deduced_param_attrs,
228 coroutine_by_move_body_def_id: coroutine::coroutine_by_move_body_def_id,
229 ..providers.queries
230 };
231}
232
233fn remap_mir_for_const_eval_select<'tcx>(
234 tcx: TyCtxt<'tcx>,
235 mut body: Body<'tcx>,
236 context: hir::Constness,
237) -> Body<'tcx> {
238 for bb in body.basic_blocks.as_mut().iter_mut() {
239 let terminator = bb.terminator.as_mut().expect("invalid terminator");
240 match terminator.kind {
241 TerminatorKind::Call {
242 func: Operand::Constant(box ConstOperand { ref const_, .. }),
243 ref mut args,
244 destination,
245 target,
246 unwind,
247 fn_span,
248 ..
249 } if let ty::FnDef(def_id, _) = *const_.ty().kind()
250 && tcx.is_intrinsic(def_id, sym::const_eval_select) =>
251 {
252 let Ok([tupled_args, called_in_const, called_at_rt]) = take_array(args) else {
253 unreachable!()
254 };
255 let ty = tupled_args.node.ty(&body.local_decls, tcx);
256 let fields = ty.tuple_fields();
257 let num_args = fields.len();
258 let func =
259 if context == hir::Constness::Const { called_in_const } else { called_at_rt };
260 let (method, place): (fn(Place<'tcx>) -> Operand<'tcx>, Place<'tcx>) =
261 match tupled_args.node {
262 Operand::Constant(_) => {
263 let local = body.local_decls.push(LocalDecl::new(ty, fn_span));
267 bb.statements.push(Statement {
268 source_info: SourceInfo::outermost(fn_span),
269 kind: StatementKind::Assign(Box::new((
270 local.into(),
271 Rvalue::Use(tupled_args.node.clone()),
272 ))),
273 });
274 (Operand::Move, local.into())
275 }
276 Operand::Move(place) => (Operand::Move, place),
277 Operand::Copy(place) => (Operand::Copy, place),
278 };
279 let place_elems = place.projection;
280 let arguments = (0..num_args)
281 .map(|x| {
282 let mut place_elems = place_elems.to_vec();
283 place_elems.push(ProjectionElem::Field(x.into(), fields[x]));
284 let projection = tcx.mk_place_elems(&place_elems);
285 let place = Place { local: place.local, projection };
286 Spanned { node: method(place), span: DUMMY_SP }
287 })
288 .collect();
289 terminator.kind = TerminatorKind::Call {
290 func: func.node,
291 args: arguments,
292 destination,
293 target,
294 unwind,
295 call_source: CallSource::Misc,
296 fn_span,
297 };
298 }
299 _ => {}
300 }
301 }
302 body
303}
304
305fn take_array<T, const N: usize>(b: &mut Box<[T]>) -> Result<[T; N], Box<[T]>> {
306 let b: Box<[T; N]> = std::mem::take(b).try_into()?;
307 Ok(*b)
308}
309
310fn is_mir_available(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
311 tcx.mir_keys(()).contains(&def_id)
312}
313
314fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet<LocalDefId> {
317 let mut set: FxIndexSet<_> = tcx.hir_body_owners().collect();
319
320 set.retain(|&def_id| !matches!(tcx.def_kind(def_id), DefKind::GlobalAsm));
323
324 for body_owner in tcx.hir_body_owners() {
327 if let DefKind::Closure = tcx.def_kind(body_owner)
328 && tcx.needs_coroutine_by_move_body_def_id(body_owner.to_def_id())
329 {
330 set.insert(tcx.coroutine_by_move_body_def_id(body_owner).expect_local());
331 }
332 }
333
334 for item in tcx.hir_crate_items(()).free_items() {
337 if let DefKind::Struct | DefKind::Enum = tcx.def_kind(item.owner_id) {
338 for variant in tcx.adt_def(item.owner_id).variants() {
339 if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
340 set.insert(ctor_def_id.expect_local());
341 }
342 }
343 }
344 }
345
346 set
347}
348
349fn mir_const_qualif(tcx: TyCtxt<'_>, def: LocalDefId) -> ConstQualifs {
350 let body = &tcx.mir_built(def).borrow();
355 let ccx = check_consts::ConstCx::new(tcx, body);
356 match ccx.const_kind {
358 Some(ConstContext::Const { .. } | ConstContext::Static(_) | ConstContext::ConstFn) => {}
359 None => span_bug!(
360 tcx.def_span(def),
361 "`mir_const_qualif` should only be called on const fns and const items"
362 ),
363 }
364
365 if body.return_ty().references_error() {
366 tcx.dcx().span_delayed_bug(body.span, "mir_const_qualif: MIR had errors");
368 return Default::default();
369 }
370
371 let mut validator = check_consts::check::Checker::new(&ccx);
372 validator.check_body();
373
374 validator.qualifs_in_return_place()
377}
378
379fn mir_built(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
380 let mut body = build_mir(tcx, def);
381
382 pass_manager::dump_mir_for_phase_change(tcx, &body);
383
384 pm::run_passes(
385 tcx,
386 &mut body,
387 &[
388 &Lint(check_inline::CheckForceInline),
390 &Lint(check_call_recursion::CheckCallRecursion),
391 &Lint(check_packed_ref::CheckPackedRef),
392 &Lint(check_const_item_mutation::CheckConstItemMutation),
393 &Lint(function_item_references::FunctionItemReferences),
394 &Lint(check_undefined_transmutes::CheckUndefinedTransmutes),
395 &Lint(check_unnecessary_transmutes::CheckUnnecessaryTransmutes),
396 &simplify::SimplifyCfg::Initial,
398 &Lint(sanity_check::SanityCheck),
399 ],
400 None,
401 pm::Optimizations::Allowed,
402 );
403 tcx.alloc_steal_mir(body)
404}
405
406fn mir_promoted(
408 tcx: TyCtxt<'_>,
409 def: LocalDefId,
410) -> (&Steal<Body<'_>>, &Steal<IndexVec<Promoted, Body<'_>>>) {
411 let const_qualifs = match tcx.def_kind(def) {
416 DefKind::Fn | DefKind::AssocFn | DefKind::Closure
417 if tcx.constness(def) == hir::Constness::Const
418 || tcx.is_const_default_method(def.to_def_id()) =>
419 {
420 tcx.mir_const_qualif(def)
421 }
422 DefKind::AssocConst
423 | DefKind::Const
424 | DefKind::Static { .. }
425 | DefKind::InlineConst
426 | DefKind::AnonConst => tcx.mir_const_qualif(def),
427 _ => ConstQualifs::default(),
428 };
429
430 tcx.ensure_done().has_ffi_unwind_calls(def);
432
433 if tcx.needs_coroutine_by_move_body_def_id(def.to_def_id()) {
435 tcx.ensure_done().coroutine_by_move_body_def_id(def);
436 }
437
438 let mut body = tcx.mir_built(def).steal();
439 if let Some(error_reported) = const_qualifs.tainted_by_errors {
440 body.tainted_by_errors = Some(error_reported);
441 }
442
443 RequiredConstsVisitor::compute_required_consts(&mut body);
446
447 let promote_pass = promote_consts::PromoteTemps::default();
449 pm::run_passes(
450 tcx,
451 &mut body,
452 &[&promote_pass, &simplify::SimplifyCfg::PromoteConsts, &coverage::InstrumentCoverage],
453 Some(MirPhase::Analysis(AnalysisPhase::Initial)),
454 pm::Optimizations::Allowed,
455 );
456
457 lint_tail_expr_drop_order::run_lint(tcx, def, &body);
458
459 let promoted = promote_pass.promoted_fragments.into_inner();
460 (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
461}
462
463fn mir_for_ctfe(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &Body<'_> {
465 tcx.arena.alloc(inner_mir_for_ctfe(tcx, def_id))
466}
467
468fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: LocalDefId) -> Body<'_> {
469 if tcx.is_constructor(def.to_def_id()) {
471 return shim::build_adt_ctor(tcx, def.to_def_id());
476 }
477
478 let body = tcx.mir_drops_elaborated_and_const_checked(def);
479 let body = match tcx.hir_body_const_context(def) {
480 Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => body.steal(),
483 Some(hir::ConstContext::ConstFn) => body.borrow().clone(),
484 None => bug!("`mir_for_ctfe` called on non-const {def:?}"),
485 };
486
487 let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::Const);
488 pm::run_passes(tcx, &mut body, &[&ctfe_limit::CtfeLimit], None, pm::Optimizations::Allowed);
489
490 body
491}
492
493fn mir_drops_elaborated_and_const_checked(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
497 if tcx.is_coroutine(def.to_def_id()) {
498 tcx.ensure_done().mir_coroutine_witnesses(def);
499 }
500
501 let tainted_by_errors = if !tcx.is_synthetic_mir(def) {
503 tcx.mir_borrowck(tcx.typeck_root_def_id(def.to_def_id()).expect_local()).err()
504 } else {
505 None
506 };
507
508 let is_fn_like = tcx.def_kind(def).is_fn_like();
509 if is_fn_like {
510 if pm::should_run_pass(tcx, &inline::Inline, pm::Optimizations::Allowed)
512 || inline::ForceInline::should_run_pass_for_callee(tcx, def.to_def_id())
513 {
514 tcx.ensure_done().mir_inliner_callees(ty::InstanceKind::Item(def.to_def_id()));
515 }
516 }
517
518 let (body, _) = tcx.mir_promoted(def);
519 let mut body = body.steal();
520
521 if let Some(error_reported) = tainted_by_errors {
522 body.tainted_by_errors = Some(error_reported);
523 }
524
525 let root = tcx.typeck_root_def_id(def.to_def_id());
530 match tcx.def_kind(root) {
531 DefKind::Fn
532 | DefKind::AssocFn
533 | DefKind::Static { .. }
534 | DefKind::Const
535 | DefKind::AssocConst => {
536 if let Err(guar) = tcx.ensure_ok().check_well_formed(root.expect_local()) {
537 body.tainted_by_errors = Some(guar);
538 }
539 }
540 _ => {}
541 }
542
543 run_analysis_to_runtime_passes(tcx, &mut body);
544
545 tcx.alloc_steal_mir(body)
546}
547
548pub fn run_analysis_to_runtime_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
551 assert!(body.phase == MirPhase::Analysis(AnalysisPhase::Initial));
552 let did = body.source.def_id();
553
554 debug!("analysis_mir_cleanup({:?})", did);
555 run_analysis_cleanup_passes(tcx, body);
556 assert!(body.phase == MirPhase::Analysis(AnalysisPhase::PostCleanup));
557
558 if check_consts::post_drop_elaboration::checking_enabled(&ConstCx::new(tcx, body)) {
560 pm::run_passes(
561 tcx,
562 body,
563 &[
564 &remove_uninit_drops::RemoveUninitDrops,
565 &simplify::SimplifyCfg::RemoveFalseEdges,
566 &Lint(post_drop_elaboration::CheckLiveDrops),
567 ],
568 None,
569 pm::Optimizations::Allowed,
570 );
571 }
572
573 debug!("runtime_mir_lowering({:?})", did);
574 run_runtime_lowering_passes(tcx, body);
575 assert!(body.phase == MirPhase::Runtime(RuntimePhase::Initial));
576
577 debug!("runtime_mir_cleanup({:?})", did);
578 run_runtime_cleanup_passes(tcx, body);
579 assert!(body.phase == MirPhase::Runtime(RuntimePhase::PostCleanup));
580}
581
582fn run_analysis_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
586 let passes: &[&dyn MirPass<'tcx>] = &[
587 &impossible_predicates::ImpossiblePredicates,
588 &cleanup_post_borrowck::CleanupPostBorrowck,
589 &remove_noop_landing_pads::RemoveNoopLandingPads,
590 &simplify::SimplifyCfg::PostAnalysis,
591 &deref_separator::Derefer,
592 ];
593
594 pm::run_passes(
595 tcx,
596 body,
597 passes,
598 Some(MirPhase::Analysis(AnalysisPhase::PostCleanup)),
599 pm::Optimizations::Allowed,
600 );
601}
602
603fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
605 let passes: &[&dyn MirPass<'tcx>] = &[
606 &add_call_guards::CriticalCallEdges,
608 &post_analysis_normalize::PostAnalysisNormalize,
610 &add_subtyping_projections::Subtyper,
612 &elaborate_drops::ElaborateDrops,
613 &Lint(check_call_recursion::CheckDropRecursion),
615 &abort_unwinding_calls::AbortUnwindingCalls,
619 &add_moves_for_packed_drops::AddMovesForPackedDrops,
622 &add_retag::AddRetag,
625 &elaborate_box_derefs::ElaborateBoxDerefs,
626 &coroutine::StateTransform,
627 &Lint(known_panics_lint::KnownPanicsLint),
628 ];
629 pm::run_passes_no_validate(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::Initial)));
630}
631
632fn run_runtime_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
634 let passes: &[&dyn MirPass<'tcx>] = &[
635 &lower_intrinsics::LowerIntrinsics,
636 &remove_place_mention::RemovePlaceMention,
637 &simplify::SimplifyCfg::PreOptimizations,
638 ];
639
640 pm::run_passes(
641 tcx,
642 body,
643 passes,
644 Some(MirPhase::Runtime(RuntimePhase::PostCleanup)),
645 pm::Optimizations::Allowed,
646 );
647
648 for decl in &mut body.local_decls {
651 decl.local_info = ClearCrossCrate::Clear;
652 }
653}
654
655pub(crate) fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
656 fn o1<T>(x: T) -> WithMinOptLevel<T> {
657 WithMinOptLevel(1, x)
658 }
659
660 let def_id = body.source.def_id();
661 let optimizations = if tcx.def_kind(def_id).has_codegen_attrs()
662 && tcx.codegen_fn_attrs(def_id).optimize.do_not_optimize()
663 {
664 pm::Optimizations::Suppressed
665 } else {
666 pm::Optimizations::Allowed
667 };
668
669 pm::run_passes(
671 tcx,
672 body,
673 &[
674 &check_alignment::CheckAlignment,
676 &check_null::CheckNull,
677 &lower_slice_len::LowerSliceLenCalls,
682 &instsimplify::InstSimplify::BeforeInline,
685 &inline::ForceInline,
687 &inline::Inline,
689 &remove_storage_markers::RemoveStorageMarkers,
692 &remove_zsts::RemoveZsts,
694 &remove_unneeded_drops::RemoveUnneededDrops,
695 &unreachable_enum_branching::UnreachableEnumBranching,
698 &unreachable_prop::UnreachablePropagation,
699 &o1(simplify::SimplifyCfg::AfterUnreachableEnumBranching),
700 &ref_prop::ReferencePropagation,
703 &sroa::ScalarReplacementOfAggregates,
704 &multiple_return_terminators::MultipleReturnTerminators,
705 &instsimplify::InstSimplify::AfterSimplifyCfg,
708 &simplify::SimplifyLocals::BeforeConstProp,
709 &dead_store_elimination::DeadStoreElimination::Initial,
710 &gvn::GVN,
711 &simplify::SimplifyLocals::AfterGVN,
712 &match_branches::MatchBranchSimplification,
713 &dataflow_const_prop::DataflowConstProp,
714 &single_use_consts::SingleUseConsts,
715 &o1(simplify_branches::SimplifyConstCondition::AfterConstProp),
716 &jump_threading::JumpThreading,
717 &early_otherwise_branch::EarlyOtherwiseBranch,
718 &simplify_comparison_integral::SimplifyComparisonIntegral,
719 &dest_prop::DestinationPropagation,
720 &o1(simplify_branches::SimplifyConstCondition::Final),
721 &o1(remove_noop_landing_pads::RemoveNoopLandingPads),
722 &o1(simplify::SimplifyCfg::Final),
723 &strip_debuginfo::StripDebugInfo,
725 ©_prop::CopyProp,
726 &dead_store_elimination::DeadStoreElimination::Final,
727 &nrvo::RenameReturnPlace,
728 &simplify::SimplifyLocals::Final,
729 &multiple_return_terminators::MultipleReturnTerminators,
730 &large_enums::EnumSizeOpt { discrepancy: 128 },
731 &add_call_guards::CriticalCallEdges,
733 &prettify::ReorderBasicBlocks,
735 &prettify::ReorderLocals,
736 &dump_mir::Marker("PreCodegen"),
738 ],
739 Some(MirPhase::Runtime(RuntimePhase::Optimized)),
740 optimizations,
741 );
742}
743
744fn optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> &Body<'_> {
746 tcx.arena.alloc(inner_optimized_mir(tcx, did))
747}
748
749fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
750 if tcx.is_constructor(did.to_def_id()) {
751 return shim::build_adt_ctor(tcx, did.to_def_id());
756 }
757
758 match tcx.hir_body_const_context(did) {
759 Some(hir::ConstContext::ConstFn) => tcx.ensure_done().mir_for_ctfe(did),
763 None => {}
764 Some(other) => panic!("do not use `optimized_mir` for constants: {other:?}"),
765 }
766 debug!("about to call mir_drops_elaborated...");
767 let body = tcx.mir_drops_elaborated_and_const_checked(did).steal();
768 let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::NotConst);
769
770 if body.tainted_by_errors.is_some() {
771 return body;
772 }
773
774 mentioned_items::MentionedItems.run_pass(tcx, &mut body);
778
779 if let TerminatorKind::Unreachable = body.basic_blocks[START_BLOCK].terminator().kind
783 && body.basic_blocks[START_BLOCK].statements.is_empty()
784 {
785 return body;
786 }
787
788 run_optimization_passes(tcx, &mut body);
789
790 body
791}
792
793fn promoted_mir(tcx: TyCtxt<'_>, def: LocalDefId) -> &IndexVec<Promoted, Body<'_>> {
796 if tcx.is_constructor(def.to_def_id()) {
797 return tcx.arena.alloc(IndexVec::new());
798 }
799
800 if !tcx.is_synthetic_mir(def) {
801 tcx.ensure_done().mir_borrowck(tcx.typeck_root_def_id(def.to_def_id()).expect_local());
802 }
803 let mut promoted = tcx.mir_promoted(def).1.steal();
804
805 for body in &mut promoted {
806 run_analysis_to_runtime_passes(tcx, body);
807 }
808
809 tcx.arena.alloc(promoted)
810}