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