Move rustc_mir::transform to rustc_mir_transform.

This commit is contained in:
Camille GILLOT 2021-01-01 01:53:25 +01:00
parent 31a61ccc38
commit bba4be681d
64 changed files with 775 additions and 698 deletions

View file

@ -3928,6 +3928,7 @@ dependencies = [
"rustc_middle",
"rustc_mir",
"rustc_mir_build",
"rustc_mir_transform",
"rustc_parse",
"rustc_passes",
"rustc_plugin_impl",
@ -4071,10 +4072,8 @@ dependencies = [
name = "rustc_mir"
version = "0.0.0"
dependencies = [
"coverage_test_macros",
"either",
"gsgdt",
"itertools 0.9.0",
"polonius-engine",
"regex",
"rustc_apfloat",
@ -4120,6 +4119,29 @@ dependencies = [
"tracing",
]
[[package]]
name = "rustc_mir_transform"
version = "0.0.0"
dependencies = [
"coverage_test_macros",
"itertools 0.9.0",
"rustc_ast",
"rustc_attr",
"rustc_data_structures",
"rustc_errors",
"rustc_hir",
"rustc_index",
"rustc_middle",
"rustc_mir",
"rustc_serialize",
"rustc_session",
"rustc_span",
"rustc_target",
"rustc_trait_selection",
"smallvec",
"tracing",
]
[[package]]
name = "rustc_parse"
version = "0.0.0"

View file

@ -34,6 +34,7 @@ rustc_hir = { path = "../rustc_hir" }
rustc_metadata = { path = "../rustc_metadata" }
rustc_mir = { path = "../rustc_mir" }
rustc_mir_build = { path = "../rustc_mir_build" }
rustc_mir_transform = { path = "../rustc_mir_transform" }
rustc_passes = { path = "../rustc_passes" }
rustc_typeck = { path = "../rustc_typeck" }
rustc_lint = { path = "../rustc_lint" }

View file

@ -742,6 +742,7 @@ pub fn prepare_outputs(
mir::provide(providers);
mir_borrowck::provide(providers);
mir_build::provide(providers);
rustc_mir_transform::provide(providers);
rustc_privacy::provide(providers);
typeck::provide(providers);
ty::provide(providers);
@ -913,7 +914,7 @@ fn analysis(tcx: TyCtxt<'_>, (): ()) -> Result<()> {
for def_id in tcx.body_owners() {
tcx.ensure().thir_check_unsafety(def_id);
if !tcx.sess.opts.debugging_opts.thir_unsafeck {
mir::transform::check_unsafety::check_unsafety(tcx, def_id);
rustc_mir_transform::check_unsafety::check_unsafety(tcx, def_id);
}
if tcx.hir().body_const_context(def_id).is_some() {
@ -1061,7 +1062,7 @@ pub fn start_codegen<'tcx>(
info!("Post-codegen\n{:?}", tcx.debug_stats());
if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, outputs) {
if let Err(e) = rustc_mir_transform::dump_mir::emit_mir(tcx, outputs) {
tcx.sess.err(&format!("could not emit MIR: {}", e));
tcx.sess.abort_if_errors();
}

View file

@ -9,7 +9,6 @@ doctest = false
[dependencies]
either = "1.5.0"
gsgdt = "0.1.2"
itertools = "0.9"
polonius-engine = "0.13.0"
regex = "1"
smallvec = { version = "1.0", features = ["union", "may_dangle"] }
@ -30,6 +29,3 @@ rustc_session = { path = "../rustc_session" }
rustc_target = { path = "../rustc_target" }
rustc_trait_selection = { path = "../rustc_trait_selection" }
rustc_span = { path = "../rustc_span" }
[dev-dependencies]
coverage_test_macros = { path = "src/transform/coverage/test_macros" }

View file

@ -79,7 +79,7 @@ fn place_contents_drop_state_cannot_differ<'tcx>(
}
}
pub(crate) fn on_lookup_result_bits<'tcx, F>(
pub fn on_lookup_result_bits<'tcx, F>(
tcx: TyCtxt<'tcx>,
body: &Body<'tcx>,
move_data: &MoveData<'tcx>,
@ -96,7 +96,7 @@ pub(crate) fn on_lookup_result_bits<'tcx, F>(
}
}
pub(crate) fn on_all_children_bits<'tcx, F>(
pub fn on_all_children_bits<'tcx, F>(
tcx: TyCtxt<'tcx>,
body: &Body<'tcx>,
move_data: &MoveData<'tcx>,
@ -138,7 +138,7 @@ fn on_all_children_bits<'tcx, F>(
on_all_children_bits(tcx, body, move_data, move_path_index, &mut each_child);
}
pub(crate) fn on_all_drop_children_bits<'tcx, F>(
pub fn on_all_drop_children_bits<'tcx, F>(
tcx: TyCtxt<'tcx>,
body: &Body<'tcx>,
ctxt: &MoveDataParamEnv<'tcx>,
@ -161,7 +161,7 @@ pub(crate) fn on_all_drop_children_bits<'tcx, F>(
})
}
pub(crate) fn drop_flag_effects_for_function_entry<'tcx, F>(
pub fn drop_flag_effects_for_function_entry<'tcx, F>(
tcx: TyCtxt<'tcx>,
body: &Body<'tcx>,
ctxt: &MoveDataParamEnv<'tcx>,
@ -179,7 +179,7 @@ pub(crate) fn drop_flag_effects_for_function_entry<'tcx, F>(
}
}
pub(crate) fn drop_flag_effects_for_location<'tcx, F>(
pub fn drop_flag_effects_for_location<'tcx, F>(
tcx: TyCtxt<'tcx>,
body: &Body<'tcx>,
ctxt: &MoveDataParamEnv<'tcx>,

View file

@ -3,7 +3,11 @@
use rustc_session::Session;
use rustc_span::symbol::{sym, Symbol};
pub(crate) use self::drop_flag_effects::*;
pub use self::drop_flag_effects::{
drop_flag_effects_for_function_entry, drop_flag_effects_for_location,
move_path_children_matching, on_all_children_bits, on_all_drop_children_bits,
on_lookup_result_bits,
};
pub use self::framework::{
fmt, lattice, visit_results, Analysis, AnalysisDomain, Backward, Direction, Engine, Forward,
GenKill, GenKillAnalysis, JoinSemiLattice, Results, ResultsCursor, ResultsRefCursor,
@ -26,7 +30,7 @@ pub struct MoveDataParamEnv<'tcx> {
pub param_env: ty::ParamEnv<'tcx>,
}
pub(crate) fn has_rustc_mir_with(
pub fn has_rustc_mir_with(
_sess: &Session,
attrs: &[ast::Attribute],
name: Symbol,

View file

@ -420,7 +420,7 @@ impl<'mir, 'tcx: 'mir, M: super::intern::CompileTimeMachine<'mir, 'tcx, !>>
/// A helper function that allocates memory for the layout given and gives you access to mutate
/// it. Once your own mutation code is done, the backing `Allocation` is removed from the
/// current `Memory` and returned.
pub(crate) fn intern_with_temp_alloc(
pub fn intern_with_temp_alloc(
&mut self,
layout: TyAndLayout<'tcx>,
f: impl FnOnce(

View file

@ -296,7 +296,7 @@ fn try_read_immediate_from_mplace(
/// Note that for a given layout, this operation will either always fail or always
/// succeed! Whether it succeeds depends on whether the layout can be represented
/// in an `Immediate`, not on which data is stored there currently.
pub(crate) fn try_read_immediate(
pub fn try_read_immediate(
&self,
src: &OpTy<'tcx, M::PointerTag>,
) -> InterpResult<'tcx, Result<ImmTy<'tcx, M::PointerTag>, MPlaceTy<'tcx, M::PointerTag>>> {
@ -547,7 +547,7 @@ pub(super) fn eval_operands(
// in patterns via the `const_eval` module
/// The `val` and `layout` are assumed to already be in our interpreter
/// "universe" (param_env).
crate fn const_to_op(
pub fn const_to_op(
&self,
val: &ty::Const<'tcx>,
layout: Option<TyAndLayout<'tcx>>,
@ -566,7 +566,7 @@ pub(super) fn eval_operands(
}
}
crate fn mir_const_to_op(
pub fn mir_const_to_op(
&self,
val: &mir::ConstantKind<'tcx>,
layout: Option<TyAndLayout<'tcx>>,

View file

@ -76,7 +76,7 @@ pub fn step(&mut self) -> InterpResult<'tcx, bool> {
/// Runs the interpretation logic for the given `mir::Statement` at the current frame and
/// statement counter. This also moves the statement counter forward.
crate fn statement(&mut self, stmt: &mir::Statement<'tcx>) -> InterpResult<'tcx> {
pub fn statement(&mut self, stmt: &mir::Statement<'tcx>) -> InterpResult<'tcx> {
info!("{:?}", stmt);
use rustc_middle::mir::StatementKind::*;

View file

@ -37,7 +37,6 @@
pub mod dataflow;
pub mod interpret;
pub mod monomorphize;
mod shim;
pub mod transform;
pub mod util;
@ -45,15 +44,11 @@
pub fn provide(providers: &mut Providers) {
const_eval::provide(providers);
shim::provide(providers);
transform::provide(providers);
monomorphize::partitioning::provide(providers);
monomorphize::polymorphize::provide(providers);
providers.eval_to_const_value_raw = const_eval::eval_to_const_value_raw_provider;
providers.eval_to_allocation_raw = const_eval::eval_to_allocation_raw_provider;
providers.const_caller_location = const_eval::const_caller_location;
providers.mir_callgraph_reachable = transform::inline::cycle::mir_callgraph_reachable;
providers.mir_inliner_callees = transform::inline::cycle::mir_inliner_callees;
providers.destructure_const = |tcx, param_env_and_value| {
let (param_env, value) = param_env_and_value.into_parts();
const_eval::destructure_const(tcx, param_env, value)

View file

@ -1,149 +1,12 @@
use crate::{shim, util};
use required_consts::RequiredConstsVisitor;
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::steal::Steal;
use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_index::vec::IndexVec;
use rustc_middle::mir::visit::Visitor as _;
use rustc_middle::mir::{traversal, Body, ConstQualifs, MirPhase, Promoted};
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::{self, TyCtxt, TypeFoldable};
use rustc_span::{Span, Symbol};
use rustc_middle::mir::Body;
use rustc_middle::ty::TyCtxt;
use std::borrow::Cow;
pub mod abort_unwinding_calls;
pub mod add_call_guards;
pub mod add_moves_for_packed_drops;
pub mod add_retag;
pub mod check_const_item_mutation;
pub mod check_consts;
pub mod check_packed_ref;
pub mod check_unsafety;
pub mod cleanup_post_borrowck;
pub mod const_debuginfo;
pub mod const_goto;
pub mod const_prop;
pub mod coverage;
pub mod deaggregator;
pub mod deduplicate_blocks;
pub mod dest_prop;
pub mod dump_mir;
pub mod early_otherwise_branch;
pub mod elaborate_drops;
pub mod function_item_references;
pub mod generator;
pub mod inline;
pub mod instcombine;
pub mod lower_intrinsics;
pub mod lower_slice_len;
pub mod match_branches;
pub mod multiple_return_terminators;
pub mod nrvo;
pub mod promote_consts;
pub mod remove_noop_landing_pads;
pub mod remove_storage_markers;
pub mod remove_unneeded_drops;
pub mod remove_zsts;
pub mod required_consts;
pub mod rustc_peek;
pub mod separate_const_switch;
pub mod simplify;
pub mod simplify_branches;
pub mod simplify_comparison_integral;
pub mod simplify_try;
pub mod uninhabited_enum_branching;
pub mod unreachable_prop;
pub mod validate;
pub use rustc_middle::mir::MirSource;
pub(crate) fn provide(providers: &mut Providers) {
self::check_unsafety::provide(providers);
self::check_packed_ref::provide(providers);
*providers = Providers {
mir_keys,
mir_const,
mir_const_qualif: |tcx, def_id| {
let def_id = def_id.expect_local();
if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
tcx.mir_const_qualif_const_arg(def)
} else {
mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
}
},
mir_const_qualif_const_arg: |tcx, (did, param_did)| {
mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
},
mir_promoted,
mir_drops_elaborated_and_const_checked,
mir_for_ctfe,
mir_for_ctfe_of_const_arg,
optimized_mir,
is_mir_available,
is_ctfe_mir_available: |tcx, did| is_mir_available(tcx, did),
promoted_mir: |tcx, def_id| {
let def_id = def_id.expect_local();
if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
tcx.promoted_mir_of_const_arg(def)
} else {
promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
}
},
promoted_mir_of_const_arg: |tcx, (did, param_did)| {
promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
},
..*providers
};
coverage::query::provide(providers);
}
fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
let def_id = def_id.expect_local();
tcx.mir_keys(()).contains(&def_id)
}
/// Finds the full set of `DefId`s within the current crate that have
/// MIR associated with them.
fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxHashSet<LocalDefId> {
let mut set = FxHashSet::default();
// All body-owners have MIR associated with them.
set.extend(tcx.body_owners());
// Additionally, tuple struct/variant constructors have MIR, but
// they don't have a BodyId, so we need to build them separately.
struct GatherCtors<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
set: &'a mut FxHashSet<LocalDefId>,
}
impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
fn visit_variant_data(
&mut self,
v: &'tcx hir::VariantData<'tcx>,
_: Symbol,
_: &'tcx hir::Generics<'tcx>,
_: hir::HirId,
_: Span,
) {
if let hir::VariantData::Tuple(_, hir_id) = *v {
self.set.insert(self.tcx.hir().local_def_id(hir_id));
}
intravisit::walk_struct_def(self, v)
}
type Map = intravisit::ErasedMap<'tcx>;
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
NestedVisitorMap::None
}
}
tcx.hir()
.krate()
.visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
set
}
/// Generates a default name for the pass based on the name of the
/// type `T`.
pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
@ -161,467 +24,3 @@ fn name(&self) -> Cow<'_, str> {
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
}
pub fn run_passes(
tcx: TyCtxt<'tcx>,
body: &mut Body<'tcx>,
mir_phase: MirPhase,
passes: &[&[&dyn MirPass<'tcx>]],
) {
let phase_index = mir_phase.phase_index();
let validate = tcx.sess.opts.debugging_opts.validate_mir;
if body.phase >= mir_phase {
return;
}
if validate {
validate::Validator { when: format!("input to phase {:?}", mir_phase), mir_phase }
.run_pass(tcx, body);
}
let mut index = 0;
let mut run_pass = |pass: &dyn MirPass<'tcx>| {
let run_hooks = |body: &_, index, is_after| {
dump_mir::on_mir_pass(
tcx,
&format_args!("{:03}-{:03}", phase_index, index),
&pass.name(),
body,
is_after,
);
};
run_hooks(body, index, false);
pass.run_pass(tcx, body);
run_hooks(body, index, true);
if validate {
validate::Validator {
when: format!("after {} in phase {:?}", pass.name(), mir_phase),
mir_phase,
}
.run_pass(tcx, body);
}
index += 1;
};
for pass_group in passes {
for pass in *pass_group {
run_pass(*pass);
}
}
body.phase = mir_phase;
if mir_phase == MirPhase::Optimization {
validate::Validator { when: format!("end of phase {:?}", mir_phase), mir_phase }
.run_pass(tcx, body);
}
}
fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
let const_kind = tcx.hir().body_const_context(def.did);
// No need to const-check a non-const `fn`.
if const_kind.is_none() {
return Default::default();
}
// N.B., this `borrow()` is guaranteed to be valid (i.e., the value
// cannot yet be stolen), because `mir_promoted()`, which steals
// from `mir_const(), forces this query to execute before
// performing the steal.
let body = &tcx.mir_const(def).borrow();
if body.return_ty().references_error() {
tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
return Default::default();
}
let ccx = check_consts::ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def.did) };
let mut validator = check_consts::check::Checker::new(&ccx);
validator.check_body();
// We return the qualifs in the return place for every MIR body, even though it is only used
// when deciding to promote a reference to a `const` for now.
validator.qualifs_in_return_place()
}
/// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
fn mir_const<'tcx>(
tcx: TyCtxt<'tcx>,
def: ty::WithOptConstParam<LocalDefId>,
) -> &'tcx Steal<Body<'tcx>> {
if let Some(def) = def.try_upgrade(tcx) {
return tcx.mir_const(def);
}
// Unsafety check uses the raw mir, so make sure it is run.
if !tcx.sess.opts.debugging_opts.thir_unsafeck {
if let Some(param_did) = def.const_param_did {
tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did));
} else {
tcx.ensure().unsafety_check_result(def.did);
}
}
let mut body = tcx.mir_built(def).steal();
util::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(()));
run_passes(
tcx,
&mut body,
MirPhase::Const,
&[&[
// MIR-level lints.
&check_packed_ref::CheckPackedRef,
&check_const_item_mutation::CheckConstItemMutation,
&function_item_references::FunctionItemReferences,
// What we need to do constant evaluation.
&simplify::SimplifyCfg::new("initial"),
&rustc_peek::SanityCheck,
]],
);
tcx.alloc_steal_mir(body)
}
/// Compute the main MIR body and the list of MIR bodies of the promoteds.
fn mir_promoted(
tcx: TyCtxt<'tcx>,
def: ty::WithOptConstParam<LocalDefId>,
) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
if let Some(def) = def.try_upgrade(tcx) {
return tcx.mir_promoted(def);
}
// Ensure that we compute the `mir_const_qualif` for constants at
// this point, before we steal the mir-const result.
// Also this means promotion can rely on all const checks having been done.
let _ = tcx.mir_const_qualif_opt_const_arg(def);
let _ = tcx.mir_abstract_const_opt_const_arg(def.to_global());
let mut body = tcx.mir_const(def).steal();
let mut required_consts = Vec::new();
let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
for (bb, bb_data) in traversal::reverse_postorder(&body) {
required_consts_visitor.visit_basic_block_data(bb, bb_data);
}
body.required_consts = required_consts;
let promote_pass = promote_consts::PromoteTemps::default();
let promote: &[&dyn MirPass<'tcx>] = &[
// What we need to run borrowck etc.
&promote_pass,
&simplify::SimplifyCfg::new("promote-consts"),
];
let opt_coverage: &[&dyn MirPass<'tcx>] =
if tcx.sess.instrument_coverage() { &[&coverage::InstrumentCoverage] } else { &[] };
run_passes(tcx, &mut body, MirPhase::ConstPromotion, &[promote, opt_coverage]);
let promoted = promote_pass.promoted_fragments.into_inner();
(tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
}
/// Compute the MIR that is used during CTFE (and thus has no optimizations run on it)
fn mir_for_ctfe<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Body<'tcx> {
let did = def_id.expect_local();
if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
tcx.mir_for_ctfe_of_const_arg(def)
} else {
tcx.arena.alloc(inner_mir_for_ctfe(tcx, ty::WithOptConstParam::unknown(did)))
}
}
/// Same as `mir_for_ctfe`, but used to get the MIR of a const generic parameter.
/// The docs on `WithOptConstParam` explain this a bit more, but the TLDR is that
/// we'd get cycle errors with `mir_for_ctfe`, because typeck would need to typeck
/// the const parameter while type checking the main body, which in turn would try
/// to type check the main body again.
fn mir_for_ctfe_of_const_arg<'tcx>(
tcx: TyCtxt<'tcx>,
(did, param_did): (LocalDefId, DefId),
) -> &'tcx Body<'tcx> {
tcx.arena.alloc(inner_mir_for_ctfe(
tcx,
ty::WithOptConstParam { did, const_param_did: Some(param_did) },
))
}
fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
// FIXME: don't duplicate this between the optimized_mir/mir_for_ctfe queries
if tcx.is_constructor(def.did.to_def_id()) {
// There's no reason to run all of the MIR passes on constructors when
// we can just output the MIR we want directly. This also saves const
// qualification and borrow checking the trouble of special casing
// constructors.
return shim::build_adt_ctor(tcx, def.did.to_def_id());
}
let context = tcx
.hir()
.body_const_context(def.did)
.expect("mir_for_ctfe should not be used for runtime functions");
let mut body = tcx.mir_drops_elaborated_and_const_checked(def).borrow().clone();
match context {
// Do not const prop functions, either they get executed at runtime or exported to metadata,
// so we run const prop on them, or they don't, in which case we const evaluate some control
// flow paths of the function and any errors in those paths will get emitted as const eval
// errors.
hir::ConstContext::ConstFn => {}
// Static items always get evaluated, so we can just let const eval see if any erroneous
// control flow paths get executed.
hir::ConstContext::Static(_) => {}
// Associated constants get const prop run so we detect common failure situations in the
// crate that defined the constant.
// Technically we want to not run on regular const items, but oli-obk doesn't know how to
// conveniently detect that at this point without looking at the HIR.
hir::ConstContext::Const => {
#[rustfmt::skip]
let optimizations: &[&dyn MirPass<'_>] = &[
&const_prop::ConstProp,
];
#[rustfmt::skip]
run_passes(
tcx,
&mut body,
MirPhase::Optimization,
&[
optimizations,
],
);
}
}
debug_assert!(!body.has_free_regions(tcx), "Free regions in MIR for CTFE");
body
}
/// Obtain just the main MIR (no promoteds) and run some cleanups on it. This also runs
/// mir borrowck *before* doing so in order to ensure that borrowck can be run and doesn't
/// end up missing the source MIR due to stealing happening.
fn mir_drops_elaborated_and_const_checked<'tcx>(
tcx: TyCtxt<'tcx>,
def: ty::WithOptConstParam<LocalDefId>,
) -> &'tcx Steal<Body<'tcx>> {
if let Some(def) = def.try_upgrade(tcx) {
return tcx.mir_drops_elaborated_and_const_checked(def);
}
// (Mir-)Borrowck uses `mir_promoted`, so we have to force it to
// execute before we can steal.
if let Some(param_did) = def.const_param_did {
tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
} else {
tcx.ensure().mir_borrowck(def.did);
}
let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
use rustc_middle::hir::map::blocks::FnLikeNode;
let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some();
if is_fn_like {
let did = def.did.to_def_id();
let def = ty::WithOptConstParam::unknown(did);
// Do not compute the mir call graph without said call graph actually being used.
if inline::is_enabled(tcx) {
let _ = tcx.mir_inliner_callees(ty::InstanceDef::Item(def));
}
}
let (body, _) = tcx.mir_promoted(def);
let mut body = body.steal();
run_post_borrowck_cleanup_passes(tcx, &mut body);
check_consts::post_drop_elaboration::check_live_drops(tcx, &body);
tcx.alloc_steal_mir(body)
}
/// After this series of passes, no lifetime analysis based on borrowing can be done.
fn run_post_borrowck_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
debug!("post_borrowck_cleanup({:?})", body.source.def_id());
let post_borrowck_cleanup: &[&dyn MirPass<'tcx>] = &[
// Remove all things only needed by analysis
&simplify_branches::SimplifyBranches::new("initial"),
&remove_noop_landing_pads::RemoveNoopLandingPads,
&cleanup_post_borrowck::CleanupNonCodegenStatements,
&simplify::SimplifyCfg::new("early-opt"),
// These next passes must be executed together
&add_call_guards::CriticalCallEdges,
&elaborate_drops::ElaborateDrops,
// This will remove extraneous landing pads which are no longer
// necessary as well as well as forcing any call in a non-unwinding
// function calling a possibly-unwinding function to abort the process.
&abort_unwinding_calls::AbortUnwindingCalls,
// AddMovesForPackedDrops needs to run after drop
// elaboration.
&add_moves_for_packed_drops::AddMovesForPackedDrops,
// `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
// but before optimizations begin.
&add_retag::AddRetag,
&lower_intrinsics::LowerIntrinsics,
&simplify::SimplifyCfg::new("elaborate-drops"),
// `Deaggregator` is conceptually part of MIR building, some backends rely on it happening
// and it can help optimizations.
&deaggregator::Deaggregator,
];
run_passes(tcx, body, MirPhase::DropLowering, &[post_borrowck_cleanup]);
}
fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
let mir_opt_level = tcx.sess.mir_opt_level();
// Lowering generator control-flow and variables has to happen before we do anything else
// to them. We run some optimizations before that, because they may be harder to do on the state
// machine than on MIR with async primitives.
let optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[
&lower_slice_len::LowerSliceLenCalls, // has to be done before inlining, otherwise actual call will be almost always inlined. Also simple, so can just do first
&unreachable_prop::UnreachablePropagation,
&uninhabited_enum_branching::UninhabitedEnumBranching,
&simplify::SimplifyCfg::new("after-uninhabited-enum-branching"),
&inline::Inline,
&generator::StateTransform,
];
// Even if we don't do optimizations, we still have to lower generators for codegen.
let no_optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[&generator::StateTransform];
// The main optimizations that we do on MIR.
let optimizations: &[&dyn MirPass<'tcx>] = &[
&remove_storage_markers::RemoveStorageMarkers,
&remove_zsts::RemoveZsts,
&const_goto::ConstGoto,
&remove_unneeded_drops::RemoveUnneededDrops,
&match_branches::MatchBranchSimplification,
// inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
&multiple_return_terminators::MultipleReturnTerminators,
&instcombine::InstCombine,
&separate_const_switch::SeparateConstSwitch,
&const_prop::ConstProp,
&simplify_branches::SimplifyBranches::new("after-const-prop"),
&early_otherwise_branch::EarlyOtherwiseBranch,
&simplify_comparison_integral::SimplifyComparisonIntegral,
&simplify_try::SimplifyArmIdentity,
&simplify_try::SimplifyBranchSame,
&dest_prop::DestinationPropagation,
&simplify_branches::SimplifyBranches::new("final"),
&remove_noop_landing_pads::RemoveNoopLandingPads,
&simplify::SimplifyCfg::new("final"),
&nrvo::RenameReturnPlace,
&const_debuginfo::ConstDebugInfo,
&simplify::SimplifyLocals,
&multiple_return_terminators::MultipleReturnTerminators,
&deduplicate_blocks::DeduplicateBlocks,
];
// Optimizations to run even if mir optimizations have been disabled.
let no_optimizations: &[&dyn MirPass<'tcx>] = &[
// FIXME(#70073): This pass is responsible for both optimization as well as some lints.
&const_prop::ConstProp,
];
// Some cleanup necessary at least for LLVM and potentially other codegen backends.
let pre_codegen_cleanup: &[&dyn MirPass<'tcx>] = &[
&add_call_guards::CriticalCallEdges,
// Dump the end result for testing and debugging purposes.
&dump_mir::Marker("PreCodegen"),
];
// End of pass declarations, now actually run the passes.
// Generator Lowering
#[rustfmt::skip]
run_passes(
tcx,
body,
MirPhase::GeneratorLowering,
&[
if mir_opt_level > 0 {
optimizations_with_generators
} else {
no_optimizations_with_generators
}
],
);
// Main optimization passes
#[rustfmt::skip]
run_passes(
tcx,
body,
MirPhase::Optimization,
&[
if mir_opt_level > 0 { optimizations } else { no_optimizations },
pre_codegen_cleanup,
],
);
}
/// Optimize the MIR and prepare it for codegen.
fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> {
let did = did.expect_local();
assert_eq!(ty::WithOptConstParam::try_lookup(did, tcx), None);
tcx.arena.alloc(inner_optimized_mir(tcx, did))
}
fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
if tcx.is_constructor(did.to_def_id()) {
// There's no reason to run all of the MIR passes on constructors when
// we can just output the MIR we want directly. This also saves const
// qualification and borrow checking the trouble of special casing
// constructors.
return shim::build_adt_ctor(tcx, did.to_def_id());
}
match tcx.hir().body_const_context(did) {
// Run the `mir_for_ctfe` query, which depends on `mir_drops_elaborated_and_const_checked`
// which we are going to steal below. Thus we need to run `mir_for_ctfe` first, so it
// computes and caches its result.
Some(hir::ConstContext::ConstFn) => tcx.ensure().mir_for_ctfe(did),
None => {}
Some(other) => panic!("do not use `optimized_mir` for constants: {:?}", other),
}
let mut body =
tcx.mir_drops_elaborated_and_const_checked(ty::WithOptConstParam::unknown(did)).steal();
run_optimization_passes(tcx, &mut body);
debug_assert!(!body.has_free_regions(tcx), "Free regions in optimized MIR");
body
}
/// Fetch all the promoteds of an item and prepare their MIR bodies to be ready for
/// constant evaluation once all substitutions become known.
fn promoted_mir<'tcx>(
tcx: TyCtxt<'tcx>,
def: ty::WithOptConstParam<LocalDefId>,
) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
if tcx.is_constructor(def.did.to_def_id()) {
return tcx.arena.alloc(IndexVec::new());
}
if let Some(param_did) = def.const_param_did {
tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
} else {
tcx.ensure().mir_borrowck(def.did);
}
let (_, promoted) = tcx.mir_promoted(def);
let mut promoted = promoted.steal();
for body in &mut promoted {
run_post_borrowck_cleanup_passes(tcx, body);
}
debug_assert!(!promoted.has_free_regions(tcx), "Free regions in promoted MIR");
tcx.arena.alloc(promoted)
}

View file

@ -7,10 +7,10 @@
pub mod collect_writes;
mod find_self_call;
mod generic_graph;
pub(crate) mod generic_graphviz;
pub mod generic_graphviz;
mod graphviz;
pub mod pretty;
pub(crate) mod spanview;
pub mod spanview;
pub use self::aggregate::expand_aggregate;
pub use self::alignment::is_disaligned;

View file

@ -7,7 +7,6 @@
use super::graphviz::write_mir_fn_graphviz;
use super::spanview::write_mir_fn_spanview;
use crate::transform::MirSource;
use either::Either;
use rustc_data_structures::fx::FxHashMap;
use rustc_hir::def_id::DefId;
@ -16,6 +15,7 @@
read_target_uint, AllocId, Allocation, ConstValue, GlobalAlloc, Pointer, Provenance,
};
use rustc_middle::mir::visit::Visitor;
use rustc_middle::mir::MirSource;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, TyCtxt, TyS, TypeFoldable, TypeVisitor};
use rustc_target::abi::Size;

View file

@ -0,0 +1,29 @@
[package]
authors = ["The Rust Project Developers"]
name = "rustc_mir_transform"
version = "0.0.0"
edition = "2018"
[lib]
doctest = false
[dependencies]
itertools = "0.9"
smallvec = { version = "1.6.1", features = ["union", "may_dangle"] }
tracing = "0.1"
rustc_ast = { path = "../rustc_ast" }
rustc_attr = { path = "../rustc_attr" }
rustc_data_structures = { path = "../rustc_data_structures" }
rustc_errors = { path = "../rustc_errors" }
rustc_hir = { path = "../rustc_hir" }
rustc_index = { path = "../rustc_index" }
rustc_middle = { path = "../rustc_middle" }
rustc_mir = { path = "../rustc_mir" }
rustc_serialize = { path = "../rustc_serialize" }
rustc_session = { path = "../rustc_session" }
rustc_target = { path = "../rustc_target" }
rustc_trait_selection = { path = "../rustc_trait_selection" }
rustc_span = { path = "../rustc_span" }
[dev-dependencies]
coverage_test_macros = { path = "src/coverage/test_macros" }

View file

@ -1,4 +1,4 @@
use crate::transform::MirPass;
use crate::MirPass;
use rustc_hir::def::DefKind;
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
use rustc_middle::mir::*;

View file

@ -1,4 +1,4 @@
use crate::transform::MirPass;
use crate::MirPass;
use rustc_index::vec::{Idx, IndexVec};
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;

View file

@ -1,9 +1,9 @@
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;
use crate::transform::MirPass;
use crate::util;
use crate::util::patch::MirPatch;
use crate::MirPass;
// This pass moves values being dropped that are within a packed
// struct to a separate local before dropping them, to ensure that

View file

@ -4,7 +4,7 @@
//! of MIR building, and only after this pass we think of the program has having the
//! normal MIR semantics.
use crate::transform::MirPass;
use crate::MirPass;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty, TyCtxt};

View file

@ -6,7 +6,7 @@
use rustc_session::lint::builtin::CONST_ITEM_MUTATION;
use rustc_span::def_id::DefId;
use crate::transform::MirPass;
use crate::MirPass;
pub struct CheckConstItemMutation;

View file

@ -6,8 +6,8 @@
use rustc_session::lint::builtin::UNALIGNED_REFERENCES;
use rustc_span::symbol::sym;
use crate::transform::MirPass;
use crate::util;
use crate::MirPass;
pub(crate) fn provide(providers: &mut Providers) {
*providers = Providers { unsafe_derive_on_repr_packed, ..*providers };

View file

@ -18,7 +18,7 @@
//! [`ForMatchGuard`]: rustc_middle::mir::FakeReadCause::ForMatchGuard
//! [`Nop`]: rustc_middle::mir::StatementKind::Nop
use crate::transform::MirPass;
use crate::MirPass;
use rustc_middle::mir::visit::MutVisitor;
use rustc_middle::mir::{Body, BorrowKind, Location, Rvalue};
use rustc_middle::mir::{Statement, StatementKind};

View file

@ -9,7 +9,7 @@
ty::TyCtxt,
};
use crate::transform::MirPass;
use crate::MirPass;
use rustc_index::{bit_set::BitSet, vec::IndexVec};
pub struct ConstDebugInfo;

View file

@ -17,7 +17,7 @@
//! }
//! ```
use crate::transform::MirPass;
use crate::MirPass;
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;
use rustc_middle::{mir::visit::Visitor, ty::ParamEnv};

View file

@ -28,13 +28,13 @@
use rustc_target::spec::abi::Abi;
use rustc_trait_selection::traits;
use crate::const_eval::ConstEvalErr;
use crate::interpret::{
use crate::MirPass;
use rustc_mir::const_eval::ConstEvalErr;
use rustc_mir::interpret::{
self, compile_time_machine, AllocId, Allocation, ConstValue, CtfeValidationMode, Frame, ImmTy,
Immediate, InterpCx, InterpResult, LocalState, LocalValue, MemPlace, MemoryKind, OpTy,
Operand as InterpOperand, PlaceTy, Scalar, ScalarMaybeUninit, StackPopCleanup, StackPopUnwind,
};
use crate::transform::MirPass;
/// The maximum number of bytes that we'll allocate space for a local or the return value.
/// Needed for #66397, because otherwise we eval into large places and that can cause OOM or just

View file

@ -44,7 +44,7 @@
//! points, which can be enabled via environment variable:
//!
//! ```shell
//! RUSTC_LOG=rustc_mir::transform::coverage=debug
//! RUSTC_LOG=rustc_mir_transform::transform::coverage=debug
//! ```
//!
//! Other module paths with coverage-related debug logs may also be of interest, particularly for
@ -52,7 +52,7 @@
//! code generation pass). For example:
//!
//! ```shell
//! RUSTC_LOG=rustc_mir::transform::coverage,rustc_codegen_ssa::coverageinfo,rustc_codegen_llvm::coverageinfo=debug
//! RUSTC_LOG=rustc_mir_transform::transform::coverage,rustc_codegen_ssa::coverageinfo,rustc_codegen_llvm::coverageinfo=debug
//! ```
//!
//! Coverage Debug Options
@ -181,13 +181,11 @@ fn from_env() -> Self {
}
};
}
_ => {
bug!(
"Unsupported setting `{}` in environment variable {}",
option,
RUSTC_COVERAGE_DEBUG_OPTIONS
)
}
_ => bug!(
"Unsupported setting `{}` in environment variable {}",
option,
RUSTC_COVERAGE_DEBUG_OPTIONS
),
};
}
}

View file

@ -12,8 +12,8 @@
use graph::{BasicCoverageBlock, BasicCoverageBlockData, CoverageGraph};
use spans::{CoverageSpan, CoverageSpans};
use crate::transform::MirPass;
use crate::util::pretty;
use crate::MirPass;
use rustc_data_structures::fingerprint::Fingerprint;
use rustc_data_structures::graph::WithNumNodes;

View file

@ -1,5 +1,5 @@
use crate::transform::MirPass;
use crate::util::expand_aggregate;
use crate::MirPass;
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;

View file

@ -3,7 +3,7 @@
use std::{collections::hash_map::Entry, hash::Hash, hash::Hasher, iter};
use crate::transform::MirPass;
use crate::MirPass;
use rustc_data_structures::fx::FxHashMap;
use rustc_middle::mir::visit::MutVisitor;

View file

@ -96,11 +96,9 @@
//! [previous attempt]: https://github.com/rust-lang/rust/pull/47954
//! [subsequent approach]: https://github.com/rust-lang/rust/pull/71003
use crate::dataflow::impls::{MaybeInitializedLocals, MaybeLiveLocals};
use crate::dataflow::Analysis;
use crate::{
transform::MirPass,
util::{dump_mir, PassWhere},
MirPass,
};
use itertools::Itertools;
use rustc_data_structures::unify::{InPlaceUnificationTable, UnifyKey};
@ -115,6 +113,8 @@
Rvalue, Statement, StatementKind, Terminator, TerminatorKind,
};
use rustc_middle::ty::TyCtxt;
use rustc_mir::dataflow::impls::{MaybeInitializedLocals, MaybeLiveLocals};
use rustc_mir::dataflow::Analysis;
// Empirical measurements have resulted in some observations:
// - Running on a body with a single block and 500 locals takes barely any time

View file

@ -5,8 +5,8 @@
use std::fs::File;
use std::io;
use crate::transform::MirPass;
use crate::util as mir_util;
use crate::MirPass;
use rustc_middle::mir::Body;
use rustc_middle::ty::TyCtxt;
use rustc_session::config::{OutputFilenames, OutputType};

View file

@ -1,4 +1,4 @@
use crate::{transform::MirPass, util::patch::MirPatch};
use crate::{util::patch::MirPatch, MirPass};
use rustc_middle::mir::*;
use rustc_middle::ty::{Ty, TyCtxt};
use std::fmt::Debug;

View file

@ -1,18 +1,18 @@
use crate::dataflow;
use crate::dataflow::impls::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
use crate::dataflow::move_paths::{LookupResult, MoveData, MovePathIndex};
use crate::dataflow::on_lookup_result_bits;
use crate::dataflow::MoveDataParamEnv;
use crate::dataflow::{on_all_children_bits, on_all_drop_children_bits};
use crate::dataflow::{Analysis, ResultsCursor};
use crate::transform::MirPass;
use crate::util::elaborate_drops::{elaborate_drop, DropFlagState, Unwind};
use crate::util::elaborate_drops::{DropElaborator, DropFlagMode, DropStyle};
use crate::util::patch::MirPatch;
use crate::MirPass;
use rustc_data_structures::fx::FxHashMap;
use rustc_index::bit_set::BitSet;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, TyCtxt};
use rustc_mir::dataflow;
use rustc_mir::dataflow::impls::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
use rustc_mir::dataflow::move_paths::{LookupResult, MoveData, MovePathIndex};
use rustc_mir::dataflow::on_lookup_result_bits;
use rustc_mir::dataflow::MoveDataParamEnv;
use rustc_mir::dataflow::{on_all_children_bits, on_all_drop_children_bits};
use rustc_mir::dataflow::{Analysis, ResultsCursor};
use rustc_span::Span;
use rustc_target::abi::VariantIdx;
use std::fmt;

View file

@ -11,7 +11,7 @@
use rustc_span::{symbol::sym, Span};
use rustc_target::spec::abi::Abi;
use crate::transform::MirPass;
use crate::MirPass;
pub struct FunctionItemReferences;

View file

@ -49,15 +49,11 @@
//! For generators with state 1 (returned) and state 2 (poisoned) it does nothing.
//! Otherwise it drops all the values in scope at the last suspension point.
use crate::dataflow::impls::{
MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive,
};
use crate::dataflow::{self, Analysis};
use crate::transform::simplify;
use crate::transform::MirPass;
use crate::simplify;
use crate::util::dump_mir;
use crate::util::expand_aggregate;
use crate::util::storage;
use crate::MirPass;
use rustc_data_structures::fx::FxHashMap;
use rustc_hir as hir;
use rustc_hir::lang_items::LangItem;
@ -68,6 +64,10 @@
use rustc_middle::ty::subst::{Subst, SubstsRef};
use rustc_middle::ty::GeneratorSubsts;
use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
use rustc_mir::dataflow::impls::{
MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive,
};
use rustc_mir::dataflow::{self, Analysis};
use rustc_target::abi::VariantIdx;
use rustc_target::spec::PanicStrategy;
use std::{iter, ops};

View file

@ -13,7 +13,7 @@
use rustc_target::spec::abi::Abi;
use super::simplify::{remove_dead_blocks, CfgSimplifier};
use crate::transform::MirPass;
use crate::MirPass;
use std::iter;
use std::ops::{Range, RangeFrom};

View file

@ -1,6 +1,6 @@
//! Performs various peephole optimizations.
use crate::transform::MirPass;
use crate::MirPass;
use rustc_hir::Mutability;
use rustc_middle::mir::{
BinOp, Body, Constant, LocalDecls, Operand, Place, ProjectionElem, Rvalue, SourceInfo,

View file

@ -0,0 +1,632 @@
#![feature(bindings_after_at)]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(crate_visibility_modifier)]
#![feature(const_panic)]
#![feature(in_band_lifetimes)]
#![feature(iter_zip)]
#![feature(map_try_insert)]
#![feature(min_specialization)]
#![feature(option_get_or_insert_default)]
#![feature(once_cell)]
#![feature(never_type)]
#![feature(trusted_step)]
#![feature(try_blocks)]
#[macro_use]
extern crate tracing;
#[macro_use]
extern crate rustc_middle;
use required_consts::RequiredConstsVisitor;
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::steal::Steal;
use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_index::vec::IndexVec;
use rustc_middle::mir::visit::Visitor as _;
use rustc_middle::mir::{traversal, Body, ConstQualifs, MirPhase, Promoted};
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::{self, TyCtxt, TypeFoldable};
use rustc_mir::util;
use rustc_span::{Span, Symbol};
mod abort_unwinding_calls;
mod add_call_guards;
mod add_moves_for_packed_drops;
mod add_retag;
mod check_const_item_mutation;
mod check_packed_ref;
pub mod check_unsafety;
mod cleanup_post_borrowck;
mod const_debuginfo;
mod const_goto;
mod const_prop;
mod coverage;
mod deaggregator;
mod deduplicate_blocks;
mod dest_prop;
pub mod dump_mir;
mod early_otherwise_branch;
mod elaborate_drops;
mod function_item_references;
mod generator;
mod inline;
mod instcombine;
mod lower_intrinsics;
mod lower_slice_len;
mod match_branches;
mod multiple_return_terminators;
mod nrvo;
mod remove_noop_landing_pads;
mod remove_storage_markers;
mod remove_unneeded_drops;
mod remove_zsts;
mod required_consts;
mod separate_const_switch;
mod shim;
mod simplify;
mod simplify_branches;
mod simplify_comparison_integral;
mod simplify_try;
mod uninhabited_enum_branching;
mod unreachable_prop;
use rustc_mir::transform::check_consts;
use rustc_mir::transform::promote_consts;
use rustc_mir::transform::rustc_peek;
use rustc_mir::transform::validate;
use rustc_mir::transform::MirPass;
pub fn provide(providers: &mut Providers) {
check_unsafety::provide(providers);
check_packed_ref::provide(providers);
coverage::query::provide(providers);
shim::provide(providers);
*providers = Providers {
mir_keys,
mir_const,
mir_const_qualif: |tcx, def_id| {
let def_id = def_id.expect_local();
if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
tcx.mir_const_qualif_const_arg(def)
} else {
mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
}
},
mir_const_qualif_const_arg: |tcx, (did, param_did)| {
mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
},
mir_promoted,
mir_drops_elaborated_and_const_checked,
mir_for_ctfe,
mir_for_ctfe_of_const_arg,
optimized_mir,
is_mir_available,
is_ctfe_mir_available: |tcx, did| is_mir_available(tcx, did),
mir_callgraph_reachable: inline::cycle::mir_callgraph_reachable,
mir_inliner_callees: inline::cycle::mir_inliner_callees,
promoted_mir: |tcx, def_id| {
let def_id = def_id.expect_local();
if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
tcx.promoted_mir_of_const_arg(def)
} else {
promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
}
},
promoted_mir_of_const_arg: |tcx, (did, param_did)| {
promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
},
..*providers
};
}
fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
let def_id = def_id.expect_local();
tcx.mir_keys(()).contains(&def_id)
}
/// Finds the full set of `DefId`s within the current crate that have
/// MIR associated with them.
fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxHashSet<LocalDefId> {
let mut set = FxHashSet::default();
// All body-owners have MIR associated with them.
set.extend(tcx.body_owners());
// Additionally, tuple struct/variant constructors have MIR, but
// they don't have a BodyId, so we need to build them separately.
struct GatherCtors<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
set: &'a mut FxHashSet<LocalDefId>,
}
impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
fn visit_variant_data(
&mut self,
v: &'tcx hir::VariantData<'tcx>,
_: Symbol,
_: &'tcx hir::Generics<'tcx>,
_: hir::HirId,
_: Span,
) {
if let hir::VariantData::Tuple(_, hir_id) = *v {
self.set.insert(self.tcx.hir().local_def_id(hir_id));
}
intravisit::walk_struct_def(self, v)
}
type Map = intravisit::ErasedMap<'tcx>;
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
NestedVisitorMap::None
}
}
tcx.hir()
.krate()
.visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
set
}
fn run_passes(
tcx: TyCtxt<'tcx>,
body: &mut Body<'tcx>,
mir_phase: MirPhase,
passes: &[&[&dyn MirPass<'tcx>]],
) {
let phase_index = mir_phase.phase_index();
let validate = tcx.sess.opts.debugging_opts.validate_mir;
if body.phase >= mir_phase {
return;
}
if validate {
validate::Validator { when: format!("input to phase {:?}", mir_phase), mir_phase }
.run_pass(tcx, body);
}
let mut index = 0;
let mut run_pass = |pass: &dyn MirPass<'tcx>| {
let run_hooks = |body: &_, index, is_after| {
dump_mir::on_mir_pass(
tcx,
&format_args!("{:03}-{:03}", phase_index, index),
&pass.name(),
body,
is_after,
);
};
run_hooks(body, index, false);
pass.run_pass(tcx, body);
run_hooks(body, index, true);
if validate {
validate::Validator {
when: format!("after {} in phase {:?}", pass.name(), mir_phase),
mir_phase,
}
.run_pass(tcx, body);
}
index += 1;
};
for pass_group in passes {
for pass in *pass_group {
run_pass(*pass);
}
}
body.phase = mir_phase;
if mir_phase == MirPhase::Optimization {
validate::Validator { when: format!("end of phase {:?}", mir_phase), mir_phase }
.run_pass(tcx, body);
}
}
fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
let const_kind = tcx.hir().body_const_context(def.did);
// No need to const-check a non-const `fn`.
if const_kind.is_none() {
return Default::default();
}
// N.B., this `borrow()` is guaranteed to be valid (i.e., the value
// cannot yet be stolen), because `mir_promoted()`, which steals
// from `mir_const(), forces this query to execute before
// performing the steal.
let body = &tcx.mir_const(def).borrow();
if body.return_ty().references_error() {
tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
return Default::default();
}
let ccx = check_consts::ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def.did) };
let mut validator = check_consts::check::Checker::new(&ccx);
validator.check_body();
// We return the qualifs in the return place for every MIR body, even though it is only used
// when deciding to promote a reference to a `const` for now.
validator.qualifs_in_return_place()
}
/// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
fn mir_const<'tcx>(
tcx: TyCtxt<'tcx>,
def: ty::WithOptConstParam<LocalDefId>,
) -> &'tcx Steal<Body<'tcx>> {
if let Some(def) = def.try_upgrade(tcx) {
return tcx.mir_const(def);
}
// Unsafety check uses the raw mir, so make sure it is run.
if !tcx.sess.opts.debugging_opts.thir_unsafeck {
if let Some(param_did) = def.const_param_did {
tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did));
} else {
tcx.ensure().unsafety_check_result(def.did);
}
}
let mut body = tcx.mir_built(def).steal();
util::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(()));
run_passes(
tcx,
&mut body,
MirPhase::Const,
&[&[
// MIR-level lints.
&check_packed_ref::CheckPackedRef,
&check_const_item_mutation::CheckConstItemMutation,
&function_item_references::FunctionItemReferences,
// What we need to do constant evaluation.
&simplify::SimplifyCfg::new("initial"),
&rustc_peek::SanityCheck,
]],
);
tcx.alloc_steal_mir(body)
}
/// Compute the main MIR body and the list of MIR bodies of the promoteds.
fn mir_promoted(
tcx: TyCtxt<'tcx>,
def: ty::WithOptConstParam<LocalDefId>,
) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
if let Some(def) = def.try_upgrade(tcx) {
return tcx.mir_promoted(def);
}
// Ensure that we compute the `mir_const_qualif` for constants at
// this point, before we steal the mir-const result.
// Also this means promotion can rely on all const checks having been done.
let _ = tcx.mir_const_qualif_opt_const_arg(def);
let _ = tcx.mir_abstract_const_opt_const_arg(def.to_global());
let mut body = tcx.mir_const(def).steal();
let mut required_consts = Vec::new();
let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
for (bb, bb_data) in traversal::reverse_postorder(&body) {
required_consts_visitor.visit_basic_block_data(bb, bb_data);
}
body.required_consts = required_consts;
let promote_pass = promote_consts::PromoteTemps::default();
let promote: &[&dyn MirPass<'tcx>] = &[
// What we need to run borrowck etc.
&promote_pass,
&simplify::SimplifyCfg::new("promote-consts"),
];
let opt_coverage: &[&dyn MirPass<'tcx>] =
if tcx.sess.instrument_coverage() { &[&coverage::InstrumentCoverage] } else { &[] };
run_passes(tcx, &mut body, MirPhase::ConstPromotion, &[promote, opt_coverage]);
let promoted = promote_pass.promoted_fragments.into_inner();
(tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
}
/// Compute the MIR that is used during CTFE (and thus has no optimizations run on it)
fn mir_for_ctfe<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Body<'tcx> {
let did = def_id.expect_local();
if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
tcx.mir_for_ctfe_of_const_arg(def)
} else {
tcx.arena.alloc(inner_mir_for_ctfe(tcx, ty::WithOptConstParam::unknown(did)))
}
}
/// Same as `mir_for_ctfe`, but used to get the MIR of a const generic parameter.
/// The docs on `WithOptConstParam` explain this a bit more, but the TLDR is that
/// we'd get cycle errors with `mir_for_ctfe`, because typeck would need to typeck
/// the const parameter while type checking the main body, which in turn would try
/// to type check the main body again.
fn mir_for_ctfe_of_const_arg<'tcx>(
tcx: TyCtxt<'tcx>,
(did, param_did): (LocalDefId, DefId),
) -> &'tcx Body<'tcx> {
tcx.arena.alloc(inner_mir_for_ctfe(
tcx,
ty::WithOptConstParam { did, const_param_did: Some(param_did) },
))
}
fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
// FIXME: don't duplicate this between the optimized_mir/mir_for_ctfe queries
if tcx.is_constructor(def.did.to_def_id()) {
// There's no reason to run all of the MIR passes on constructors when
// we can just output the MIR we want directly. This also saves const
// qualification and borrow checking the trouble of special casing
// constructors.
return shim::build_adt_ctor(tcx, def.did.to_def_id());
}
let context = tcx
.hir()
.body_const_context(def.did)
.expect("mir_for_ctfe should not be used for runtime functions");
let mut body = tcx.mir_drops_elaborated_and_const_checked(def).borrow().clone();
match context {
// Do not const prop functions, either they get executed at runtime or exported to metadata,
// so we run const prop on them, or they don't, in which case we const evaluate some control
// flow paths of the function and any errors in those paths will get emitted as const eval
// errors.
hir::ConstContext::ConstFn => {}
// Static items always get evaluated, so we can just let const eval see if any erroneous
// control flow paths get executed.
hir::ConstContext::Static(_) => {}
// Associated constants get const prop run so we detect common failure situations in the
// crate that defined the constant.
// Technically we want to not run on regular const items, but oli-obk doesn't know how to
// conveniently detect that at this point without looking at the HIR.
hir::ConstContext::Const => {
#[rustfmt::skip]
let optimizations: &[&dyn MirPass<'_>] = &[
&const_prop::ConstProp,
];
#[rustfmt::skip]
run_passes(
tcx,
&mut body,
MirPhase::Optimization,
&[
optimizations,
],
);
}
}
debug_assert!(!body.has_free_regions(tcx), "Free regions in MIR for CTFE");
body
}
/// Obtain just the main MIR (no promoteds) and run some cleanups on it. This also runs
/// mir borrowck *before* doing so in order to ensure that borrowck can be run and doesn't
/// end up missing the source MIR due to stealing happening.
fn mir_drops_elaborated_and_const_checked<'tcx>(
tcx: TyCtxt<'tcx>,
def: ty::WithOptConstParam<LocalDefId>,
) -> &'tcx Steal<Body<'tcx>> {
if let Some(def) = def.try_upgrade(tcx) {
return tcx.mir_drops_elaborated_and_const_checked(def);
}
// (Mir-)Borrowck uses `mir_promoted`, so we have to force it to
// execute before we can steal.
if let Some(param_did) = def.const_param_did {
tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
} else {
tcx.ensure().mir_borrowck(def.did);
}
let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
use rustc_middle::hir::map::blocks::FnLikeNode;
let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some();
if is_fn_like {
let did = def.did.to_def_id();
let def = ty::WithOptConstParam::unknown(did);
// Do not compute the mir call graph without said call graph actually being used.
if inline::is_enabled(tcx) {
let _ = tcx.mir_inliner_callees(ty::InstanceDef::Item(def));
}
}
let (body, _) = tcx.mir_promoted(def);
let mut body = body.steal();
run_post_borrowck_cleanup_passes(tcx, &mut body);
check_consts::post_drop_elaboration::check_live_drops(tcx, &body);
tcx.alloc_steal_mir(body)
}
/// After this series of passes, no lifetime analysis based on borrowing can be done.
fn run_post_borrowck_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
debug!("post_borrowck_cleanup({:?})", body.source.def_id());
let post_borrowck_cleanup: &[&dyn MirPass<'tcx>] = &[
// Remove all things only needed by analysis
&simplify_branches::SimplifyBranches::new("initial"),
&remove_noop_landing_pads::RemoveNoopLandingPads,
&cleanup_post_borrowck::CleanupNonCodegenStatements,
&simplify::SimplifyCfg::new("early-opt"),
// These next passes must be executed together
&add_call_guards::CriticalCallEdges,
&elaborate_drops::ElaborateDrops,
// This will remove extraneous landing pads which are no longer
// necessary as well as well as forcing any call in a non-unwinding
// function calling a possibly-unwinding function to abort the process.
&abort_unwinding_calls::AbortUnwindingCalls,
// AddMovesForPackedDrops needs to run after drop
// elaboration.
&add_moves_for_packed_drops::AddMovesForPackedDrops,
// `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
// but before optimizations begin.
&add_retag::AddRetag,
&lower_intrinsics::LowerIntrinsics,
&simplify::SimplifyCfg::new("elaborate-drops"),
// `Deaggregator` is conceptually part of MIR building, some backends rely on it happening
// and it can help optimizations.
&deaggregator::Deaggregator,
];
run_passes(tcx, body, MirPhase::DropLowering, &[post_borrowck_cleanup]);
}
fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
let mir_opt_level = tcx.sess.mir_opt_level();
// Lowering generator control-flow and variables has to happen before we do anything else
// to them. We run some optimizations before that, because they may be harder to do on the state
// machine than on MIR with async primitives.
let optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[
&lower_slice_len::LowerSliceLenCalls, // has to be done before inlining, otherwise actual call will be almost always inlined. Also simple, so can just do first
&unreachable_prop::UnreachablePropagation,
&uninhabited_enum_branching::UninhabitedEnumBranching,
&simplify::SimplifyCfg::new("after-uninhabited-enum-branching"),
&inline::Inline,
&generator::StateTransform,
];
// Even if we don't do optimizations, we still have to lower generators for codegen.
let no_optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[&generator::StateTransform];
// The main optimizations that we do on MIR.
let optimizations: &[&dyn MirPass<'tcx>] = &[
&remove_storage_markers::RemoveStorageMarkers,
&remove_zsts::RemoveZsts,
&const_goto::ConstGoto,
&remove_unneeded_drops::RemoveUnneededDrops,
&match_branches::MatchBranchSimplification,
// inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
&multiple_return_terminators::MultipleReturnTerminators,
&instcombine::InstCombine,
&separate_const_switch::SeparateConstSwitch,
&const_prop::ConstProp,
&simplify_branches::SimplifyBranches::new("after-const-prop"),
&early_otherwise_branch::EarlyOtherwiseBranch,
&simplify_comparison_integral::SimplifyComparisonIntegral,
&simplify_try::SimplifyArmIdentity,
&simplify_try::SimplifyBranchSame,
&dest_prop::DestinationPropagation,
&simplify_branches::SimplifyBranches::new("final"),
&remove_noop_landing_pads::RemoveNoopLandingPads,
&simplify::SimplifyCfg::new("final"),
&nrvo::RenameReturnPlace,
&const_debuginfo::ConstDebugInfo,
&simplify::SimplifyLocals,
&multiple_return_terminators::MultipleReturnTerminators,
&deduplicate_blocks::DeduplicateBlocks,
];
// Optimizations to run even if mir optimizations have been disabled.
let no_optimizations: &[&dyn MirPass<'tcx>] = &[
// FIXME(#70073): This pass is responsible for both optimization as well as some lints.
&const_prop::ConstProp,
];
// Some cleanup necessary at least for LLVM and potentially other codegen backends.
let pre_codegen_cleanup: &[&dyn MirPass<'tcx>] = &[
&add_call_guards::CriticalCallEdges,
// Dump the end result for testing and debugging purposes.
&dump_mir::Marker("PreCodegen"),
];
// End of pass declarations, now actually run the passes.
// Generator Lowering
#[rustfmt::skip]
run_passes(
tcx,
body,
MirPhase::GeneratorLowering,
&[
if mir_opt_level > 0 {
optimizations_with_generators
} else {
no_optimizations_with_generators
}
],
);
// Main optimization passes
#[rustfmt::skip]
run_passes(
tcx,
body,
MirPhase::Optimization,
&[
if mir_opt_level > 0 { optimizations } else { no_optimizations },
pre_codegen_cleanup,
],
);
}
/// Optimize the MIR and prepare it for codegen.
fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> {
let did = did.expect_local();
assert_eq!(ty::WithOptConstParam::try_lookup(did, tcx), None);
tcx.arena.alloc(inner_optimized_mir(tcx, did))
}
fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
if tcx.is_constructor(did.to_def_id()) {
// There's no reason to run all of the MIR passes on constructors when
// we can just output the MIR we want directly. This also saves const
// qualification and borrow checking the trouble of special casing
// constructors.
return shim::build_adt_ctor(tcx, did.to_def_id());
}
match tcx.hir().body_const_context(did) {
// Run the `mir_for_ctfe` query, which depends on `mir_drops_elaborated_and_const_checked`
// which we are going to steal below. Thus we need to run `mir_for_ctfe` first, so it
// computes and caches its result.
Some(hir::ConstContext::ConstFn) => tcx.ensure().mir_for_ctfe(did),
None => {}
Some(other) => panic!("do not use `optimized_mir` for constants: {:?}", other),
}
let mut body =
tcx.mir_drops_elaborated_and_const_checked(ty::WithOptConstParam::unknown(did)).steal();
run_optimization_passes(tcx, &mut body);
debug_assert!(!body.has_free_regions(tcx), "Free regions in optimized MIR");
body
}
/// Fetch all the promoteds of an item and prepare their MIR bodies to be ready for
/// constant evaluation once all substitutions become known.
fn promoted_mir<'tcx>(
tcx: TyCtxt<'tcx>,
def: ty::WithOptConstParam<LocalDefId>,
) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
if tcx.is_constructor(def.did.to_def_id()) {
return tcx.arena.alloc(IndexVec::new());
}
if let Some(param_did) = def.const_param_did {
tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
} else {
tcx.ensure().mir_borrowck(def.did);
}
let (_, promoted) = tcx.mir_promoted(def);
let mut promoted = promoted.steal();
for body in &mut promoted {
run_post_borrowck_cleanup_passes(tcx, body);
}
debug_assert!(!promoted.has_free_regions(tcx), "Free regions in promoted MIR");
tcx.arena.alloc(promoted)
}

View file

@ -1,6 +1,6 @@
//! Lowers intrinsic calls
use crate::transform::MirPass;
use crate::MirPass;
use rustc_middle::mir::*;
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{self, Ty, TyCtxt};

View file

@ -1,11 +1,11 @@
//! This pass lowers calls to core::slice::len to just Len op.
//! It should run before inlining!
use crate::transform::MirPass;
use rustc_hir::def_id::DefId;
use rustc_index::vec::IndexVec;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, TyCtxt};
use rustc_mir::transform::MirPass;
pub struct LowerSliceLenCalls;

View file

@ -1,4 +1,4 @@
use crate::transform::MirPass;
use crate::MirPass;
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;
use std::iter;
@ -134,7 +134,7 @@ fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
let const_cmp = Operand::const_from_scalar(
tcx,
switch_ty,
crate::interpret::Scalar::from_uint(val, size),
rustc_mir::interpret::Scalar::from_uint(val, size),
rustc_span::DUMMY_SP,
);
let op = if f_b { BinOp::Eq } else { BinOp::Ne };

View file

@ -1,7 +1,7 @@
//! This pass removes jumps to basic blocks containing only a return, and replaces them with a
//! return instead.
use crate::transform::{simplify, MirPass};
use crate::{simplify, MirPass};
use rustc_index::bit_set::BitSet;
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;

View file

@ -6,7 +6,7 @@
use rustc_middle::mir::{self, BasicBlock, Local, Location};
use rustc_middle::ty::TyCtxt;
use crate::transform::MirPass;
use crate::MirPass;
/// This pass looks for MIR that always copies the same local into the return place and eliminates
/// the copy by renaming all uses of that local to `_0`.

View file

@ -1,5 +1,5 @@
use crate::transform::MirPass;
use crate::util::patch::MirPatch;
use crate::MirPass;
use rustc_index::bit_set::BitSet;
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;

View file

@ -1,6 +1,6 @@
//! This pass removes storage markers if they won't be emitted during codegen.
use crate::transform::MirPass;
use crate::MirPass;
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;

View file

@ -1,6 +1,6 @@
//! This pass replaces a drop of a type that does not need dropping, with a goto
use crate::transform::MirPass;
use crate::MirPass;
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;

View file

@ -1,6 +1,6 @@
//! Removes assignments to ZST places.
use crate::transform::MirPass;
use crate::MirPass;
use rustc_middle::mir::tcx::PlaceTy;
use rustc_middle::mir::{Body, LocalDecls, Place, StatementKind};
use rustc_middle::ty::{self, Ty, TyCtxt};

View file

@ -37,7 +37,7 @@
//! simplicity rather than completeness (it notably
//! sometimes duplicates abusively).
use crate::transform::MirPass;
use crate::MirPass;
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;
use smallvec::SmallVec;

View file

@ -15,13 +15,13 @@
use std::fmt;
use std::iter;
use crate::transform::{
abort_unwinding_calls, add_call_guards, add_moves_for_packed_drops, remove_noop_landing_pads,
run_passes, simplify,
};
use crate::util::elaborate_drops::{self, DropElaborator, DropFlagMode, DropStyle};
use crate::util::expand_aggregate;
use crate::util::patch::MirPatch;
use crate::{
abort_unwinding_calls, add_call_guards, add_moves_for_packed_drops, remove_noop_landing_pads,
run_passes, simplify,
};
pub fn provide(providers: &mut Providers) {
providers.mir_shims = make_shim;

View file

@ -27,7 +27,7 @@
//! naively generate still contains the `_a = ()` write in the unreachable block "after" the
//! return.
use crate::transform::MirPass;
use crate::MirPass;
use rustc_index::vec::{Idx, IndexVec};
use rustc_middle::mir::coverage::*;
use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};

View file

@ -1,6 +1,6 @@
//! A pass that simplifies branches when their condition is known.
use crate::transform::MirPass;
use crate::MirPass;
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;

View file

@ -9,7 +9,7 @@
//!
//! into just `x`.
use crate::transform::{simplify, MirPass};
use crate::{simplify, MirPass};
use itertools::Itertools as _;
use rustc_index::{bit_set::BitSet, vec::IndexVec};
use rustc_middle::mir::visit::{NonUseContext, PlaceContext, Visitor};

View file

@ -1,6 +1,6 @@
//! A pass that eliminates branches on uninhabited enum variants.
use crate::transform::MirPass;
use crate::MirPass;
use rustc_data_structures::stable_set::FxHashSet;
use rustc_middle::mir::{
BasicBlock, BasicBlockData, Body, Local, Operand, Rvalue, StatementKind, SwitchTargets,

View file

@ -2,8 +2,8 @@
//! when all of their successors are unreachable. This is achieved through a
//! post-order traversal of the blocks.
use crate::transform::simplify;
use crate::transform::MirPass;
use crate::simplify;
use crate::MirPass;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;