1 use crate::{build, shim};
2 use rustc_index::vec::IndexVec;
3 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
4 use rustc::mir::{Body, MirPhase, Promoted, QualifSet};
5 use rustc::ty::{TyCtxt, InstanceDef, TypeFoldable};
6 use rustc::ty::query::Providers;
7 use rustc::ty::steal::Steal;
9 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
10 use rustc::util::nodemap::DefIdSet;
16 pub mod add_moves_for_packed_drops;
17 pub mod cleanup_post_borrowck;
19 pub mod check_unsafety;
20 pub mod simplify_branches;
22 pub mod erase_regions;
23 pub mod no_landing_pads;
25 pub mod elaborate_drops;
26 pub mod add_call_guards;
27 pub mod promote_consts;
28 pub mod qualify_min_const_fn;
29 pub mod remove_noop_landing_pads;
37 pub mod uniform_array_move_out;
38 pub mod uninhabited_enum_branching;
40 pub(crate) fn provide(providers: &mut Providers<'_>) {
41 self::check_unsafety::provide(providers);
42 *providers = Providers {
55 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
56 tcx.mir_keys(def_id.krate).contains(&def_id)
59 /// Finds the full set of `DefId`s within the current crate that have
60 /// MIR associated with them.
61 fn mir_keys(tcx: TyCtxt<'_>, krate: CrateNum) -> &DefIdSet {
62 assert_eq!(krate, LOCAL_CRATE);
64 let mut set = DefIdSet::default();
66 // All body-owners have MIR associated with them.
67 set.extend(tcx.body_owners());
69 // Additionally, tuple struct/variant constructors have MIR, but
70 // they don't have a BodyId, so we need to build them separately.
71 struct GatherCtors<'a, 'tcx> {
73 set: &'a mut DefIdSet,
75 impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
76 fn visit_variant_data(&mut self,
77 v: &'tcx hir::VariantData,
79 _: &'tcx hir::Generics,
82 if let hir::VariantData::Tuple(_, hir_id) = *v {
83 self.set.insert(self.tcx.hir().local_def_id(hir_id));
85 intravisit::walk_struct_def(self, v)
87 fn nested_visit_map<'b>(&'b mut self) -> NestedVisitorMap<'b, 'tcx> {
88 NestedVisitorMap::None
91 tcx.hir().krate().visit_all_item_likes(&mut GatherCtors {
99 fn mir_built(tcx: TyCtxt<'_>, def_id: DefId) -> &Steal<Body<'_>> {
100 let mir = build::mir_build(tcx, def_id);
101 tcx.alloc_steal_mir(mir)
104 /// Where a specific `mir::Body` comes from.
105 #[derive(Debug, Copy, Clone)]
106 pub struct MirSource<'tcx> {
107 pub instance: InstanceDef<'tcx>,
109 /// If `Some`, this is a promoted rvalue within the parent function.
110 pub promoted: Option<Promoted>,
113 impl<'tcx> MirSource<'tcx> {
114 pub fn item(def_id: DefId) -> Self {
116 instance: InstanceDef::Item(def_id),
122 pub fn def_id(&self) -> DefId {
123 self.instance.def_id()
127 /// Generates a default name for the pass based on the name of the
129 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
130 let name = ::std::any::type_name::<T>();
131 if let Some(tail) = name.rfind(":") {
132 Cow::from(&name[tail+1..])
138 /// A streamlined trait that you can implement to create a pass; the
139 /// pass will be named after the type, and it will consist of a main
140 /// loop that goes over each available MIR and applies `run_pass`.
141 pub trait MirPass<'tcx> {
142 fn name(&self) -> Cow<'_, str> {
143 default_name::<Self>()
146 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>);
151 body: &mut Body<'tcx>,
152 instance: InstanceDef<'tcx>,
153 promoted: Option<Promoted>,
155 passes: &[&dyn MirPass<'tcx>],
157 let phase_index = mir_phase.phase_index();
159 if body.phase >= mir_phase {
163 let source = MirSource {
168 let mut run_pass = |pass: &dyn MirPass<'tcx>| {
169 let run_hooks = |body: &_, index, is_after| {
170 dump_mir::on_mir_pass(tcx, &format_args!("{:03}-{:03}", phase_index, index),
171 &pass.name(), source, body, is_after);
173 run_hooks(body, index, false);
174 pass.run_pass(tcx, source, body);
175 run_hooks(body, index, true);
184 body.phase = mir_phase;
187 fn mir_const_qualif(tcx: TyCtxt<'_>, def_id: DefId) -> QualifSet {
188 let const_kind = check_consts::ConstKind::for_item(tcx, def_id);
190 // No need to const-check a non-const `fn`.
191 if const_kind.is_none() {
192 return Default::default();
195 // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
196 // cannot yet be stolen), because `mir_validated()`, which steals
197 // from `mir_const(), forces this query to execute before
198 // performing the steal.
199 let body = &tcx.mir_const(def_id).borrow();
201 if body.return_ty().references_error() {
202 tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
203 return Default::default();
206 let item = check_consts::Item {
211 param_env: tcx.param_env(def_id),
214 let mut validator = check_consts::validation::Validator::new(&item);
215 validator.check_body();
217 // We return the qualifs in the return place for every MIR body, even though it is only used
218 // when deciding to promote a reference to a `const` for now.
219 validator.qualifs_in_return_place().into()
222 fn mir_const(tcx: TyCtxt<'_>, def_id: DefId) -> &Steal<Body<'_>> {
223 // Unsafety check uses the raw mir, so make sure it is run
224 let _ = tcx.unsafety_check_result(def_id);
226 let mut body = tcx.mir_built(def_id).steal();
227 run_passes(tcx, &mut body, InstanceDef::Item(def_id), None, MirPhase::Const, &[
228 // What we need to do constant evaluation.
229 &simplify::SimplifyCfg::new("initial"),
230 &rustc_peek::SanityCheck,
231 &uniform_array_move_out::UniformArrayMoveOut,
233 tcx.alloc_steal_mir(body)
239 ) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
240 // Ensure that we compute the `mir_const_qualif` for constants at
241 // this point, before we steal the mir-const result.
242 let _ = tcx.mir_const_qualif(def_id);
244 let mut body = tcx.mir_const(def_id).steal();
245 let promote_pass = promote_consts::PromoteTemps::default();
246 run_passes(tcx, &mut body, InstanceDef::Item(def_id), None, MirPhase::Validated, &[
247 // What we need to run borrowck etc.
249 &simplify::SimplifyCfg::new("qualify-consts"),
251 let promoted = promote_pass.promoted_fragments.into_inner();
252 (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
255 fn run_optimization_passes<'tcx>(
257 body: &mut Body<'tcx>,
259 promoted: Option<Promoted>,
261 run_passes(tcx, body, InstanceDef::Item(def_id), promoted, MirPhase::Optimized, &[
262 // Remove all things only needed by analysis
263 &no_landing_pads::NoLandingPads::new(tcx),
264 &simplify_branches::SimplifyBranches::new("initial"),
265 &remove_noop_landing_pads::RemoveNoopLandingPads,
266 &cleanup_post_borrowck::CleanupNonCodegenStatements,
268 &simplify::SimplifyCfg::new("early-opt"),
270 // These next passes must be executed together
271 &add_call_guards::CriticalCallEdges,
272 &elaborate_drops::ElaborateDrops,
273 &no_landing_pads::NoLandingPads::new(tcx),
274 // AddMovesForPackedDrops needs to run after drop
276 &add_moves_for_packed_drops::AddMovesForPackedDrops,
277 // AddRetag needs to run after ElaborateDrops, and it needs
278 // an AllCallEdges pass right before it. Otherwise it should
279 // run fairly late, but before optimizations begin.
280 &add_call_guards::AllCallEdges,
281 &add_retag::AddRetag,
283 &simplify::SimplifyCfg::new("elaborate-drops"),
285 // No lifetime analysis based on borrowing can be done from here on out.
287 // From here on out, regions are gone.
288 &erase_regions::EraseRegions,
291 // Optimizations begin.
292 &uninhabited_enum_branching::UninhabitedEnumBranching,
293 &simplify::SimplifyCfg::new("after-uninhabited-enum-branching"),
294 &uniform_array_move_out::RestoreSubsliceArrayMoveOut::new(tcx),
297 // Lowering generator control-flow and variables
298 // has to happen before we do anything else to them.
299 &generator::StateTransform,
301 &instcombine::InstCombine,
302 &const_prop::ConstProp,
303 &simplify_branches::SimplifyBranches::new("after-const-prop"),
304 &deaggregator::Deaggregator,
305 ©_prop::CopyPropagation,
306 &simplify_branches::SimplifyBranches::new("after-copy-prop"),
307 &remove_noop_landing_pads::RemoveNoopLandingPads,
308 &simplify::SimplifyCfg::new("final"),
309 &simplify::SimplifyLocals,
311 &add_call_guards::CriticalCallEdges,
312 &dump_mir::Marker("PreCodegen"),
316 fn optimized_mir(tcx: TyCtxt<'_>, def_id: DefId) -> &Body<'_> {
317 if tcx.is_constructor(def_id) {
318 // There's no reason to run all of the MIR passes on constructors when
319 // we can just output the MIR we want directly. This also saves const
320 // qualification and borrow checking the trouble of special casing
322 return shim::build_adt_ctor(tcx, def_id);
325 // (Mir-)Borrowck uses `mir_validated`, so we have to force it to
326 // execute before we can steal.
327 tcx.ensure().mir_borrowck(def_id);
329 let (body, _) = tcx.mir_validated(def_id);
330 let mut body = body.steal();
331 run_optimization_passes(tcx, &mut body, def_id, None);
332 tcx.arena.alloc(body)
335 fn promoted_mir<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
336 if tcx.is_constructor(def_id) {
337 return tcx.intern_promoted(IndexVec::new());
340 tcx.ensure().mir_borrowck(def_id);
341 let (_, promoted) = tcx.mir_validated(def_id);
342 let mut promoted = promoted.steal();
344 for (p, mut body) in promoted.iter_enumerated_mut() {
345 run_optimization_passes(tcx, &mut body, def_id, Some(p));
348 tcx.intern_promoted(promoted)