1 #![allow(rustc::potential_query_instability)]
2 #![feature(box_patterns)]
3 #![feature(box_syntax)]
4 #![feature(crate_visibility_modifier)]
5 #![feature(let_chains)]
7 #![feature(map_try_insert)]
8 #![feature(min_specialization)]
9 #![feature(never_type)]
10 #![feature(once_cell)]
11 #![feature(option_get_or_insert_default)]
12 #![feature(trusted_step)]
13 #![feature(try_blocks)]
14 #![recursion_limit = "256"]
19 extern crate rustc_middle;
21 use required_consts::RequiredConstsVisitor;
22 use rustc_const_eval::util;
23 use rustc_data_structures::fx::FxIndexSet;
24 use rustc_data_structures::steal::Steal;
26 use rustc_hir::def_id::{DefId, LocalDefId};
27 use rustc_hir::intravisit::{self, Visitor};
28 use rustc_index::vec::IndexVec;
29 use rustc_middle::mir::visit::Visitor as _;
30 use rustc_middle::mir::{traversal, Body, ConstQualifs, MirPass, MirPhase, Promoted};
31 use rustc_middle::ty::query::Providers;
32 use rustc_middle::ty::{self, TyCtxt, TypeFoldable};
33 use rustc_span::{Span, Symbol};
38 use pass_manager::{self as pm, Lint, MirLint, WithMinOptLevel};
40 mod abort_unwinding_calls;
42 mod add_moves_for_packed_drops;
44 mod check_const_item_mutation;
46 pub mod check_unsafety;
47 // This pass is public to allow external drivers to perform MIR cleanup
48 pub mod cleanup_post_borrowck;
55 mod deduplicate_blocks;
59 mod early_otherwise_branch;
61 mod function_item_references;
69 mod multiple_return_terminators;
70 mod normalize_array_len;
72 // This pass is public to allow external drivers to perform MIR cleanup
73 pub mod remove_false_edges;
74 mod remove_noop_landing_pads;
75 mod remove_storage_markers;
76 mod remove_uninit_drops;
77 mod remove_unneeded_drops;
81 mod separate_const_switch;
83 // This pass is public to allow external drivers to perform MIR cleanup
85 mod simplify_branches;
86 mod simplify_comparison_integral;
88 mod uninhabited_enum_branching;
91 use rustc_const_eval::transform::check_consts::{self, ConstCx};
92 use rustc_const_eval::transform::promote_consts;
93 use rustc_const_eval::transform::validate;
94 use rustc_mir_dataflow::rustc_peek;
96 pub fn provide(providers: &mut Providers) {
97 check_unsafety::provide(providers);
98 check_packed_ref::provide(providers);
99 coverage::query::provide(providers);
100 shim::provide(providers);
101 *providers = Providers {
104 mir_const_qualif: |tcx, def_id| {
105 let def_id = def_id.expect_local();
106 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
107 tcx.mir_const_qualif_const_arg(def)
109 mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
112 mir_const_qualif_const_arg: |tcx, (did, param_did)| {
113 mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
116 mir_drops_elaborated_and_const_checked,
118 mir_for_ctfe_of_const_arg,
121 is_ctfe_mir_available: |tcx, did| is_mir_available(tcx, did),
122 mir_callgraph_reachable: inline::cycle::mir_callgraph_reachable,
123 mir_inliner_callees: inline::cycle::mir_inliner_callees,
124 promoted_mir: |tcx, def_id| {
125 let def_id = def_id.expect_local();
126 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
127 tcx.promoted_mir_of_const_arg(def)
129 promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
132 promoted_mir_of_const_arg: |tcx, (did, param_did)| {
133 promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
139 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
140 let def_id = def_id.expect_local();
141 tcx.mir_keys(()).contains(&def_id)
144 /// Finds the full set of `DefId`s within the current crate that have
145 /// MIR associated with them.
146 fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet<LocalDefId> {
147 let mut set = FxIndexSet::default();
149 // All body-owners have MIR associated with them.
150 set.extend(tcx.hir().body_owners());
152 // Additionally, tuple struct/variant constructors have MIR, but
153 // they don't have a BodyId, so we need to build them separately.
154 struct GatherCtors<'a, 'tcx> {
156 set: &'a mut FxIndexSet<LocalDefId>,
158 impl<'tcx> Visitor<'tcx> for GatherCtors<'_, 'tcx> {
159 fn visit_variant_data(
161 v: &'tcx hir::VariantData<'tcx>,
163 _: &'tcx hir::Generics<'tcx>,
167 if let hir::VariantData::Tuple(_, hir_id) = *v {
168 self.set.insert(self.tcx.hir().local_def_id(hir_id));
170 intravisit::walk_struct_def(self, v)
173 tcx.hir().visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
178 fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
179 let const_kind = tcx.hir().body_const_context(def.did);
181 // No need to const-check a non-const `fn`.
182 if const_kind.is_none() {
183 return Default::default();
186 // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
187 // cannot yet be stolen), because `mir_promoted()`, which steals
188 // from `mir_const(), forces this query to execute before
189 // performing the steal.
190 let body = &tcx.mir_const(def).borrow();
192 if body.return_ty().references_error() {
193 tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
194 return Default::default();
197 let ccx = check_consts::ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def.did) };
199 let mut validator = check_consts::check::Checker::new(&ccx);
200 validator.check_body();
202 // We return the qualifs in the return place for every MIR body, even though it is only used
203 // when deciding to promote a reference to a `const` for now.
204 validator.qualifs_in_return_place()
207 /// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
210 def: ty::WithOptConstParam<LocalDefId>,
211 ) -> &'tcx Steal<Body<'tcx>> {
212 if let Some(def) = def.try_upgrade(tcx) {
213 return tcx.mir_const(def);
216 // Unsafety check uses the raw mir, so make sure it is run.
217 if !tcx.sess.opts.debugging_opts.thir_unsafeck {
218 if let Some(param_did) = def.const_param_did {
219 tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did));
221 tcx.ensure().unsafety_check_result(def.did);
225 let mut body = tcx.mir_built(def).steal();
227 rustc_middle::mir::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(()));
234 &Lint(check_packed_ref::CheckPackedRef),
235 &Lint(check_const_item_mutation::CheckConstItemMutation),
236 &Lint(function_item_references::FunctionItemReferences),
237 // What we need to do constant evaluation.
238 &simplify::SimplifyCfg::new("initial"),
239 &rustc_peek::SanityCheck, // Just a lint
240 &marker::PhaseChange(MirPhase::Const),
243 tcx.alloc_steal_mir(body)
246 /// Compute the main MIR body and the list of MIR bodies of the promoteds.
247 fn mir_promoted<'tcx>(
249 def: ty::WithOptConstParam<LocalDefId>,
250 ) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
251 if let Some(def) = def.try_upgrade(tcx) {
252 return tcx.mir_promoted(def);
255 // Ensure that we compute the `mir_const_qualif` for constants at
256 // this point, before we steal the mir-const result.
257 // Also this means promotion can rely on all const checks having been done.
258 let const_qualifs = tcx.mir_const_qualif_opt_const_arg(def);
259 let mut body = tcx.mir_const(def).steal();
260 if let Some(error_reported) = const_qualifs.tainted_by_errors {
261 body.tainted_by_errors = Some(error_reported);
264 let mut required_consts = Vec::new();
265 let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
266 for (bb, bb_data) in traversal::reverse_postorder(&body) {
267 required_consts_visitor.visit_basic_block_data(bb, bb_data);
269 body.required_consts = required_consts;
271 // What we need to run borrowck etc.
272 let promote_pass = promote_consts::PromoteTemps::default();
278 &simplify::SimplifyCfg::new("promote-consts"),
279 &coverage::InstrumentCoverage,
283 let promoted = promote_pass.promoted_fragments.into_inner();
284 (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
287 /// Compute the MIR that is used during CTFE (and thus has no optimizations run on it)
288 fn mir_for_ctfe<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Body<'tcx> {
289 let did = def_id.expect_local();
290 if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
291 tcx.mir_for_ctfe_of_const_arg(def)
293 tcx.arena.alloc(inner_mir_for_ctfe(tcx, ty::WithOptConstParam::unknown(did)))
297 /// Same as `mir_for_ctfe`, but used to get the MIR of a const generic parameter.
298 /// The docs on `WithOptConstParam` explain this a bit more, but the TLDR is that
299 /// we'd get cycle errors with `mir_for_ctfe`, because typeck would need to typeck
300 /// the const parameter while type checking the main body, which in turn would try
301 /// to type check the main body again.
302 fn mir_for_ctfe_of_const_arg<'tcx>(
304 (did, param_did): (LocalDefId, DefId),
305 ) -> &'tcx Body<'tcx> {
306 tcx.arena.alloc(inner_mir_for_ctfe(
308 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
312 fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
313 // FIXME: don't duplicate this between the optimized_mir/mir_for_ctfe queries
314 if tcx.is_constructor(def.did.to_def_id()) {
315 // There's no reason to run all of the MIR passes on constructors when
316 // we can just output the MIR we want directly. This also saves const
317 // qualification and borrow checking the trouble of special casing
319 return shim::build_adt_ctor(tcx, def.did.to_def_id());
324 .body_const_context(def.did)
325 .expect("mir_for_ctfe should not be used for runtime functions");
327 let mut body = tcx.mir_drops_elaborated_and_const_checked(def).borrow().clone();
330 // Do not const prop functions, either they get executed at runtime or exported to metadata,
331 // so we run const prop on them, or they don't, in which case we const evaluate some control
332 // flow paths of the function and any errors in those paths will get emitted as const eval
334 hir::ConstContext::ConstFn => {}
335 // Static items always get evaluated, so we can just let const eval see if any erroneous
336 // control flow paths get executed.
337 hir::ConstContext::Static(_) => {}
338 // Associated constants get const prop run so we detect common failure situations in the
339 // crate that defined the constant.
340 // Technically we want to not run on regular const items, but oli-obk doesn't know how to
341 // conveniently detect that at this point without looking at the HIR.
342 hir::ConstContext::Const => {
346 &[&const_prop::ConstProp, &marker::PhaseChange(MirPhase::Optimized)],
351 debug_assert!(!body.has_free_regions(), "Free regions in MIR for CTFE");
356 /// Obtain just the main MIR (no promoteds) and run some cleanups on it. This also runs
357 /// mir borrowck *before* doing so in order to ensure that borrowck can be run and doesn't
358 /// end up missing the source MIR due to stealing happening.
359 fn mir_drops_elaborated_and_const_checked<'tcx>(
361 def: ty::WithOptConstParam<LocalDefId>,
362 ) -> &'tcx Steal<Body<'tcx>> {
363 if let Some(def) = def.try_upgrade(tcx) {
364 return tcx.mir_drops_elaborated_and_const_checked(def);
367 let mir_borrowck = tcx.mir_borrowck_opt_const_arg(def);
369 let is_fn_like = tcx.def_kind(def.did).is_fn_like();
371 let did = def.did.to_def_id();
372 let def = ty::WithOptConstParam::unknown(did);
374 // Do not compute the mir call graph without said call graph actually being used.
375 if inline::Inline.is_enabled(&tcx.sess) {
376 let _ = tcx.mir_inliner_callees(ty::InstanceDef::Item(def));
380 let (body, _) = tcx.mir_promoted(def);
381 let mut body = body.steal();
382 if let Some(error_reported) = mir_borrowck.tainted_by_errors {
383 body.tainted_by_errors = Some(error_reported);
387 pm::run_passes(tcx, &mut body, &[&remove_false_edges::RemoveFalseEdges]);
389 // Do a little drop elaboration before const-checking if `const_precise_live_drops` is enabled.
390 if check_consts::post_drop_elaboration::checking_enabled(&ConstCx::new(tcx, &body)) {
395 &simplify::SimplifyCfg::new("remove-false-edges"),
396 &remove_uninit_drops::RemoveUninitDrops,
399 check_consts::post_drop_elaboration::check_live_drops(tcx, &body); // FIXME: make this a MIR lint
402 run_post_borrowck_cleanup_passes(tcx, &mut body);
403 assert!(body.phase == MirPhase::Deaggregated);
404 tcx.alloc_steal_mir(body)
407 /// After this series of passes, no lifetime analysis based on borrowing can be done.
408 fn run_post_borrowck_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
409 debug!("post_borrowck_cleanup({:?})", body.source.def_id());
411 let post_borrowck_cleanup: &[&dyn MirPass<'tcx>] = &[
412 // Remove all things only needed by analysis
413 &simplify_branches::SimplifyConstCondition::new("initial"),
414 &remove_noop_landing_pads::RemoveNoopLandingPads,
415 &cleanup_post_borrowck::CleanupNonCodegenStatements,
416 &simplify::SimplifyCfg::new("early-opt"),
417 // These next passes must be executed together
418 &add_call_guards::CriticalCallEdges,
419 &elaborate_drops::ElaborateDrops,
420 // This will remove extraneous landing pads which are no longer
421 // necessary as well as well as forcing any call in a non-unwinding
422 // function calling a possibly-unwinding function to abort the process.
423 &abort_unwinding_calls::AbortUnwindingCalls,
424 // AddMovesForPackedDrops needs to run after drop
426 &add_moves_for_packed_drops::AddMovesForPackedDrops,
427 // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
428 // but before optimizations begin.
429 &add_retag::AddRetag,
430 &lower_intrinsics::LowerIntrinsics,
431 &simplify::SimplifyCfg::new("elaborate-drops"),
432 // `Deaggregator` is conceptually part of MIR building, some backends rely on it happening
433 // and it can help optimizations.
434 &deaggregator::Deaggregator,
435 &deref_separator::Derefer,
436 &Lint(const_prop_lint::ConstProp),
439 pm::run_passes(tcx, body, post_borrowck_cleanup);
442 fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
443 fn o1<T>(x: T) -> WithMinOptLevel<T> {
444 WithMinOptLevel(1, x)
447 // Lowering generator control-flow and variables has to happen before we do anything else
448 // to them. We run some optimizations before that, because they may be harder to do on the state
449 // machine than on MIR with async primitives.
454 &reveal_all::RevealAll, // has to be done before inlining, since inlined code is in RevealAll mode.
455 &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
456 &normalize_array_len::NormalizeArrayLen, // has to run after `slice::len` lowering
457 &unreachable_prop::UnreachablePropagation,
458 &uninhabited_enum_branching::UninhabitedEnumBranching,
459 &o1(simplify::SimplifyCfg::new("after-uninhabited-enum-branching")),
461 &generator::StateTransform,
465 assert!(body.phase == MirPhase::GeneratorsLowered);
467 // The main optimizations that we do on MIR.
472 &remove_storage_markers::RemoveStorageMarkers,
473 &remove_zsts::RemoveZsts,
474 &const_goto::ConstGoto,
475 &remove_unneeded_drops::RemoveUnneededDrops,
476 &match_branches::MatchBranchSimplification,
477 // inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
478 &multiple_return_terminators::MultipleReturnTerminators,
479 &instcombine::InstCombine,
480 &separate_const_switch::SeparateConstSwitch,
482 // FIXME(#70073): This pass is responsible for both optimization as well as some lints.
483 &const_prop::ConstProp,
485 // Const-prop runs unconditionally, but doesn't mutate the MIR at mir-opt-level=0.
486 &o1(simplify_branches::SimplifyConstCondition::new("after-const-prop")),
487 &early_otherwise_branch::EarlyOtherwiseBranch,
488 &simplify_comparison_integral::SimplifyComparisonIntegral,
489 &simplify_try::SimplifyArmIdentity,
490 &simplify_try::SimplifyBranchSame,
491 &dest_prop::DestinationPropagation,
492 &o1(simplify_branches::SimplifyConstCondition::new("final")),
493 &o1(remove_noop_landing_pads::RemoveNoopLandingPads),
494 &o1(simplify::SimplifyCfg::new("final")),
495 &nrvo::RenameReturnPlace,
496 &const_debuginfo::ConstDebugInfo,
497 &simplify::SimplifyLocals,
498 &multiple_return_terminators::MultipleReturnTerminators,
499 &deduplicate_blocks::DeduplicateBlocks,
500 // Some cleanup necessary at least for LLVM and potentially other codegen backends.
501 &add_call_guards::CriticalCallEdges,
502 &marker::PhaseChange(MirPhase::Optimized),
503 // Dump the end result for testing and debugging purposes.
504 &dump_mir::Marker("PreCodegen"),
509 /// Optimize the MIR and prepare it for codegen.
510 fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> {
511 let did = did.expect_local();
512 assert_eq!(ty::WithOptConstParam::try_lookup(did, tcx), None);
513 tcx.arena.alloc(inner_optimized_mir(tcx, did))
516 fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
517 if tcx.is_constructor(did.to_def_id()) {
518 // There's no reason to run all of the MIR passes on constructors when
519 // we can just output the MIR we want directly. This also saves const
520 // qualification and borrow checking the trouble of special casing
522 return shim::build_adt_ctor(tcx, did.to_def_id());
525 match tcx.hir().body_const_context(did) {
526 // Run the `mir_for_ctfe` query, which depends on `mir_drops_elaborated_and_const_checked`
527 // which we are going to steal below. Thus we need to run `mir_for_ctfe` first, so it
528 // computes and caches its result.
529 Some(hir::ConstContext::ConstFn) => tcx.ensure().mir_for_ctfe(did),
531 Some(other) => panic!("do not use `optimized_mir` for constants: {:?}", other),
534 tcx.mir_drops_elaborated_and_const_checked(ty::WithOptConstParam::unknown(did)).steal();
535 run_optimization_passes(tcx, &mut body);
537 debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR");
542 /// Fetch all the promoteds of an item and prepare their MIR bodies to be ready for
543 /// constant evaluation once all substitutions become known.
544 fn promoted_mir<'tcx>(
546 def: ty::WithOptConstParam<LocalDefId>,
547 ) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
548 if tcx.is_constructor(def.did.to_def_id()) {
549 return tcx.arena.alloc(IndexVec::new());
552 let tainted_by_errors = tcx.mir_borrowck_opt_const_arg(def).tainted_by_errors;
553 let mut promoted = tcx.mir_promoted(def).1.steal();
555 for body in &mut promoted {
556 if let Some(error_reported) = tainted_by_errors {
557 body.tainted_by_errors = Some(error_reported);
559 run_post_borrowck_cleanup_passes(tcx, body);
562 debug_assert!(!promoted.has_free_regions(), "Free regions in promoted MIR");
564 tcx.arena.alloc(promoted)