]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/mod.rs
Fix font color for help button in ayu and dark themes
[rust.git] / src / librustc_mir / transform / mod.rs
1 use crate::{shim, util};
2 use required_consts::RequiredConstsVisitor;
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_hir as hir;
5 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
6 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
7 use rustc_index::vec::IndexVec;
8 use rustc_middle::mir::visit::Visitor as _;
9 use rustc_middle::mir::{traversal, Body, ConstQualifs, MirPhase, Promoted};
10 use rustc_middle::ty::query::Providers;
11 use rustc_middle::ty::steal::Steal;
12 use rustc_middle::ty::{self, InstanceDef, TyCtxt, TypeFoldable};
13 use rustc_span::{Span, Symbol};
14 use std::borrow::Cow;
15
16 pub mod add_call_guards;
17 pub mod add_moves_for_packed_drops;
18 pub mod add_retag;
19 pub mod check_consts;
20 pub mod check_packed_ref;
21 pub mod check_unsafety;
22 pub mod cleanup_post_borrowck;
23 pub mod const_prop;
24 pub mod copy_prop;
25 pub mod deaggregator;
26 pub mod dump_mir;
27 pub mod elaborate_drops;
28 pub mod generator;
29 pub mod inline;
30 pub mod instcombine;
31 pub mod instrument_coverage;
32 pub mod match_branches;
33 pub mod no_landing_pads;
34 pub mod nrvo;
35 pub mod promote_consts;
36 pub mod qualify_min_const_fn;
37 pub mod remove_noop_landing_pads;
38 pub mod required_consts;
39 pub mod rustc_peek;
40 pub mod simplify;
41 pub mod simplify_branches;
42 pub mod simplify_try;
43 pub mod uninhabited_enum_branching;
44 pub mod unreachable_prop;
45 pub mod validate;
46
47 pub(crate) fn provide(providers: &mut Providers) {
48     self::check_unsafety::provide(providers);
49     *providers = Providers {
50         mir_keys,
51         mir_const,
52         mir_const_qualif: |tcx, def_id| {
53             let def_id = def_id.expect_local();
54             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
55                 tcx.mir_const_qualif_const_arg(def)
56             } else {
57                 mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
58             }
59         },
60         mir_const_qualif_const_arg: |tcx, (did, param_did)| {
61             mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
62         },
63         mir_validated,
64         mir_drops_elaborated_and_const_checked,
65         optimized_mir,
66         optimized_mir_of_const_arg,
67         is_mir_available,
68         promoted_mir: |tcx, def_id| {
69             let def_id = def_id.expect_local();
70             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
71                 tcx.promoted_mir_of_const_arg(def)
72             } else {
73                 promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
74             }
75         },
76         promoted_mir_of_const_arg: |tcx, (did, param_did)| {
77             promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
78         },
79         ..*providers
80     };
81     instrument_coverage::provide(providers);
82 }
83
84 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
85     tcx.mir_keys(def_id.krate).contains(&def_id.expect_local())
86 }
87
88 /// Finds the full set of `DefId`s within the current crate that have
89 /// MIR associated with them.
90 fn mir_keys(tcx: TyCtxt<'_>, krate: CrateNum) -> FxHashSet<LocalDefId> {
91     assert_eq!(krate, LOCAL_CRATE);
92
93     let mut set = FxHashSet::default();
94
95     // All body-owners have MIR associated with them.
96     set.extend(tcx.body_owners());
97
98     // Additionally, tuple struct/variant constructors have MIR, but
99     // they don't have a BodyId, so we need to build them separately.
100     struct GatherCtors<'a, 'tcx> {
101         tcx: TyCtxt<'tcx>,
102         set: &'a mut FxHashSet<LocalDefId>,
103     }
104     impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
105         fn visit_variant_data(
106             &mut self,
107             v: &'tcx hir::VariantData<'tcx>,
108             _: Symbol,
109             _: &'tcx hir::Generics<'tcx>,
110             _: hir::HirId,
111             _: Span,
112         ) {
113             if let hir::VariantData::Tuple(_, hir_id) = *v {
114                 self.set.insert(self.tcx.hir().local_def_id(hir_id));
115             }
116             intravisit::walk_struct_def(self, v)
117         }
118         type Map = intravisit::ErasedMap<'tcx>;
119         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
120             NestedVisitorMap::None
121         }
122     }
123     tcx.hir()
124         .krate()
125         .visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
126
127     set
128 }
129
130 /// Where a specific `mir::Body` comes from.
131 #[derive(Debug, Copy, Clone)]
132 pub struct MirSource<'tcx> {
133     pub instance: InstanceDef<'tcx>,
134
135     /// If `Some`, this is a promoted rvalue within the parent function.
136     pub promoted: Option<Promoted>,
137 }
138
139 impl<'tcx> MirSource<'tcx> {
140     pub fn item(def_id: DefId) -> Self {
141         MirSource {
142             instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
143             promoted: None,
144         }
145     }
146
147     pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
148         self.instance.with_opt_param()
149     }
150
151     #[inline]
152     pub fn def_id(&self) -> DefId {
153         self.instance.def_id()
154     }
155 }
156
157 /// Generates a default name for the pass based on the name of the
158 /// type `T`.
159 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
160     let name = ::std::any::type_name::<T>();
161     if let Some(tail) = name.rfind(':') { Cow::from(&name[tail + 1..]) } else { Cow::from(name) }
162 }
163
164 /// A streamlined trait that you can implement to create a pass; the
165 /// pass will be named after the type, and it will consist of a main
166 /// loop that goes over each available MIR and applies `run_pass`.
167 pub trait MirPass<'tcx> {
168     fn name(&self) -> Cow<'_, str> {
169         default_name::<Self>()
170     }
171
172     fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>);
173 }
174
175 pub fn run_passes(
176     tcx: TyCtxt<'tcx>,
177     body: &mut Body<'tcx>,
178     instance: InstanceDef<'tcx>,
179     promoted: Option<Promoted>,
180     mir_phase: MirPhase,
181     passes: &[&[&dyn MirPass<'tcx>]],
182 ) {
183     let phase_index = mir_phase.phase_index();
184     let source = MirSource { instance, promoted };
185     let validate = tcx.sess.opts.debugging_opts.validate_mir;
186
187     if body.phase >= mir_phase {
188         return;
189     }
190
191     if validate {
192         validate::Validator { when: format!("input to phase {:?}", mir_phase) }
193             .run_pass(tcx, source, body);
194     }
195
196     let mut index = 0;
197     let mut run_pass = |pass: &dyn MirPass<'tcx>| {
198         let run_hooks = |body: &_, index, is_after| {
199             dump_mir::on_mir_pass(
200                 tcx,
201                 &format_args!("{:03}-{:03}", phase_index, index),
202                 &pass.name(),
203                 source,
204                 body,
205                 is_after,
206             );
207         };
208         run_hooks(body, index, false);
209         pass.run_pass(tcx, source, body);
210         run_hooks(body, index, true);
211
212         if validate {
213             validate::Validator { when: format!("after {} in phase {:?}", pass.name(), mir_phase) }
214                 .run_pass(tcx, source, body);
215         }
216
217         index += 1;
218     };
219
220     for pass_group in passes {
221         for pass in *pass_group {
222             run_pass(*pass);
223         }
224     }
225
226     body.phase = mir_phase;
227
228     if mir_phase == MirPhase::Optimized {
229         validate::Validator { when: format!("end of phase {:?}", mir_phase) }
230             .run_pass(tcx, source, body);
231     }
232 }
233
234 fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
235     let const_kind = tcx.hir().body_const_context(def.did);
236
237     // No need to const-check a non-const `fn`.
238     if const_kind.is_none() {
239         return Default::default();
240     }
241
242     // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
243     // cannot yet be stolen), because `mir_validated()`, which steals
244     // from `mir_const(), forces this query to execute before
245     // performing the steal.
246     let body = &tcx.mir_const(def).borrow();
247
248     if body.return_ty().references_error() {
249         tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
250         return Default::default();
251     }
252
253     let ccx = check_consts::ConstCx {
254         body,
255         tcx,
256         def_id: def.did,
257         const_kind,
258         param_env: tcx.param_env(def.did),
259     };
260
261     let mut validator = check_consts::validation::Validator::new(&ccx);
262     validator.check_body();
263
264     // We return the qualifs in the return place for every MIR body, even though it is only used
265     // when deciding to promote a reference to a `const` for now.
266     validator.qualifs_in_return_place()
267 }
268
269 /// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
270 fn mir_const<'tcx>(
271     tcx: TyCtxt<'tcx>,
272     def: ty::WithOptConstParam<LocalDefId>,
273 ) -> &'tcx Steal<Body<'tcx>> {
274     if let Some(def) = def.try_upgrade(tcx) {
275         return tcx.mir_const(def);
276     }
277
278     // Unsafety check uses the raw mir, so make sure it is run.
279     if let Some(param_did) = def.const_param_did {
280         tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did));
281     } else {
282         tcx.ensure().unsafety_check_result(def.did);
283     }
284
285     let mut body = tcx.mir_built(def).steal();
286
287     util::dump_mir(
288         tcx,
289         None,
290         "mir_map",
291         &0,
292         MirSource { instance: InstanceDef::Item(def.to_global()), promoted: None },
293         &body,
294         |_, _| Ok(()),
295     );
296
297     run_passes(
298         tcx,
299         &mut body,
300         InstanceDef::Item(def.to_global()),
301         None,
302         MirPhase::Const,
303         &[&[
304             // MIR-level lints.
305             &check_packed_ref::CheckPackedRef,
306             // What we need to do constant evaluation.
307             &simplify::SimplifyCfg::new("initial"),
308             &rustc_peek::SanityCheck,
309         ]],
310     );
311     tcx.alloc_steal_mir(body)
312 }
313
314 fn mir_validated(
315     tcx: TyCtxt<'tcx>,
316     def: ty::WithOptConstParam<LocalDefId>,
317 ) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
318     if let Some(def) = def.try_upgrade(tcx) {
319         return tcx.mir_validated(def);
320     }
321
322     // Ensure that we compute the `mir_const_qualif` for constants at
323     // this point, before we steal the mir-const result.
324     // Also this means promotion can rely on all const checks having been done.
325     let _ = tcx.mir_const_qualif_opt_const_arg(def);
326
327     let mut body = tcx.mir_const(def).steal();
328
329     let mut required_consts = Vec::new();
330     let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
331     for (bb, bb_data) in traversal::reverse_postorder(&body) {
332         required_consts_visitor.visit_basic_block_data(bb, bb_data);
333     }
334     body.required_consts = required_consts;
335
336     let promote_pass = promote_consts::PromoteTemps::default();
337     let promote: &[&dyn MirPass<'tcx>] = &[
338         // What we need to run borrowck etc.
339         &promote_pass,
340         &simplify::SimplifyCfg::new("promote-consts"),
341     ];
342
343     let opt_coverage: &[&dyn MirPass<'tcx>] = if tcx.sess.opts.debugging_opts.instrument_coverage {
344         &[&instrument_coverage::InstrumentCoverage]
345     } else {
346         &[]
347     };
348
349     run_passes(
350         tcx,
351         &mut body,
352         InstanceDef::Item(def.to_global()),
353         None,
354         MirPhase::Validated,
355         &[promote, opt_coverage],
356     );
357
358     let promoted = promote_pass.promoted_fragments.into_inner();
359     (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
360 }
361
362 fn mir_drops_elaborated_and_const_checked<'tcx>(
363     tcx: TyCtxt<'tcx>,
364     def: ty::WithOptConstParam<LocalDefId>,
365 ) -> &'tcx Steal<Body<'tcx>> {
366     if let Some(def) = def.try_upgrade(tcx) {
367         return tcx.mir_drops_elaborated_and_const_checked(def);
368     }
369
370     // (Mir-)Borrowck uses `mir_validated`, so we have to force it to
371     // execute before we can steal.
372     if let Some(param_did) = def.const_param_did {
373         tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
374     } else {
375         tcx.ensure().mir_borrowck(def.did);
376     }
377
378     let (body, _) = tcx.mir_validated(def);
379     let mut body = body.steal();
380
381     run_post_borrowck_cleanup_passes(tcx, &mut body, def.did, None);
382     check_consts::post_drop_elaboration::check_live_drops(tcx, def.did, &body);
383     tcx.alloc_steal_mir(body)
384 }
385
386 /// After this series of passes, no lifetime analysis based on borrowing can be done.
387 fn run_post_borrowck_cleanup_passes<'tcx>(
388     tcx: TyCtxt<'tcx>,
389     body: &mut Body<'tcx>,
390     def_id: LocalDefId,
391     promoted: Option<Promoted>,
392 ) {
393     debug!("post_borrowck_cleanup({:?})", def_id);
394
395     let post_borrowck_cleanup: &[&dyn MirPass<'tcx>] = &[
396         // Remove all things only needed by analysis
397         &no_landing_pads::NoLandingPads::new(tcx),
398         &simplify_branches::SimplifyBranches::new("initial"),
399         &remove_noop_landing_pads::RemoveNoopLandingPads,
400         &cleanup_post_borrowck::CleanupNonCodegenStatements,
401         &simplify::SimplifyCfg::new("early-opt"),
402         // These next passes must be executed together
403         &add_call_guards::CriticalCallEdges,
404         &elaborate_drops::ElaborateDrops,
405         &no_landing_pads::NoLandingPads::new(tcx),
406         // AddMovesForPackedDrops needs to run after drop
407         // elaboration.
408         &add_moves_for_packed_drops::AddMovesForPackedDrops,
409         // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
410         // but before optimizations begin.
411         &add_retag::AddRetag,
412         &simplify::SimplifyCfg::new("elaborate-drops"),
413         // `Deaggregator` is conceptually part of MIR building, some backends rely on it happening
414         // and it can help optimizations.
415         &deaggregator::Deaggregator,
416     ];
417
418     run_passes(
419         tcx,
420         body,
421         InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id())),
422         promoted,
423         MirPhase::DropElab,
424         &[post_borrowck_cleanup],
425     );
426 }
427
428 fn run_optimization_passes<'tcx>(
429     tcx: TyCtxt<'tcx>,
430     body: &mut Body<'tcx>,
431     def_id: LocalDefId,
432     promoted: Option<Promoted>,
433 ) {
434     let optimizations: &[&dyn MirPass<'tcx>] = &[
435         &unreachable_prop::UnreachablePropagation,
436         &uninhabited_enum_branching::UninhabitedEnumBranching,
437         &simplify::SimplifyCfg::new("after-uninhabited-enum-branching"),
438         &inline::Inline,
439         // Lowering generator control-flow and variables has to happen before we do anything else
440         // to them. We do this inside the "optimizations" block so that it can benefit from
441         // optimizations that run before, that might be harder to do on the state machine than MIR
442         // with async primitives.
443         &generator::StateTransform,
444         &instcombine::InstCombine,
445         &match_branches::MatchBranchSimplification,
446         &const_prop::ConstProp,
447         &simplify_branches::SimplifyBranches::new("after-const-prop"),
448         &simplify_try::SimplifyArmIdentity,
449         &simplify_try::SimplifyBranchSame,
450         &copy_prop::CopyPropagation,
451         &simplify_branches::SimplifyBranches::new("after-copy-prop"),
452         &remove_noop_landing_pads::RemoveNoopLandingPads,
453         &simplify::SimplifyCfg::new("after-remove-noop-landing-pads"),
454         &simplify::SimplifyCfg::new("final"),
455         &nrvo::RenameReturnPlace,
456         &simplify::SimplifyLocals,
457     ];
458
459     let no_optimizations: &[&dyn MirPass<'tcx>] = &[
460         // Even if we don't do optimizations, we still have to lower generators for codegen.
461         &generator::StateTransform,
462         // FIXME(#70073): This pass is responsible for both optimization as well as some lints.
463         &const_prop::ConstProp,
464     ];
465
466     let pre_codegen_cleanup: &[&dyn MirPass<'tcx>] = &[
467         &add_call_guards::CriticalCallEdges,
468         // Dump the end result for testing and debugging purposes.
469         &dump_mir::Marker("PreCodegen"),
470     ];
471
472     let mir_opt_level = tcx.sess.opts.debugging_opts.mir_opt_level;
473
474     #[rustfmt::skip]
475     run_passes(
476         tcx,
477         body,
478         InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id())),
479         promoted,
480         MirPhase::Optimized,
481         &[
482             if mir_opt_level > 0 { optimizations } else { no_optimizations },
483             pre_codegen_cleanup,
484         ],
485     );
486 }
487
488 fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> {
489     let did = did.expect_local();
490     if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
491         tcx.optimized_mir_of_const_arg(def)
492     } else {
493         tcx.arena.alloc(inner_optimized_mir(tcx, ty::WithOptConstParam::unknown(did)))
494     }
495 }
496
497 fn optimized_mir_of_const_arg<'tcx>(
498     tcx: TyCtxt<'tcx>,
499     (did, param_did): (LocalDefId, DefId),
500 ) -> &'tcx Body<'tcx> {
501     tcx.arena.alloc(inner_optimized_mir(
502         tcx,
503         ty::WithOptConstParam { did, const_param_did: Some(param_did) },
504     ))
505 }
506
507 fn inner_optimized_mir(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
508     if tcx.is_constructor(def.did.to_def_id()) {
509         // There's no reason to run all of the MIR passes on constructors when
510         // we can just output the MIR we want directly. This also saves const
511         // qualification and borrow checking the trouble of special casing
512         // constructors.
513         return shim::build_adt_ctor(tcx, def.did.to_def_id());
514     }
515
516     let mut body = tcx.mir_drops_elaborated_and_const_checked(def).steal();
517     run_optimization_passes(tcx, &mut body, def.did, None);
518
519     debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR");
520
521     body
522 }
523
524 fn promoted_mir<'tcx>(
525     tcx: TyCtxt<'tcx>,
526     def: ty::WithOptConstParam<LocalDefId>,
527 ) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
528     if tcx.is_constructor(def.did.to_def_id()) {
529         return tcx.arena.alloc(IndexVec::new());
530     }
531
532     if let Some(param_did) = def.const_param_did {
533         tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
534     } else {
535         tcx.ensure().mir_borrowck(def.did);
536     }
537     let (_, promoted) = tcx.mir_validated(def);
538     let mut promoted = promoted.steal();
539
540     for (p, mut body) in promoted.iter_enumerated_mut() {
541         run_post_borrowck_cleanup_passes(tcx, &mut body, def.did, Some(p));
542         run_optimization_passes(tcx, &mut body, def.did, Some(p));
543     }
544
545     debug_assert!(!promoted.has_free_regions(), "Free regions in promoted MIR");
546
547     tcx.arena.alloc(promoted)
548 }