1 use crate::{shim, util};
2 use required_consts::RequiredConstsVisitor;
3 use rustc_data_structures::fx::FxHashSet;
5 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
6 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
7 use rustc_index::vec::IndexVec;
8 use rustc_middle::mir::visit::Visitor as _;
9 use rustc_middle::mir::{traversal, Body, ConstQualifs, CoverageData, MirPhase, Promoted};
10 use rustc_middle::ty::query::Providers;
11 use rustc_middle::ty::steal::Steal;
12 use rustc_middle::ty::{InstanceDef, TyCtxt, TypeFoldable};
13 use rustc_span::{Span, Symbol};
16 pub mod add_call_guards;
17 pub mod add_moves_for_packed_drops;
20 pub mod check_packed_ref;
21 pub mod check_unsafety;
22 pub mod cleanup_post_borrowck;
27 pub mod elaborate_drops;
31 pub mod instrument_coverage;
32 pub mod no_landing_pads;
34 pub mod promote_consts;
35 pub mod qualify_min_const_fn;
36 pub mod remove_noop_landing_pads;
37 pub mod required_consts;
40 pub mod simplify_branches;
42 pub mod uninhabited_enum_branching;
43 pub mod unreachable_prop;
46 pub(crate) fn provide(providers: &mut Providers<'_>) {
47 self::check_unsafety::provide(providers);
48 *providers = Providers {
53 mir_drops_elaborated_and_const_checked,
62 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
63 tcx.mir_keys(def_id.krate).contains(&def_id.expect_local())
66 /// Finds the full set of `DefId`s within the current crate that have
67 /// MIR associated with them.
68 fn mir_keys(tcx: TyCtxt<'_>, krate: CrateNum) -> FxHashSet<LocalDefId> {
69 assert_eq!(krate, LOCAL_CRATE);
71 let mut set = FxHashSet::default();
73 // All body-owners have MIR associated with them.
74 set.extend(tcx.body_owners());
76 // Additionally, tuple struct/variant constructors have MIR, but
77 // they don't have a BodyId, so we need to build them separately.
78 struct GatherCtors<'a, 'tcx> {
80 set: &'a mut FxHashSet<LocalDefId>,
82 impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
83 fn visit_variant_data(
85 v: &'tcx hir::VariantData<'tcx>,
87 _: &'tcx hir::Generics<'tcx>,
91 if let hir::VariantData::Tuple(_, hir_id) = *v {
92 self.set.insert(self.tcx.hir().local_def_id(hir_id));
94 intravisit::walk_struct_def(self, v)
96 type Map = intravisit::ErasedMap<'tcx>;
97 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
98 NestedVisitorMap::None
103 .visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
108 /// Where a specific `mir::Body` comes from.
109 #[derive(Debug, Copy, Clone)]
110 pub struct MirSource<'tcx> {
111 pub instance: InstanceDef<'tcx>,
113 /// If `Some`, this is a promoted rvalue within the parent function.
114 pub promoted: Option<Promoted>,
117 impl<'tcx> MirSource<'tcx> {
118 pub fn item(def_id: DefId) -> Self {
119 MirSource { instance: InstanceDef::Item(def_id), promoted: None }
123 pub fn def_id(&self) -> DefId {
124 self.instance.def_id()
128 /// Generates a default name for the pass based on the name of the
130 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
131 let name = ::std::any::type_name::<T>();
132 if let Some(tail) = name.rfind(':') { Cow::from(&name[tail + 1..]) } else { Cow::from(name) }
135 /// A streamlined trait that you can implement to create a pass; the
136 /// pass will be named after the type, and it will consist of a main
137 /// loop that goes over each available MIR and applies `run_pass`.
138 pub trait MirPass<'tcx> {
139 fn name(&self) -> Cow<'_, str> {
140 default_name::<Self>()
143 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>);
148 body: &mut Body<'tcx>,
149 instance: InstanceDef<'tcx>,
150 promoted: Option<Promoted>,
152 passes: &[&[&dyn MirPass<'tcx>]],
154 let phase_index = mir_phase.phase_index();
155 let source = MirSource { instance, promoted };
156 let validate = tcx.sess.opts.debugging_opts.validate_mir;
158 if body.phase >= mir_phase {
163 validate::Validator { when: format!("input to phase {:?}", mir_phase) }
164 .run_pass(tcx, source, body);
168 let mut run_pass = |pass: &dyn MirPass<'tcx>| {
169 let run_hooks = |body: &_, index, is_after| {
170 dump_mir::on_mir_pass(
172 &format_args!("{:03}-{:03}", phase_index, index),
179 run_hooks(body, index, false);
180 pass.run_pass(tcx, source, body);
181 run_hooks(body, index, true);
184 validate::Validator { when: format!("after {} in phase {:?}", pass.name(), mir_phase) }
185 .run_pass(tcx, source, body);
191 for pass_group in passes {
192 for pass in *pass_group {
197 body.phase = mir_phase;
199 if mir_phase == MirPhase::Optimized {
200 validate::Validator { when: format!("end of phase {:?}", mir_phase) }
201 .run_pass(tcx, source, body);
205 fn mir_const_qualif(tcx: TyCtxt<'_>, def_id: DefId) -> ConstQualifs {
206 let const_kind = tcx.hir().body_const_context(def_id.expect_local());
208 // No need to const-check a non-const `fn`.
209 if const_kind.is_none() {
210 return Default::default();
213 // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
214 // cannot yet be stolen), because `mir_validated()`, which steals
215 // from `mir_const(), forces this query to execute before
216 // performing the steal.
217 let body = &tcx.mir_const(def_id).borrow();
219 if body.return_ty().references_error() {
220 tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
221 return Default::default();
225 check_consts::ConstCx { body, tcx, def_id, const_kind, param_env: tcx.param_env(def_id) };
227 let mut validator = check_consts::validation::Validator::new(&ccx);
228 validator.check_body();
230 // We return the qualifs in the return place for every MIR body, even though it is only used
231 // when deciding to promote a reference to a `const` for now.
232 validator.qualifs_in_return_place()
235 /// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
236 fn mir_const(tcx: TyCtxt<'_>, def_id: DefId) -> Steal<Body<'_>> {
237 let def_id = def_id.expect_local();
239 // Unsafety check uses the raw mir, so make sure it is run.
240 let _ = tcx.unsafety_check_result(def_id);
242 let mut body = tcx.mir_built(def_id).steal();
244 util::dump_mir(tcx, None, "mir_map", &0, MirSource::item(def_id.to_def_id()), &body, |_, _| {
251 InstanceDef::Item(def_id.to_def_id()),
256 &check_packed_ref::CheckPackedRef,
257 // What we need to do constant evaluation.
258 &simplify::SimplifyCfg::new("initial"),
259 &rustc_peek::SanityCheck,
262 tcx.alloc_steal_mir(body)
268 ) -> (Steal<Body<'tcx>>, Steal<IndexVec<Promoted, Body<'tcx>>>) {
269 // Ensure that we compute the `mir_const_qualif` for constants at
270 // this point, before we steal the mir-const result.
271 let _ = tcx.mir_const_qualif(def_id.to_def_id());
273 let mut body = tcx.mir_const(def_id.to_def_id()).steal();
275 let mut required_consts = Vec::new();
276 let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
277 for (bb, bb_data) in traversal::reverse_postorder(&body) {
278 required_consts_visitor.visit_basic_block_data(bb, bb_data);
280 body.required_consts = required_consts;
282 let promote_pass = promote_consts::PromoteTemps::default();
286 InstanceDef::Item(def_id.to_def_id()),
290 // What we need to run borrowck etc.
292 &simplify::SimplifyCfg::new("qualify-consts"),
293 // If the `instrument-coverage` option is enabled, analyze the CFG, identify each
294 // conditional branch, construct a coverage map to be passed to LLVM, and inject counters
296 &instrument_coverage::InstrumentCoverage,
300 let promoted = promote_pass.promoted_fragments.into_inner();
301 (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
304 fn mir_drops_elaborated_and_const_checked<'tcx>(
307 ) -> Steal<Body<'tcx>> {
308 // (Mir-)Borrowck uses `mir_validated`, so we have to force it to
309 // execute before we can steal.
310 tcx.ensure().mir_borrowck(def_id);
312 let (body, _) = tcx.mir_validated(def_id);
313 let mut body = body.steal();
315 run_post_borrowck_cleanup_passes(tcx, &mut body, def_id, None);
316 check_consts::post_drop_elaboration::check_live_drops(tcx, def_id, &body);
317 tcx.alloc_steal_mir(body)
320 /// After this series of passes, no lifetime analysis based on borrowing can be done.
321 fn run_post_borrowck_cleanup_passes<'tcx>(
323 body: &mut Body<'tcx>,
325 promoted: Option<Promoted>,
327 debug!("post_borrowck_cleanup({:?})", def_id);
329 let post_borrowck_cleanup: &[&dyn MirPass<'tcx>] = &[
330 // Remove all things only needed by analysis
331 &no_landing_pads::NoLandingPads::new(tcx),
332 &simplify_branches::SimplifyBranches::new("initial"),
333 &remove_noop_landing_pads::RemoveNoopLandingPads,
334 &cleanup_post_borrowck::CleanupNonCodegenStatements,
335 &simplify::SimplifyCfg::new("early-opt"),
336 // These next passes must be executed together
337 &add_call_guards::CriticalCallEdges,
338 &elaborate_drops::ElaborateDrops,
339 &no_landing_pads::NoLandingPads::new(tcx),
340 // AddMovesForPackedDrops needs to run after drop
342 &add_moves_for_packed_drops::AddMovesForPackedDrops,
343 // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
344 // but before optimizations begin.
345 &add_retag::AddRetag,
346 &simplify::SimplifyCfg::new("elaborate-drops"),
352 InstanceDef::Item(def_id.to_def_id()),
355 &[post_borrowck_cleanup],
359 fn run_optimization_passes<'tcx>(
361 body: &mut Body<'tcx>,
363 promoted: Option<Promoted>,
365 let optimizations: &[&dyn MirPass<'tcx>] = &[
366 &unreachable_prop::UnreachablePropagation,
367 &uninhabited_enum_branching::UninhabitedEnumBranching,
368 &simplify::SimplifyCfg::new("after-uninhabited-enum-branching"),
370 // Lowering generator control-flow and variables has to happen before we do anything else
371 // to them. We do this inside the "optimizations" block so that it can benefit from
372 // optimizations that run before, that might be harder to do on the state machine than MIR
373 // with async primitives.
374 &generator::StateTransform,
375 &instcombine::InstCombine,
376 &const_prop::ConstProp,
377 &simplify_branches::SimplifyBranches::new("after-const-prop"),
378 // Run deaggregation here because:
379 // 1. Some codegen backends require it
380 // 2. It creates additional possibilities for some MIR optimizations to trigger
381 // FIXME(#70073): Why is this done here and not in `post_borrowck_cleanup`?
382 &deaggregator::Deaggregator,
383 &simplify_try::SimplifyArmIdentity,
384 &simplify_try::SimplifyBranchSame,
385 ©_prop::CopyPropagation,
386 &simplify_branches::SimplifyBranches::new("after-copy-prop"),
387 &remove_noop_landing_pads::RemoveNoopLandingPads,
388 &simplify::SimplifyCfg::new("after-remove-noop-landing-pads"),
389 &simplify::SimplifyCfg::new("final"),
390 &nrvo::RenameReturnPlace,
391 &simplify::SimplifyLocals,
394 let no_optimizations: &[&dyn MirPass<'tcx>] = &[
395 // Even if we don't do optimizations, we still have to lower generators for codegen.
396 &generator::StateTransform,
397 // FIXME(#70073): This pass is responsible for both optimization as well as some lints.
398 &const_prop::ConstProp,
399 // Even if we don't do optimizations, still run deaggregation because some backends assume
400 // that deaggregation always occurs.
401 &deaggregator::Deaggregator,
404 let pre_codegen_cleanup: &[&dyn MirPass<'tcx>] = &[
405 &add_call_guards::CriticalCallEdges,
406 // Dump the end result for testing and debugging purposes.
407 &dump_mir::Marker("PreCodegen"),
410 let mir_opt_level = tcx.sess.opts.debugging_opts.mir_opt_level;
416 InstanceDef::Item(def_id.to_def_id()),
420 if mir_opt_level > 0 { optimizations } else { no_optimizations },
426 fn coverage_data(tcx: TyCtxt<'_>, def_id: DefId) -> Option<CoverageData> {
427 let body = tcx.optimized_mir(def_id);
428 body.coverage_data.clone()
431 fn optimized_mir(tcx: TyCtxt<'_>, def_id: DefId) -> Body<'_> {
432 if tcx.is_constructor(def_id) {
433 // There's no reason to run all of the MIR passes on constructors when
434 // we can just output the MIR we want directly. This also saves const
435 // qualification and borrow checking the trouble of special casing
437 return shim::build_adt_ctor(tcx, def_id);
440 let def_id = def_id.expect_local();
442 let mut body = tcx.mir_drops_elaborated_and_const_checked(def_id).steal();
443 run_optimization_passes(tcx, &mut body, def_id, None);
445 debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR");
450 fn promoted_mir(tcx: TyCtxt<'_>, def_id: DefId) -> IndexVec<Promoted, Body<'_>> {
451 if tcx.is_constructor(def_id) {
452 return IndexVec::new();
455 let def_id = def_id.expect_local();
457 tcx.ensure().mir_borrowck(def_id);
458 let (_, promoted) = tcx.mir_validated(def_id);
459 let mut promoted = promoted.steal();
461 for (p, mut body) in promoted.iter_enumerated_mut() {
462 run_post_borrowck_cleanup_passes(tcx, &mut body, def_id, Some(p));
463 run_optimization_passes(tcx, &mut body, def_id, Some(p));
466 debug_assert!(!promoted.has_free_regions(), "Free regions in promoted MIR");