]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/lib.rs
Rollup merge of #93400 - ChayimFriedman2:dont-suggest-using-const-with-bounds-unused...
[rust.git] / compiler / rustc_mir_transform / src / lib.rs
1 #![feature(box_patterns)]
2 #![feature(box_syntax)]
3 #![feature(crate_visibility_modifier)]
4 #![feature(let_else)]
5 #![feature(map_try_insert)]
6 #![feature(min_specialization)]
7 #![feature(option_get_or_insert_default)]
8 #![feature(once_cell)]
9 #![feature(never_type)]
10 #![feature(trusted_step)]
11 #![feature(try_blocks)]
12 #![recursion_limit = "256"]
13 #![allow(rustc::potential_query_instability)]
14
15 #[macro_use]
16 extern crate tracing;
17 #[macro_use]
18 extern crate rustc_middle;
19
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;
24 use rustc_hir as hir;
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};
33
34 #[macro_use]
35 mod pass_manager;
36
37 use pass_manager::{self as pm, Lint, MirLint, WithMinOptLevel};
38
39 mod abort_unwinding_calls;
40 mod add_call_guards;
41 mod add_moves_for_packed_drops;
42 mod add_retag;
43 mod check_const_item_mutation;
44 mod check_packed_ref;
45 pub mod check_unsafety;
46 // This pass is public to allow external drivers to perform MIR cleanup
47 pub mod cleanup_post_borrowck;
48 mod const_debuginfo;
49 mod const_goto;
50 mod const_prop;
51 mod coverage;
52 mod deaggregator;
53 mod deduplicate_blocks;
54 mod dest_prop;
55 pub mod dump_mir;
56 mod early_otherwise_branch;
57 mod elaborate_drops;
58 mod function_item_references;
59 mod generator;
60 mod inline;
61 mod instcombine;
62 mod lower_intrinsics;
63 mod lower_slice_len;
64 mod marker;
65 mod match_branches;
66 mod multiple_return_terminators;
67 mod normalize_array_len;
68 mod nrvo;
69 // This pass is public to allow external drivers to perform MIR cleanup
70 pub mod remove_false_edges;
71 mod remove_noop_landing_pads;
72 mod remove_storage_markers;
73 mod remove_uninit_drops;
74 mod remove_unneeded_drops;
75 mod remove_zsts;
76 mod required_consts;
77 mod reveal_all;
78 mod separate_const_switch;
79 mod shim;
80 // This pass is public to allow external drivers to perform MIR cleanup
81 pub mod simplify;
82 mod simplify_branches;
83 mod simplify_comparison_integral;
84 mod simplify_try;
85 mod uninhabited_enum_branching;
86 mod unreachable_prop;
87
88 use rustc_const_eval::transform::check_consts::{self, ConstCx};
89 use rustc_const_eval::transform::promote_consts;
90 use rustc_const_eval::transform::validate;
91 use rustc_mir_dataflow::rustc_peek;
92
93 pub fn provide(providers: &mut Providers) {
94     check_unsafety::provide(providers);
95     check_packed_ref::provide(providers);
96     coverage::query::provide(providers);
97     shim::provide(providers);
98     *providers = Providers {
99         mir_keys,
100         mir_const,
101         mir_const_qualif: |tcx, def_id| {
102             let def_id = def_id.expect_local();
103             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
104                 tcx.mir_const_qualif_const_arg(def)
105             } else {
106                 mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
107             }
108         },
109         mir_const_qualif_const_arg: |tcx, (did, param_did)| {
110             mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
111         },
112         mir_promoted,
113         mir_drops_elaborated_and_const_checked,
114         mir_for_ctfe,
115         mir_for_ctfe_of_const_arg,
116         optimized_mir,
117         is_mir_available,
118         is_ctfe_mir_available: |tcx, did| is_mir_available(tcx, did),
119         mir_callgraph_reachable: inline::cycle::mir_callgraph_reachable,
120         mir_inliner_callees: inline::cycle::mir_inliner_callees,
121         promoted_mir: |tcx, def_id| {
122             let def_id = def_id.expect_local();
123             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
124                 tcx.promoted_mir_of_const_arg(def)
125             } else {
126                 promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
127             }
128         },
129         promoted_mir_of_const_arg: |tcx, (did, param_did)| {
130             promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
131         },
132         ..*providers
133     };
134 }
135
136 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
137     let def_id = def_id.expect_local();
138     tcx.mir_keys(()).contains(&def_id)
139 }
140
141 /// Finds the full set of `DefId`s within the current crate that have
142 /// MIR associated with them.
143 fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet<LocalDefId> {
144     let mut set = FxIndexSet::default();
145
146     // All body-owners have MIR associated with them.
147     set.extend(tcx.hir().body_owners());
148
149     // Additionally, tuple struct/variant constructors have MIR, but
150     // they don't have a BodyId, so we need to build them separately.
151     struct GatherCtors<'a, 'tcx> {
152         tcx: TyCtxt<'tcx>,
153         set: &'a mut FxIndexSet<LocalDefId>,
154     }
155     impl<'tcx> Visitor<'tcx> for GatherCtors<'_, 'tcx> {
156         fn visit_variant_data(
157             &mut self,
158             v: &'tcx hir::VariantData<'tcx>,
159             _: Symbol,
160             _: &'tcx hir::Generics<'tcx>,
161             _: hir::HirId,
162             _: Span,
163         ) {
164             if let hir::VariantData::Tuple(_, hir_id) = *v {
165                 self.set.insert(self.tcx.hir().local_def_id(hir_id));
166             }
167             intravisit::walk_struct_def(self, v)
168         }
169     }
170     tcx.hir().visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
171
172     set
173 }
174
175 fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
176     let const_kind = tcx.hir().body_const_context(def.did);
177
178     // No need to const-check a non-const `fn`.
179     if const_kind.is_none() {
180         return Default::default();
181     }
182
183     // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
184     // cannot yet be stolen), because `mir_promoted()`, which steals
185     // from `mir_const(), forces this query to execute before
186     // performing the steal.
187     let body = &tcx.mir_const(def).borrow();
188
189     if body.return_ty().references_error() {
190         tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
191         return Default::default();
192     }
193
194     let ccx = check_consts::ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def.did) };
195
196     let mut validator = check_consts::check::Checker::new(&ccx);
197     validator.check_body();
198
199     // We return the qualifs in the return place for every MIR body, even though it is only used
200     // when deciding to promote a reference to a `const` for now.
201     validator.qualifs_in_return_place()
202 }
203
204 /// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
205 fn mir_const<'tcx>(
206     tcx: TyCtxt<'tcx>,
207     def: ty::WithOptConstParam<LocalDefId>,
208 ) -> &'tcx Steal<Body<'tcx>> {
209     if let Some(def) = def.try_upgrade(tcx) {
210         return tcx.mir_const(def);
211     }
212
213     // Unsafety check uses the raw mir, so make sure it is run.
214     if !tcx.sess.opts.debugging_opts.thir_unsafeck {
215         if let Some(param_did) = def.const_param_did {
216             tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did));
217         } else {
218             tcx.ensure().unsafety_check_result(def.did);
219         }
220     }
221
222     let mut body = tcx.mir_built(def).steal();
223
224     rustc_middle::mir::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(()));
225
226     pm::run_passes(
227         tcx,
228         &mut body,
229         &[
230             // MIR-level lints.
231             &Lint(check_packed_ref::CheckPackedRef),
232             &Lint(check_const_item_mutation::CheckConstItemMutation),
233             &Lint(function_item_references::FunctionItemReferences),
234             // What we need to do constant evaluation.
235             &simplify::SimplifyCfg::new("initial"),
236             &rustc_peek::SanityCheck, // Just a lint
237             &marker::PhaseChange(MirPhase::Const),
238         ],
239     );
240     tcx.alloc_steal_mir(body)
241 }
242
243 /// Compute the main MIR body and the list of MIR bodies of the promoteds.
244 fn mir_promoted<'tcx>(
245     tcx: TyCtxt<'tcx>,
246     def: ty::WithOptConstParam<LocalDefId>,
247 ) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
248     if let Some(def) = def.try_upgrade(tcx) {
249         return tcx.mir_promoted(def);
250     }
251
252     // Ensure that we compute the `mir_const_qualif` for constants at
253     // this point, before we steal the mir-const result.
254     // Also this means promotion can rely on all const checks having been done.
255     let const_qualifs = tcx.mir_const_qualif_opt_const_arg(def);
256     let mut body = tcx.mir_const(def).steal();
257     if let Some(error_reported) = const_qualifs.tainted_by_errors {
258         body.tainted_by_errors = Some(error_reported);
259     }
260
261     let mut required_consts = Vec::new();
262     let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
263     for (bb, bb_data) in traversal::reverse_postorder(&body) {
264         required_consts_visitor.visit_basic_block_data(bb, bb_data);
265     }
266     body.required_consts = required_consts;
267
268     // What we need to run borrowck etc.
269     let promote_pass = promote_consts::PromoteTemps::default();
270     pm::run_passes(
271         tcx,
272         &mut body,
273         &[
274             &promote_pass,
275             &simplify::SimplifyCfg::new("promote-consts"),
276             &coverage::InstrumentCoverage,
277         ],
278     );
279
280     let promoted = promote_pass.promoted_fragments.into_inner();
281     (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
282 }
283
284 /// Compute the MIR that is used during CTFE (and thus has no optimizations run on it)
285 fn mir_for_ctfe<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Body<'tcx> {
286     let did = def_id.expect_local();
287     if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
288         tcx.mir_for_ctfe_of_const_arg(def)
289     } else {
290         tcx.arena.alloc(inner_mir_for_ctfe(tcx, ty::WithOptConstParam::unknown(did)))
291     }
292 }
293
294 /// Same as `mir_for_ctfe`, but used to get the MIR of a const generic parameter.
295 /// The docs on `WithOptConstParam` explain this a bit more, but the TLDR is that
296 /// we'd get cycle errors with `mir_for_ctfe`, because typeck would need to typeck
297 /// the const parameter while type checking the main body, which in turn would try
298 /// to type check the main body again.
299 fn mir_for_ctfe_of_const_arg<'tcx>(
300     tcx: TyCtxt<'tcx>,
301     (did, param_did): (LocalDefId, DefId),
302 ) -> &'tcx Body<'tcx> {
303     tcx.arena.alloc(inner_mir_for_ctfe(
304         tcx,
305         ty::WithOptConstParam { did, const_param_did: Some(param_did) },
306     ))
307 }
308
309 fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
310     // FIXME: don't duplicate this between the optimized_mir/mir_for_ctfe queries
311     if tcx.is_constructor(def.did.to_def_id()) {
312         // There's no reason to run all of the MIR passes on constructors when
313         // we can just output the MIR we want directly. This also saves const
314         // qualification and borrow checking the trouble of special casing
315         // constructors.
316         return shim::build_adt_ctor(tcx, def.did.to_def_id());
317     }
318
319     let context = tcx
320         .hir()
321         .body_const_context(def.did)
322         .expect("mir_for_ctfe should not be used for runtime functions");
323
324     let mut body = tcx.mir_drops_elaborated_and_const_checked(def).borrow().clone();
325
326     match context {
327         // Do not const prop functions, either they get executed at runtime or exported to metadata,
328         // so we run const prop on them, or they don't, in which case we const evaluate some control
329         // flow paths of the function and any errors in those paths will get emitted as const eval
330         // errors.
331         hir::ConstContext::ConstFn => {}
332         // Static items always get evaluated, so we can just let const eval see if any erroneous
333         // control flow paths get executed.
334         hir::ConstContext::Static(_) => {}
335         // Associated constants get const prop run so we detect common failure situations in the
336         // crate that defined the constant.
337         // Technically we want to not run on regular const items, but oli-obk doesn't know how to
338         // conveniently detect that at this point without looking at the HIR.
339         hir::ConstContext::Const => {
340             pm::run_passes(
341                 tcx,
342                 &mut body,
343                 &[&const_prop::ConstProp, &marker::PhaseChange(MirPhase::Optimization)],
344             );
345         }
346     }
347
348     debug_assert!(!body.has_free_regions(), "Free regions in MIR for CTFE");
349
350     body
351 }
352
353 /// Obtain just the main MIR (no promoteds) and run some cleanups on it. This also runs
354 /// mir borrowck *before* doing so in order to ensure that borrowck can be run and doesn't
355 /// end up missing the source MIR due to stealing happening.
356 fn mir_drops_elaborated_and_const_checked<'tcx>(
357     tcx: TyCtxt<'tcx>,
358     def: ty::WithOptConstParam<LocalDefId>,
359 ) -> &'tcx Steal<Body<'tcx>> {
360     if let Some(def) = def.try_upgrade(tcx) {
361         return tcx.mir_drops_elaborated_and_const_checked(def);
362     }
363
364     let mir_borrowck = tcx.mir_borrowck_opt_const_arg(def);
365
366     let is_fn_like = tcx.hir().get_by_def_id(def.did).fn_kind().is_some();
367     if is_fn_like {
368         let did = def.did.to_def_id();
369         let def = ty::WithOptConstParam::unknown(did);
370
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));
374         }
375     }
376
377     let (body, _) = tcx.mir_promoted(def);
378     let mut body = body.steal();
379     if let Some(error_reported) = mir_borrowck.tainted_by_errors {
380         body.tainted_by_errors = Some(error_reported);
381     }
382
383     // IMPORTANT
384     pm::run_passes(tcx, &mut body, &[&remove_false_edges::RemoveFalseEdges]);
385
386     // Do a little drop elaboration before const-checking if `const_precise_live_drops` is enabled.
387     if check_consts::post_drop_elaboration::checking_enabled(&ConstCx::new(tcx, &body)) {
388         pm::run_passes(
389             tcx,
390             &mut body,
391             &[
392                 &simplify::SimplifyCfg::new("remove-false-edges"),
393                 &remove_uninit_drops::RemoveUninitDrops,
394             ],
395         );
396         check_consts::post_drop_elaboration::check_live_drops(tcx, &body); // FIXME: make this a MIR lint
397     }
398
399     run_post_borrowck_cleanup_passes(tcx, &mut body);
400     assert!(body.phase == MirPhase::DropLowering);
401     tcx.alloc_steal_mir(body)
402 }
403
404 /// After this series of passes, no lifetime analysis based on borrowing can be done.
405 fn run_post_borrowck_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
406     debug!("post_borrowck_cleanup({:?})", body.source.def_id());
407
408     let post_borrowck_cleanup: &[&dyn MirPass<'tcx>] = &[
409         // Remove all things only needed by analysis
410         &simplify_branches::SimplifyConstCondition::new("initial"),
411         &remove_noop_landing_pads::RemoveNoopLandingPads,
412         &cleanup_post_borrowck::CleanupNonCodegenStatements,
413         &simplify::SimplifyCfg::new("early-opt"),
414         // These next passes must be executed together
415         &add_call_guards::CriticalCallEdges,
416         &elaborate_drops::ElaborateDrops,
417         // This will remove extraneous landing pads which are no longer
418         // necessary as well as well as forcing any call in a non-unwinding
419         // function calling a possibly-unwinding function to abort the process.
420         &abort_unwinding_calls::AbortUnwindingCalls,
421         // AddMovesForPackedDrops needs to run after drop
422         // elaboration.
423         &add_moves_for_packed_drops::AddMovesForPackedDrops,
424         // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
425         // but before optimizations begin.
426         &add_retag::AddRetag,
427         &lower_intrinsics::LowerIntrinsics,
428         &simplify::SimplifyCfg::new("elaborate-drops"),
429         // `Deaggregator` is conceptually part of MIR building, some backends rely on it happening
430         // and it can help optimizations.
431         &deaggregator::Deaggregator,
432     ];
433
434     pm::run_passes(tcx, body, post_borrowck_cleanup);
435 }
436
437 fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
438     fn o1<T>(x: T) -> WithMinOptLevel<T> {
439         WithMinOptLevel(1, x)
440     }
441
442     // Lowering generator control-flow and variables has to happen before we do anything else
443     // to them. We run some optimizations before that, because they may be harder to do on the state
444     // machine than on MIR with async primitives.
445     pm::run_passes(
446         tcx,
447         body,
448         &[
449             &reveal_all::RevealAll, // has to be done before inlining, since inlined code is in RevealAll mode.
450             &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
451             &normalize_array_len::NormalizeArrayLen, // has to run after `slice::len` lowering
452             &unreachable_prop::UnreachablePropagation,
453             &uninhabited_enum_branching::UninhabitedEnumBranching,
454             &o1(simplify::SimplifyCfg::new("after-uninhabited-enum-branching")),
455             &inline::Inline,
456             &generator::StateTransform,
457         ],
458     );
459
460     assert!(body.phase == MirPhase::GeneratorLowering);
461
462     // The main optimizations that we do on MIR.
463     pm::run_passes(
464         tcx,
465         body,
466         &[
467             &remove_storage_markers::RemoveStorageMarkers,
468             &remove_zsts::RemoveZsts,
469             &const_goto::ConstGoto,
470             &remove_unneeded_drops::RemoveUnneededDrops,
471             &match_branches::MatchBranchSimplification,
472             // inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
473             &multiple_return_terminators::MultipleReturnTerminators,
474             &instcombine::InstCombine,
475             &separate_const_switch::SeparateConstSwitch,
476             //
477             // FIXME(#70073): This pass is responsible for both optimization as well as some lints.
478             &const_prop::ConstProp,
479             //
480             // Const-prop runs unconditionally, but doesn't mutate the MIR at mir-opt-level=0.
481             &o1(simplify_branches::SimplifyConstCondition::new("after-const-prop")),
482             &early_otherwise_branch::EarlyOtherwiseBranch,
483             &simplify_comparison_integral::SimplifyComparisonIntegral,
484             &simplify_try::SimplifyArmIdentity,
485             &simplify_try::SimplifyBranchSame,
486             &dest_prop::DestinationPropagation,
487             &o1(simplify_branches::SimplifyConstCondition::new("final")),
488             &o1(remove_noop_landing_pads::RemoveNoopLandingPads),
489             &o1(simplify::SimplifyCfg::new("final")),
490             &nrvo::RenameReturnPlace,
491             &const_debuginfo::ConstDebugInfo,
492             &simplify::SimplifyLocals,
493             &multiple_return_terminators::MultipleReturnTerminators,
494             &deduplicate_blocks::DeduplicateBlocks,
495             // Some cleanup necessary at least for LLVM and potentially other codegen backends.
496             &add_call_guards::CriticalCallEdges,
497             &marker::PhaseChange(MirPhase::Optimization),
498             // Dump the end result for testing and debugging purposes.
499             &dump_mir::Marker("PreCodegen"),
500         ],
501     );
502 }
503
504 /// Optimize the MIR and prepare it for codegen.
505 fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> {
506     let did = did.expect_local();
507     assert_eq!(ty::WithOptConstParam::try_lookup(did, tcx), None);
508     tcx.arena.alloc(inner_optimized_mir(tcx, did))
509 }
510
511 fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
512     if tcx.is_constructor(did.to_def_id()) {
513         // There's no reason to run all of the MIR passes on constructors when
514         // we can just output the MIR we want directly. This also saves const
515         // qualification and borrow checking the trouble of special casing
516         // constructors.
517         return shim::build_adt_ctor(tcx, did.to_def_id());
518     }
519
520     match tcx.hir().body_const_context(did) {
521         // Run the `mir_for_ctfe` query, which depends on `mir_drops_elaborated_and_const_checked`
522         // which we are going to steal below. Thus we need to run `mir_for_ctfe` first, so it
523         // computes and caches its result.
524         Some(hir::ConstContext::ConstFn) => tcx.ensure().mir_for_ctfe(did),
525         None => {}
526         Some(other) => panic!("do not use `optimized_mir` for constants: {:?}", other),
527     }
528     let mut body =
529         tcx.mir_drops_elaborated_and_const_checked(ty::WithOptConstParam::unknown(did)).steal();
530     run_optimization_passes(tcx, &mut body);
531
532     debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR");
533
534     body
535 }
536
537 /// Fetch all the promoteds of an item and prepare their MIR bodies to be ready for
538 /// constant evaluation once all substitutions become known.
539 fn promoted_mir<'tcx>(
540     tcx: TyCtxt<'tcx>,
541     def: ty::WithOptConstParam<LocalDefId>,
542 ) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
543     if tcx.is_constructor(def.did.to_def_id()) {
544         return tcx.arena.alloc(IndexVec::new());
545     }
546
547     let tainted_by_errors = tcx.mir_borrowck_opt_const_arg(def).tainted_by_errors;
548     let mut promoted = tcx.mir_promoted(def).1.steal();
549
550     for body in &mut promoted {
551         if let Some(error_reported) = tainted_by_errors {
552             body.tainted_by_errors = Some(error_reported);
553         }
554         run_post_borrowck_cleanup_passes(tcx, body);
555     }
556
557     debug_assert!(!promoted.has_free_regions(), "Free regions in promoted MIR");
558
559     tcx.arena.alloc(promoted)
560 }