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;
24 pub mod const_debuginfo;
30 pub mod early_otherwise_branch;
31 pub mod elaborate_drops;
32 pub mod function_item_references;
36 pub mod lower_intrinsics;
37 pub mod match_branches;
38 pub mod multiple_return_terminators;
39 pub mod no_landing_pads;
41 pub mod promote_consts;
42 pub mod remove_noop_landing_pads;
43 pub mod remove_unneeded_drops;
44 pub mod required_consts;
47 pub mod simplify_branches;
48 pub mod simplify_comparison_integral;
50 pub mod uninhabited_enum_branching;
51 pub mod unreachable_prop;
54 pub use rustc_middle::mir::MirSource;
56 pub(crate) fn provide(providers: &mut Providers) {
57 self::check_unsafety::provide(providers);
58 *providers = Providers {
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)
66 mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
69 mir_const_qualif_const_arg: |tcx, (did, param_did)| {
70 mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
73 mir_drops_elaborated_and_const_checked,
75 optimized_mir_of_const_arg,
77 promoted_mir: |tcx, def_id| {
78 let def_id = def_id.expect_local();
79 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
80 tcx.promoted_mir_of_const_arg(def)
82 promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
85 promoted_mir_of_const_arg: |tcx, (did, param_did)| {
86 promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
90 coverage::query::provide(providers);
93 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
94 tcx.mir_keys(def_id.krate).contains(&def_id.expect_local())
97 /// Finds the full set of `DefId`s within the current crate that have
98 /// MIR associated with them.
99 fn mir_keys(tcx: TyCtxt<'_>, krate: CrateNum) -> FxHashSet<LocalDefId> {
100 assert_eq!(krate, LOCAL_CRATE);
102 let mut set = FxHashSet::default();
104 // All body-owners have MIR associated with them.
105 set.extend(tcx.body_owners());
107 // Additionally, tuple struct/variant constructors have MIR, but
108 // they don't have a BodyId, so we need to build them separately.
109 struct GatherCtors<'a, 'tcx> {
111 set: &'a mut FxHashSet<LocalDefId>,
113 impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
114 fn visit_variant_data(
116 v: &'tcx hir::VariantData<'tcx>,
118 _: &'tcx hir::Generics<'tcx>,
122 if let hir::VariantData::Tuple(_, hir_id) = *v {
123 self.set.insert(self.tcx.hir().local_def_id(hir_id));
125 intravisit::walk_struct_def(self, v)
127 type Map = intravisit::ErasedMap<'tcx>;
128 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
129 NestedVisitorMap::None
134 .visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
139 /// Generates a default name for the pass based on the name of the
141 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
142 let name = std::any::type_name::<T>();
143 if let Some(tail) = name.rfind(':') { Cow::from(&name[tail + 1..]) } else { Cow::from(name) }
146 /// A streamlined trait that you can implement to create a pass; the
147 /// pass will be named after the type, and it will consist of a main
148 /// loop that goes over each available MIR and applies `run_pass`.
149 pub trait MirPass<'tcx> {
150 fn name(&self) -> Cow<'_, str> {
151 default_name::<Self>()
154 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
159 body: &mut Body<'tcx>,
161 passes: &[&[&dyn MirPass<'tcx>]],
163 let phase_index = mir_phase.phase_index();
164 let validate = tcx.sess.opts.debugging_opts.validate_mir;
166 if body.phase >= mir_phase {
171 validate::Validator { when: format!("input to phase {:?}", mir_phase), mir_phase }
172 .run_pass(tcx, body);
176 let mut run_pass = |pass: &dyn MirPass<'tcx>| {
177 let run_hooks = |body: &_, index, is_after| {
178 dump_mir::on_mir_pass(
180 &format_args!("{:03}-{:03}", phase_index, index),
186 run_hooks(body, index, false);
187 pass.run_pass(tcx, body);
188 run_hooks(body, index, true);
191 validate::Validator {
192 when: format!("after {} in phase {:?}", pass.name(), mir_phase),
195 .run_pass(tcx, body);
201 for pass_group in passes {
202 for pass in *pass_group {
207 body.phase = mir_phase;
209 if mir_phase == MirPhase::Optimization {
210 validate::Validator { when: format!("end of phase {:?}", mir_phase), mir_phase }
211 .run_pass(tcx, body);
215 fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
216 let const_kind = tcx.hir().body_const_context(def.did);
218 // No need to const-check a non-const `fn`.
219 if const_kind.is_none() {
220 return Default::default();
223 // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
224 // cannot yet be stolen), because `mir_promoted()`, which steals
225 // from `mir_const(), forces this query to execute before
226 // performing the steal.
227 let body = &tcx.mir_const(def).borrow();
229 if body.return_ty().references_error() {
230 tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
231 return Default::default();
234 let ccx = check_consts::ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def.did) };
236 let mut validator = check_consts::validation::Validator::new(&ccx);
237 validator.check_body();
239 // We return the qualifs in the return place for every MIR body, even though it is only used
240 // when deciding to promote a reference to a `const` for now.
241 validator.qualifs_in_return_place()
244 /// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
247 def: ty::WithOptConstParam<LocalDefId>,
248 ) -> &'tcx Steal<Body<'tcx>> {
249 if let Some(def) = def.try_upgrade(tcx) {
250 return tcx.mir_const(def);
253 // Unsafety check uses the raw mir, so make sure it is run.
254 if let Some(param_did) = def.const_param_did {
255 tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did));
257 tcx.ensure().unsafety_check_result(def.did);
260 let mut body = tcx.mir_built(def).steal();
262 util::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(()));
270 &check_packed_ref::CheckPackedRef,
271 &check_const_item_mutation::CheckConstItemMutation,
272 &function_item_references::FunctionItemReferences,
273 // What we need to do constant evaluation.
274 &simplify::SimplifyCfg::new("initial"),
275 &rustc_peek::SanityCheck,
278 tcx.alloc_steal_mir(body)
283 def: ty::WithOptConstParam<LocalDefId>,
284 ) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
285 if let Some(def) = def.try_upgrade(tcx) {
286 return tcx.mir_promoted(def);
289 // Ensure that we compute the `mir_const_qualif` for constants at
290 // this point, before we steal the mir-const result.
291 // Also this means promotion can rely on all const checks having been done.
292 let _ = tcx.mir_const_qualif_opt_const_arg(def);
293 let _ = tcx.mir_abstract_const_opt_const_arg(def.to_global());
294 let mut body = tcx.mir_const(def).steal();
296 let mut required_consts = Vec::new();
297 let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
298 for (bb, bb_data) in traversal::reverse_postorder(&body) {
299 required_consts_visitor.visit_basic_block_data(bb, bb_data);
301 body.required_consts = required_consts;
303 let promote_pass = promote_consts::PromoteTemps::default();
304 let promote: &[&dyn MirPass<'tcx>] = &[
305 // What we need to run borrowck etc.
307 &simplify::SimplifyCfg::new("promote-consts"),
310 let opt_coverage: &[&dyn MirPass<'tcx>] = if tcx.sess.opts.debugging_opts.instrument_coverage {
311 &[&coverage::InstrumentCoverage]
316 run_passes(tcx, &mut body, MirPhase::ConstPromotion, &[promote, opt_coverage]);
318 let promoted = promote_pass.promoted_fragments.into_inner();
319 (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
322 fn mir_drops_elaborated_and_const_checked<'tcx>(
324 def: ty::WithOptConstParam<LocalDefId>,
325 ) -> &'tcx Steal<Body<'tcx>> {
326 if let Some(def) = def.try_upgrade(tcx) {
327 return tcx.mir_drops_elaborated_and_const_checked(def);
330 // (Mir-)Borrowck uses `mir_promoted`, so we have to force it to
331 // execute before we can steal.
332 if let Some(param_did) = def.const_param_did {
333 tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
335 tcx.ensure().mir_borrowck(def.did);
338 let (body, _) = tcx.mir_promoted(def);
339 let mut body = body.steal();
341 run_post_borrowck_cleanup_passes(tcx, &mut body);
342 check_consts::post_drop_elaboration::check_live_drops(tcx, &body);
343 tcx.alloc_steal_mir(body)
346 /// After this series of passes, no lifetime analysis based on borrowing can be done.
347 fn run_post_borrowck_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
348 debug!("post_borrowck_cleanup({:?})", body.source.def_id());
350 let post_borrowck_cleanup: &[&dyn MirPass<'tcx>] = &[
351 // Remove all things only needed by analysis
352 &no_landing_pads::NoLandingPads::new(tcx),
353 &simplify_branches::SimplifyBranches::new("initial"),
354 &remove_noop_landing_pads::RemoveNoopLandingPads,
355 &cleanup_post_borrowck::CleanupNonCodegenStatements,
356 &simplify::SimplifyCfg::new("early-opt"),
357 // These next passes must be executed together
358 &add_call_guards::CriticalCallEdges,
359 &elaborate_drops::ElaborateDrops,
360 &no_landing_pads::NoLandingPads::new(tcx),
361 // AddMovesForPackedDrops needs to run after drop
363 &add_moves_for_packed_drops::AddMovesForPackedDrops,
364 // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
365 // but before optimizations begin.
366 &add_retag::AddRetag,
367 &simplify::SimplifyCfg::new("elaborate-drops"),
368 // `Deaggregator` is conceptually part of MIR building, some backends rely on it happening
369 // and it can help optimizations.
370 &deaggregator::Deaggregator,
373 run_passes(tcx, body, MirPhase::DropLowering, &[post_borrowck_cleanup]);
376 fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
377 let mir_opt_level = tcx.sess.opts.debugging_opts.mir_opt_level;
379 // Lowering generator control-flow and variables has to happen before we do anything else
380 // to them. We run some optimizations before that, because they may be harder to do on the state
381 // machine than on MIR with async primitives.
382 let optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[
383 &unreachable_prop::UnreachablePropagation,
384 &uninhabited_enum_branching::UninhabitedEnumBranching,
385 &simplify::SimplifyCfg::new("after-uninhabited-enum-branching"),
387 &generator::StateTransform,
390 // Even if we don't do optimizations, we still have to lower generators for codegen.
391 let no_optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[&generator::StateTransform];
393 // The main optimizations that we do on MIR.
394 let optimizations: &[&dyn MirPass<'tcx>] = &[
395 &lower_intrinsics::LowerIntrinsics,
396 &remove_unneeded_drops::RemoveUnneededDrops,
397 &match_branches::MatchBranchSimplification,
398 // inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
399 &multiple_return_terminators::MultipleReturnTerminators,
400 &instcombine::InstCombine,
401 &const_prop::ConstProp,
402 &simplify_branches::SimplifyBranches::new("after-const-prop"),
403 &early_otherwise_branch::EarlyOtherwiseBranch,
404 &simplify_comparison_integral::SimplifyComparisonIntegral,
405 &simplify_try::SimplifyArmIdentity,
406 &simplify_try::SimplifyBranchSame,
407 &dest_prop::DestinationPropagation,
408 &simplify_branches::SimplifyBranches::new("final"),
409 &remove_noop_landing_pads::RemoveNoopLandingPads,
410 &simplify::SimplifyCfg::new("final"),
411 &nrvo::RenameReturnPlace,
412 &const_debuginfo::ConstDebugInfo,
413 &simplify::SimplifyLocals,
414 &multiple_return_terminators::MultipleReturnTerminators,
417 // Optimizations to run even if mir optimizations have been disabled.
418 let no_optimizations: &[&dyn MirPass<'tcx>] = &[
419 // FIXME(#70073): This pass is responsible for both optimization as well as some lints.
420 &const_prop::ConstProp,
423 // Some cleanup necessary at least for LLVM and potentially other codegen backends.
424 let pre_codegen_cleanup: &[&dyn MirPass<'tcx>] = &[
425 &add_call_guards::CriticalCallEdges,
426 // Dump the end result for testing and debugging purposes.
427 &dump_mir::Marker("PreCodegen"),
430 // End of pass declarations, now actually run the passes.
431 // Generator Lowering
436 MirPhase::GeneratorLowering,
438 if mir_opt_level > 0 {
439 optimizations_with_generators
441 no_optimizations_with_generators
446 // Main optimization passes
451 MirPhase::Optimization,
453 if mir_opt_level > 0 { optimizations } else { no_optimizations },
459 fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> {
460 let did = did.expect_local();
461 if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
462 tcx.optimized_mir_of_const_arg(def)
464 tcx.arena.alloc(inner_optimized_mir(tcx, ty::WithOptConstParam::unknown(did)))
468 fn optimized_mir_of_const_arg<'tcx>(
470 (did, param_did): (LocalDefId, DefId),
471 ) -> &'tcx Body<'tcx> {
472 tcx.arena.alloc(inner_optimized_mir(
474 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
478 fn inner_optimized_mir(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
479 if tcx.is_constructor(def.did.to_def_id()) {
480 // There's no reason to run all of the MIR passes on constructors when
481 // we can just output the MIR we want directly. This also saves const
482 // qualification and borrow checking the trouble of special casing
484 return shim::build_adt_ctor(tcx, def.did.to_def_id());
487 let mut body = tcx.mir_drops_elaborated_and_const_checked(def).steal();
488 run_optimization_passes(tcx, &mut body);
490 debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR");
495 fn promoted_mir<'tcx>(
497 def: ty::WithOptConstParam<LocalDefId>,
498 ) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
499 if tcx.is_constructor(def.did.to_def_id()) {
500 return tcx.arena.alloc(IndexVec::new());
503 if let Some(param_did) = def.const_param_did {
504 tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
506 tcx.ensure().mir_borrowck(def.did);
508 let (_, promoted) = tcx.mir_promoted(def);
509 let mut promoted = promoted.steal();
511 for body in &mut promoted {
512 run_post_borrowck_cleanup_passes(tcx, body);
513 run_optimization_passes(tcx, body);
516 debug_assert!(!promoted.has_free_regions(), "Free regions in promoted MIR");
518 tcx.arena.alloc(promoted)