1 use crate::{shim, util};
2 use required_consts::RequiredConstsVisitor;
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_data_structures::steal::Steal;
6 use rustc_hir::def_id::{DefId, LocalDefId};
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};
16 pub mod add_call_guards;
17 pub mod add_moves_for_packed_drops;
19 pub mod check_const_item_mutation;
21 pub mod check_packed_ref;
22 pub mod check_unsafety;
23 pub mod cleanup_post_borrowck;
24 pub mod const_debuginfo;
29 pub mod deduplicate_blocks;
32 pub mod early_otherwise_branch;
33 pub mod elaborate_drops;
34 pub mod function_item_references;
38 pub mod lower_intrinsics;
39 pub mod match_branches;
40 pub mod multiple_return_terminators;
41 pub mod no_landing_pads;
43 pub mod promote_consts;
44 pub mod remove_noop_landing_pads;
45 pub mod remove_storage_markers;
46 pub mod remove_unneeded_drops;
48 pub mod required_consts;
51 pub mod simplify_branches;
52 pub mod simplify_comparison_integral;
54 pub mod uninhabited_enum_branching;
55 pub mod unreachable_prop;
58 pub use rustc_middle::mir::MirSource;
60 pub(crate) fn provide(providers: &mut Providers) {
61 self::check_unsafety::provide(providers);
62 self::check_packed_ref::provide(providers);
63 *providers = Providers {
66 mir_const_qualif: |tcx, def_id| {
67 let def_id = def_id.expect_local();
68 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
69 tcx.mir_const_qualif_const_arg(def)
71 mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
74 mir_const_qualif_const_arg: |tcx, (did, param_did)| {
75 mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
78 mir_drops_elaborated_and_const_checked,
80 mir_for_ctfe_of_const_arg,
83 is_ctfe_mir_available: |tcx, did| is_mir_available(tcx, did),
84 promoted_mir: |tcx, def_id| {
85 let def_id = def_id.expect_local();
86 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
87 tcx.promoted_mir_of_const_arg(def)
89 promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
92 promoted_mir_of_const_arg: |tcx, (did, param_did)| {
93 promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
97 coverage::query::provide(providers);
100 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
101 let def_id = def_id.expect_local();
102 tcx.mir_keys(()).contains(&def_id)
105 /// Finds the full set of `DefId`s within the current crate that have
106 /// MIR associated with them.
107 fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxHashSet<LocalDefId> {
108 let mut set = FxHashSet::default();
110 // All body-owners have MIR associated with them.
111 set.extend(tcx.body_owners());
113 // Additionally, tuple struct/variant constructors have MIR, but
114 // they don't have a BodyId, so we need to build them separately.
115 struct GatherCtors<'a, 'tcx> {
117 set: &'a mut FxHashSet<LocalDefId>,
119 impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
120 fn visit_variant_data(
122 v: &'tcx hir::VariantData<'tcx>,
124 _: &'tcx hir::Generics<'tcx>,
128 if let hir::VariantData::Tuple(_, hir_id) = *v {
129 self.set.insert(self.tcx.hir().local_def_id(hir_id));
131 intravisit::walk_struct_def(self, v)
133 type Map = intravisit::ErasedMap<'tcx>;
134 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
135 NestedVisitorMap::None
140 .visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
145 /// Generates a default name for the pass based on the name of the
147 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
148 let name = std::any::type_name::<T>();
149 if let Some(tail) = name.rfind(':') { Cow::from(&name[tail + 1..]) } else { Cow::from(name) }
152 /// A streamlined trait that you can implement to create a pass; the
153 /// pass will be named after the type, and it will consist of a main
154 /// loop that goes over each available MIR and applies `run_pass`.
155 pub trait MirPass<'tcx> {
156 fn name(&self) -> Cow<'_, str> {
157 default_name::<Self>()
160 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
165 body: &mut Body<'tcx>,
167 passes: &[&[&dyn MirPass<'tcx>]],
169 let phase_index = mir_phase.phase_index();
170 let validate = tcx.sess.opts.debugging_opts.validate_mir;
172 if body.phase >= mir_phase {
177 validate::Validator { when: format!("input to phase {:?}", mir_phase), mir_phase }
178 .run_pass(tcx, body);
182 let mut run_pass = |pass: &dyn MirPass<'tcx>| {
183 let run_hooks = |body: &_, index, is_after| {
184 dump_mir::on_mir_pass(
186 &format_args!("{:03}-{:03}", phase_index, index),
192 run_hooks(body, index, false);
193 pass.run_pass(tcx, body);
194 run_hooks(body, index, true);
197 validate::Validator {
198 when: format!("after {} in phase {:?}", pass.name(), mir_phase),
201 .run_pass(tcx, body);
207 for pass_group in passes {
208 for pass in *pass_group {
213 body.phase = mir_phase;
215 if mir_phase == MirPhase::Optimization {
216 validate::Validator { when: format!("end of phase {:?}", mir_phase), mir_phase }
217 .run_pass(tcx, body);
221 fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
222 let const_kind = tcx.hir().body_const_context(def.did);
224 // No need to const-check a non-const `fn`.
225 if const_kind.is_none() {
226 return Default::default();
229 // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
230 // cannot yet be stolen), because `mir_promoted()`, which steals
231 // from `mir_const(), forces this query to execute before
232 // performing the steal.
233 let body = &tcx.mir_const(def).borrow();
235 if body.return_ty().references_error() {
236 tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
237 return Default::default();
240 let ccx = check_consts::ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def.did) };
242 let mut validator = check_consts::validation::Validator::new(&ccx);
243 validator.check_body();
245 // We return the qualifs in the return place for every MIR body, even though it is only used
246 // when deciding to promote a reference to a `const` for now.
247 validator.qualifs_in_return_place()
250 /// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
253 def: ty::WithOptConstParam<LocalDefId>,
254 ) -> &'tcx Steal<Body<'tcx>> {
255 if let Some(def) = def.try_upgrade(tcx) {
256 return tcx.mir_const(def);
259 // Unsafety check uses the raw mir, so make sure it is run.
260 if let Some(param_did) = def.const_param_did {
261 tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did));
263 tcx.ensure().unsafety_check_result(def.did);
266 let mut body = tcx.mir_built(def).steal();
268 util::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(()));
276 &check_packed_ref::CheckPackedRef,
277 &check_const_item_mutation::CheckConstItemMutation,
278 &function_item_references::FunctionItemReferences,
279 // What we need to do constant evaluation.
280 &simplify::SimplifyCfg::new("initial"),
281 &rustc_peek::SanityCheck,
284 tcx.alloc_steal_mir(body)
287 /// Compute the main MIR body and the list of MIR bodies of the promoteds.
290 def: ty::WithOptConstParam<LocalDefId>,
291 ) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
292 if let Some(def) = def.try_upgrade(tcx) {
293 return tcx.mir_promoted(def);
296 // Ensure that we compute the `mir_const_qualif` for constants at
297 // this point, before we steal the mir-const result.
298 // Also this means promotion can rely on all const checks having been done.
299 let _ = tcx.mir_const_qualif_opt_const_arg(def);
300 let _ = tcx.mir_abstract_const_opt_const_arg(def.to_global());
301 let mut body = tcx.mir_const(def).steal();
303 let mut required_consts = Vec::new();
304 let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
305 for (bb, bb_data) in traversal::reverse_postorder(&body) {
306 required_consts_visitor.visit_basic_block_data(bb, bb_data);
308 body.required_consts = required_consts;
310 let promote_pass = promote_consts::PromoteTemps::default();
311 let promote: &[&dyn MirPass<'tcx>] = &[
312 // What we need to run borrowck etc.
314 &simplify::SimplifyCfg::new("promote-consts"),
317 let opt_coverage: &[&dyn MirPass<'tcx>] =
318 if tcx.sess.instrument_coverage() { &[&coverage::InstrumentCoverage] } else { &[] };
320 run_passes(tcx, &mut body, MirPhase::ConstPromotion, &[promote, opt_coverage]);
322 let promoted = promote_pass.promoted_fragments.into_inner();
323 (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
326 /// Compute the MIR that is used during CTFE (and thus has no optimizations run on it)
327 fn mir_for_ctfe<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Body<'tcx> {
328 let did = def_id.expect_local();
329 if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
330 tcx.mir_for_ctfe_of_const_arg(def)
332 tcx.arena.alloc(inner_mir_for_ctfe(tcx, ty::WithOptConstParam::unknown(did)))
336 /// Same as `mir_for_ctfe`, but used to get the MIR of a const generic parameter.
337 /// The docs on `WithOptConstParam` explain this a bit more, but the TLDR is that
338 /// we'd get cycle errors with `mir_for_ctfe`, because typeck would need to typeck
339 /// the const parameter while type checking the main body, which in turn would try
340 /// to type check the main body again.
341 fn mir_for_ctfe_of_const_arg<'tcx>(
343 (did, param_did): (LocalDefId, DefId),
344 ) -> &'tcx Body<'tcx> {
345 tcx.arena.alloc(inner_mir_for_ctfe(
347 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
351 fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
352 // FIXME: don't duplicate this between the optimized_mir/mir_for_ctfe queries
353 if tcx.is_constructor(def.did.to_def_id()) {
354 // There's no reason to run all of the MIR passes on constructors when
355 // we can just output the MIR we want directly. This also saves const
356 // qualification and borrow checking the trouble of special casing
358 return shim::build_adt_ctor(tcx, def.did.to_def_id());
363 .body_const_context(def.did)
364 .expect("mir_for_ctfe should not be used for runtime functions");
366 let mut body = tcx.mir_drops_elaborated_and_const_checked(def).borrow().clone();
369 // Do not const prop functions, either they get executed at runtime or exported to metadata,
370 // so we run const prop on them, or they don't, in which case we const evaluate some control
371 // flow paths of the function and any errors in those paths will get emitted as const eval
373 hir::ConstContext::ConstFn => {}
374 // Static items always get evaluated, so we can just let const eval see if any erroneous
375 // control flow paths get executed.
376 hir::ConstContext::Static(_) => {}
377 // Associated constants get const prop run so we detect common failure situations in the
378 // crate that defined the constant.
379 // Technically we want to not run on regular const items, but oli-obk doesn't know how to
380 // conveniently detect that at this point without looking at the HIR.
381 hir::ConstContext::Const => {
383 let optimizations: &[&dyn MirPass<'_>] = &[
384 &const_prop::ConstProp,
391 MirPhase::Optimization,
399 debug_assert!(!body.has_free_regions(), "Free regions in MIR for CTFE");
404 /// Obtain just the main MIR (no promoteds) and run some cleanups on it. This also runs
405 /// mir borrowck *before* doing so in order to ensure that borrowck can be run and doesn't
406 /// end up missing the source MIR due to stealing happening.
407 fn mir_drops_elaborated_and_const_checked<'tcx>(
409 def: ty::WithOptConstParam<LocalDefId>,
410 ) -> &'tcx Steal<Body<'tcx>> {
411 if let Some(def) = def.try_upgrade(tcx) {
412 return tcx.mir_drops_elaborated_and_const_checked(def);
415 // (Mir-)Borrowck uses `mir_promoted`, so we have to force it to
416 // execute before we can steal.
417 if let Some(param_did) = def.const_param_did {
418 tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
420 tcx.ensure().mir_borrowck(def.did);
423 let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
424 use rustc_middle::hir::map::blocks::FnLikeNode;
425 let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some();
427 let did = def.did.to_def_id();
428 let def = ty::WithOptConstParam::unknown(did);
430 // Do not compute the mir call graph without said call graph actually being used.
431 if inline::is_enabled(tcx) {
432 let _ = tcx.mir_inliner_callees(ty::InstanceDef::Item(def));
436 let (body, _) = tcx.mir_promoted(def);
437 let mut body = body.steal();
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)
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());
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
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,
472 run_passes(tcx, body, MirPhase::DropLowering, &[post_borrowck_cleanup]);
475 fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
476 let mir_opt_level = tcx.sess.mir_opt_level();
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"),
486 &generator::StateTransform,
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];
492 // The main optimizations that we do on MIR.
493 let optimizations: &[&dyn MirPass<'tcx>] = &[
494 &remove_storage_markers::RemoveStorageMarkers,
495 &remove_zsts::RemoveZsts,
496 &const_goto::ConstGoto,
497 &remove_unneeded_drops::RemoveUnneededDrops,
498 &match_branches::MatchBranchSimplification,
499 // inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
500 &multiple_return_terminators::MultipleReturnTerminators,
501 &instcombine::InstCombine,
502 &const_prop::ConstProp,
503 &simplify_branches::SimplifyBranches::new("after-const-prop"),
504 &early_otherwise_branch::EarlyOtherwiseBranch,
505 &simplify_comparison_integral::SimplifyComparisonIntegral,
506 &simplify_try::SimplifyArmIdentity,
507 &simplify_try::SimplifyBranchSame,
508 &dest_prop::DestinationPropagation,
509 &simplify_branches::SimplifyBranches::new("final"),
510 &remove_noop_landing_pads::RemoveNoopLandingPads,
511 &simplify::SimplifyCfg::new("final"),
512 &nrvo::RenameReturnPlace,
513 &const_debuginfo::ConstDebugInfo,
514 &simplify::SimplifyLocals,
515 &multiple_return_terminators::MultipleReturnTerminators,
516 &deduplicate_blocks::DeduplicateBlocks,
519 // Optimizations to run even if mir optimizations have been disabled.
520 let no_optimizations: &[&dyn MirPass<'tcx>] = &[
521 // FIXME(#70073): This pass is responsible for both optimization as well as some lints.
522 &const_prop::ConstProp,
525 // Some cleanup necessary at least for LLVM and potentially other codegen backends.
526 let pre_codegen_cleanup: &[&dyn MirPass<'tcx>] = &[
527 &add_call_guards::CriticalCallEdges,
528 // Dump the end result for testing and debugging purposes.
529 &dump_mir::Marker("PreCodegen"),
532 // End of pass declarations, now actually run the passes.
533 // Generator Lowering
538 MirPhase::GeneratorLowering,
540 if mir_opt_level > 0 {
541 optimizations_with_generators
543 no_optimizations_with_generators
548 // Main optimization passes
553 MirPhase::Optimization,
555 if mir_opt_level > 0 { optimizations } else { no_optimizations },
561 /// Optimize the MIR and prepare it for codegen.
562 fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> {
563 let did = did.expect_local();
564 assert_eq!(ty::WithOptConstParam::try_lookup(did, tcx), None);
565 tcx.arena.alloc(inner_optimized_mir(tcx, did))
568 fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
569 if tcx.is_constructor(did.to_def_id()) {
570 // There's no reason to run all of the MIR passes on constructors when
571 // we can just output the MIR we want directly. This also saves const
572 // qualification and borrow checking the trouble of special casing
574 return shim::build_adt_ctor(tcx, did.to_def_id());
577 match tcx.hir().body_const_context(did) {
578 // Run the `mir_for_ctfe` query, which depends on `mir_drops_elaborated_and_const_checked`
579 // which we are going to steal below. Thus we need to run `mir_for_ctfe` first, so it
580 // computes and caches its result.
581 Some(hir::ConstContext::ConstFn) => tcx.ensure().mir_for_ctfe(did),
583 Some(other) => panic!("do not use `optimized_mir` for constants: {:?}", other),
586 tcx.mir_drops_elaborated_and_const_checked(ty::WithOptConstParam::unknown(did)).steal();
587 run_optimization_passes(tcx, &mut body);
589 debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR");
594 /// Fetch all the promoteds of an item and prepare their MIR bodies to be ready for
595 /// constant evaluation once all substitutions become known.
596 fn promoted_mir<'tcx>(
598 def: ty::WithOptConstParam<LocalDefId>,
599 ) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
600 if tcx.is_constructor(def.did.to_def_id()) {
601 return tcx.arena.alloc(IndexVec::new());
604 if let Some(param_did) = def.const_param_did {
605 tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
607 tcx.ensure().mir_borrowck(def.did);
609 let (_, promoted) = tcx.mir_promoted(def);
610 let mut promoted = promoted.steal();
612 for body in &mut promoted {
613 run_post_borrowck_cleanup_passes(tcx, body);
616 debug_assert!(!promoted.has_free_regions(), "Free regions in promoted MIR");
618 tcx.arena.alloc(promoted)