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