]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/transform/mod.rs
Rollup merge of #81904 - jhpratt:const_int_fn-stabilization, r=jyn514
[rust.git] / compiler / rustc_mir / src / transform / mod.rs
1 use crate::{shim, util};
2 use required_consts::RequiredConstsVisitor;
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_data_structures::steal::Steal;
5 use rustc_hir as hir;
6 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
7 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
8 use rustc_index::vec::IndexVec;
9 use rustc_middle::mir::visit::Visitor as _;
10 use rustc_middle::mir::{traversal, Body, ConstQualifs, MirPhase, Promoted};
11 use rustc_middle::ty::query::Providers;
12 use rustc_middle::ty::{self, TyCtxt, TypeFoldable};
13 use rustc_span::{Span, Symbol};
14 use std::borrow::Cow;
15
16 pub mod add_call_guards;
17 pub mod add_moves_for_packed_drops;
18 pub mod add_retag;
19 pub mod check_const_item_mutation;
20 pub mod check_consts;
21 pub mod check_packed_ref;
22 pub mod check_unsafety;
23 pub mod cleanup_post_borrowck;
24 pub mod const_debuginfo;
25 pub mod const_prop;
26 pub mod coverage;
27 pub mod deaggregator;
28 pub mod dest_prop;
29 pub mod dump_mir;
30 pub mod early_otherwise_branch;
31 pub mod elaborate_drops;
32 pub mod function_item_references;
33 pub mod generator;
34 pub mod inline;
35 pub mod instcombine;
36 pub mod lower_intrinsics;
37 pub mod match_branches;
38 pub mod multiple_return_terminators;
39 pub mod no_landing_pads;
40 pub mod nrvo;
41 pub mod promote_consts;
42 pub mod remove_noop_landing_pads;
43 pub mod remove_unneeded_drops;
44 pub mod required_consts;
45 pub mod rustc_peek;
46 pub mod simplify;
47 pub mod simplify_branches;
48 pub mod simplify_comparison_integral;
49 pub mod simplify_try;
50 pub mod uninhabited_enum_branching;
51 pub mod unreachable_prop;
52 pub mod validate;
53
54 pub use rustc_middle::mir::MirSource;
55
56 pub(crate) fn provide(providers: &mut Providers) {
57     self::check_unsafety::provide(providers);
58     *providers = Providers {
59         mir_keys,
60         mir_const,
61         mir_const_qualif: |tcx, def_id| {
62             let def_id = def_id.expect_local();
63             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
64                 tcx.mir_const_qualif_const_arg(def)
65             } else {
66                 mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
67             }
68         },
69         mir_const_qualif_const_arg: |tcx, (did, param_did)| {
70             mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
71         },
72         mir_promoted,
73         mir_drops_elaborated_and_const_checked,
74         mir_for_ctfe,
75         mir_for_ctfe_of_const_arg,
76         optimized_mir,
77         is_mir_available,
78         is_ctfe_mir_available: |tcx, did| is_mir_available(tcx, did),
79         promoted_mir: |tcx, def_id| {
80             let def_id = def_id.expect_local();
81             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
82                 tcx.promoted_mir_of_const_arg(def)
83             } else {
84                 promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
85             }
86         },
87         promoted_mir_of_const_arg: |tcx, (did, param_did)| {
88             promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
89         },
90         ..*providers
91     };
92     coverage::query::provide(providers);
93 }
94
95 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
96     tcx.mir_keys(def_id.krate).contains(&def_id.expect_local())
97 }
98
99 /// Finds the full set of `DefId`s within the current crate that have
100 /// MIR associated with them.
101 fn mir_keys(tcx: TyCtxt<'_>, krate: CrateNum) -> FxHashSet<LocalDefId> {
102     assert_eq!(krate, LOCAL_CRATE);
103
104     let mut set = FxHashSet::default();
105
106     // All body-owners have MIR associated with them.
107     set.extend(tcx.body_owners());
108
109     // Additionally, tuple struct/variant constructors have MIR, but
110     // they don't have a BodyId, so we need to build them separately.
111     struct GatherCtors<'a, 'tcx> {
112         tcx: TyCtxt<'tcx>,
113         set: &'a mut FxHashSet<LocalDefId>,
114     }
115     impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
116         fn visit_variant_data(
117             &mut self,
118             v: &'tcx hir::VariantData<'tcx>,
119             _: Symbol,
120             _: &'tcx hir::Generics<'tcx>,
121             _: hir::HirId,
122             _: Span,
123         ) {
124             if let hir::VariantData::Tuple(_, hir_id) = *v {
125                 self.set.insert(self.tcx.hir().local_def_id(hir_id));
126             }
127             intravisit::walk_struct_def(self, v)
128         }
129         type Map = intravisit::ErasedMap<'tcx>;
130         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
131             NestedVisitorMap::None
132         }
133     }
134     tcx.hir()
135         .krate()
136         .visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
137
138     set
139 }
140
141 /// Generates a default name for the pass based on the name of the
142 /// type `T`.
143 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
144     let name = std::any::type_name::<T>();
145     if let Some(tail) = name.rfind(':') { Cow::from(&name[tail + 1..]) } else { Cow::from(name) }
146 }
147
148 /// A streamlined trait that you can implement to create a pass; the
149 /// pass will be named after the type, and it will consist of a main
150 /// loop that goes over each available MIR and applies `run_pass`.
151 pub trait MirPass<'tcx> {
152     fn name(&self) -> Cow<'_, str> {
153         default_name::<Self>()
154     }
155
156     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
157 }
158
159 pub fn run_passes(
160     tcx: TyCtxt<'tcx>,
161     body: &mut Body<'tcx>,
162     mir_phase: MirPhase,
163     passes: &[&[&dyn MirPass<'tcx>]],
164 ) {
165     let phase_index = mir_phase.phase_index();
166     let validate = tcx.sess.opts.debugging_opts.validate_mir;
167
168     if body.phase >= mir_phase {
169         return;
170     }
171
172     if validate {
173         validate::Validator { when: format!("input to phase {:?}", mir_phase), mir_phase }
174             .run_pass(tcx, body);
175     }
176
177     let mut index = 0;
178     let mut run_pass = |pass: &dyn MirPass<'tcx>| {
179         let run_hooks = |body: &_, index, is_after| {
180             dump_mir::on_mir_pass(
181                 tcx,
182                 &format_args!("{:03}-{:03}", phase_index, index),
183                 &pass.name(),
184                 body,
185                 is_after,
186             );
187         };
188         run_hooks(body, index, false);
189         pass.run_pass(tcx, body);
190         run_hooks(body, index, true);
191
192         if validate {
193             validate::Validator {
194                 when: format!("after {} in phase {:?}", pass.name(), mir_phase),
195                 mir_phase,
196             }
197             .run_pass(tcx, body);
198         }
199
200         index += 1;
201     };
202
203     for pass_group in passes {
204         for pass in *pass_group {
205             run_pass(*pass);
206         }
207     }
208
209     body.phase = mir_phase;
210
211     if mir_phase == MirPhase::Optimization {
212         validate::Validator { when: format!("end of phase {:?}", mir_phase), mir_phase }
213             .run_pass(tcx, body);
214     }
215 }
216
217 fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
218     let const_kind = tcx.hir().body_const_context(def.did);
219
220     // No need to const-check a non-const `fn`.
221     if const_kind.is_none() {
222         return Default::default();
223     }
224
225     // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
226     // cannot yet be stolen), because `mir_promoted()`, which steals
227     // from `mir_const(), forces this query to execute before
228     // performing the steal.
229     let body = &tcx.mir_const(def).borrow();
230
231     if body.return_ty().references_error() {
232         tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
233         return Default::default();
234     }
235
236     let ccx = check_consts::ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def.did) };
237
238     let mut validator = check_consts::validation::Validator::new(&ccx);
239     validator.check_body();
240
241     // We return the qualifs in the return place for every MIR body, even though it is only used
242     // when deciding to promote a reference to a `const` for now.
243     validator.qualifs_in_return_place()
244 }
245
246 /// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
247 fn mir_const<'tcx>(
248     tcx: TyCtxt<'tcx>,
249     def: ty::WithOptConstParam<LocalDefId>,
250 ) -> &'tcx Steal<Body<'tcx>> {
251     if let Some(def) = def.try_upgrade(tcx) {
252         return tcx.mir_const(def);
253     }
254
255     // Unsafety check uses the raw mir, so make sure it is run.
256     if let Some(param_did) = def.const_param_did {
257         tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did));
258     } else {
259         tcx.ensure().unsafety_check_result(def.did);
260     }
261
262     let mut body = tcx.mir_built(def).steal();
263
264     util::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(()));
265
266     run_passes(
267         tcx,
268         &mut body,
269         MirPhase::Const,
270         &[&[
271             // MIR-level lints.
272             &check_packed_ref::CheckPackedRef,
273             &check_const_item_mutation::CheckConstItemMutation,
274             &function_item_references::FunctionItemReferences,
275             // What we need to do constant evaluation.
276             &simplify::SimplifyCfg::new("initial"),
277             &rustc_peek::SanityCheck,
278         ]],
279     );
280     tcx.alloc_steal_mir(body)
281 }
282
283 /// Compute the main MIR body and the list of MIR bodies of the promoteds.
284 fn mir_promoted(
285     tcx: TyCtxt<'tcx>,
286     def: ty::WithOptConstParam<LocalDefId>,
287 ) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
288     if let Some(def) = def.try_upgrade(tcx) {
289         return tcx.mir_promoted(def);
290     }
291
292     // Ensure that we compute the `mir_const_qualif` for constants at
293     // this point, before we steal the mir-const result.
294     // Also this means promotion can rely on all const checks having been done.
295     let _ = tcx.mir_const_qualif_opt_const_arg(def);
296     let _ = tcx.mir_abstract_const_opt_const_arg(def.to_global());
297     let mut body = tcx.mir_const(def).steal();
298
299     let mut required_consts = Vec::new();
300     let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
301     for (bb, bb_data) in traversal::reverse_postorder(&body) {
302         required_consts_visitor.visit_basic_block_data(bb, bb_data);
303     }
304     body.required_consts = required_consts;
305
306     let promote_pass = promote_consts::PromoteTemps::default();
307     let promote: &[&dyn MirPass<'tcx>] = &[
308         // What we need to run borrowck etc.
309         &promote_pass,
310         &simplify::SimplifyCfg::new("promote-consts"),
311     ];
312
313     let opt_coverage: &[&dyn MirPass<'tcx>] = if tcx.sess.opts.debugging_opts.instrument_coverage {
314         &[&coverage::InstrumentCoverage]
315     } else {
316         &[]
317     };
318
319     run_passes(tcx, &mut body, MirPhase::ConstPromotion, &[promote, opt_coverage]);
320
321     let promoted = promote_pass.promoted_fragments.into_inner();
322     (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
323 }
324
325 /// Compute the MIR that is used during CTFE (and thus has no optimizations run on it)
326 fn mir_for_ctfe<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Body<'tcx> {
327     let did = def_id.expect_local();
328     if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
329         tcx.mir_for_ctfe_of_const_arg(def)
330     } else {
331         tcx.arena.alloc(inner_mir_for_ctfe(tcx, ty::WithOptConstParam::unknown(did)))
332     }
333 }
334
335 /// Same as `mir_for_ctfe`, but used to get the MIR of a const generic parameter.
336 /// The docs on `WithOptConstParam` explain this a bit more, but the TLDR is that
337 /// we'd get cycle errors with `mir_for_ctfe`, because typeck would need to typeck
338 /// the const parameter while type checking the main body, which in turn would try
339 /// to type check the main body again.
340 fn mir_for_ctfe_of_const_arg<'tcx>(
341     tcx: TyCtxt<'tcx>,
342     (did, param_did): (LocalDefId, DefId),
343 ) -> &'tcx Body<'tcx> {
344     tcx.arena.alloc(inner_mir_for_ctfe(
345         tcx,
346         ty::WithOptConstParam { did, const_param_did: Some(param_did) },
347     ))
348 }
349
350 fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
351     // FIXME: don't duplicate this between the optimized_mir/mir_for_ctfe queries
352     if tcx.is_constructor(def.did.to_def_id()) {
353         // There's no reason to run all of the MIR passes on constructors when
354         // we can just output the MIR we want directly. This also saves const
355         // qualification and borrow checking the trouble of special casing
356         // constructors.
357         return shim::build_adt_ctor(tcx, def.did.to_def_id());
358     }
359
360     let context = tcx
361         .hir()
362         .body_const_context(def.did)
363         .expect("mir_for_ctfe should not be used for runtime functions");
364
365     let mut body = tcx.mir_drops_elaborated_and_const_checked(def).borrow().clone();
366
367     match context {
368         // Do not const prop functions, either they get executed at runtime or exported to metadata,
369         // so we run const prop on them, or they don't, in which case we const evaluate some control
370         // flow paths of the function and any errors in those paths will get emitted as const eval
371         // errors.
372         hir::ConstContext::ConstFn => {}
373         // Static items always get evaluated, so we can just let const eval see if any erroneous
374         // control flow paths get executed.
375         hir::ConstContext::Static(_) => {}
376         // Associated constants get const prop run so we detect common failure situations in the
377         // crate that defined the constant.
378         // Technically we want to not run on regular const items, but oli-obk doesn't know how to
379         // conveniently detect that at this point without looking at the HIR.
380         hir::ConstContext::Const => {
381             #[rustfmt::skip]
382             let optimizations: &[&dyn MirPass<'_>] = &[
383                 &const_prop::ConstProp,
384             ];
385
386             #[rustfmt::skip]
387             run_passes(
388                 tcx,
389                 &mut body,
390                 MirPhase::Optimization,
391                 &[
392                     optimizations,
393                 ],
394             );
395         }
396     }
397
398     debug_assert!(!body.has_free_regions(), "Free regions in MIR for CTFE");
399
400     body
401 }
402
403 /// Obtain just the main MIR (no promoteds) and run some cleanups on it. This also runs
404 /// mir borrowck *before* doing so in order to ensure that borrowck can be run and doesn't
405 /// end up missing the source MIR due to stealing happening.
406 fn mir_drops_elaborated_and_const_checked<'tcx>(
407     tcx: TyCtxt<'tcx>,
408     def: ty::WithOptConstParam<LocalDefId>,
409 ) -> &'tcx Steal<Body<'tcx>> {
410     if let Some(def) = def.try_upgrade(tcx) {
411         return tcx.mir_drops_elaborated_and_const_checked(def);
412     }
413
414     // (Mir-)Borrowck uses `mir_promoted`, so we have to force it to
415     // execute before we can steal.
416     if let Some(param_did) = def.const_param_did {
417         tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
418     } else {
419         tcx.ensure().mir_borrowck(def.did);
420     }
421
422     let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
423     use rustc_middle::hir::map::blocks::FnLikeNode;
424     let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some();
425     if is_fn_like {
426         let did = def.did.to_def_id();
427         let def = ty::WithOptConstParam::unknown(did);
428
429         // Do not compute the mir call graph without said call graph actually being used.
430         // Keep this in sync with the mir inliner's optimization level.
431         if tcx.sess.opts.debugging_opts.mir_opt_level >= 2 {
432             let _ = tcx.mir_inliner_callees(ty::InstanceDef::Item(def));
433         }
434     }
435
436     let (body, _) = tcx.mir_promoted(def);
437     let mut body = body.steal();
438
439     run_post_borrowck_cleanup_passes(tcx, &mut body);
440     check_consts::post_drop_elaboration::check_live_drops(tcx, &body);
441     tcx.alloc_steal_mir(body)
442 }
443
444 /// After this series of passes, no lifetime analysis based on borrowing can be done.
445 fn run_post_borrowck_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
446     debug!("post_borrowck_cleanup({:?})", body.source.def_id());
447
448     let post_borrowck_cleanup: &[&dyn MirPass<'tcx>] = &[
449         // Remove all things only needed by analysis
450         &no_landing_pads::NoLandingPads,
451         &simplify_branches::SimplifyBranches::new("initial"),
452         &remove_noop_landing_pads::RemoveNoopLandingPads,
453         &cleanup_post_borrowck::CleanupNonCodegenStatements,
454         &simplify::SimplifyCfg::new("early-opt"),
455         // These next passes must be executed together
456         &add_call_guards::CriticalCallEdges,
457         &elaborate_drops::ElaborateDrops,
458         &no_landing_pads::NoLandingPads,
459         // AddMovesForPackedDrops needs to run after drop
460         // elaboration.
461         &add_moves_for_packed_drops::AddMovesForPackedDrops,
462         // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
463         // but before optimizations begin.
464         &add_retag::AddRetag,
465         &lower_intrinsics::LowerIntrinsics,
466         &simplify::SimplifyCfg::new("elaborate-drops"),
467         // `Deaggregator` is conceptually part of MIR building, some backends rely on it happening
468         // and it can help optimizations.
469         &deaggregator::Deaggregator,
470     ];
471
472     run_passes(tcx, body, MirPhase::DropLowering, &[post_borrowck_cleanup]);
473 }
474
475 fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
476     let mir_opt_level = tcx.sess.opts.debugging_opts.mir_opt_level;
477
478     // Lowering generator control-flow and variables has to happen before we do anything else
479     // to them. We run some optimizations before that, because they may be harder to do on the state
480     // machine than on MIR with async primitives.
481     let optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[
482         &unreachable_prop::UnreachablePropagation,
483         &uninhabited_enum_branching::UninhabitedEnumBranching,
484         &simplify::SimplifyCfg::new("after-uninhabited-enum-branching"),
485         &inline::Inline,
486         &generator::StateTransform,
487     ];
488
489     // Even if we don't do optimizations, we still have to lower generators for codegen.
490     let no_optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[&generator::StateTransform];
491
492     // The main optimizations that we do on MIR.
493     let optimizations: &[&dyn MirPass<'tcx>] = &[
494         &remove_unneeded_drops::RemoveUnneededDrops,
495         &match_branches::MatchBranchSimplification,
496         // inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
497         &multiple_return_terminators::MultipleReturnTerminators,
498         &instcombine::InstCombine,
499         &const_prop::ConstProp,
500         &simplify_branches::SimplifyBranches::new("after-const-prop"),
501         &early_otherwise_branch::EarlyOtherwiseBranch,
502         &simplify_comparison_integral::SimplifyComparisonIntegral,
503         &simplify_try::SimplifyArmIdentity,
504         &simplify_try::SimplifyBranchSame,
505         &dest_prop::DestinationPropagation,
506         &simplify_branches::SimplifyBranches::new("final"),
507         &remove_noop_landing_pads::RemoveNoopLandingPads,
508         &simplify::SimplifyCfg::new("final"),
509         &nrvo::RenameReturnPlace,
510         &const_debuginfo::ConstDebugInfo,
511         &simplify::SimplifyLocals,
512         &multiple_return_terminators::MultipleReturnTerminators,
513     ];
514
515     // Optimizations to run even if mir optimizations have been disabled.
516     let no_optimizations: &[&dyn MirPass<'tcx>] = &[
517         // FIXME(#70073): This pass is responsible for both optimization as well as some lints.
518         &const_prop::ConstProp,
519     ];
520
521     // Some cleanup necessary at least for LLVM and potentially other codegen backends.
522     let pre_codegen_cleanup: &[&dyn MirPass<'tcx>] = &[
523         &add_call_guards::CriticalCallEdges,
524         // Dump the end result for testing and debugging purposes.
525         &dump_mir::Marker("PreCodegen"),
526     ];
527
528     // End of pass declarations, now actually run the passes.
529     // Generator Lowering
530     #[rustfmt::skip]
531     run_passes(
532         tcx,
533         body,
534         MirPhase::GeneratorLowering,
535         &[
536             if mir_opt_level > 0 {
537                 optimizations_with_generators
538             } else {
539                 no_optimizations_with_generators
540             }
541         ],
542     );
543
544     // Main optimization passes
545     #[rustfmt::skip]
546     run_passes(
547         tcx,
548         body,
549         MirPhase::Optimization,
550         &[
551             if mir_opt_level > 0 { optimizations } else { no_optimizations },
552             pre_codegen_cleanup,
553         ],
554     );
555 }
556
557 /// Optimize the MIR and prepare it for codegen.
558 fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> {
559     let did = did.expect_local();
560     assert_eq!(ty::WithOptConstParam::try_lookup(did, tcx), None);
561     tcx.arena.alloc(inner_optimized_mir(tcx, did))
562 }
563
564 fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
565     if tcx.is_constructor(did.to_def_id()) {
566         // There's no reason to run all of the MIR passes on constructors when
567         // we can just output the MIR we want directly. This also saves const
568         // qualification and borrow checking the trouble of special casing
569         // constructors.
570         return shim::build_adt_ctor(tcx, did.to_def_id());
571     }
572
573     match tcx.hir().body_const_context(did) {
574         // Run the `mir_for_ctfe` query, which depends on `mir_drops_elaborated_and_const_checked`
575         // which we are going to steal below. Thus we need to run `mir_for_ctfe` first, so it
576         // computes and caches its result.
577         Some(hir::ConstContext::ConstFn) => tcx.ensure().mir_for_ctfe(did),
578         None => {}
579         Some(other) => panic!("do not use `optimized_mir` for constants: {:?}", other),
580     }
581     let mut body =
582         tcx.mir_drops_elaborated_and_const_checked(ty::WithOptConstParam::unknown(did)).steal();
583     run_optimization_passes(tcx, &mut body);
584
585     debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR");
586
587     body
588 }
589
590 /// Fetch all the promoteds of an item and prepare their MIR bodies to be ready for
591 /// constant evaluation once all substitutions become known.
592 fn promoted_mir<'tcx>(
593     tcx: TyCtxt<'tcx>,
594     def: ty::WithOptConstParam<LocalDefId>,
595 ) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
596     if tcx.is_constructor(def.did.to_def_id()) {
597         return tcx.arena.alloc(IndexVec::new());
598     }
599
600     if let Some(param_did) = def.const_param_did {
601         tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
602     } else {
603         tcx.ensure().mir_borrowck(def.did);
604     }
605     let (_, promoted) = tcx.mir_promoted(def);
606     let mut promoted = promoted.steal();
607
608     for body in &mut promoted {
609         run_post_borrowck_cleanup_passes(tcx, body);
610     }
611
612     debug_assert!(!promoted.has_free_regions(), "Free regions in promoted MIR");
613
614     tcx.arena.alloc(promoted)
615 }