1 use crate::{build, shim};
2 use rustc_data_structures::indexed_vec::IndexVec;
3 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
4 use rustc::mir::{Body, MirPhase, Promoted};
5 use rustc::ty::{TyCtxt, InstanceDef};
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;
18 pub mod check_unsafety;
19 pub mod simplify_branches;
21 pub mod erase_regions;
22 pub mod no_landing_pads;
24 pub mod elaborate_drops;
25 pub mod add_call_guards;
26 pub mod promote_consts;
27 pub mod qualify_consts;
28 pub mod qualify_min_const_fn;
29 pub mod remove_noop_landing_pads;
38 pub mod uniform_array_move_out;
40 pub(crate) fn provide(providers: &mut Providers<'_>) {
41 self::qualify_consts::provide(providers);
42 self::check_unsafety::provide(providers);
43 *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 = unsafe { ::std::intrinsics::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`.
142 fn name(&self) -> Cow<'_, str> {
143 default_name::<Self>()
146 fn run_pass<'tcx>(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>);
151 body: &mut Body<'tcx>,
152 instance: InstanceDef<'tcx>,
154 passes: &[&dyn MirPass],
156 let phase_index = mir_phase.phase_index();
158 let run_passes = |body: &mut Body<'tcx>, promoted| {
159 if body.phase >= mir_phase {
163 let source = MirSource {
168 let mut run_pass = |pass: &dyn MirPass| {
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 run_passes(body, None);
189 for (index, promoted_body) in body.promoted.iter_enumerated_mut() {
190 run_passes(promoted_body, Some(index));
192 //Let's make sure we don't miss any nested instances
193 assert!(promoted_body.promoted.is_empty())
197 fn mir_const(tcx: TyCtxt<'_>, def_id: DefId) -> &Steal<Body<'_>> {
198 // Unsafety check uses the raw mir, so make sure it is run
199 let _ = tcx.unsafety_check_result(def_id);
201 let mut body = tcx.mir_built(def_id).steal();
202 run_passes(tcx, &mut body, InstanceDef::Item(def_id), MirPhase::Const, &[
203 // What we need to do constant evaluation.
204 &simplify::SimplifyCfg::new("initial"),
205 &rustc_peek::SanityCheck,
206 &uniform_array_move_out::UniformArrayMoveOut,
208 tcx.alloc_steal_mir(body)
211 fn mir_validated(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Steal<Body<'tcx>> {
212 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
213 if let hir::BodyOwnerKind::Const = tcx.hir().body_owner_kind(hir_id) {
214 // Ensure that we compute the `mir_const_qualif` for constants at
215 // this point, before we steal the mir-const result.
216 let _ = tcx.mir_const_qualif(def_id);
219 let mut body = tcx.mir_const(def_id).steal();
220 run_passes(tcx, &mut body, InstanceDef::Item(def_id), MirPhase::Validated, &[
221 // What we need to run borrowck etc.
222 &qualify_consts::QualifyAndPromoteConstants,
223 &simplify::SimplifyCfg::new("qualify-consts"),
225 tcx.alloc_steal_mir(body)
228 fn optimized_mir(tcx: TyCtxt<'_>, def_id: DefId) -> &Body<'_> {
229 if tcx.is_constructor(def_id) {
230 // There's no reason to run all of the MIR passes on constructors when
231 // we can just output the MIR we want directly. This also saves const
232 // qualification and borrow checking the trouble of special casing
234 return shim::build_adt_ctor(tcx, def_id);
237 // (Mir-)Borrowck uses `mir_validated`, so we have to force it to
238 // execute before we can steal.
239 tcx.ensure().mir_borrowck(def_id);
241 if tcx.use_ast_borrowck() {
242 tcx.ensure().borrowck(def_id);
245 let mut body = tcx.mir_validated(def_id).steal();
246 run_passes(tcx, &mut body, InstanceDef::Item(def_id), MirPhase::Optimized, &[
247 // Remove all things only needed by analysis
248 &no_landing_pads::NoLandingPads,
249 &simplify_branches::SimplifyBranches::new("initial"),
250 &remove_noop_landing_pads::RemoveNoopLandingPads,
251 &cleanup_post_borrowck::CleanupNonCodegenStatements,
253 &simplify::SimplifyCfg::new("early-opt"),
255 // These next passes must be executed together
256 &add_call_guards::CriticalCallEdges,
257 &elaborate_drops::ElaborateDrops,
258 &no_landing_pads::NoLandingPads,
259 // AddMovesForPackedDrops needs to run after drop
261 &add_moves_for_packed_drops::AddMovesForPackedDrops,
262 // AddRetag needs to run after ElaborateDrops, and it needs
263 // an AllCallEdges pass right before it. Otherwise it should
264 // run fairly late, but before optimizations begin.
265 &add_call_guards::AllCallEdges,
266 &add_retag::AddRetag,
268 &simplify::SimplifyCfg::new("elaborate-drops"),
270 // No lifetime analysis based on borrowing can be done from here on out.
272 // From here on out, regions are gone.
273 &erase_regions::EraseRegions,
275 &lower_128bit::Lower128Bit,
278 // Optimizations begin.
279 &uniform_array_move_out::RestoreSubsliceArrayMoveOut,
282 // Lowering generator control-flow and variables
283 // has to happen before we do anything else to them.
284 &generator::StateTransform,
286 &instcombine::InstCombine,
287 &const_prop::ConstProp,
288 &simplify_branches::SimplifyBranches::new("after-const-prop"),
289 &deaggregator::Deaggregator,
290 ©_prop::CopyPropagation,
291 &simplify_branches::SimplifyBranches::new("after-copy-prop"),
292 &remove_noop_landing_pads::RemoveNoopLandingPads,
293 &simplify::SimplifyCfg::new("final"),
294 &simplify::SimplifyLocals,
296 &add_call_guards::CriticalCallEdges,
297 &dump_mir::Marker("PreCodegen"),
299 tcx.arena.alloc(body)
302 fn promoted_mir<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
303 let body = tcx.optimized_mir(def_id);