]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/mod.rs
Rollup merge of #70038 - DutchGhost:const-forget-tests, r=RalfJung
[rust.git] / src / librustc_mir / transform / mod.rs
1 use crate::{shim, util};
2 use rustc::mir::{BodyAndCache, ConstQualifs, MirPhase, Promoted};
3 use rustc::ty::query::Providers;
4 use rustc::ty::steal::Steal;
5 use rustc::ty::{InstanceDef, TyCtxt, TypeFoldable};
6 use rustc_ast::ast;
7 use rustc_hir as hir;
8 use rustc_hir::def_id::{CrateNum, DefId, DefIdSet, LOCAL_CRATE};
9 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
10 use rustc_index::vec::IndexVec;
11 use rustc_span::Span;
12 use std::borrow::Cow;
13
14 pub mod add_call_guards;
15 pub mod add_moves_for_packed_drops;
16 pub mod add_retag;
17 pub mod check_consts;
18 pub mod check_unsafety;
19 pub mod cleanup_post_borrowck;
20 pub mod const_prop;
21 pub mod copy_prop;
22 pub mod deaggregator;
23 pub mod dump_mir;
24 pub mod elaborate_drops;
25 pub mod erase_regions;
26 pub mod generator;
27 pub mod inline;
28 pub mod instcombine;
29 pub mod no_landing_pads;
30 pub mod promote_consts;
31 pub mod qualify_min_const_fn;
32 pub mod remove_noop_landing_pads;
33 pub mod rustc_peek;
34 pub mod simplify;
35 pub mod simplify_branches;
36 pub mod simplify_try;
37 pub mod uninhabited_enum_branching;
38 pub mod unreachable_prop;
39
40 pub(crate) fn provide(providers: &mut Providers<'_>) {
41     self::check_unsafety::provide(providers);
42     *providers = Providers {
43         mir_keys,
44         mir_const,
45         mir_const_qualif,
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(
76             &mut self,
77             v: &'tcx hir::VariantData<'tcx>,
78             _: ast::Name,
79             _: &'tcx hir::Generics<'tcx>,
80             _: hir::HirId,
81             _: Span,
82         ) {
83             if let hir::VariantData::Tuple(_, hir_id) = *v {
84                 self.set.insert(self.tcx.hir().local_def_id(hir_id));
85             }
86             intravisit::walk_struct_def(self, v)
87         }
88         type Map = intravisit::ErasedMap<'tcx>;
89         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
90             NestedVisitorMap::None
91         }
92     }
93     tcx.hir()
94         .krate()
95         .visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
96
97     tcx.arena.alloc(set)
98 }
99
100 /// Where a specific `mir::Body` comes from.
101 #[derive(Debug, Copy, Clone)]
102 pub struct MirSource<'tcx> {
103     pub instance: InstanceDef<'tcx>,
104
105     /// If `Some`, this is a promoted rvalue within the parent function.
106     pub promoted: Option<Promoted>,
107 }
108
109 impl<'tcx> MirSource<'tcx> {
110     pub fn item(def_id: DefId) -> Self {
111         MirSource { instance: InstanceDef::Item(def_id), promoted: None }
112     }
113
114     #[inline]
115     pub fn def_id(&self) -> DefId {
116         self.instance.def_id()
117     }
118 }
119
120 /// Generates a default name for the pass based on the name of the
121 /// type `T`.
122 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
123     let name = ::std::any::type_name::<T>();
124     if let Some(tail) = name.rfind(':') { Cow::from(&name[tail + 1..]) } else { Cow::from(name) }
125 }
126
127 /// A streamlined trait that you can implement to create a pass; the
128 /// pass will be named after the type, and it will consist of a main
129 /// loop that goes over each available MIR and applies `run_pass`.
130 pub trait MirPass<'tcx> {
131     fn name(&self) -> Cow<'_, str> {
132         default_name::<Self>()
133     }
134
135     fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut BodyAndCache<'tcx>);
136 }
137
138 pub fn run_passes(
139     tcx: TyCtxt<'tcx>,
140     body: &mut BodyAndCache<'tcx>,
141     instance: InstanceDef<'tcx>,
142     promoted: Option<Promoted>,
143     mir_phase: MirPhase,
144     passes: &[&dyn MirPass<'tcx>],
145 ) {
146     let phase_index = mir_phase.phase_index();
147
148     if body.phase >= mir_phase {
149         return;
150     }
151
152     let source = MirSource { instance, promoted };
153     let mut index = 0;
154     let mut run_pass = |pass: &dyn MirPass<'tcx>| {
155         let run_hooks = |body: &_, index, is_after| {
156             dump_mir::on_mir_pass(
157                 tcx,
158                 &format_args!("{:03}-{:03}", phase_index, index),
159                 &pass.name(),
160                 source,
161                 body,
162                 is_after,
163             );
164         };
165         run_hooks(body, index, false);
166         pass.run_pass(tcx, source, body);
167         run_hooks(body, index, true);
168
169         index += 1;
170     };
171
172     for pass in passes {
173         run_pass(*pass);
174     }
175
176     body.phase = mir_phase;
177 }
178
179 fn mir_const_qualif(tcx: TyCtxt<'_>, def_id: DefId) -> ConstQualifs {
180     let const_kind = check_consts::ConstKind::for_item(tcx, def_id);
181
182     // No need to const-check a non-const `fn`.
183     if const_kind.is_none() {
184         return Default::default();
185     }
186
187     // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
188     // cannot yet be stolen), because `mir_validated()`, which steals
189     // from `mir_const(), forces this query to execute before
190     // performing the steal.
191     let body = &tcx.mir_const(def_id).borrow();
192
193     if body.return_ty().references_error() {
194         tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
195         return Default::default();
196     }
197
198     let item = check_consts::Item {
199         body: body.unwrap_read_only(),
200         tcx,
201         def_id,
202         const_kind,
203         param_env: tcx.param_env(def_id),
204     };
205
206     let mut validator = check_consts::validation::Validator::new(&item);
207     validator.check_body();
208
209     // We return the qualifs in the return place for every MIR body, even though it is only used
210     // when deciding to promote a reference to a `const` for now.
211     validator.qualifs_in_return_place()
212 }
213
214 fn mir_const(tcx: TyCtxt<'_>, def_id: DefId) -> &Steal<BodyAndCache<'_>> {
215     // Unsafety check uses the raw mir, so make sure it is run
216     let _ = tcx.unsafety_check_result(def_id);
217
218     let mut body = tcx.mir_built(def_id).steal();
219
220     util::dump_mir(tcx, None, "mir_map", &0, MirSource::item(def_id), &body, |_, _| Ok(()));
221
222     run_passes(
223         tcx,
224         &mut body,
225         InstanceDef::Item(def_id),
226         None,
227         MirPhase::Const,
228         &[
229             // What we need to do constant evaluation.
230             &simplify::SimplifyCfg::new("initial"),
231             &rustc_peek::SanityCheck,
232         ],
233     );
234     body.ensure_predecessors();
235     tcx.alloc_steal_mir(body)
236 }
237
238 fn mir_validated(
239     tcx: TyCtxt<'tcx>,
240     def_id: DefId,
241 ) -> (&'tcx Steal<BodyAndCache<'tcx>>, &'tcx Steal<IndexVec<Promoted, BodyAndCache<'tcx>>>) {
242     // Ensure that we compute the `mir_const_qualif` for constants at
243     // this point, before we steal the mir-const result.
244     let _ = tcx.mir_const_qualif(def_id);
245
246     let mut body = tcx.mir_const(def_id).steal();
247     let promote_pass = promote_consts::PromoteTemps::default();
248     run_passes(
249         tcx,
250         &mut body,
251         InstanceDef::Item(def_id),
252         None,
253         MirPhase::Validated,
254         &[
255             // What we need to run borrowck etc.
256             &promote_pass,
257             &simplify::SimplifyCfg::new("qualify-consts"),
258         ],
259     );
260
261     let promoted = promote_pass.promoted_fragments.into_inner();
262     (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
263 }
264
265 fn run_optimization_passes<'tcx>(
266     tcx: TyCtxt<'tcx>,
267     body: &mut BodyAndCache<'tcx>,
268     def_id: DefId,
269     promoted: Option<Promoted>,
270 ) {
271     run_passes(
272         tcx,
273         body,
274         InstanceDef::Item(def_id),
275         promoted,
276         MirPhase::Optimized,
277         &[
278             // Remove all things only needed by analysis
279             &no_landing_pads::NoLandingPads::new(tcx),
280             &simplify_branches::SimplifyBranches::new("initial"),
281             &remove_noop_landing_pads::RemoveNoopLandingPads,
282             &cleanup_post_borrowck::CleanupNonCodegenStatements,
283             &simplify::SimplifyCfg::new("early-opt"),
284             // These next passes must be executed together
285             &add_call_guards::CriticalCallEdges,
286             &elaborate_drops::ElaborateDrops,
287             &no_landing_pads::NoLandingPads::new(tcx),
288             // AddMovesForPackedDrops needs to run after drop
289             // elaboration.
290             &add_moves_for_packed_drops::AddMovesForPackedDrops,
291             // AddRetag needs to run after ElaborateDrops, and it needs
292             // an AllCallEdges pass right before it.  Otherwise it should
293             // run fairly late, but before optimizations begin.
294             &add_call_guards::AllCallEdges,
295             &add_retag::AddRetag,
296             &simplify::SimplifyCfg::new("elaborate-drops"),
297             // No lifetime analysis based on borrowing can be done from here on out.
298
299             // From here on out, regions are gone.
300             &erase_regions::EraseRegions,
301             // Optimizations begin.
302             &unreachable_prop::UnreachablePropagation,
303             &uninhabited_enum_branching::UninhabitedEnumBranching,
304             &simplify::SimplifyCfg::new("after-uninhabited-enum-branching"),
305             &inline::Inline,
306             // Lowering generator control-flow and variables
307             // has to happen before we do anything else to them.
308             &generator::StateTransform,
309             &instcombine::InstCombine,
310             &const_prop::ConstProp,
311             &simplify_branches::SimplifyBranches::new("after-const-prop"),
312             &deaggregator::Deaggregator,
313             &copy_prop::CopyPropagation,
314             &simplify_branches::SimplifyBranches::new("after-copy-prop"),
315             &remove_noop_landing_pads::RemoveNoopLandingPads,
316             &simplify::SimplifyCfg::new("after-remove-noop-landing-pads"),
317             &simplify_try::SimplifyArmIdentity,
318             &simplify_try::SimplifyBranchSame,
319             &simplify::SimplifyCfg::new("final"),
320             &simplify::SimplifyLocals,
321             &add_call_guards::CriticalCallEdges,
322             &dump_mir::Marker("PreCodegen"),
323         ],
324     );
325 }
326
327 fn optimized_mir(tcx: TyCtxt<'_>, def_id: DefId) -> &BodyAndCache<'_> {
328     if tcx.is_constructor(def_id) {
329         // There's no reason to run all of the MIR passes on constructors when
330         // we can just output the MIR we want directly. This also saves const
331         // qualification and borrow checking the trouble of special casing
332         // constructors.
333         return shim::build_adt_ctor(tcx, def_id);
334     }
335
336     // (Mir-)Borrowck uses `mir_validated`, so we have to force it to
337     // execute before we can steal.
338     tcx.ensure().mir_borrowck(def_id);
339
340     let (body, _) = tcx.mir_validated(def_id);
341     let mut body = body.steal();
342     run_optimization_passes(tcx, &mut body, def_id, None);
343     body.ensure_predecessors();
344     tcx.arena.alloc(body)
345 }
346
347 fn promoted_mir(tcx: TyCtxt<'_>, def_id: DefId) -> &IndexVec<Promoted, BodyAndCache<'_>> {
348     if tcx.is_constructor(def_id) {
349         return tcx.intern_promoted(IndexVec::new());
350     }
351
352     tcx.ensure().mir_borrowck(def_id);
353     let (_, promoted) = tcx.mir_validated(def_id);
354     let mut promoted = promoted.steal();
355
356     for (p, mut body) in promoted.iter_enumerated_mut() {
357         run_optimization_passes(tcx, &mut body, def_id, Some(p));
358         body.ensure_predecessors();
359     }
360
361     tcx.intern_promoted(promoted)
362 }