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