1 #![feature(box_patterns)]
2 #![feature(box_syntax)]
3 #![feature(crate_visibility_modifier)]
5 #![feature(map_try_insert)]
6 #![feature(min_specialization)]
7 #![feature(option_get_or_insert_default)]
9 #![feature(never_type)]
10 #![feature(trusted_step)]
11 #![feature(try_blocks)]
12 #![recursion_limit = "256"]
13 #![cfg_attr(not(bootstrap), allow(rustc::potential_query_instability))]
18 extern crate rustc_middle;
20 use required_consts::RequiredConstsVisitor;
21 use rustc_const_eval::util;
22 use rustc_data_structures::fx::FxIndexSet;
23 use rustc_data_structures::steal::Steal;
25 use rustc_hir::def_id::{DefId, LocalDefId};
26 use rustc_hir::intravisit::{self, Visitor};
27 use rustc_index::vec::IndexVec;
28 use rustc_middle::mir::visit::Visitor as _;
29 use rustc_middle::mir::{traversal, Body, ConstQualifs, MirPass, MirPhase, Promoted};
30 use rustc_middle::ty::query::Providers;
31 use rustc_middle::ty::{self, TyCtxt, TypeFoldable};
32 use rustc_span::{Span, Symbol};
37 use pass_manager::{self as pm, Lint, MirLint, WithMinOptLevel};
39 mod abort_unwinding_calls;
41 mod add_moves_for_packed_drops;
43 mod check_const_item_mutation;
45 pub mod check_unsafety;
46 mod cleanup_post_borrowck;
52 mod deduplicate_blocks;
55 mod early_otherwise_branch;
57 mod function_item_references;
65 mod multiple_return_terminators;
66 mod normalize_array_len;
68 mod remove_false_edges;
69 mod remove_noop_landing_pads;
70 mod remove_storage_markers;
71 mod remove_uninit_drops;
72 mod remove_unneeded_drops;
76 mod separate_const_switch;
79 mod simplify_branches;
80 mod simplify_comparison_integral;
82 mod uninhabited_enum_branching;
85 use rustc_const_eval::transform::check_consts::{self, ConstCx};
86 use rustc_const_eval::transform::promote_consts;
87 use rustc_const_eval::transform::validate;
88 use rustc_mir_dataflow::rustc_peek;
90 pub fn provide(providers: &mut Providers) {
91 check_unsafety::provide(providers);
92 check_packed_ref::provide(providers);
93 coverage::query::provide(providers);
94 shim::provide(providers);
95 *providers = Providers {
98 mir_const_qualif: |tcx, def_id| {
99 let def_id = def_id.expect_local();
100 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
101 tcx.mir_const_qualif_const_arg(def)
103 mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
106 mir_const_qualif_const_arg: |tcx, (did, param_did)| {
107 mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
110 mir_drops_elaborated_and_const_checked,
112 mir_for_ctfe_of_const_arg,
115 is_ctfe_mir_available: |tcx, did| is_mir_available(tcx, did),
116 mir_callgraph_reachable: inline::cycle::mir_callgraph_reachable,
117 mir_inliner_callees: inline::cycle::mir_inliner_callees,
118 promoted_mir: |tcx, def_id| {
119 let def_id = def_id.expect_local();
120 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
121 tcx.promoted_mir_of_const_arg(def)
123 promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
126 promoted_mir_of_const_arg: |tcx, (did, param_did)| {
127 promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
133 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
134 let def_id = def_id.expect_local();
135 tcx.mir_keys(()).contains(&def_id)
138 /// Finds the full set of `DefId`s within the current crate that have
139 /// MIR associated with them.
140 fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet<LocalDefId> {
141 let mut set = FxIndexSet::default();
143 // All body-owners have MIR associated with them.
144 set.extend(tcx.hir().body_owners());
146 // Additionally, tuple struct/variant constructors have MIR, but
147 // they don't have a BodyId, so we need to build them separately.
148 struct GatherCtors<'a, 'tcx> {
150 set: &'a mut FxIndexSet<LocalDefId>,
152 impl<'tcx> Visitor<'tcx> for GatherCtors<'_, 'tcx> {
153 fn visit_variant_data(
155 v: &'tcx hir::VariantData<'tcx>,
157 _: &'tcx hir::Generics<'tcx>,
161 if let hir::VariantData::Tuple(_, hir_id) = *v {
162 self.set.insert(self.tcx.hir().local_def_id(hir_id));
164 intravisit::walk_struct_def(self, v)
167 tcx.hir().visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
172 fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
173 let const_kind = tcx.hir().body_const_context(def.did);
175 // No need to const-check a non-const `fn`.
176 if const_kind.is_none() {
177 return Default::default();
180 // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
181 // cannot yet be stolen), because `mir_promoted()`, which steals
182 // from `mir_const(), forces this query to execute before
183 // performing the steal.
184 let body = &tcx.mir_const(def).borrow();
186 if body.return_ty().references_error() {
187 tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
188 return Default::default();
191 let ccx = check_consts::ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def.did) };
193 let mut validator = check_consts::check::Checker::new(&ccx);
194 validator.check_body();
196 // We return the qualifs in the return place for every MIR body, even though it is only used
197 // when deciding to promote a reference to a `const` for now.
198 validator.qualifs_in_return_place()
201 /// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
204 def: ty::WithOptConstParam<LocalDefId>,
205 ) -> &'tcx Steal<Body<'tcx>> {
206 if let Some(def) = def.try_upgrade(tcx) {
207 return tcx.mir_const(def);
210 // Unsafety check uses the raw mir, so make sure it is run.
211 if !tcx.sess.opts.debugging_opts.thir_unsafeck {
212 if let Some(param_did) = def.const_param_did {
213 tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did));
215 tcx.ensure().unsafety_check_result(def.did);
219 let mut body = tcx.mir_built(def).steal();
221 rustc_middle::mir::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(()));
228 &Lint(check_packed_ref::CheckPackedRef),
229 &Lint(check_const_item_mutation::CheckConstItemMutation),
230 &Lint(function_item_references::FunctionItemReferences),
231 // What we need to do constant evaluation.
232 &simplify::SimplifyCfg::new("initial"),
233 &rustc_peek::SanityCheck, // Just a lint
234 &marker::PhaseChange(MirPhase::Const),
237 tcx.alloc_steal_mir(body)
240 /// Compute the main MIR body and the list of MIR bodies of the promoteds.
241 fn mir_promoted<'tcx>(
243 def: ty::WithOptConstParam<LocalDefId>,
244 ) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
245 if let Some(def) = def.try_upgrade(tcx) {
246 return tcx.mir_promoted(def);
249 // Ensure that we compute the `mir_const_qualif` for constants at
250 // this point, before we steal the mir-const result.
251 // Also this means promotion can rely on all const checks having been done.
252 let _ = tcx.mir_const_qualif_opt_const_arg(def);
253 let mut body = tcx.mir_const(def).steal();
255 let mut required_consts = Vec::new();
256 let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
257 for (bb, bb_data) in traversal::reverse_postorder(&body) {
258 required_consts_visitor.visit_basic_block_data(bb, bb_data);
260 body.required_consts = required_consts;
262 // What we need to run borrowck etc.
263 let promote_pass = promote_consts::PromoteTemps::default();
269 &simplify::SimplifyCfg::new("promote-consts"),
270 &coverage::InstrumentCoverage,
274 let promoted = promote_pass.promoted_fragments.into_inner();
275 (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
278 /// Compute the MIR that is used during CTFE (and thus has no optimizations run on it)
279 fn mir_for_ctfe<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Body<'tcx> {
280 let did = def_id.expect_local();
281 if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
282 tcx.mir_for_ctfe_of_const_arg(def)
284 tcx.arena.alloc(inner_mir_for_ctfe(tcx, ty::WithOptConstParam::unknown(did)))
288 /// Same as `mir_for_ctfe`, but used to get the MIR of a const generic parameter.
289 /// The docs on `WithOptConstParam` explain this a bit more, but the TLDR is that
290 /// we'd get cycle errors with `mir_for_ctfe`, because typeck would need to typeck
291 /// the const parameter while type checking the main body, which in turn would try
292 /// to type check the main body again.
293 fn mir_for_ctfe_of_const_arg<'tcx>(
295 (did, param_did): (LocalDefId, DefId),
296 ) -> &'tcx Body<'tcx> {
297 tcx.arena.alloc(inner_mir_for_ctfe(
299 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
303 fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
304 // FIXME: don't duplicate this between the optimized_mir/mir_for_ctfe queries
305 if tcx.is_constructor(def.did.to_def_id()) {
306 // There's no reason to run all of the MIR passes on constructors when
307 // we can just output the MIR we want directly. This also saves const
308 // qualification and borrow checking the trouble of special casing
310 return shim::build_adt_ctor(tcx, def.did.to_def_id());
315 .body_const_context(def.did)
316 .expect("mir_for_ctfe should not be used for runtime functions");
318 let mut body = tcx.mir_drops_elaborated_and_const_checked(def).borrow().clone();
321 // Do not const prop functions, either they get executed at runtime or exported to metadata,
322 // so we run const prop on them, or they don't, in which case we const evaluate some control
323 // flow paths of the function and any errors in those paths will get emitted as const eval
325 hir::ConstContext::ConstFn => {}
326 // Static items always get evaluated, so we can just let const eval see if any erroneous
327 // control flow paths get executed.
328 hir::ConstContext::Static(_) => {}
329 // Associated constants get const prop run so we detect common failure situations in the
330 // crate that defined the constant.
331 // Technically we want to not run on regular const items, but oli-obk doesn't know how to
332 // conveniently detect that at this point without looking at the HIR.
333 hir::ConstContext::Const => {
337 &[&const_prop::ConstProp, &marker::PhaseChange(MirPhase::Optimization)],
342 debug_assert!(!body.has_free_regions(), "Free regions in MIR for CTFE");
347 /// Obtain just the main MIR (no promoteds) and run some cleanups on it. This also runs
348 /// mir borrowck *before* doing so in order to ensure that borrowck can be run and doesn't
349 /// end up missing the source MIR due to stealing happening.
350 fn mir_drops_elaborated_and_const_checked<'tcx>(
352 def: ty::WithOptConstParam<LocalDefId>,
353 ) -> &'tcx Steal<Body<'tcx>> {
354 if let Some(def) = def.try_upgrade(tcx) {
355 return tcx.mir_drops_elaborated_and_const_checked(def);
358 // (Mir-)Borrowck uses `mir_promoted`, so we have to force it to
359 // execute before we can steal.
360 if let Some(param_did) = def.const_param_did {
361 tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
363 tcx.ensure().mir_borrowck(def.did);
366 let is_fn_like = tcx.hir().get_by_def_id(def.did).fn_kind().is_some();
368 let did = def.did.to_def_id();
369 let def = ty::WithOptConstParam::unknown(did);
371 // Do not compute the mir call graph without said call graph actually being used.
372 if inline::Inline.is_enabled(&tcx.sess) {
373 let _ = tcx.mir_inliner_callees(ty::InstanceDef::Item(def));
377 let (body, _) = tcx.mir_promoted(def);
378 let mut body = body.steal();
381 pm::run_passes(tcx, &mut body, &[&remove_false_edges::RemoveFalseEdges]);
383 // Do a little drop elaboration before const-checking if `const_precise_live_drops` is enabled.
384 if check_consts::post_drop_elaboration::checking_enabled(&ConstCx::new(tcx, &body)) {
389 &simplify::SimplifyCfg::new("remove-false-edges"),
390 &remove_uninit_drops::RemoveUninitDrops,
393 check_consts::post_drop_elaboration::check_live_drops(tcx, &body); // FIXME: make this a MIR lint
396 run_post_borrowck_cleanup_passes(tcx, &mut body);
397 assert!(body.phase == MirPhase::DropLowering);
398 tcx.alloc_steal_mir(body)
401 /// After this series of passes, no lifetime analysis based on borrowing can be done.
402 fn run_post_borrowck_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
403 debug!("post_borrowck_cleanup({:?})", body.source.def_id());
405 let post_borrowck_cleanup: &[&dyn MirPass<'tcx>] = &[
406 // Remove all things only needed by analysis
407 &simplify_branches::SimplifyConstCondition::new("initial"),
408 &remove_noop_landing_pads::RemoveNoopLandingPads,
409 &cleanup_post_borrowck::CleanupNonCodegenStatements,
410 &simplify::SimplifyCfg::new("early-opt"),
411 // These next passes must be executed together
412 &add_call_guards::CriticalCallEdges,
413 &elaborate_drops::ElaborateDrops,
414 // This will remove extraneous landing pads which are no longer
415 // necessary as well as well as forcing any call in a non-unwinding
416 // function calling a possibly-unwinding function to abort the process.
417 &abort_unwinding_calls::AbortUnwindingCalls,
418 // AddMovesForPackedDrops needs to run after drop
420 &add_moves_for_packed_drops::AddMovesForPackedDrops,
421 // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
422 // but before optimizations begin.
423 &add_retag::AddRetag,
424 &lower_intrinsics::LowerIntrinsics,
425 &simplify::SimplifyCfg::new("elaborate-drops"),
426 // `Deaggregator` is conceptually part of MIR building, some backends rely on it happening
427 // and it can help optimizations.
428 &deaggregator::Deaggregator,
431 pm::run_passes(tcx, body, post_borrowck_cleanup);
434 fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
435 fn o1<T>(x: T) -> WithMinOptLevel<T> {
436 WithMinOptLevel(1, x)
439 // Lowering generator control-flow and variables has to happen before we do anything else
440 // to them. We run some optimizations before that, because they may be harder to do on the state
441 // machine than on MIR with async primitives.
446 &reveal_all::RevealAll, // has to be done before inlining, since inlined code is in RevealAll mode.
447 &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
448 &normalize_array_len::NormalizeArrayLen, // has to run after `slice::len` lowering
449 &unreachable_prop::UnreachablePropagation,
450 &uninhabited_enum_branching::UninhabitedEnumBranching,
451 &o1(simplify::SimplifyCfg::new("after-uninhabited-enum-branching")),
453 &generator::StateTransform,
457 assert!(body.phase == MirPhase::GeneratorLowering);
459 // The main optimizations that we do on MIR.
464 &remove_storage_markers::RemoveStorageMarkers,
465 &remove_zsts::RemoveZsts,
466 &const_goto::ConstGoto,
467 &remove_unneeded_drops::RemoveUnneededDrops,
468 &match_branches::MatchBranchSimplification,
469 // inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
470 &multiple_return_terminators::MultipleReturnTerminators,
471 &instcombine::InstCombine,
472 &separate_const_switch::SeparateConstSwitch,
474 // FIXME(#70073): This pass is responsible for both optimization as well as some lints.
475 &const_prop::ConstProp,
477 // Const-prop runs unconditionally, but doesn't mutate the MIR at mir-opt-level=0.
478 &o1(simplify_branches::SimplifyConstCondition::new("after-const-prop")),
479 &early_otherwise_branch::EarlyOtherwiseBranch,
480 &simplify_comparison_integral::SimplifyComparisonIntegral,
481 &simplify_try::SimplifyArmIdentity,
482 &simplify_try::SimplifyBranchSame,
483 &dest_prop::DestinationPropagation,
484 &o1(simplify_branches::SimplifyConstCondition::new("final")),
485 &o1(remove_noop_landing_pads::RemoveNoopLandingPads),
486 &o1(simplify::SimplifyCfg::new("final")),
487 &nrvo::RenameReturnPlace,
488 &const_debuginfo::ConstDebugInfo,
489 &simplify::SimplifyLocals,
490 &multiple_return_terminators::MultipleReturnTerminators,
491 &deduplicate_blocks::DeduplicateBlocks,
492 // Some cleanup necessary at least for LLVM and potentially other codegen backends.
493 &add_call_guards::CriticalCallEdges,
494 &marker::PhaseChange(MirPhase::Optimization),
495 // Dump the end result for testing and debugging purposes.
496 &dump_mir::Marker("PreCodegen"),
501 /// Optimize the MIR and prepare it for codegen.
502 fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> {
503 let did = did.expect_local();
504 assert_eq!(ty::WithOptConstParam::try_lookup(did, tcx), None);
505 tcx.arena.alloc(inner_optimized_mir(tcx, did))
508 fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
509 if tcx.is_constructor(did.to_def_id()) {
510 // There's no reason to run all of the MIR passes on constructors when
511 // we can just output the MIR we want directly. This also saves const
512 // qualification and borrow checking the trouble of special casing
514 return shim::build_adt_ctor(tcx, did.to_def_id());
517 match tcx.hir().body_const_context(did) {
518 // Run the `mir_for_ctfe` query, which depends on `mir_drops_elaborated_and_const_checked`
519 // which we are going to steal below. Thus we need to run `mir_for_ctfe` first, so it
520 // computes and caches its result.
521 Some(hir::ConstContext::ConstFn) => tcx.ensure().mir_for_ctfe(did),
523 Some(other) => panic!("do not use `optimized_mir` for constants: {:?}", other),
526 tcx.mir_drops_elaborated_and_const_checked(ty::WithOptConstParam::unknown(did)).steal();
527 run_optimization_passes(tcx, &mut body);
529 debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR");
534 /// Fetch all the promoteds of an item and prepare their MIR bodies to be ready for
535 /// constant evaluation once all substitutions become known.
536 fn promoted_mir<'tcx>(
538 def: ty::WithOptConstParam<LocalDefId>,
539 ) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
540 if tcx.is_constructor(def.did.to_def_id()) {
541 return tcx.arena.alloc(IndexVec::new());
544 if let Some(param_did) = def.const_param_did {
545 tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
547 tcx.ensure().mir_borrowck(def.did);
549 let (_, promoted) = tcx.mir_promoted(def);
550 let mut promoted = promoted.steal();
552 for body in &mut promoted {
553 run_post_borrowck_cleanup_passes(tcx, body);
556 debug_assert!(!promoted.has_free_regions(), "Free regions in promoted MIR");
558 tcx.arena.alloc(promoted)