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