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