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