use std::iter;
use rustc_abi::Integer;
use rustc_index::IndexSlice;
use rustc_middle::mir::patch::MirPatch;
use rustc_middle::mir::*;
use rustc_middle::ty::layout::{IntegerExt, TyAndLayout};
use rustc_middle::ty::{self, ScalarInt, Ty, TyCtxt};
use rustc_type_ir::TyKind::*;
use super::simplify::simplify_cfg;
pub(super) struct MatchBranchSimplification;
impl<'tcx> crate::MirPass<'tcx> for MatchBranchSimplification {
fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
sess.mir_opt_level() >= 1
}
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
let def_id = body.source.def_id();
let typing_env = body.typing_env(tcx);
let mut should_cleanup = false;
for i in 0..body.basic_blocks.len() {
let bbs = &*body.basic_blocks;
let bb_idx = BasicBlock::from_usize(i);
if !tcx.consider_optimizing(|| format!("MatchBranchSimplification {def_id:?} ")) {
continue;
}
match bbs[bb_idx].terminator().kind {
TerminatorKind::SwitchInt {
discr: ref _discr @ (Operand::Copy(_) | Operand::Move(_)),
ref targets,
..
} if !targets.all_targets().contains(&bb_idx) => {}
_ => continue,
};
if SimplifyToIf.simplify(tcx, body, bb_idx, typing_env).is_some() {
should_cleanup = true;
continue;
}
if SimplifyToExp::default().simplify(tcx, body, bb_idx, typing_env).is_some() {
should_cleanup = true;
continue;
}
}
if should_cleanup {
simplify_cfg(body);
}
}
}
trait SimplifyMatch<'tcx> {
fn simplify(
&mut self,
tcx: TyCtxt<'tcx>,
body: &mut Body<'tcx>,
switch_bb_idx: BasicBlock,
typing_env: ty::TypingEnv<'tcx>,
) -> Option<()> {
let bbs = &body.basic_blocks;
let (discr, targets) = match bbs[switch_bb_idx].terminator().kind {
TerminatorKind::SwitchInt { ref discr, ref targets, .. } => (discr, targets),
_ => unreachable!(),
};
let discr_ty = discr.ty(body.local_decls(), tcx);
self.can_simplify(tcx, targets, typing_env, bbs, discr_ty)?;
let mut patch = MirPatch::new(body);
let discr = discr.clone();
let source_info = bbs[switch_bb_idx].terminator().source_info;
let discr_local = patch.new_temp(discr_ty, source_info.span);
let (_, first) = targets.iter().next().unwrap();
let statement_index = bbs[switch_bb_idx].statements.len();
let parent_end = Location { block: switch_bb_idx, statement_index };
patch.add_statement(parent_end, StatementKind::StorageLive(discr_local));
patch.add_assign(parent_end, Place::from(discr_local), Rvalue::Use(discr));
self.new_stmts(
tcx,
targets,
typing_env,
&mut patch,
parent_end,
bbs,
discr_local,
discr_ty,
);
patch.add_statement(parent_end, StatementKind::StorageDead(discr_local));
patch.patch_terminator(switch_bb_idx, bbs[first].terminator().kind.clone());
patch.apply(body);
Some(())
}
fn can_simplify(
&mut self,
tcx: TyCtxt<'tcx>,
targets: &SwitchTargets,
typing_env: ty::TypingEnv<'tcx>,
bbs: &IndexSlice<BasicBlock, BasicBlockData<'tcx>>,
discr_ty: Ty<'tcx>,
) -> Option<()>;
fn new_stmts(
&self,
tcx: TyCtxt<'tcx>,
targets: &SwitchTargets,
typing_env: ty::TypingEnv<'tcx>,
patch: &mut MirPatch<'tcx>,
parent_end: Location,
bbs: &IndexSlice<BasicBlock, BasicBlockData<'tcx>>,
discr_local: Local,
discr_ty: Ty<'tcx>,
);
}
struct SimplifyToIf;
impl<'tcx> SimplifyMatch<'tcx> for SimplifyToIf {
fn can_simplify(
&mut self,
tcx: TyCtxt<'tcx>,
targets: &SwitchTargets,
typing_env: ty::TypingEnv<'tcx>,
bbs: &IndexSlice<BasicBlock, BasicBlockData<'tcx>>,
_discr_ty: Ty<'tcx>,
) -> Option<()> {
if targets.iter().len() != 1 {
return None;
}
let (_, first) = targets.iter().next().unwrap();
let second = targets.otherwise();
if first == second {
return None;
}
if bbs[first].terminator().kind != bbs[second].terminator().kind {
return None;
}
let first_stmts = &bbs[first].statements;
let second_stmts = &bbs[second].statements;
if first_stmts.len() != second_stmts.len() {
return None;
}
for (f, s) in iter::zip(first_stmts, second_stmts) {
match (&f.kind, &s.kind) {
(f_s, s_s) if f_s == s_s => {}
(
StatementKind::Assign(box (lhs_f, Rvalue::Use(Operand::Constant(f_c)))),
StatementKind::Assign(box (lhs_s, Rvalue::Use(Operand::Constant(s_c)))),
) if lhs_f == lhs_s
&& f_c.const_.ty().is_bool()
&& s_c.const_.ty().is_bool()
&& f_c.const_.try_eval_bool(tcx, typing_env).is_some()
&& s_c.const_.try_eval_bool(tcx, typing_env).is_some() => {}
_ => return None,
}
}
Some(())
}
fn new_stmts(
&self,
tcx: TyCtxt<'tcx>,
targets: &SwitchTargets,
typing_env: ty::TypingEnv<'tcx>,
patch: &mut MirPatch<'tcx>,
parent_end: Location,
bbs: &IndexSlice<BasicBlock, BasicBlockData<'tcx>>,
discr_local: Local,
discr_ty: Ty<'tcx>,
) {
let (val, first) = targets.iter().next().unwrap();
let second = targets.otherwise();
let first = &bbs[first];
let second = &bbs[second];
for (f, s) in iter::zip(&first.statements, &second.statements) {
match (&f.kind, &s.kind) {
(f_s, s_s) if f_s == s_s => {
patch.add_statement(parent_end, f.kind.clone());
}
(
StatementKind::Assign(box (lhs, Rvalue::Use(Operand::Constant(f_c)))),
StatementKind::Assign(box (_, Rvalue::Use(Operand::Constant(s_c)))),
) => {
let f_b = f_c.const_.try_eval_bool(tcx, typing_env).unwrap();
let s_b = s_c.const_.try_eval_bool(tcx, typing_env).unwrap();
if f_b == s_b {
patch.add_statement(parent_end, f.kind.clone());
} else {
let size = tcx.layout_of(typing_env.as_query_input(discr_ty)).unwrap().size;
let const_cmp = Operand::const_from_scalar(
tcx,
discr_ty,
rustc_const_eval::interpret::Scalar::from_uint(val, size),
rustc_span::DUMMY_SP,
);
let op = if f_b { BinOp::Eq } else { BinOp::Ne };
let rhs = Rvalue::BinaryOp(
op,
Box::new((Operand::Copy(Place::from(discr_local)), const_cmp)),
);
patch.add_assign(parent_end, *lhs, rhs);
}
}
_ => unreachable!(),
}
}
}
}
fn can_cast(
tcx: TyCtxt<'_>,
src_val: impl Into<u128>,
src_layout: TyAndLayout<'_>,
cast_ty: Ty<'_>,
target_scalar: ScalarInt,
) -> bool {
let from_scalar = ScalarInt::try_from_uint(src_val.into(), src_layout.size).unwrap();
let v = match src_layout.ty.kind() {
Uint(_) => from_scalar.to_uint(src_layout.size),
Int(_) => from_scalar.to_int(src_layout.size) as u128,
_ => unreachable!("invalid int"),
};
let size = match *cast_ty.kind() {
Int(t) => Integer::from_int_ty(&tcx, t).size(),
Uint(t) => Integer::from_uint_ty(&tcx, t).size(),
_ => unreachable!("invalid int"),
};
let v = size.truncate(v);
let cast_scalar = ScalarInt::try_from_uint(v, size).unwrap();
cast_scalar == target_scalar
}
#[derive(Default)]
struct SimplifyToExp {
transform_kinds: Vec<TransformKind>,
}
#[derive(Clone, Copy)]
enum ExpectedTransformKind<'a, 'tcx> {
Same(&'a StatementKind<'tcx>),
SameByEq { place: &'a Place<'tcx>, ty: Ty<'tcx>, scalar: ScalarInt },
Cast { place: &'a Place<'tcx>, ty: Ty<'tcx> },
}
enum TransformKind {
Same,
Cast,
}
impl From<ExpectedTransformKind<'_, '_>> for TransformKind {
fn from(compare_type: ExpectedTransformKind<'_, '_>) -> Self {
match compare_type {
ExpectedTransformKind::Same(_) => TransformKind::Same,
ExpectedTransformKind::SameByEq { .. } => TransformKind::Same,
ExpectedTransformKind::Cast { .. } => TransformKind::Cast,
}
}
}
impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp {
fn can_simplify(
&mut self,
tcx: TyCtxt<'tcx>,
targets: &SwitchTargets,
typing_env: ty::TypingEnv<'tcx>,
bbs: &IndexSlice<BasicBlock, BasicBlockData<'tcx>>,
discr_ty: Ty<'tcx>,
) -> Option<()> {
if targets.iter().len() < 2 || targets.iter().len() > 64 {
return None;
}
if !targets.is_distinct() {
return None;
}
if !bbs[targets.otherwise()].is_empty_unreachable() {
return None;
}
let mut target_iter = targets.iter();
let (first_case_val, first_target) = target_iter.next().unwrap();
let first_terminator_kind = &bbs[first_target].terminator().kind;
if !targets
.iter()
.all(|(_, other_target)| first_terminator_kind == &bbs[other_target].terminator().kind)
{
return None;
}
let discr_layout = tcx.layout_of(typing_env.as_query_input(discr_ty)).unwrap();
let first_stmts = &bbs[first_target].statements;
let (second_case_val, second_target) = target_iter.next().unwrap();
let second_stmts = &bbs[second_target].statements;
if first_stmts.len() != second_stmts.len() {
return None;
}
let mut expected_transform_kinds = Vec::new();
for (f, s) in iter::zip(first_stmts, second_stmts) {
let compare_type = match (&f.kind, &s.kind) {
(f_s, s_s) if f_s == s_s => ExpectedTransformKind::Same(f_s),
(
StatementKind::Assign(box (lhs_f, Rvalue::Use(Operand::Constant(f_c)))),
StatementKind::Assign(box (lhs_s, Rvalue::Use(Operand::Constant(s_c)))),
) if lhs_f == lhs_s
&& f_c.const_.ty() == s_c.const_.ty()
&& f_c.const_.ty().is_integral() =>
{
match (
f_c.const_.try_eval_scalar_int(tcx, typing_env),
s_c.const_.try_eval_scalar_int(tcx, typing_env),
) {
(Some(f), Some(s)) if f == s => ExpectedTransformKind::SameByEq {
place: lhs_f,
ty: f_c.const_.ty(),
scalar: f,
},
(Some(f), Some(s))
if (can_cast(
tcx,
first_case_val,
discr_layout,
f_c.const_.ty(),
f,
) && can_cast(
tcx,
second_case_val,
discr_layout,
f_c.const_.ty(),
s,
)) =>
{
ExpectedTransformKind::Cast { place: lhs_f, ty: f_c.const_.ty() }
}
_ => {
return None;
}
}
}
_ => return None,
};
expected_transform_kinds.push(compare_type);
}
for (other_val, other_target) in target_iter {
let other_stmts = &bbs[other_target].statements;
if expected_transform_kinds.len() != other_stmts.len() {
return None;
}
for (f, s) in iter::zip(&expected_transform_kinds, other_stmts) {
match (*f, &s.kind) {
(ExpectedTransformKind::Same(f_s), s_s) if f_s == s_s => {}
(
ExpectedTransformKind::SameByEq { place: lhs_f, ty: f_ty, scalar },
StatementKind::Assign(box (lhs_s, Rvalue::Use(Operand::Constant(s_c)))),
) if lhs_f == lhs_s
&& s_c.const_.ty() == f_ty
&& s_c.const_.try_eval_scalar_int(tcx, typing_env) == Some(scalar) => {}
(
ExpectedTransformKind::Cast { place: lhs_f, ty: f_ty },
StatementKind::Assign(box (lhs_s, Rvalue::Use(Operand::Constant(s_c)))),
) if let Some(f) = s_c.const_.try_eval_scalar_int(tcx, typing_env)
&& lhs_f == lhs_s
&& s_c.const_.ty() == f_ty
&& can_cast(tcx, other_val, discr_layout, f_ty, f) => {}
_ => return None,
}
}
}
self.transform_kinds = expected_transform_kinds.into_iter().map(|c| c.into()).collect();
Some(())
}
fn new_stmts(
&self,
_tcx: TyCtxt<'tcx>,
targets: &SwitchTargets,
_typing_env: ty::TypingEnv<'tcx>,
patch: &mut MirPatch<'tcx>,
parent_end: Location,
bbs: &IndexSlice<BasicBlock, BasicBlockData<'tcx>>,
discr_local: Local,
discr_ty: Ty<'tcx>,
) {
let (_, first) = targets.iter().next().unwrap();
let first = &bbs[first];
for (t, s) in iter::zip(&self.transform_kinds, &first.statements) {
match (t, &s.kind) {
(TransformKind::Same, _) => {
patch.add_statement(parent_end, s.kind.clone());
}
(
TransformKind::Cast,
StatementKind::Assign(box (lhs, Rvalue::Use(Operand::Constant(f_c)))),
) => {
let operand = Operand::Copy(Place::from(discr_local));
let r_val = if f_c.const_.ty() == discr_ty {
Rvalue::Use(operand)
} else {
Rvalue::Cast(CastKind::IntToInt, operand, f_c.const_.ty())
};
patch.add_assign(parent_end, *lhs, r_val);
}
_ => unreachable!(),
}
}
}
}