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::{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};
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;
29 pub mod early_otherwise_branch;
30 pub mod elaborate_drops;
31 pub mod function_item_references;
35 pub mod lower_intrinsics;
36 pub mod match_branches;
37 pub mod multiple_return_terminators;
38 pub mod no_landing_pads;
40 pub mod promote_consts;
41 pub mod remove_noop_landing_pads;
42 pub mod remove_unneeded_drops;
43 pub mod required_consts;
46 pub mod simplify_branches;
47 pub mod simplify_comparison_integral;
49 pub mod uninhabited_enum_branching;
50 pub mod unreachable_prop;
53 pub use rustc_middle::mir::MirSource;
55 pub(crate) fn provide(providers: &mut Providers) {
56 self::check_unsafety::provide(providers);
57 *providers = Providers {
60 mir_const_qualif: |tcx, def_id| {
61 let def_id = def_id.expect_local();
62 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
63 tcx.mir_const_qualif_const_arg(def)
65 mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
68 mir_const_qualif_const_arg: |tcx, (did, param_did)| {
69 mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
72 mir_drops_elaborated_and_const_checked,
74 optimized_mir_of_const_arg,
76 promoted_mir: |tcx, def_id| {
77 let def_id = def_id.expect_local();
78 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
79 tcx.promoted_mir_of_const_arg(def)
81 promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
84 promoted_mir_of_const_arg: |tcx, (did, param_did)| {
85 promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
89 coverage::query::provide(providers);
92 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
93 tcx.mir_keys(def_id.krate).contains(&def_id.expect_local())
96 /// Finds the full set of `DefId`s within the current crate that have
97 /// MIR associated with them.
98 fn mir_keys(tcx: TyCtxt<'_>, krate: CrateNum) -> FxHashSet<LocalDefId> {
99 assert_eq!(krate, LOCAL_CRATE);
101 let mut set = FxHashSet::default();
103 // All body-owners have MIR associated with them.
104 set.extend(tcx.body_owners());
106 // Additionally, tuple struct/variant constructors have MIR, but
107 // they don't have a BodyId, so we need to build them separately.
108 struct GatherCtors<'a, 'tcx> {
110 set: &'a mut FxHashSet<LocalDefId>,
112 impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
113 fn visit_variant_data(
115 v: &'tcx hir::VariantData<'tcx>,
117 _: &'tcx hir::Generics<'tcx>,
121 if let hir::VariantData::Tuple(_, hir_id) = *v {
122 self.set.insert(self.tcx.hir().local_def_id(hir_id));
124 intravisit::walk_struct_def(self, v)
126 type Map = intravisit::ErasedMap<'tcx>;
127 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
128 NestedVisitorMap::None
133 .visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
138 /// Generates a default name for the pass based on the name of the
140 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
141 let name = std::any::type_name::<T>();
142 if let Some(tail) = name.rfind(':') { Cow::from(&name[tail + 1..]) } else { Cow::from(name) }
145 /// A streamlined trait that you can implement to create a pass; the
146 /// pass will be named after the type, and it will consist of a main
147 /// loop that goes over each available MIR and applies `run_pass`.
148 pub trait MirPass<'tcx> {
149 fn name(&self) -> Cow<'_, str> {
150 default_name::<Self>()
153 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
158 body: &mut Body<'tcx>,
160 passes: &[&[&dyn MirPass<'tcx>]],
162 let phase_index = mir_phase.phase_index();
163 let validate = tcx.sess.opts.debugging_opts.validate_mir;
165 if body.phase >= mir_phase {
170 validate::Validator { when: format!("input to phase {:?}", mir_phase), mir_phase }
171 .run_pass(tcx, body);
175 let mut run_pass = |pass: &dyn MirPass<'tcx>| {
176 let run_hooks = |body: &_, index, is_after| {
177 dump_mir::on_mir_pass(
179 &format_args!("{:03}-{:03}", phase_index, index),
185 run_hooks(body, index, false);
186 pass.run_pass(tcx, body);
187 run_hooks(body, index, true);
190 validate::Validator {
191 when: format!("after {} in phase {:?}", pass.name(), mir_phase),
194 .run_pass(tcx, body);
200 for pass_group in passes {
201 for pass in *pass_group {
206 body.phase = mir_phase;
208 if mir_phase == MirPhase::Optimization {
209 validate::Validator { when: format!("end of phase {:?}", mir_phase), mir_phase }
210 .run_pass(tcx, body);
214 fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
215 let const_kind = tcx.hir().body_const_context(def.did);
217 // No need to const-check a non-const `fn`.
218 if const_kind.is_none() {
219 return Default::default();
222 // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
223 // cannot yet be stolen), because `mir_promoted()`, which steals
224 // from `mir_const(), forces this query to execute before
225 // performing the steal.
226 let body = &tcx.mir_const(def).borrow();
228 if body.return_ty().references_error() {
229 tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
230 return Default::default();
233 let ccx = check_consts::ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def.did) };
235 let mut validator = check_consts::validation::Validator::new(&ccx);
236 validator.check_body();
238 // We return the qualifs in the return place for every MIR body, even though it is only used
239 // when deciding to promote a reference to a `const` for now.
240 validator.qualifs_in_return_place()
243 /// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
246 def: ty::WithOptConstParam<LocalDefId>,
247 ) -> &'tcx Steal<Body<'tcx>> {
248 if let Some(def) = def.try_upgrade(tcx) {
249 return tcx.mir_const(def);
252 // Unsafety check uses the raw mir, so make sure it is run.
253 if let Some(param_did) = def.const_param_did {
254 tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did));
256 tcx.ensure().unsafety_check_result(def.did);
259 let mut body = tcx.mir_built(def).steal();
261 util::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(()));
269 &check_packed_ref::CheckPackedRef,
270 &check_const_item_mutation::CheckConstItemMutation,
271 &function_item_references::FunctionItemReferences,
272 // What we need to do constant evaluation.
273 &simplify::SimplifyCfg::new("initial"),
274 &rustc_peek::SanityCheck,
277 tcx.alloc_steal_mir(body)
282 def: ty::WithOptConstParam<LocalDefId>,
283 ) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
284 if let Some(def) = def.try_upgrade(tcx) {
285 return tcx.mir_promoted(def);
288 // Ensure that we compute the `mir_const_qualif` for constants at
289 // this point, before we steal the mir-const result.
290 // Also this means promotion can rely on all const checks having been done.
291 let _ = tcx.mir_const_qualif_opt_const_arg(def);
292 let _ = tcx.mir_abstract_const_opt_const_arg(def.to_global());
293 let mut body = tcx.mir_const(def).steal();
295 let mut required_consts = Vec::new();
296 let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
297 for (bb, bb_data) in traversal::reverse_postorder(&body) {
298 required_consts_visitor.visit_basic_block_data(bb, bb_data);
300 body.required_consts = required_consts;
302 let promote_pass = promote_consts::PromoteTemps::default();
303 let promote: &[&dyn MirPass<'tcx>] = &[
304 // What we need to run borrowck etc.
306 &simplify::SimplifyCfg::new("promote-consts"),
309 let opt_coverage: &[&dyn MirPass<'tcx>] = if tcx.sess.opts.debugging_opts.instrument_coverage {
310 &[&coverage::InstrumentCoverage]
315 run_passes(tcx, &mut body, MirPhase::ConstPromotion, &[promote, opt_coverage]);
317 let promoted = promote_pass.promoted_fragments.into_inner();
318 (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
321 fn mir_drops_elaborated_and_const_checked<'tcx>(
323 def: ty::WithOptConstParam<LocalDefId>,
324 ) -> &'tcx Steal<Body<'tcx>> {
325 if let Some(def) = def.try_upgrade(tcx) {
326 return tcx.mir_drops_elaborated_and_const_checked(def);
329 // (Mir-)Borrowck uses `mir_promoted`, so we have to force it to
330 // execute before we can steal.
331 if let Some(param_did) = def.const_param_did {
332 tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
334 tcx.ensure().mir_borrowck(def.did);
337 let (body, _) = tcx.mir_promoted(def);
338 let mut body = body.steal();
340 run_post_borrowck_cleanup_passes(tcx, &mut body);
341 check_consts::post_drop_elaboration::check_live_drops(tcx, &body);
342 tcx.alloc_steal_mir(body)
345 /// After this series of passes, no lifetime analysis based on borrowing can be done.
346 fn run_post_borrowck_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
347 debug!("post_borrowck_cleanup({:?})", body.source.def_id());
349 let post_borrowck_cleanup: &[&dyn MirPass<'tcx>] = &[
350 // Remove all things only needed by analysis
351 &no_landing_pads::NoLandingPads::new(tcx),
352 &simplify_branches::SimplifyBranches::new("initial"),
353 &remove_noop_landing_pads::RemoveNoopLandingPads,
354 &cleanup_post_borrowck::CleanupNonCodegenStatements,
355 &simplify::SimplifyCfg::new("early-opt"),
356 // These next passes must be executed together
357 &add_call_guards::CriticalCallEdges,
358 &elaborate_drops::ElaborateDrops,
359 &no_landing_pads::NoLandingPads::new(tcx),
360 // AddMovesForPackedDrops needs to run after drop
362 &add_moves_for_packed_drops::AddMovesForPackedDrops,
363 // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
364 // but before optimizations begin.
365 &add_retag::AddRetag,
366 &simplify::SimplifyCfg::new("elaborate-drops"),
367 // `Deaggregator` is conceptually part of MIR building, some backends rely on it happening
368 // and it can help optimizations.
369 &deaggregator::Deaggregator,
372 run_passes(tcx, body, MirPhase::DropLowering, &[post_borrowck_cleanup]);
375 fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
376 let mir_opt_level = tcx.sess.opts.debugging_opts.mir_opt_level;
378 // Lowering generator control-flow and variables has to happen before we do anything else
379 // to them. We run some optimizations before that, because they may be harder to do on the state
380 // machine than on MIR with async primitives.
381 let optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[
382 &unreachable_prop::UnreachablePropagation,
383 &uninhabited_enum_branching::UninhabitedEnumBranching,
384 &simplify::SimplifyCfg::new("after-uninhabited-enum-branching"),
386 &generator::StateTransform,
389 // Even if we don't do optimizations, we still have to lower generators for codegen.
390 let no_optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[&generator::StateTransform];
392 // The main optimizations that we do on MIR.
393 let optimizations: &[&dyn MirPass<'tcx>] = &[
394 &lower_intrinsics::LowerIntrinsics,
395 &remove_unneeded_drops::RemoveUnneededDrops,
396 &match_branches::MatchBranchSimplification,
397 // inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
398 &multiple_return_terminators::MultipleReturnTerminators,
399 &instcombine::InstCombine,
400 &const_prop::ConstProp,
401 &simplify_branches::SimplifyBranches::new("after-const-prop"),
402 &early_otherwise_branch::EarlyOtherwiseBranch,
403 &simplify_comparison_integral::SimplifyComparisonIntegral,
404 &simplify_try::SimplifyArmIdentity,
405 &simplify_try::SimplifyBranchSame,
406 &dest_prop::DestinationPropagation,
407 &simplify_branches::SimplifyBranches::new("final"),
408 &remove_noop_landing_pads::RemoveNoopLandingPads,
409 &simplify::SimplifyCfg::new("final"),
410 &nrvo::RenameReturnPlace,
411 &simplify::SimplifyLocals,
412 &multiple_return_terminators::MultipleReturnTerminators,
415 // Optimizations to run even if mir optimizations have been disabled.
416 let no_optimizations: &[&dyn MirPass<'tcx>] = &[
417 // FIXME(#70073): This pass is responsible for both optimization as well as some lints.
418 &const_prop::ConstProp,
421 // Some cleanup necessary at least for LLVM and potentially other codegen backends.
422 let pre_codegen_cleanup: &[&dyn MirPass<'tcx>] = &[
423 &add_call_guards::CriticalCallEdges,
424 // Dump the end result for testing and debugging purposes.
425 &dump_mir::Marker("PreCodegen"),
428 // End of pass declarations, now actually run the passes.
429 // Generator Lowering
434 MirPhase::GeneratorLowering,
436 if mir_opt_level > 0 {
437 optimizations_with_generators
439 no_optimizations_with_generators
444 // Main optimization passes
449 MirPhase::Optimization,
451 if mir_opt_level > 0 { optimizations } else { no_optimizations },
457 fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> {
458 let did = did.expect_local();
459 if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
460 tcx.optimized_mir_of_const_arg(def)
462 tcx.arena.alloc(inner_optimized_mir(tcx, ty::WithOptConstParam::unknown(did)))
466 fn optimized_mir_of_const_arg<'tcx>(
468 (did, param_did): (LocalDefId, DefId),
469 ) -> &'tcx Body<'tcx> {
470 tcx.arena.alloc(inner_optimized_mir(
472 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
476 fn inner_optimized_mir(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
477 if tcx.is_constructor(def.did.to_def_id()) {
478 // There's no reason to run all of the MIR passes on constructors when
479 // we can just output the MIR we want directly. This also saves const
480 // qualification and borrow checking the trouble of special casing
482 return shim::build_adt_ctor(tcx, def.did.to_def_id());
485 let mut body = tcx.mir_drops_elaborated_and_const_checked(def).steal();
486 run_optimization_passes(tcx, &mut body);
488 debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR");
493 fn promoted_mir<'tcx>(
495 def: ty::WithOptConstParam<LocalDefId>,
496 ) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
497 if tcx.is_constructor(def.did.to_def_id()) {
498 return tcx.arena.alloc(IndexVec::new());
501 if let Some(param_did) = def.const_param_did {
502 tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
504 tcx.ensure().mir_borrowck(def.did);
506 let (_, promoted) = tcx.mir_promoted(def);
507 let mut promoted = promoted.steal();
509 for body in &mut promoted {
510 run_post_borrowck_cleanup_passes(tcx, body);
511 run_optimization_passes(tcx, body);
514 debug_assert!(!promoted.has_free_regions(), "Free regions in promoted MIR");
516 tcx.arena.alloc(promoted)