]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/mod.rs
Auto merge of #61891 - eddyb:lifetime-cleanups, r=oli-obk
[rust.git] / src / librustc_mir / transform / mod.rs
1 use crate::{build, shim};
2 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
3 use rustc::mir::{Body, MirPhase, Promoted};
4 use rustc::ty::{TyCtxt, InstanceDef};
5 use rustc::ty::query::Providers;
6 use rustc::ty::steal::Steal;
7 use rustc::hir;
8 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
9 use rustc::util::nodemap::DefIdSet;
10 use std::borrow::Cow;
11 use syntax::ast;
12 use syntax_pos::Span;
13
14 pub mod add_retag;
15 pub mod add_moves_for_packed_drops;
16 pub mod cleanup_post_borrowck;
17 pub mod check_unsafety;
18 pub mod simplify_branches;
19 pub mod simplify;
20 pub mod erase_regions;
21 pub mod no_landing_pads;
22 pub mod rustc_peek;
23 pub mod elaborate_drops;
24 pub mod add_call_guards;
25 pub mod promote_consts;
26 pub mod qualify_consts;
27 pub mod qualify_min_const_fn;
28 pub mod remove_noop_landing_pads;
29 pub mod dump_mir;
30 pub mod deaggregator;
31 pub mod instcombine;
32 pub mod copy_prop;
33 pub mod const_prop;
34 pub mod generator;
35 pub mod inline;
36 pub mod lower_128bit;
37 pub mod uniform_array_move_out;
38
39 pub(crate) fn provide(providers: &mut Providers<'_>) {
40     self::qualify_consts::provide(providers);
41     self::check_unsafety::provide(providers);
42     *providers = Providers {
43         mir_keys,
44         mir_built,
45         mir_const,
46         mir_validated,
47         optimized_mir,
48         is_mir_available,
49         ..*providers
50     };
51 }
52
53 fn is_mir_available<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
54     tcx.mir_keys(def_id.krate).contains(&def_id)
55 }
56
57 /// Finds the full set of `DefId`s within the current crate that have
58 /// MIR associated with them.
59 fn mir_keys<'tcx>(tcx: TyCtxt<'tcx>, krate: CrateNum) -> &'tcx DefIdSet {
60     assert_eq!(krate, LOCAL_CRATE);
61
62     let mut set = DefIdSet::default();
63
64     // All body-owners have MIR associated with them.
65     set.extend(tcx.body_owners());
66
67     // Additionally, tuple struct/variant constructors have MIR, but
68     // they don't have a BodyId, so we need to build them separately.
69     struct GatherCtors<'a, 'tcx> {
70         tcx: TyCtxt<'tcx>,
71         set: &'a mut DefIdSet,
72     }
73     impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
74         fn visit_variant_data(&mut self,
75                               v: &'tcx hir::VariantData,
76                               _: ast::Name,
77                               _: &'tcx hir::Generics,
78                               _: hir::HirId,
79                               _: Span) {
80             if let hir::VariantData::Tuple(_, hir_id) = *v {
81                 self.set.insert(self.tcx.hir().local_def_id_from_hir_id(hir_id));
82             }
83             intravisit::walk_struct_def(self, v)
84         }
85         fn nested_visit_map<'b>(&'b mut self) -> NestedVisitorMap<'b, 'tcx> {
86             NestedVisitorMap::None
87         }
88     }
89     tcx.hir().krate().visit_all_item_likes(&mut GatherCtors {
90         tcx,
91         set: &mut set,
92     }.as_deep_visitor());
93
94     tcx.arena.alloc(set)
95 }
96
97 fn mir_built<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Steal<Body<'tcx>> {
98     let mir = build::mir_build(tcx, def_id);
99     tcx.alloc_steal_mir(mir)
100 }
101
102 /// Where a specific `mir::Body` comes from.
103 #[derive(Debug, Copy, Clone)]
104 pub struct MirSource<'tcx> {
105     pub instance: InstanceDef<'tcx>,
106
107     /// If `Some`, this is a promoted rvalue within the parent function.
108     pub promoted: Option<Promoted>,
109 }
110
111 impl<'tcx> MirSource<'tcx> {
112     pub fn item(def_id: DefId) -> Self {
113         MirSource {
114             instance: InstanceDef::Item(def_id),
115             promoted: None
116         }
117     }
118
119     #[inline]
120     pub fn def_id(&self) -> DefId {
121         self.instance.def_id()
122     }
123 }
124
125 /// Generates a default name for the pass based on the name of the
126 /// type `T`.
127 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
128     let name = unsafe { ::std::intrinsics::type_name::<T>() };
129     if let Some(tail) = name.rfind(":") {
130         Cow::from(&name[tail+1..])
131     } else {
132         Cow::from(name)
133     }
134 }
135
136 /// A streamlined trait that you can implement to create a pass; the
137 /// pass will be named after the type, and it will consist of a main
138 /// loop that goes over each available MIR and applies `run_pass`.
139 pub trait MirPass {
140     fn name<'a>(&'a self) -> Cow<'a, str> {
141         default_name::<Self>()
142     }
143
144     fn run_pass<'tcx>(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>);
145 }
146
147 pub fn run_passes(
148     tcx: TyCtxt<'tcx>,
149     body: &mut Body<'tcx>,
150     instance: InstanceDef<'tcx>,
151     mir_phase: MirPhase,
152     passes: &[&dyn MirPass],
153 ) {
154     let phase_index = mir_phase.phase_index();
155
156     let run_passes = |body: &mut Body<'tcx>, promoted| {
157         if body.phase >= mir_phase {
158             return;
159         }
160
161         let source = MirSource {
162             instance,
163             promoted,
164         };
165         let mut index = 0;
166         let mut run_pass = |pass: &dyn MirPass| {
167             let run_hooks = |body: &_, index, is_after| {
168                 dump_mir::on_mir_pass(tcx, &format_args!("{:03}-{:03}", phase_index, index),
169                                       &pass.name(), source, body, is_after);
170             };
171             run_hooks(body, index, false);
172             pass.run_pass(tcx, source, body);
173             run_hooks(body, index, true);
174
175             index += 1;
176         };
177
178         for pass in passes {
179             run_pass(*pass);
180         }
181
182         body.phase = mir_phase;
183     };
184
185     run_passes(body, None);
186
187     for (index, promoted_body) in body.promoted.iter_enumerated_mut() {
188         run_passes(promoted_body, Some(index));
189
190         //Let's make sure we don't miss any nested instances
191         assert!(promoted_body.promoted.is_empty())
192     }
193 }
194
195 fn mir_const<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Steal<Body<'tcx>> {
196     // Unsafety check uses the raw mir, so make sure it is run
197     let _ = tcx.unsafety_check_result(def_id);
198
199     let mut body = tcx.mir_built(def_id).steal();
200     run_passes(tcx, &mut body, InstanceDef::Item(def_id), MirPhase::Const, &[
201         // What we need to do constant evaluation.
202         &simplify::SimplifyCfg::new("initial"),
203         &rustc_peek::SanityCheck,
204         &uniform_array_move_out::UniformArrayMoveOut,
205     ]);
206     tcx.alloc_steal_mir(body)
207 }
208
209 fn mir_validated(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Steal<Body<'tcx>> {
210     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
211     if let hir::BodyOwnerKind::Const = tcx.hir().body_owner_kind(hir_id) {
212         // Ensure that we compute the `mir_const_qualif` for constants at
213         // this point, before we steal the mir-const result.
214         let _ = tcx.mir_const_qualif(def_id);
215     }
216
217     let mut body = tcx.mir_const(def_id).steal();
218     run_passes(tcx, &mut body, InstanceDef::Item(def_id), MirPhase::Validated, &[
219         // What we need to run borrowck etc.
220         &qualify_consts::QualifyAndPromoteConstants,
221         &simplify::SimplifyCfg::new("qualify-consts"),
222     ]);
223     tcx.alloc_steal_mir(body)
224 }
225
226 fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Body<'tcx> {
227     if tcx.is_constructor(def_id) {
228         // There's no reason to run all of the MIR passes on constructors when
229         // we can just output the MIR we want directly. This also saves const
230         // qualification and borrow checking the trouble of special casing
231         // constructors.
232         return shim::build_adt_ctor(tcx, def_id);
233     }
234
235     // (Mir-)Borrowck uses `mir_validated`, so we have to force it to
236     // execute before we can steal.
237     tcx.ensure().mir_borrowck(def_id);
238
239     if tcx.use_ast_borrowck() {
240         tcx.ensure().borrowck(def_id);
241     }
242
243     let mut body = tcx.mir_validated(def_id).steal();
244     run_passes(tcx, &mut body, InstanceDef::Item(def_id), MirPhase::Optimized, &[
245         // Remove all things only needed by analysis
246         &no_landing_pads::NoLandingPads,
247         &simplify_branches::SimplifyBranches::new("initial"),
248         &remove_noop_landing_pads::RemoveNoopLandingPads,
249         &cleanup_post_borrowck::CleanupNonCodegenStatements,
250
251         &simplify::SimplifyCfg::new("early-opt"),
252
253         // These next passes must be executed together
254         &add_call_guards::CriticalCallEdges,
255         &elaborate_drops::ElaborateDrops,
256         &no_landing_pads::NoLandingPads,
257         // AddMovesForPackedDrops needs to run after drop
258         // elaboration.
259         &add_moves_for_packed_drops::AddMovesForPackedDrops,
260         // AddRetag needs to run after ElaborateDrops, and it needs
261         // an AllCallEdges pass right before it.  Otherwise it should
262         // run fairly late, but before optimizations begin.
263         &add_call_guards::AllCallEdges,
264         &add_retag::AddRetag,
265
266         &simplify::SimplifyCfg::new("elaborate-drops"),
267
268         // No lifetime analysis based on borrowing can be done from here on out.
269
270         // From here on out, regions are gone.
271         &erase_regions::EraseRegions,
272
273         &lower_128bit::Lower128Bit,
274
275
276         // Optimizations begin.
277         &uniform_array_move_out::RestoreSubsliceArrayMoveOut,
278         &inline::Inline,
279
280         // Lowering generator control-flow and variables
281         // has to happen before we do anything else to them.
282         &generator::StateTransform,
283
284         &instcombine::InstCombine,
285         &const_prop::ConstProp,
286         &simplify_branches::SimplifyBranches::new("after-const-prop"),
287         &deaggregator::Deaggregator,
288         &copy_prop::CopyPropagation,
289         &simplify_branches::SimplifyBranches::new("after-copy-prop"),
290         &remove_noop_landing_pads::RemoveNoopLandingPads,
291         &simplify::SimplifyCfg::new("final"),
292         &simplify::SimplifyLocals,
293
294         &add_call_guards::CriticalCallEdges,
295         &dump_mir::Marker("PreCodegen"),
296     ]);
297     tcx.arena.alloc(body)
298 }