]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/lib.rs
Remove debugging-related code
[rust.git] / compiler / rustc_mir_transform / src / lib.rs
1 #![allow(rustc::potential_query_instability)]
2 #![feature(box_patterns)]
3 #![feature(drain_filter)]
4 #![feature(let_chains)]
5 #![feature(map_try_insert)]
6 #![feature(min_specialization)]
7 #![feature(never_type)]
8 #![feature(once_cell)]
9 #![feature(option_get_or_insert_default)]
10 #![feature(trusted_step)]
11 #![feature(try_blocks)]
12 #![feature(yeet_expr)]
13 #![feature(if_let_guard)]
14 #![recursion_limit = "256"]
15
16 #[macro_use]
17 extern crate tracing;
18 #[macro_use]
19 extern crate rustc_middle;
20
21 use required_consts::RequiredConstsVisitor;
22 use rustc_const_eval::util;
23 use rustc_data_structures::fx::FxIndexSet;
24 use rustc_data_structures::steal::Steal;
25 use rustc_hir as hir;
26 use rustc_hir::def_id::{DefId, LocalDefId};
27 use rustc_hir::intravisit::{self, Visitor};
28 use rustc_index::vec::IndexVec;
29 use rustc_middle::mir::visit::Visitor as _;
30 use rustc_middle::mir::{
31     traversal, AnalysisPhase, Body, ConstQualifs, Constant, LocalDecl, MirPass, MirPhase, Operand,
32     Place, ProjectionElem, Promoted, RuntimePhase, Rvalue, SourceInfo, Statement, StatementKind,
33     TerminatorKind,
34 };
35 use rustc_middle::ty::query::Providers;
36 use rustc_middle::ty::{self, TyCtxt, TypeVisitable};
37 use rustc_span::sym;
38
39 #[macro_use]
40 mod pass_manager;
41
42 use pass_manager::{self as pm, Lint, MirLint, WithMinOptLevel};
43
44 mod abort_unwinding_calls;
45 mod add_call_guards;
46 mod add_moves_for_packed_drops;
47 mod add_retag;
48 mod check_const_item_mutation;
49 mod check_packed_ref;
50 pub mod check_unsafety;
51 // This pass is public to allow external drivers to perform MIR cleanup
52 pub mod cleanup_post_borrowck;
53 mod const_debuginfo;
54 mod const_goto;
55 mod const_prop;
56 mod const_prop_lint;
57 mod coverage;
58 mod ctfe_limit;
59 mod dataflow_const_prop;
60 mod dead_store_elimination;
61 mod deaggregator;
62 mod deduce_param_attrs;
63 mod deduplicate_blocks;
64 mod deref_separator;
65 mod dest_prop;
66 pub mod dump_mir;
67 mod early_otherwise_branch;
68 mod elaborate_box_derefs;
69 mod elaborate_drops;
70 mod ffi_unwind_calls;
71 mod function_item_references;
72 mod generator;
73 mod inline;
74 mod instcombine;
75 mod lower_intrinsics;
76 mod lower_slice_len;
77 mod match_branches;
78 mod multiple_return_terminators;
79 mod normalize_array_len;
80 mod nrvo;
81 mod remove_noop_landing_pads;
82 mod remove_storage_markers;
83 mod remove_uninit_drops;
84 mod remove_unneeded_drops;
85 mod remove_zsts;
86 mod required_consts;
87 mod reveal_all;
88 mod separate_const_switch;
89 mod shim;
90 // This pass is public to allow external drivers to perform MIR cleanup
91 pub mod simplify;
92 mod simplify_branches;
93 mod simplify_comparison_integral;
94 mod simplify_try;
95 mod sroa;
96 mod uninhabited_enum_branching;
97 mod unreachable_prop;
98
99 use rustc_const_eval::transform::check_consts::{self, ConstCx};
100 use rustc_const_eval::transform::promote_consts;
101 use rustc_const_eval::transform::validate;
102 use rustc_mir_dataflow::rustc_peek;
103
104 pub fn provide(providers: &mut Providers) {
105     check_unsafety::provide(providers);
106     check_packed_ref::provide(providers);
107     coverage::query::provide(providers);
108     ffi_unwind_calls::provide(providers);
109     shim::provide(providers);
110     *providers = Providers {
111         mir_keys,
112         mir_const,
113         mir_const_qualif: |tcx, def_id| {
114             let def_id = def_id.expect_local();
115             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
116                 tcx.mir_const_qualif_const_arg(def)
117             } else {
118                 mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
119             }
120         },
121         mir_const_qualif_const_arg: |tcx, (did, param_did)| {
122             mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
123         },
124         mir_promoted,
125         mir_drops_elaborated_and_const_checked,
126         mir_for_ctfe,
127         mir_for_ctfe_of_const_arg,
128         optimized_mir,
129         is_mir_available,
130         is_ctfe_mir_available: |tcx, did| is_mir_available(tcx, did),
131         mir_callgraph_reachable: inline::cycle::mir_callgraph_reachable,
132         mir_inliner_callees: inline::cycle::mir_inliner_callees,
133         promoted_mir: |tcx, def_id| {
134             let def_id = def_id.expect_local();
135             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
136                 tcx.promoted_mir_of_const_arg(def)
137             } else {
138                 promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
139             }
140         },
141         promoted_mir_of_const_arg: |tcx, (did, param_did)| {
142             promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
143         },
144         deduced_param_attrs: deduce_param_attrs::deduced_param_attrs,
145         ..*providers
146     };
147 }
148
149 fn remap_mir_for_const_eval_select<'tcx>(
150     tcx: TyCtxt<'tcx>,
151     mut body: Body<'tcx>,
152     context: hir::Constness,
153 ) -> Body<'tcx> {
154     for bb in body.basic_blocks.as_mut().iter_mut() {
155         let terminator = bb.terminator.as_mut().expect("invalid terminator");
156         match terminator.kind {
157             TerminatorKind::Call {
158                 func: Operand::Constant(box Constant { ref literal, .. }),
159                 ref mut args,
160                 destination,
161                 target,
162                 cleanup,
163                 fn_span,
164                 ..
165             } if let ty::FnDef(def_id, _) = *literal.ty().kind()
166                 && tcx.item_name(def_id) == sym::const_eval_select
167                 && tcx.is_intrinsic(def_id) =>
168             {
169                 let [tupled_args, called_in_const, called_at_rt]: [_; 3] = std::mem::take(args).try_into().unwrap();
170                 let ty = tupled_args.ty(&body.local_decls, tcx);
171                 let fields = ty.tuple_fields();
172                 let num_args = fields.len();
173                 let func = if context == hir::Constness::Const { called_in_const } else { called_at_rt };
174                 let (method, place): (fn(Place<'tcx>) -> Operand<'tcx>, Place<'tcx>) = match tupled_args {
175                     Operand::Constant(_) => {
176                         // there is no good way of extracting a tuple arg from a constant (const generic stuff)
177                         // so we just create a temporary and deconstruct that.
178                         let local = body.local_decls.push(LocalDecl::new(ty, fn_span));
179                         bb.statements.push(Statement {
180                             source_info: SourceInfo::outermost(fn_span),
181                             kind: StatementKind::Assign(Box::new((local.into(), Rvalue::Use(tupled_args.clone())))),
182                         });
183                         (Operand::Move, local.into())
184                     }
185                     Operand::Move(place) => (Operand::Move, place),
186                     Operand::Copy(place) => (Operand::Copy, place),
187                 };
188                 let place_elems = place.projection;
189                 let arguments = (0..num_args).map(|x| {
190                     let mut place_elems = place_elems.to_vec();
191                     place_elems.push(ProjectionElem::Field(x.into(), fields[x]));
192                     let projection = tcx.intern_place_elems(&place_elems);
193                     let place = Place {
194                         local: place.local,
195                         projection,
196                     };
197                     method(place)
198                 }).collect();
199                 terminator.kind = TerminatorKind::Call { func, args: arguments, destination, target, cleanup, from_hir_call: false, fn_span };
200             }
201             _ => {}
202         }
203     }
204     body
205 }
206
207 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
208     let def_id = def_id.expect_local();
209     tcx.mir_keys(()).contains(&def_id)
210 }
211
212 /// Finds the full set of `DefId`s within the current crate that have
213 /// MIR associated with them.
214 fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet<LocalDefId> {
215     let mut set = FxIndexSet::default();
216
217     // All body-owners have MIR associated with them.
218     set.extend(tcx.hir().body_owners());
219
220     // Additionally, tuple struct/variant constructors have MIR, but
221     // they don't have a BodyId, so we need to build them separately.
222     struct GatherCtors<'a> {
223         set: &'a mut FxIndexSet<LocalDefId>,
224     }
225     impl<'tcx> Visitor<'tcx> for GatherCtors<'_> {
226         fn visit_variant_data(&mut self, v: &'tcx hir::VariantData<'tcx>) {
227             if let hir::VariantData::Tuple(_, _, def_id) = *v {
228                 self.set.insert(def_id);
229             }
230             intravisit::walk_struct_def(self, v)
231         }
232     }
233     tcx.hir().visit_all_item_likes_in_crate(&mut GatherCtors { set: &mut set });
234
235     set
236 }
237
238 fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
239     let const_kind = tcx.hir().body_const_context(def.did);
240
241     // No need to const-check a non-const `fn`.
242     if const_kind.is_none() {
243         return Default::default();
244     }
245
246     // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
247     // cannot yet be stolen), because `mir_promoted()`, which steals
248     // from `mir_const(), forces this query to execute before
249     // performing the steal.
250     let body = &tcx.mir_const(def).borrow();
251
252     if body.return_ty().references_error() {
253         tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
254         return Default::default();
255     }
256
257     let ccx = check_consts::ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def.did) };
258
259     let mut validator = check_consts::check::Checker::new(&ccx);
260     validator.check_body();
261
262     // We return the qualifs in the return place for every MIR body, even though it is only used
263     // when deciding to promote a reference to a `const` for now.
264     validator.qualifs_in_return_place()
265 }
266
267 /// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
268 /// FIXME(oli-obk): it's unclear whether we still need this phase (and its corresponding query).
269 /// We used to have this for pre-miri MIR based const eval.
270 fn mir_const(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> &Steal<Body<'_>> {
271     if let Some(def) = def.try_upgrade(tcx) {
272         return tcx.mir_const(def);
273     }
274
275     // Unsafety check uses the raw mir, so make sure it is run.
276     if !tcx.sess.opts.unstable_opts.thir_unsafeck {
277         if let Some(param_did) = def.const_param_did {
278             tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did));
279         } else {
280             tcx.ensure().unsafety_check_result(def.did);
281         }
282     }
283
284     // has_ffi_unwind_calls query uses the raw mir, so make sure it is run.
285     tcx.ensure().has_ffi_unwind_calls(def.did);
286
287     let mut body = tcx.mir_built(def).steal();
288
289     pass_manager::dump_mir_for_phase_change(tcx, &body);
290
291     pm::run_passes(
292         tcx,
293         &mut body,
294         &[
295             // MIR-level lints.
296             &Lint(check_packed_ref::CheckPackedRef),
297             &Lint(check_const_item_mutation::CheckConstItemMutation),
298             &Lint(function_item_references::FunctionItemReferences),
299             // What we need to do constant evaluation.
300             &simplify::SimplifyCfg::new("initial"),
301             &rustc_peek::SanityCheck, // Just a lint
302         ],
303         None,
304     );
305     tcx.alloc_steal_mir(body)
306 }
307
308 /// Compute the main MIR body and the list of MIR bodies of the promoteds.
309 fn mir_promoted(
310     tcx: TyCtxt<'_>,
311     def: ty::WithOptConstParam<LocalDefId>,
312 ) -> (&Steal<Body<'_>>, &Steal<IndexVec<Promoted, Body<'_>>>) {
313     if let Some(def) = def.try_upgrade(tcx) {
314         return tcx.mir_promoted(def);
315     }
316
317     // Ensure that we compute the `mir_const_qualif` for constants at
318     // this point, before we steal the mir-const result.
319     // Also this means promotion can rely on all const checks having been done.
320     let const_qualifs = tcx.mir_const_qualif_opt_const_arg(def);
321     let mut body = tcx.mir_const(def).steal();
322     if let Some(error_reported) = const_qualifs.tainted_by_errors {
323         body.tainted_by_errors = Some(error_reported);
324     }
325
326     let mut required_consts = Vec::new();
327     let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
328     for (bb, bb_data) in traversal::reverse_postorder(&body) {
329         required_consts_visitor.visit_basic_block_data(bb, bb_data);
330     }
331     body.required_consts = required_consts;
332
333     // What we need to run borrowck etc.
334     let promote_pass = promote_consts::PromoteTemps::default();
335     pm::run_passes(
336         tcx,
337         &mut body,
338         &[
339             &promote_pass,
340             &simplify::SimplifyCfg::new("promote-consts"),
341             &coverage::InstrumentCoverage,
342         ],
343         Some(MirPhase::Analysis(AnalysisPhase::Initial)),
344     );
345
346     let promoted = promote_pass.promoted_fragments.into_inner();
347     (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
348 }
349
350 /// Compute the MIR that is used during CTFE (and thus has no optimizations run on it)
351 fn mir_for_ctfe(tcx: TyCtxt<'_>, def_id: DefId) -> &Body<'_> {
352     let did = def_id.expect_local();
353     if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
354         tcx.mir_for_ctfe_of_const_arg(def)
355     } else {
356         tcx.arena.alloc(inner_mir_for_ctfe(tcx, ty::WithOptConstParam::unknown(did)))
357     }
358 }
359
360 /// Same as `mir_for_ctfe`, but used to get the MIR of a const generic parameter.
361 /// The docs on `WithOptConstParam` explain this a bit more, but the TLDR is that
362 /// we'd get cycle errors with `mir_for_ctfe`, because typeck would need to typeck
363 /// the const parameter while type checking the main body, which in turn would try
364 /// to type check the main body again.
365 fn mir_for_ctfe_of_const_arg(tcx: TyCtxt<'_>, (did, param_did): (LocalDefId, DefId)) -> &Body<'_> {
366     tcx.arena.alloc(inner_mir_for_ctfe(
367         tcx,
368         ty::WithOptConstParam { did, const_param_did: Some(param_did) },
369     ))
370 }
371
372 fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
373     // FIXME: don't duplicate this between the optimized_mir/mir_for_ctfe queries
374     if tcx.is_constructor(def.did.to_def_id()) {
375         // There's no reason to run all of the MIR passes on constructors when
376         // we can just output the MIR we want directly. This also saves const
377         // qualification and borrow checking the trouble of special casing
378         // constructors.
379         return shim::build_adt_ctor(tcx, def.did.to_def_id());
380     }
381
382     let context = tcx
383         .hir()
384         .body_const_context(def.did)
385         .expect("mir_for_ctfe should not be used for runtime functions");
386
387     let body = tcx.mir_drops_elaborated_and_const_checked(def).borrow().clone();
388
389     let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::Const);
390
391     match context {
392         // Do not const prop functions, either they get executed at runtime or exported to metadata,
393         // so we run const prop on them, or they don't, in which case we const evaluate some control
394         // flow paths of the function and any errors in those paths will get emitted as const eval
395         // errors.
396         hir::ConstContext::ConstFn => {}
397         // Static items always get evaluated, so we can just let const eval see if any erroneous
398         // control flow paths get executed.
399         hir::ConstContext::Static(_) => {}
400         // Associated constants get const prop run so we detect common failure situations in the
401         // crate that defined the constant.
402         // Technically we want to not run on regular const items, but oli-obk doesn't know how to
403         // conveniently detect that at this point without looking at the HIR.
404         hir::ConstContext::Const => {
405             pm::run_passes(
406                 tcx,
407                 &mut body,
408                 &[&const_prop::ConstProp],
409                 Some(MirPhase::Runtime(RuntimePhase::Optimized)),
410             );
411         }
412     }
413
414     debug_assert!(!body.has_free_regions(), "Free regions in MIR for CTFE");
415
416     body
417 }
418
419 /// Obtain just the main MIR (no promoteds) and run some cleanups on it. This also runs
420 /// mir borrowck *before* doing so in order to ensure that borrowck can be run and doesn't
421 /// end up missing the source MIR due to stealing happening.
422 fn mir_drops_elaborated_and_const_checked(
423     tcx: TyCtxt<'_>,
424     def: ty::WithOptConstParam<LocalDefId>,
425 ) -> &Steal<Body<'_>> {
426     if let Some(def) = def.try_upgrade(tcx) {
427         return tcx.mir_drops_elaborated_and_const_checked(def);
428     }
429
430     let mir_borrowck = tcx.mir_borrowck_opt_const_arg(def);
431
432     let is_fn_like = tcx.def_kind(def.did).is_fn_like();
433     if is_fn_like {
434         let did = def.did.to_def_id();
435         let def = ty::WithOptConstParam::unknown(did);
436
437         // Do not compute the mir call graph without said call graph actually being used.
438         if inline::Inline.is_enabled(&tcx.sess) {
439             let _ = tcx.mir_inliner_callees(ty::InstanceDef::Item(def));
440         }
441     }
442
443     let (body, _) = tcx.mir_promoted(def);
444     let mut body = body.steal();
445     if let Some(error_reported) = mir_borrowck.tainted_by_errors {
446         body.tainted_by_errors = Some(error_reported);
447     }
448
449     run_analysis_to_runtime_passes(tcx, &mut body);
450
451     tcx.alloc_steal_mir(body)
452 }
453
454 fn run_analysis_to_runtime_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
455     assert!(body.phase == MirPhase::Analysis(AnalysisPhase::Initial));
456     let did = body.source.def_id();
457
458     debug!("analysis_mir_cleanup({:?})", did);
459     run_analysis_cleanup_passes(tcx, body);
460     assert!(body.phase == MirPhase::Analysis(AnalysisPhase::PostCleanup));
461
462     // Do a little drop elaboration before const-checking if `const_precise_live_drops` is enabled.
463     if check_consts::post_drop_elaboration::checking_enabled(&ConstCx::new(tcx, &body)) {
464         pm::run_passes(
465             tcx,
466             body,
467             &[
468                 &remove_uninit_drops::RemoveUninitDrops,
469                 &simplify::SimplifyCfg::new("remove-false-edges"),
470             ],
471             None,
472         );
473         check_consts::post_drop_elaboration::check_live_drops(tcx, &body); // FIXME: make this a MIR lint
474     }
475
476     debug!("runtime_mir_lowering({:?})", did);
477     run_runtime_lowering_passes(tcx, body);
478     assert!(body.phase == MirPhase::Runtime(RuntimePhase::Initial));
479
480     debug!("runtime_mir_cleanup({:?})", did);
481     run_runtime_cleanup_passes(tcx, body);
482     assert!(body.phase == MirPhase::Runtime(RuntimePhase::PostCleanup));
483 }
484
485 // FIXME(JakobDegen): Can we make these lists of passes consts?
486
487 /// After this series of passes, no lifetime analysis based on borrowing can be done.
488 fn run_analysis_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
489     let passes: &[&dyn MirPass<'tcx>] = &[
490         &cleanup_post_borrowck::CleanupPostBorrowck,
491         &remove_noop_landing_pads::RemoveNoopLandingPads,
492         &simplify::SimplifyCfg::new("early-opt"),
493         &deref_separator::Derefer,
494     ];
495
496     pm::run_passes(tcx, body, passes, Some(MirPhase::Analysis(AnalysisPhase::PostCleanup)));
497 }
498
499 /// Returns the sequence of passes that lowers analysis to runtime MIR.
500 fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
501     let passes: &[&dyn MirPass<'tcx>] = &[
502         // These next passes must be executed together
503         &add_call_guards::CriticalCallEdges,
504         &elaborate_drops::ElaborateDrops,
505         // This will remove extraneous landing pads which are no longer
506         // necessary as well as well as forcing any call in a non-unwinding
507         // function calling a possibly-unwinding function to abort the process.
508         &abort_unwinding_calls::AbortUnwindingCalls,
509         // AddMovesForPackedDrops needs to run after drop
510         // elaboration.
511         &add_moves_for_packed_drops::AddMovesForPackedDrops,
512         // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
513         // but before optimizations begin.
514         &elaborate_box_derefs::ElaborateBoxDerefs,
515         &generator::StateTransform,
516         &add_retag::AddRetag,
517         // Deaggregator is necessary for const prop. We may want to consider implementing
518         // CTFE support for aggregates.
519         &deaggregator::Deaggregator,
520         &Lint(const_prop_lint::ConstProp),
521         &ctfe_limit::CtfeLimit,
522     ];
523     pm::run_passes_no_validate(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::Initial)));
524 }
525
526 /// Returns the sequence of passes that do the initial cleanup of runtime MIR.
527 fn run_runtime_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
528     let passes: &[&dyn MirPass<'tcx>] =
529         &[&lower_intrinsics::LowerIntrinsics, &simplify::SimplifyCfg::new("elaborate-drops")];
530
531     pm::run_passes(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::PostCleanup)));
532 }
533
534 fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
535     fn o1<T>(x: T) -> WithMinOptLevel<T> {
536         WithMinOptLevel(1, x)
537     }
538
539     // The main optimizations that we do on MIR.
540     pm::run_passes(
541         tcx,
542         body,
543         &[
544             &reveal_all::RevealAll, // has to be done before inlining, since inlined code is in RevealAll mode.
545             &lower_slice_len::LowerSliceLenCalls, // has to be done before inlining, otherwise actual call will be almost always inlined. Also simple, so can just do first
546             &normalize_array_len::NormalizeArrayLen, // has to run after `slice::len` lowering
547             &unreachable_prop::UnreachablePropagation,
548             &uninhabited_enum_branching::UninhabitedEnumBranching,
549             &o1(simplify::SimplifyCfg::new("after-uninhabited-enum-branching")),
550             &inline::Inline,
551             &remove_storage_markers::RemoveStorageMarkers,
552             &remove_zsts::RemoveZsts,
553             &const_goto::ConstGoto,
554             &remove_unneeded_drops::RemoveUnneededDrops,
555             &sroa::ScalarReplacementOfAggregates,
556             &match_branches::MatchBranchSimplification,
557             // inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
558             &multiple_return_terminators::MultipleReturnTerminators,
559             &instcombine::InstCombine,
560             &separate_const_switch::SeparateConstSwitch,
561             &simplify::SimplifyLocals::new("before-const-prop"),
562             //
563             // FIXME(#70073): This pass is responsible for both optimization as well as some lints.
564             &const_prop::ConstProp,
565             &dataflow_const_prop::DataflowConstProp,
566             //
567             // Const-prop runs unconditionally, but doesn't mutate the MIR at mir-opt-level=0.
568             &const_debuginfo::ConstDebugInfo,
569             &o1(simplify_branches::SimplifyConstCondition::new("after-const-prop")),
570             &early_otherwise_branch::EarlyOtherwiseBranch,
571             &simplify_comparison_integral::SimplifyComparisonIntegral,
572             &simplify_try::SimplifyArmIdentity,
573             &simplify_try::SimplifyBranchSame,
574             &dead_store_elimination::DeadStoreElimination,
575             &dest_prop::DestinationPropagation,
576             &o1(simplify_branches::SimplifyConstCondition::new("final")),
577             &o1(remove_noop_landing_pads::RemoveNoopLandingPads),
578             &o1(simplify::SimplifyCfg::new("final")),
579             &nrvo::RenameReturnPlace,
580             &simplify::SimplifyLocals::new("final"),
581             &multiple_return_terminators::MultipleReturnTerminators,
582             &deduplicate_blocks::DeduplicateBlocks,
583             // Some cleanup necessary at least for LLVM and potentially other codegen backends.
584             &add_call_guards::CriticalCallEdges,
585             // Dump the end result for testing and debugging purposes.
586             &dump_mir::Marker("PreCodegen"),
587         ],
588         Some(MirPhase::Runtime(RuntimePhase::Optimized)),
589     );
590 }
591
592 /// Optimize the MIR and prepare it for codegen.
593 fn optimized_mir(tcx: TyCtxt<'_>, did: DefId) -> &Body<'_> {
594     let did = did.expect_local();
595     assert_eq!(ty::WithOptConstParam::try_lookup(did, tcx), None);
596     tcx.arena.alloc(inner_optimized_mir(tcx, did))
597 }
598
599 fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
600     if tcx.is_constructor(did.to_def_id()) {
601         // There's no reason to run all of the MIR passes on constructors when
602         // we can just output the MIR we want directly. This also saves const
603         // qualification and borrow checking the trouble of special casing
604         // constructors.
605         return shim::build_adt_ctor(tcx, did.to_def_id());
606     }
607
608     match tcx.hir().body_const_context(did) {
609         // Run the `mir_for_ctfe` query, which depends on `mir_drops_elaborated_and_const_checked`
610         // which we are going to steal below. Thus we need to run `mir_for_ctfe` first, so it
611         // computes and caches its result.
612         Some(hir::ConstContext::ConstFn) => tcx.ensure().mir_for_ctfe(did),
613         None => {}
614         Some(other) => panic!("do not use `optimized_mir` for constants: {:?}", other),
615     }
616     debug!("about to call mir_drops_elaborated...");
617     let body =
618         tcx.mir_drops_elaborated_and_const_checked(ty::WithOptConstParam::unknown(did)).steal();
619     let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::NotConst);
620     debug!("body: {:#?}", body);
621     run_optimization_passes(tcx, &mut body);
622
623     debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR");
624
625     body
626 }
627
628 /// Fetch all the promoteds of an item and prepare their MIR bodies to be ready for
629 /// constant evaluation once all substitutions become known.
630 fn promoted_mir(
631     tcx: TyCtxt<'_>,
632     def: ty::WithOptConstParam<LocalDefId>,
633 ) -> &IndexVec<Promoted, Body<'_>> {
634     if tcx.is_constructor(def.did.to_def_id()) {
635         return tcx.arena.alloc(IndexVec::new());
636     }
637
638     let tainted_by_errors = tcx.mir_borrowck_opt_const_arg(def).tainted_by_errors;
639     let mut promoted = tcx.mir_promoted(def).1.steal();
640
641     for body in &mut promoted {
642         if let Some(error_reported) = tainted_by_errors {
643             body.tainted_by_errors = Some(error_reported);
644         }
645         run_analysis_to_runtime_passes(tcx, body);
646     }
647
648     debug_assert!(!promoted.has_free_regions(), "Free regions in promoted MIR");
649
650     tcx.arena.alloc(promoted)
651 }