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