]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/transform/mod.rs
Auto merge of #78864 - Mark-Simulacrum:warn-on-forbids, r=pnkfelix
[rust.git] / compiler / rustc_mir / src / transform / mod.rs
1 use crate::{shim, util};
2 use required_consts::RequiredConstsVisitor;
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_data_structures::steal::Steal;
5 use rustc_hir as hir;
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};
14 use std::borrow::Cow;
15
16 pub mod add_call_guards;
17 pub mod add_moves_for_packed_drops;
18 pub mod add_retag;
19 pub mod check_const_item_mutation;
20 pub mod check_consts;
21 pub mod check_packed_ref;
22 pub mod check_unsafety;
23 pub mod cleanup_post_borrowck;
24 pub mod const_prop;
25 pub mod coverage;
26 pub mod deaggregator;
27 pub mod dest_prop;
28 pub mod dump_mir;
29 pub mod early_otherwise_branch;
30 pub mod elaborate_drops;
31 pub mod function_item_references;
32 pub mod generator;
33 pub mod inline;
34 pub mod instcombine;
35 pub mod lower_intrinsics;
36 pub mod match_branches;
37 pub mod multiple_return_terminators;
38 pub mod no_landing_pads;
39 pub mod nrvo;
40 pub mod promote_consts;
41 pub mod remove_noop_landing_pads;
42 pub mod remove_unneeded_drops;
43 pub mod required_consts;
44 pub mod rustc_peek;
45 pub mod simplify;
46 pub mod simplify_branches;
47 pub mod simplify_comparison_integral;
48 pub mod simplify_try;
49 pub mod uninhabited_enum_branching;
50 pub mod unreachable_prop;
51 pub mod validate;
52
53 pub use rustc_middle::mir::MirSource;
54
55 pub(crate) fn provide(providers: &mut Providers) {
56     self::check_unsafety::provide(providers);
57     *providers = Providers {
58         mir_keys,
59         mir_const,
60         mir_const_qualif: |tcx, def_id| {
61             let def_id = def_id.expect_local();
62             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
63                 tcx.mir_const_qualif_const_arg(def)
64             } else {
65                 mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
66             }
67         },
68         mir_const_qualif_const_arg: |tcx, (did, param_did)| {
69             mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
70         },
71         mir_promoted,
72         mir_drops_elaborated_and_const_checked,
73         optimized_mir,
74         optimized_mir_of_const_arg,
75         is_mir_available,
76         promoted_mir: |tcx, def_id| {
77             let def_id = def_id.expect_local();
78             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
79                 tcx.promoted_mir_of_const_arg(def)
80             } else {
81                 promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
82             }
83         },
84         promoted_mir_of_const_arg: |tcx, (did, param_did)| {
85             promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
86         },
87         ..*providers
88     };
89     coverage::query::provide(providers);
90 }
91
92 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
93     tcx.mir_keys(def_id.krate).contains(&def_id.expect_local())
94 }
95
96 /// Finds the full set of `DefId`s within the current crate that have
97 /// MIR associated with them.
98 fn mir_keys(tcx: TyCtxt<'_>, krate: CrateNum) -> FxHashSet<LocalDefId> {
99     assert_eq!(krate, LOCAL_CRATE);
100
101     let mut set = FxHashSet::default();
102
103     // All body-owners have MIR associated with them.
104     set.extend(tcx.body_owners());
105
106     // Additionally, tuple struct/variant constructors have MIR, but
107     // they don't have a BodyId, so we need to build them separately.
108     struct GatherCtors<'a, 'tcx> {
109         tcx: TyCtxt<'tcx>,
110         set: &'a mut FxHashSet<LocalDefId>,
111     }
112     impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
113         fn visit_variant_data(
114             &mut self,
115             v: &'tcx hir::VariantData<'tcx>,
116             _: Symbol,
117             _: &'tcx hir::Generics<'tcx>,
118             _: hir::HirId,
119             _: Span,
120         ) {
121             if let hir::VariantData::Tuple(_, hir_id) = *v {
122                 self.set.insert(self.tcx.hir().local_def_id(hir_id));
123             }
124             intravisit::walk_struct_def(self, v)
125         }
126         type Map = intravisit::ErasedMap<'tcx>;
127         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
128             NestedVisitorMap::None
129         }
130     }
131     tcx.hir()
132         .krate()
133         .visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
134
135     set
136 }
137
138 /// Generates a default name for the pass based on the name of the
139 /// type `T`.
140 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
141     let name = std::any::type_name::<T>();
142     if let Some(tail) = name.rfind(':') { Cow::from(&name[tail + 1..]) } else { Cow::from(name) }
143 }
144
145 /// A streamlined trait that you can implement to create a pass; the
146 /// pass will be named after the type, and it will consist of a main
147 /// loop that goes over each available MIR and applies `run_pass`.
148 pub trait MirPass<'tcx> {
149     fn name(&self) -> Cow<'_, str> {
150         default_name::<Self>()
151     }
152
153     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
154 }
155
156 pub fn run_passes(
157     tcx: TyCtxt<'tcx>,
158     body: &mut Body<'tcx>,
159     mir_phase: MirPhase,
160     passes: &[&[&dyn MirPass<'tcx>]],
161 ) {
162     let phase_index = mir_phase.phase_index();
163     let validate = tcx.sess.opts.debugging_opts.validate_mir;
164
165     if body.phase >= mir_phase {
166         return;
167     }
168
169     if validate {
170         validate::Validator { when: format!("input to phase {:?}", mir_phase), mir_phase }
171             .run_pass(tcx, body);
172     }
173
174     let mut index = 0;
175     let mut run_pass = |pass: &dyn MirPass<'tcx>| {
176         let run_hooks = |body: &_, index, is_after| {
177             dump_mir::on_mir_pass(
178                 tcx,
179                 &format_args!("{:03}-{:03}", phase_index, index),
180                 &pass.name(),
181                 body,
182                 is_after,
183             );
184         };
185         run_hooks(body, index, false);
186         pass.run_pass(tcx, body);
187         run_hooks(body, index, true);
188
189         if validate {
190             validate::Validator {
191                 when: format!("after {} in phase {:?}", pass.name(), mir_phase),
192                 mir_phase,
193             }
194             .run_pass(tcx, body);
195         }
196
197         index += 1;
198     };
199
200     for pass_group in passes {
201         for pass in *pass_group {
202             run_pass(*pass);
203         }
204     }
205
206     body.phase = mir_phase;
207
208     if mir_phase == MirPhase::Optimization {
209         validate::Validator { when: format!("end of phase {:?}", mir_phase), mir_phase }
210             .run_pass(tcx, body);
211     }
212 }
213
214 fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
215     let const_kind = tcx.hir().body_const_context(def.did);
216
217     // No need to const-check a non-const `fn`.
218     if const_kind.is_none() {
219         return Default::default();
220     }
221
222     // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
223     // cannot yet be stolen), because `mir_promoted()`, which steals
224     // from `mir_const(), forces this query to execute before
225     // performing the steal.
226     let body = &tcx.mir_const(def).borrow();
227
228     if body.return_ty().references_error() {
229         tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
230         return Default::default();
231     }
232
233     let ccx = check_consts::ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def.did) };
234
235     let mut validator = check_consts::validation::Validator::new(&ccx);
236     validator.check_body();
237
238     // We return the qualifs in the return place for every MIR body, even though it is only used
239     // when deciding to promote a reference to a `const` for now.
240     validator.qualifs_in_return_place()
241 }
242
243 /// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
244 fn mir_const<'tcx>(
245     tcx: TyCtxt<'tcx>,
246     def: ty::WithOptConstParam<LocalDefId>,
247 ) -> &'tcx Steal<Body<'tcx>> {
248     if let Some(def) = def.try_upgrade(tcx) {
249         return tcx.mir_const(def);
250     }
251
252     // Unsafety check uses the raw mir, so make sure it is run.
253     if let Some(param_did) = def.const_param_did {
254         tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did));
255     } else {
256         tcx.ensure().unsafety_check_result(def.did);
257     }
258
259     let mut body = tcx.mir_built(def).steal();
260
261     util::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(()));
262
263     run_passes(
264         tcx,
265         &mut body,
266         MirPhase::Const,
267         &[&[
268             // MIR-level lints.
269             &check_packed_ref::CheckPackedRef,
270             &check_const_item_mutation::CheckConstItemMutation,
271             &function_item_references::FunctionItemReferences,
272             // What we need to do constant evaluation.
273             &simplify::SimplifyCfg::new("initial"),
274             &rustc_peek::SanityCheck,
275         ]],
276     );
277     tcx.alloc_steal_mir(body)
278 }
279
280 fn mir_promoted(
281     tcx: TyCtxt<'tcx>,
282     def: ty::WithOptConstParam<LocalDefId>,
283 ) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
284     if let Some(def) = def.try_upgrade(tcx) {
285         return tcx.mir_promoted(def);
286     }
287
288     // Ensure that we compute the `mir_const_qualif` for constants at
289     // this point, before we steal the mir-const result.
290     // Also this means promotion can rely on all const checks having been done.
291     let _ = tcx.mir_const_qualif_opt_const_arg(def);
292     let _ = tcx.mir_abstract_const_opt_const_arg(def.to_global());
293     let mut body = tcx.mir_const(def).steal();
294
295     let mut required_consts = Vec::new();
296     let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
297     for (bb, bb_data) in traversal::reverse_postorder(&body) {
298         required_consts_visitor.visit_basic_block_data(bb, bb_data);
299     }
300     body.required_consts = required_consts;
301
302     let promote_pass = promote_consts::PromoteTemps::default();
303     let promote: &[&dyn MirPass<'tcx>] = &[
304         // What we need to run borrowck etc.
305         &promote_pass,
306         &simplify::SimplifyCfg::new("promote-consts"),
307     ];
308
309     let opt_coverage: &[&dyn MirPass<'tcx>] = if tcx.sess.opts.debugging_opts.instrument_coverage {
310         &[&coverage::InstrumentCoverage]
311     } else {
312         &[]
313     };
314
315     run_passes(tcx, &mut body, MirPhase::ConstPromotion, &[promote, opt_coverage]);
316
317     let promoted = promote_pass.promoted_fragments.into_inner();
318     (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
319 }
320
321 fn mir_drops_elaborated_and_const_checked<'tcx>(
322     tcx: TyCtxt<'tcx>,
323     def: ty::WithOptConstParam<LocalDefId>,
324 ) -> &'tcx Steal<Body<'tcx>> {
325     if let Some(def) = def.try_upgrade(tcx) {
326         return tcx.mir_drops_elaborated_and_const_checked(def);
327     }
328
329     // (Mir-)Borrowck uses `mir_promoted`, so we have to force it to
330     // execute before we can steal.
331     if let Some(param_did) = def.const_param_did {
332         tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
333     } else {
334         tcx.ensure().mir_borrowck(def.did);
335     }
336
337     let (body, _) = tcx.mir_promoted(def);
338     let mut body = body.steal();
339
340     run_post_borrowck_cleanup_passes(tcx, &mut body);
341     check_consts::post_drop_elaboration::check_live_drops(tcx, &body);
342     tcx.alloc_steal_mir(body)
343 }
344
345 /// After this series of passes, no lifetime analysis based on borrowing can be done.
346 fn run_post_borrowck_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
347     debug!("post_borrowck_cleanup({:?})", body.source.def_id());
348
349     let post_borrowck_cleanup: &[&dyn MirPass<'tcx>] = &[
350         // Remove all things only needed by analysis
351         &no_landing_pads::NoLandingPads::new(tcx),
352         &simplify_branches::SimplifyBranches::new("initial"),
353         &remove_noop_landing_pads::RemoveNoopLandingPads,
354         &cleanup_post_borrowck::CleanupNonCodegenStatements,
355         &simplify::SimplifyCfg::new("early-opt"),
356         // These next passes must be executed together
357         &add_call_guards::CriticalCallEdges,
358         &elaborate_drops::ElaborateDrops,
359         &no_landing_pads::NoLandingPads::new(tcx),
360         // AddMovesForPackedDrops needs to run after drop
361         // elaboration.
362         &add_moves_for_packed_drops::AddMovesForPackedDrops,
363         // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
364         // but before optimizations begin.
365         &add_retag::AddRetag,
366         &simplify::SimplifyCfg::new("elaborate-drops"),
367         // `Deaggregator` is conceptually part of MIR building, some backends rely on it happening
368         // and it can help optimizations.
369         &deaggregator::Deaggregator,
370     ];
371
372     run_passes(tcx, body, MirPhase::DropLowering, &[post_borrowck_cleanup]);
373 }
374
375 fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
376     let mir_opt_level = tcx.sess.opts.debugging_opts.mir_opt_level;
377
378     // Lowering generator control-flow and variables has to happen before we do anything else
379     // to them. We run some optimizations before that, because they may be harder to do on the state
380     // machine than on MIR with async primitives.
381     let optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[
382         &unreachable_prop::UnreachablePropagation,
383         &uninhabited_enum_branching::UninhabitedEnumBranching,
384         &simplify::SimplifyCfg::new("after-uninhabited-enum-branching"),
385         &inline::Inline,
386         &generator::StateTransform,
387     ];
388
389     // Even if we don't do optimizations, we still have to lower generators for codegen.
390     let no_optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[&generator::StateTransform];
391
392     // The main optimizations that we do on MIR.
393     let optimizations: &[&dyn MirPass<'tcx>] = &[
394         &lower_intrinsics::LowerIntrinsics,
395         &remove_unneeded_drops::RemoveUnneededDrops,
396         &match_branches::MatchBranchSimplification,
397         // inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
398         &multiple_return_terminators::MultipleReturnTerminators,
399         &instcombine::InstCombine,
400         &const_prop::ConstProp,
401         &simplify_branches::SimplifyBranches::new("after-const-prop"),
402         &early_otherwise_branch::EarlyOtherwiseBranch,
403         &simplify_comparison_integral::SimplifyComparisonIntegral,
404         &simplify_try::SimplifyArmIdentity,
405         &simplify_try::SimplifyBranchSame,
406         &dest_prop::DestinationPropagation,
407         &simplify_branches::SimplifyBranches::new("final"),
408         &remove_noop_landing_pads::RemoveNoopLandingPads,
409         &simplify::SimplifyCfg::new("final"),
410         &nrvo::RenameReturnPlace,
411         &simplify::SimplifyLocals,
412         &multiple_return_terminators::MultipleReturnTerminators,
413     ];
414
415     // Optimizations to run even if mir optimizations have been disabled.
416     let no_optimizations: &[&dyn MirPass<'tcx>] = &[
417         // FIXME(#70073): This pass is responsible for both optimization as well as some lints.
418         &const_prop::ConstProp,
419     ];
420
421     // Some cleanup necessary at least for LLVM and potentially other codegen backends.
422     let pre_codegen_cleanup: &[&dyn MirPass<'tcx>] = &[
423         &add_call_guards::CriticalCallEdges,
424         // Dump the end result for testing and debugging purposes.
425         &dump_mir::Marker("PreCodegen"),
426     ];
427
428     // End of pass declarations, now actually run the passes.
429     // Generator Lowering
430     #[rustfmt::skip]
431     run_passes(
432         tcx,
433         body,
434         MirPhase::GeneratorLowering,
435         &[
436             if mir_opt_level > 0 {
437                 optimizations_with_generators
438             } else {
439                 no_optimizations_with_generators
440             }
441         ],
442     );
443
444     // Main optimization passes
445     #[rustfmt::skip]
446     run_passes(
447         tcx,
448         body,
449         MirPhase::Optimization,
450         &[
451             if mir_opt_level > 0 { optimizations } else { no_optimizations },
452             pre_codegen_cleanup,
453         ],
454     );
455 }
456
457 fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> {
458     let did = did.expect_local();
459     if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
460         tcx.optimized_mir_of_const_arg(def)
461     } else {
462         tcx.arena.alloc(inner_optimized_mir(tcx, ty::WithOptConstParam::unknown(did)))
463     }
464 }
465
466 fn optimized_mir_of_const_arg<'tcx>(
467     tcx: TyCtxt<'tcx>,
468     (did, param_did): (LocalDefId, DefId),
469 ) -> &'tcx Body<'tcx> {
470     tcx.arena.alloc(inner_optimized_mir(
471         tcx,
472         ty::WithOptConstParam { did, const_param_did: Some(param_did) },
473     ))
474 }
475
476 fn inner_optimized_mir(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
477     if tcx.is_constructor(def.did.to_def_id()) {
478         // There's no reason to run all of the MIR passes on constructors when
479         // we can just output the MIR we want directly. This also saves const
480         // qualification and borrow checking the trouble of special casing
481         // constructors.
482         return shim::build_adt_ctor(tcx, def.did.to_def_id());
483     }
484
485     let mut body = tcx.mir_drops_elaborated_and_const_checked(def).steal();
486     run_optimization_passes(tcx, &mut body);
487
488     debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR");
489
490     body
491 }
492
493 fn promoted_mir<'tcx>(
494     tcx: TyCtxt<'tcx>,
495     def: ty::WithOptConstParam<LocalDefId>,
496 ) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
497     if tcx.is_constructor(def.did.to_def_id()) {
498         return tcx.arena.alloc(IndexVec::new());
499     }
500
501     if let Some(param_did) = def.const_param_did {
502         tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
503     } else {
504         tcx.ensure().mir_borrowck(def.did);
505     }
506     let (_, promoted) = tcx.mir_promoted(def);
507     let mut promoted = promoted.steal();
508
509     for body in &mut promoted {
510         run_post_borrowck_cleanup_passes(tcx, body);
511         run_optimization_passes(tcx, body);
512     }
513
514     debug_assert!(!promoted.has_free_regions(), "Free regions in promoted MIR");
515
516     tcx.arena.alloc(promoted)
517 }