2016-09-10 21:33:29 +00:00
|
|
|
//! Performs various peephole optimizations.
|
|
|
|
|
2023-04-20 00:52:49 +00:00
|
|
|
use crate::simplify::combine_duplicate_switch_targets;
|
2021-01-01 00:53:25 +00:00
|
|
|
use crate::MirPass;
|
2020-05-31 14:22:23 +00:00
|
|
|
use rustc_hir::Mutability;
|
2023-04-20 00:52:49 +00:00
|
|
|
use rustc_middle::mir::*;
|
2023-02-26 21:50:19 +00:00
|
|
|
use rustc_middle::ty::layout::ValidityRequirement;
|
2023-03-25 21:32:31 +00:00
|
|
|
use rustc_middle::ty::util::IntTypeExt;
|
2023-02-22 20:51:29 +00:00
|
|
|
use rustc_middle::ty::{self, ParamEnv, SubstsRef, Ty, TyCtxt};
|
2023-02-26 21:50:19 +00:00
|
|
|
use rustc_span::symbol::Symbol;
|
2023-03-28 19:32:57 +00:00
|
|
|
use rustc_target::abi::FieldIdx;
|
2016-09-10 21:33:29 +00:00
|
|
|
|
2017-04-25 22:22:59 +00:00
|
|
|
pub struct InstCombine;
|
2016-09-10 21:33:29 +00:00
|
|
|
|
2019-08-04 20:20:00 +00:00
|
|
|
impl<'tcx> MirPass<'tcx> for InstCombine {
|
2021-12-02 17:17:32 +00:00
|
|
|
fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
|
|
|
|
sess.mir_opt_level() > 0
|
|
|
|
}
|
|
|
|
|
2020-10-04 18:01:38 +00:00
|
|
|
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
|
2022-12-12 02:07:33 +00:00
|
|
|
let ctx = InstCombineContext {
|
|
|
|
tcx,
|
|
|
|
local_decls: &body.local_decls,
|
|
|
|
param_env: tcx.param_env_reveal_all_normalized(body.source.def_id()),
|
|
|
|
};
|
2022-07-04 00:00:00 +00:00
|
|
|
for block in body.basic_blocks.as_mut() {
|
2021-01-18 00:00:00 +00:00
|
|
|
for statement in block.statements.iter_mut() {
|
|
|
|
match statement.kind {
|
|
|
|
StatementKind::Assign(box (_place, ref mut rvalue)) => {
|
|
|
|
ctx.combine_bool_cmp(&statement.source_info, rvalue);
|
|
|
|
ctx.combine_ref_deref(&statement.source_info, rvalue);
|
|
|
|
ctx.combine_len(&statement.source_info, rvalue);
|
2023-02-19 20:50:00 +00:00
|
|
|
ctx.combine_cast(&statement.source_info, rvalue);
|
2021-01-18 00:00:00 +00:00
|
|
|
}
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
}
|
2022-02-23 07:19:57 +00:00
|
|
|
|
|
|
|
ctx.combine_primitive_clone(
|
|
|
|
&mut block.terminator.as_mut().unwrap(),
|
|
|
|
&mut block.statements,
|
|
|
|
);
|
2022-12-12 02:07:33 +00:00
|
|
|
ctx.combine_intrinsic_assert(
|
|
|
|
&mut block.terminator.as_mut().unwrap(),
|
|
|
|
&mut block.statements,
|
|
|
|
);
|
2023-04-20 00:52:49 +00:00
|
|
|
combine_duplicate_switch_targets(block.terminator.as_mut().unwrap());
|
2020-11-15 21:34:50 +00:00
|
|
|
}
|
2016-09-10 21:33:29 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-18 00:00:00 +00:00
|
|
|
struct InstCombineContext<'tcx, 'a> {
|
2019-10-20 20:11:04 +00:00
|
|
|
tcx: TyCtxt<'tcx>,
|
2021-01-18 00:00:00 +00:00
|
|
|
local_decls: &'a LocalDecls<'tcx>,
|
2022-12-12 02:07:33 +00:00
|
|
|
param_env: ParamEnv<'tcx>,
|
2017-04-25 22:22:59 +00:00
|
|
|
}
|
|
|
|
|
2021-12-06 08:48:37 +00:00
|
|
|
impl<'tcx> InstCombineContext<'tcx, '_> {
|
2021-01-18 00:00:00 +00:00
|
|
|
fn should_combine(&self, source_info: &SourceInfo, rvalue: &Rvalue<'tcx>) -> bool {
|
2020-11-18 13:49:46 +00:00
|
|
|
self.tcx.consider_optimizing(|| {
|
2021-01-18 00:00:00 +00:00
|
|
|
format!("InstCombine - Rvalue: {:?} SourceInfo: {:?}", rvalue, source_info)
|
2020-11-18 13:49:46 +00:00
|
|
|
})
|
|
|
|
}
|
2019-10-20 20:11:04 +00:00
|
|
|
|
2021-01-18 00:00:00 +00:00
|
|
|
/// Transform boolean comparisons into logical operations.
|
|
|
|
fn combine_bool_cmp(&self, source_info: &SourceInfo, rvalue: &mut Rvalue<'tcx>) {
|
|
|
|
match rvalue {
|
2021-03-05 09:32:47 +00:00
|
|
|
Rvalue::BinaryOp(op @ (BinOp::Eq | BinOp::Ne), box (a, b)) => {
|
2021-01-18 00:00:00 +00:00
|
|
|
let new = match (op, self.try_eval_bool(a), self.try_eval_bool(b)) {
|
|
|
|
// Transform "Eq(a, true)" ==> "a"
|
2021-06-07 16:33:00 +00:00
|
|
|
(BinOp::Eq, _, Some(true)) => Some(Rvalue::Use(a.clone())),
|
2021-01-18 00:00:00 +00:00
|
|
|
|
|
|
|
// Transform "Ne(a, false)" ==> "a"
|
2021-06-07 16:33:00 +00:00
|
|
|
(BinOp::Ne, _, Some(false)) => Some(Rvalue::Use(a.clone())),
|
2021-01-18 00:00:00 +00:00
|
|
|
|
|
|
|
// Transform "Eq(true, b)" ==> "b"
|
2021-06-07 16:33:00 +00:00
|
|
|
(BinOp::Eq, Some(true), _) => Some(Rvalue::Use(b.clone())),
|
2021-01-18 00:00:00 +00:00
|
|
|
|
|
|
|
// Transform "Ne(false, b)" ==> "b"
|
2021-06-07 16:33:00 +00:00
|
|
|
(BinOp::Ne, Some(false), _) => Some(Rvalue::Use(b.clone())),
|
2021-01-18 00:00:00 +00:00
|
|
|
|
|
|
|
// Transform "Eq(false, b)" ==> "Not(b)"
|
2021-06-07 16:33:00 +00:00
|
|
|
(BinOp::Eq, Some(false), _) => Some(Rvalue::UnaryOp(UnOp::Not, b.clone())),
|
|
|
|
|
2021-01-18 00:00:00 +00:00
|
|
|
// Transform "Ne(true, b)" ==> "Not(b)"
|
2021-06-07 16:33:00 +00:00
|
|
|
(BinOp::Ne, Some(true), _) => Some(Rvalue::UnaryOp(UnOp::Not, b.clone())),
|
|
|
|
|
2021-01-18 00:00:00 +00:00
|
|
|
// Transform "Eq(a, false)" ==> "Not(a)"
|
2021-06-07 16:33:00 +00:00
|
|
|
(BinOp::Eq, _, Some(false)) => Some(Rvalue::UnaryOp(UnOp::Not, a.clone())),
|
|
|
|
|
2021-01-18 00:00:00 +00:00
|
|
|
// Transform "Ne(a, true)" ==> "Not(a)"
|
2021-06-07 16:33:00 +00:00
|
|
|
(BinOp::Ne, _, Some(true)) => Some(Rvalue::UnaryOp(UnOp::Not, a.clone())),
|
|
|
|
|
2021-01-18 00:00:00 +00:00
|
|
|
_ => None,
|
|
|
|
};
|
|
|
|
|
2022-03-01 10:43:12 +00:00
|
|
|
if let Some(new) = new && self.should_combine(source_info, rvalue) {
|
|
|
|
*rvalue = new;
|
2019-07-29 22:07:28 +00:00
|
|
|
}
|
2020-11-18 13:49:46 +00:00
|
|
|
}
|
2017-11-25 19:59:16 +00:00
|
|
|
|
2021-01-18 00:00:00 +00:00
|
|
|
_ => {}
|
2020-08-29 12:16:39 +00:00
|
|
|
}
|
2016-09-10 21:33:29 +00:00
|
|
|
}
|
2020-08-29 12:16:39 +00:00
|
|
|
|
2021-01-18 00:00:00 +00:00
|
|
|
fn try_eval_bool(&self, a: &Operand<'_>) -> Option<bool> {
|
|
|
|
let a = a.constant()?;
|
2021-03-08 16:18:03 +00:00
|
|
|
if a.literal.ty().is_bool() { a.literal.try_to_bool() } else { None }
|
2020-09-03 17:48:27 +00:00
|
|
|
}
|
|
|
|
|
2021-01-18 00:00:00 +00:00
|
|
|
/// Transform "&(*a)" ==> "a".
|
|
|
|
fn combine_ref_deref(&self, source_info: &SourceInfo, rvalue: &mut Rvalue<'tcx>) {
|
2019-10-20 20:09:36 +00:00
|
|
|
if let Rvalue::Ref(_, _, place) = rvalue {
|
2021-01-18 00:00:00 +00:00
|
|
|
if let Some((base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
|
2022-12-03 05:57:33 +00:00
|
|
|
if rvalue.ty(self.local_decls, self.tcx) != base.ty(self.local_decls, self.tcx).ty {
|
2021-01-18 00:00:00 +00:00
|
|
|
return;
|
2019-10-20 20:09:36 +00:00
|
|
|
}
|
2016-09-10 21:33:29 +00:00
|
|
|
|
2021-01-18 00:00:00 +00:00
|
|
|
if !self.should_combine(source_info, rvalue) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
*rvalue = Rvalue::Use(Operand::Copy(Place {
|
|
|
|
local: base.local,
|
2023-02-17 03:33:08 +00:00
|
|
|
projection: self.tcx.mk_place_elems(base.projection),
|
2021-01-18 00:00:00 +00:00
|
|
|
}));
|
2017-11-25 19:59:16 +00:00
|
|
|
}
|
|
|
|
}
|
2016-09-10 21:33:29 +00:00
|
|
|
}
|
|
|
|
|
2021-01-18 00:00:00 +00:00
|
|
|
/// Transform "Len([_; N])" ==> "N".
|
|
|
|
fn combine_len(&self, source_info: &SourceInfo, rvalue: &mut Rvalue<'tcx>) {
|
|
|
|
if let Rvalue::Len(ref place) = *rvalue {
|
|
|
|
let place_ty = place.ty(self.local_decls, self.tcx).ty;
|
2021-03-08 16:18:03 +00:00
|
|
|
if let ty::Array(_, len) = *place_ty.kind() {
|
2021-01-18 00:00:00 +00:00
|
|
|
if !self.should_combine(source_info, rvalue) {
|
|
|
|
return;
|
|
|
|
}
|
2020-11-15 21:34:50 +00:00
|
|
|
|
2022-02-16 09:56:01 +00:00
|
|
|
let literal = ConstantKind::from_const(len, self.tcx);
|
|
|
|
let constant = Constant { span: source_info.span, literal, user_ty: None };
|
2021-08-05 03:36:38 +00:00
|
|
|
*rvalue = Rvalue::Use(Operand::Constant(Box::new(constant)));
|
2020-12-28 22:19:35 +00:00
|
|
|
}
|
|
|
|
}
|
2020-11-15 21:34:50 +00:00
|
|
|
}
|
2022-02-23 07:19:57 +00:00
|
|
|
|
2023-02-19 20:50:00 +00:00
|
|
|
fn combine_cast(&self, _source_info: &SourceInfo, rvalue: &mut Rvalue<'tcx>) {
|
2023-03-25 21:32:31 +00:00
|
|
|
if let Rvalue::Cast(kind, operand, cast_ty) = rvalue {
|
|
|
|
let operand_ty = operand.ty(self.local_decls, self.tcx);
|
|
|
|
if operand_ty == *cast_ty {
|
2023-02-19 20:50:00 +00:00
|
|
|
*rvalue = Rvalue::Use(operand.clone());
|
2023-03-25 21:32:31 +00:00
|
|
|
} else if *kind == CastKind::Transmute {
|
|
|
|
// Transmuting an integer to another integer is just a signedness cast
|
|
|
|
if let (ty::Int(int), ty::Uint(uint)) | (ty::Uint(uint), ty::Int(int)) = (operand_ty.kind(), cast_ty.kind())
|
|
|
|
&& int.bit_width() == uint.bit_width()
|
|
|
|
{
|
|
|
|
// The width check isn't strictly necessary, as different widths
|
|
|
|
// are UB and thus we'd be allowed to turn it into a cast anyway.
|
|
|
|
// But let's keep the UB around for codegen to exploit later.
|
|
|
|
// (If `CastKind::Transmute` ever becomes *not* UB for mismatched sizes,
|
|
|
|
// then the width check is necessary for big-endian correctness.)
|
|
|
|
*kind = CastKind::IntToInt;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Transmuting a fieldless enum to its repr is a discriminant read
|
|
|
|
if let ty::Adt(adt_def, ..) = operand_ty.kind()
|
|
|
|
&& adt_def.is_enum()
|
|
|
|
&& adt_def.is_payloadfree()
|
|
|
|
&& let Some(place) = operand.place()
|
|
|
|
&& let Some(repr_int) = adt_def.repr().int
|
|
|
|
&& repr_int.to_ty(self.tcx) == *cast_ty
|
|
|
|
{
|
|
|
|
*rvalue = Rvalue::Discriminant(place);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Transmuting a transparent struct/union to a field's type is a projection
|
|
|
|
if let ty::Adt(adt_def, substs) = operand_ty.kind()
|
|
|
|
&& adt_def.repr().transparent()
|
|
|
|
&& (adt_def.is_struct() || adt_def.is_union())
|
|
|
|
&& let Some(place) = operand.place()
|
|
|
|
{
|
|
|
|
let variant = adt_def.non_enum_variant();
|
|
|
|
for (i, field) in variant.fields.iter().enumerate() {
|
|
|
|
let field_ty = field.ty(self.tcx, substs);
|
|
|
|
if field_ty == *cast_ty {
|
2023-03-28 19:32:57 +00:00
|
|
|
let place = place.project_deeper(&[ProjectionElem::Field(FieldIdx::from_usize(i), *cast_ty)], self.tcx);
|
2023-03-25 21:32:31 +00:00
|
|
|
let operand = if operand.is_move() { Operand::Move(place) } else { Operand::Copy(place) };
|
|
|
|
*rvalue = Rvalue::Use(operand);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-02-19 20:50:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-23 07:19:57 +00:00
|
|
|
fn combine_primitive_clone(
|
|
|
|
&self,
|
|
|
|
terminator: &mut Terminator<'tcx>,
|
|
|
|
statements: &mut Vec<Statement<'tcx>>,
|
|
|
|
) {
|
2022-04-16 13:27:54 +00:00
|
|
|
let TerminatorKind::Call { func, args, destination, target, .. } = &mut terminator.kind
|
2022-02-23 07:19:57 +00:00
|
|
|
else { return };
|
|
|
|
|
|
|
|
// It's definitely not a clone if there are multiple arguments
|
|
|
|
if args.len() != 1 {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-04-16 13:27:54 +00:00
|
|
|
let Some(destination_block) = *target
|
2022-02-23 07:19:57 +00:00
|
|
|
else { return };
|
|
|
|
|
|
|
|
// Only bother looking more if it's easy to know what we're calling
|
|
|
|
let Some((fn_def_id, fn_substs)) = func.const_fn_def()
|
|
|
|
else { return };
|
|
|
|
|
|
|
|
// Clone needs one subst, so we can cheaply rule out other stuff
|
|
|
|
if fn_substs.len() != 1 {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// These types are easily available from locals, so check that before
|
|
|
|
// doing DefId lookups to figure out what we're actually calling.
|
|
|
|
let arg_ty = args[0].ty(self.local_decls, self.tcx);
|
|
|
|
|
|
|
|
let ty::Ref(_region, inner_ty, Mutability::Not) = *arg_ty.kind()
|
|
|
|
else { return };
|
|
|
|
|
2022-03-05 23:19:57 +00:00
|
|
|
if !inner_ty.is_trivially_pure_clone_copy() {
|
2022-02-23 07:19:57 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
let trait_def_id = self.tcx.trait_of_item(fn_def_id);
|
|
|
|
if trait_def_id.is_none() || trait_def_id != self.tcx.lang_items().clone_trait() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if !self.tcx.consider_optimizing(|| {
|
|
|
|
format!(
|
|
|
|
"InstCombine - Call: {:?} SourceInfo: {:?}",
|
|
|
|
(fn_def_id, fn_substs),
|
|
|
|
terminator.source_info
|
|
|
|
)
|
|
|
|
}) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
let Some(arg_place) = args.pop().unwrap().place()
|
|
|
|
else { return };
|
|
|
|
|
|
|
|
statements.push(Statement {
|
|
|
|
source_info: terminator.source_info,
|
2022-05-22 14:39:32 +00:00
|
|
|
kind: StatementKind::Assign(Box::new((
|
2022-04-16 13:27:54 +00:00
|
|
|
*destination,
|
2022-02-23 07:19:57 +00:00
|
|
|
Rvalue::Use(Operand::Copy(
|
|
|
|
arg_place.project_deeper(&[ProjectionElem::Deref], self.tcx),
|
|
|
|
)),
|
2022-05-22 14:39:32 +00:00
|
|
|
))),
|
2022-02-23 07:19:57 +00:00
|
|
|
});
|
|
|
|
terminator.kind = TerminatorKind::Goto { target: destination_block };
|
|
|
|
}
|
2022-12-12 02:07:33 +00:00
|
|
|
|
|
|
|
fn combine_intrinsic_assert(
|
|
|
|
&self,
|
|
|
|
terminator: &mut Terminator<'tcx>,
|
|
|
|
_statements: &mut Vec<Statement<'tcx>>,
|
|
|
|
) {
|
|
|
|
let TerminatorKind::Call { func, target, .. } = &mut terminator.kind else { return; };
|
|
|
|
let Some(target_block) = target else { return; };
|
|
|
|
let func_ty = func.ty(self.local_decls, self.tcx);
|
|
|
|
let Some((intrinsic_name, substs)) = resolve_rust_intrinsic(self.tcx, func_ty) else {
|
|
|
|
return;
|
|
|
|
};
|
|
|
|
// The intrinsics we are interested in have one generic parameter
|
|
|
|
if substs.is_empty() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
let ty = substs.type_at(0);
|
|
|
|
|
2023-02-22 20:51:29 +00:00
|
|
|
let known_is_valid = intrinsic_assert_panics(self.tcx, self.param_env, ty, intrinsic_name);
|
|
|
|
match known_is_valid {
|
|
|
|
// We don't know the layout or it's not validity assertion at all, don't touch it
|
|
|
|
None => {}
|
|
|
|
Some(true) => {
|
2023-02-14 00:59:40 +00:00
|
|
|
// If we know the assert panics, indicate to later opts that the call diverges
|
|
|
|
*target = None;
|
|
|
|
}
|
2023-02-22 20:51:29 +00:00
|
|
|
Some(false) => {
|
2023-02-14 00:59:40 +00:00
|
|
|
// If we know the assert does not panic, turn the call into a Goto
|
|
|
|
terminator.kind = TerminatorKind::Goto { target: *target_block };
|
|
|
|
}
|
2022-12-12 02:07:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn intrinsic_assert_panics<'tcx>(
|
2023-02-22 20:51:29 +00:00
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
param_env: ty::ParamEnv<'tcx>,
|
|
|
|
ty: Ty<'tcx>,
|
2022-12-12 02:07:33 +00:00
|
|
|
intrinsic_name: Symbol,
|
2023-02-22 20:51:29 +00:00
|
|
|
) -> Option<bool> {
|
2023-02-26 21:50:19 +00:00
|
|
|
let requirement = ValidityRequirement::from_intrinsic(intrinsic_name)?;
|
|
|
|
Some(!tcx.check_validity_requirement((requirement, param_env.and(ty))).ok()?)
|
2022-12-12 02:07:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn resolve_rust_intrinsic<'tcx>(
|
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
func_ty: Ty<'tcx>,
|
|
|
|
) -> Option<(Symbol, SubstsRef<'tcx>)> {
|
|
|
|
if let ty::FnDef(def_id, substs) = *func_ty.kind() {
|
|
|
|
if tcx.is_intrinsic(def_id) {
|
|
|
|
return Some((tcx.item_name(def_id), substs));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
None
|
2022-02-23 07:19:57 +00:00
|
|
|
}
|