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