2022-03-08 17:20:31 +00:00
|
|
|
//! Propagates constants for early reporting of statically known
|
|
|
|
//! assertion failures
|
|
|
|
|
2023-03-30 18:08:09 +00:00
|
|
|
use either::Left;
|
2022-11-18 10:18:32 +01:00
|
|
|
|
2022-08-07 10:36:42 -04:00
|
|
|
use rustc_const_eval::interpret::Immediate;
|
2022-07-12 12:17:58 +00:00
|
|
|
use rustc_const_eval::interpret::{
|
2023-03-07 14:32:16 +00:00
|
|
|
self, InterpCx, InterpResult, LocalValue, MemoryKind, OpTy, Scalar, StackPopCleanup,
|
2022-07-12 12:17:58 +00:00
|
|
|
};
|
2022-03-08 17:20:31 +00:00
|
|
|
use rustc_hir::def::DefKind;
|
|
|
|
use rustc_hir::HirId;
|
2023-03-30 18:40:47 +00:00
|
|
|
use rustc_index::bit_set::BitSet;
|
2022-07-25 13:54:49 +00:00
|
|
|
use rustc_middle::mir::visit::Visitor;
|
2023-03-07 14:31:43 +00:00
|
|
|
use rustc_middle::mir::*;
|
2022-03-08 17:20:31 +00:00
|
|
|
use rustc_middle::ty::layout::{LayoutError, LayoutOf, LayoutOfHelpers, TyAndLayout};
|
2022-09-16 15:31:10 +02:00
|
|
|
use rustc_middle::ty::InternalSubsts;
|
2023-02-22 02:18:40 +00:00
|
|
|
use rustc_middle::ty::{
|
|
|
|
self, ConstInt, Instance, ParamEnv, ScalarInt, Ty, TyCtxt, TypeVisitableExt,
|
|
|
|
};
|
2022-03-08 17:20:31 +00:00
|
|
|
use rustc_session::lint;
|
2022-07-12 12:17:58 +00:00
|
|
|
use rustc_span::Span;
|
2022-03-08 17:20:31 +00:00
|
|
|
use rustc_target::abi::{HasDataLayout, Size, TargetDataLayout};
|
|
|
|
use rustc_trait_selection::traits;
|
2022-11-18 10:18:32 +01:00
|
|
|
|
|
|
|
use crate::const_prop::CanConstProp;
|
|
|
|
use crate::const_prop::ConstPropMachine;
|
|
|
|
use crate::const_prop::ConstPropMode;
|
|
|
|
use crate::MirLint;
|
2022-03-08 17:20:31 +00:00
|
|
|
|
|
|
|
/// 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
|
|
|
|
/// Severely regress performance.
|
|
|
|
const MAX_ALLOC_LIMIT: u64 = 1024;
|
2022-11-18 10:18:32 +01:00
|
|
|
|
2022-03-08 17:20:31 +00:00
|
|
|
pub struct ConstProp;
|
|
|
|
|
2022-03-11 14:52:58 +00:00
|
|
|
impl<'tcx> MirLint<'tcx> for ConstProp {
|
|
|
|
fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
|
2022-03-08 17:20:31 +00:00
|
|
|
// will be evaluated by miri and produce its errors there
|
|
|
|
if body.source.promoted.is_some() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
let def_id = body.source.def_id().expect_local();
|
2022-03-29 23:50:01 +02:00
|
|
|
let is_fn_like = tcx.def_kind(def_id).is_fn_like();
|
2022-03-08 17:20:31 +00:00
|
|
|
let is_assoc_const = tcx.def_kind(def_id) == DefKind::AssocConst;
|
|
|
|
|
|
|
|
// Only run const prop on functions, methods, closures and associated constants
|
|
|
|
if !is_fn_like && !is_assoc_const {
|
|
|
|
// skip anon_const/statics/consts because they'll be evaluated by miri anyway
|
|
|
|
trace!("ConstProp skipped for {:?}", def_id);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-02-07 01:29:48 -07:00
|
|
|
let is_generator = tcx.type_of(def_id.to_def_id()).subst_identity().is_generator();
|
2022-03-08 17:20:31 +00:00
|
|
|
// FIXME(welseywiser) const prop doesn't work on generators because of query cycles
|
|
|
|
// computing their layout.
|
|
|
|
if is_generator {
|
|
|
|
trace!("ConstProp skipped for generator {:?}", def_id);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check if it's even possible to satisfy the 'where' clauses
|
|
|
|
// for this item.
|
|
|
|
// This branch will never be taken for any normal function.
|
|
|
|
// However, it's possible to `#!feature(trivial_bounds)]` to write
|
|
|
|
// a function with impossible to satisfy clauses, e.g.:
|
|
|
|
// `fn foo() where String: Copy {}`
|
|
|
|
//
|
|
|
|
// We don't usually need to worry about this kind of case,
|
|
|
|
// since we would get a compilation error if the user tried
|
|
|
|
// to call it. However, since we can do const propagation
|
|
|
|
// even without any calls to the function, we need to make
|
|
|
|
// sure that it even makes sense to try to evaluate the body.
|
|
|
|
// If there are unsatisfiable where clauses, then all bets are
|
|
|
|
// off, and we just give up.
|
|
|
|
//
|
|
|
|
// We manually filter the predicates, skipping anything that's not
|
|
|
|
// "global". We are in a potentially generic context
|
|
|
|
// (e.g. we are evaluating a function without substituting generic
|
|
|
|
// parameters, so this filtering serves two purposes:
|
|
|
|
//
|
|
|
|
// 1. We skip evaluating any predicates that we would
|
|
|
|
// never be able prove are unsatisfiable (e.g. `<T as Foo>`
|
|
|
|
// 2. We avoid trying to normalize predicates involving generic
|
|
|
|
// parameters (e.g. `<T as Foo>::MyItem`). This can confuse
|
|
|
|
// the normalization code (leading to cycle errors), since
|
|
|
|
// it's usually never invoked in this way.
|
|
|
|
let predicates = tcx
|
|
|
|
.predicates_of(def_id.to_def_id())
|
|
|
|
.predicates
|
|
|
|
.iter()
|
|
|
|
.filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
|
2023-04-06 23:11:19 +00:00
|
|
|
if traits::impossible_predicates(tcx, traits::elaborate(tcx, predicates).collect()) {
|
2022-03-08 17:20:31 +00:00
|
|
|
trace!("ConstProp skipped for {:?}: found unsatisfiable predicates", def_id);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
trace!("ConstProp starting for {:?}", def_id);
|
|
|
|
|
|
|
|
let dummy_body = &Body::new(
|
|
|
|
body.source,
|
2023-03-31 00:32:44 -07:00
|
|
|
(*body.basic_blocks).to_owned(),
|
2022-03-08 17:20:31 +00:00
|
|
|
body.source_scopes.clone(),
|
|
|
|
body.local_decls.clone(),
|
|
|
|
Default::default(),
|
|
|
|
body.arg_count,
|
|
|
|
Default::default(),
|
|
|
|
body.span,
|
|
|
|
body.generator_kind(),
|
|
|
|
body.tainted_by_errors,
|
|
|
|
);
|
|
|
|
|
|
|
|
// FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
|
|
|
|
// constants, instead of just checking for const-folding succeeding.
|
|
|
|
// That would require a uniform one-def no-mutation analysis
|
|
|
|
// and RPO (or recursing when needing the value of a local).
|
|
|
|
let mut optimization_finder = ConstPropagator::new(body, dummy_body, tcx);
|
|
|
|
optimization_finder.visit_body(body);
|
|
|
|
|
|
|
|
trace!("ConstProp done for {:?}", def_id);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Finds optimization opportunities on the MIR.
|
|
|
|
struct ConstPropagator<'mir, 'tcx> {
|
|
|
|
ecx: InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>,
|
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
param_env: ParamEnv<'tcx>,
|
2023-03-30 18:40:47 +00:00
|
|
|
worklist: Vec<BasicBlock>,
|
|
|
|
visited_blocks: BitSet<BasicBlock>,
|
2022-03-08 17:20:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'tcx> LayoutOfHelpers<'tcx> for ConstPropagator<'_, 'tcx> {
|
|
|
|
type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
|
|
|
|
err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl HasDataLayout for ConstPropagator<'_, '_> {
|
|
|
|
#[inline]
|
|
|
|
fn data_layout(&self) -> &TargetDataLayout {
|
|
|
|
&self.tcx.data_layout
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'tcx> ty::layout::HasTyCtxt<'tcx> for ConstPropagator<'_, 'tcx> {
|
|
|
|
#[inline]
|
|
|
|
fn tcx(&self) -> TyCtxt<'tcx> {
|
|
|
|
self.tcx
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'tcx> ty::layout::HasParamEnv<'tcx> for ConstPropagator<'_, 'tcx> {
|
|
|
|
#[inline]
|
|
|
|
fn param_env(&self) -> ty::ParamEnv<'tcx> {
|
|
|
|
self.param_env
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
|
|
|
|
fn new(
|
|
|
|
body: &Body<'tcx>,
|
|
|
|
dummy_body: &'mir Body<'tcx>,
|
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
) -> ConstPropagator<'mir, 'tcx> {
|
|
|
|
let def_id = body.source.def_id();
|
|
|
|
let substs = &InternalSubsts::identity_for_item(tcx, def_id);
|
|
|
|
let param_env = tcx.param_env_reveal_all_normalized(def_id);
|
|
|
|
|
|
|
|
let can_const_prop = CanConstProp::check(tcx, param_env, body);
|
|
|
|
let mut ecx = InterpCx::new(
|
|
|
|
tcx,
|
2022-04-21 18:26:43 +08:00
|
|
|
tcx.def_span(def_id),
|
2022-03-08 17:20:31 +00:00
|
|
|
param_env,
|
2023-03-07 15:20:57 +00:00
|
|
|
ConstPropMachine::new(can_const_prop),
|
2022-03-08 17:20:31 +00:00
|
|
|
);
|
|
|
|
|
2022-04-16 09:27:54 -04:00
|
|
|
let ret_layout = ecx
|
2022-08-03 01:02:46 -04:00
|
|
|
.layout_of(body.bound_return_ty().subst(tcx, substs))
|
2022-03-08 17:20:31 +00:00
|
|
|
.ok()
|
2022-04-16 09:27:54 -04:00
|
|
|
// Don't bother allocating memory for large values.
|
2022-07-02 22:02:12 -04:00
|
|
|
// I don't know how return types can seem to be unsized but this happens in the
|
|
|
|
// `type/type-unsatisfiable.rs` test.
|
|
|
|
.filter(|ret_layout| {
|
2022-11-13 12:14:59 +01:00
|
|
|
ret_layout.is_sized() && ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT)
|
2022-07-02 22:02:12 -04:00
|
|
|
})
|
2022-04-16 09:27:54 -04:00
|
|
|
.unwrap_or_else(|| ecx.layout_of(tcx.types.unit).unwrap());
|
|
|
|
|
|
|
|
let ret = ecx
|
|
|
|
.allocate(ret_layout, MemoryKind::Stack)
|
|
|
|
.expect("couldn't perform small allocation")
|
|
|
|
.into();
|
2022-03-08 17:20:31 +00:00
|
|
|
|
|
|
|
ecx.push_stack_frame(
|
|
|
|
Instance::new(def_id, substs),
|
|
|
|
dummy_body,
|
2022-04-16 09:27:54 -04:00
|
|
|
&ret,
|
2022-03-08 17:20:31 +00:00
|
|
|
StackPopCleanup::Root { cleanup: false },
|
|
|
|
)
|
|
|
|
.expect("failed to push initial stack frame");
|
|
|
|
|
2023-03-30 18:40:47 +00:00
|
|
|
ConstPropagator {
|
|
|
|
ecx,
|
|
|
|
tcx,
|
|
|
|
param_env,
|
|
|
|
worklist: vec![START_BLOCK],
|
|
|
|
visited_blocks: BitSet::new_empty(body.basic_blocks.len()),
|
|
|
|
}
|
2023-03-30 18:01:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn body(&self) -> &'mir Body<'tcx> {
|
|
|
|
self.ecx.frame().body
|
|
|
|
}
|
|
|
|
|
|
|
|
fn local_decls(&self) -> &'mir LocalDecls<'tcx> {
|
|
|
|
&self.body().local_decls
|
2022-03-08 17:20:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn get_const(&self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
|
|
|
|
let op = match self.ecx.eval_place_to_op(place, None) {
|
2022-08-07 10:36:42 -04:00
|
|
|
Ok(op) => {
|
|
|
|
if matches!(*op, interpret::Operand::Immediate(Immediate::Uninit)) {
|
|
|
|
// Make sure nobody accidentally uses this value.
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
op
|
|
|
|
}
|
2022-03-08 17:20:31 +00:00
|
|
|
Err(e) => {
|
|
|
|
trace!("get_const failed: {}", e);
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// Try to read the local as an immediate so that if it is representable as a scalar, we can
|
|
|
|
// handle it as such, but otherwise, just return the value as is.
|
2022-08-01 19:05:20 -04:00
|
|
|
Some(match self.ecx.read_immediate_raw(&op) {
|
2022-11-18 10:18:32 +01:00
|
|
|
Ok(Left(imm)) => imm.into(),
|
2022-03-08 17:20:31 +00:00
|
|
|
_ => op,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Remove `local` from the pool of `Locals`. Allows writing to them,
|
|
|
|
/// but not reading from them anymore.
|
|
|
|
fn remove_const(ecx: &mut InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>, local: Local) {
|
2023-03-07 14:32:16 +00:00
|
|
|
ecx.frame_mut().locals[local].value =
|
|
|
|
LocalValue::Live(interpret::Operand::Immediate(interpret::Immediate::Uninit));
|
2023-03-13 17:43:14 +00:00
|
|
|
ecx.machine.written_only_inside_own_block_locals.remove(&local);
|
2022-03-08 17:20:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
|
2023-03-30 18:01:42 +00:00
|
|
|
source_info.scope.lint_root(&self.body().source_scopes)
|
2022-03-08 17:20:31 +00:00
|
|
|
}
|
|
|
|
|
2023-03-30 18:08:09 +00:00
|
|
|
fn use_ecx<F, T>(&mut self, location: Location, f: F) -> Option<T>
|
2022-03-08 17:20:31 +00:00
|
|
|
where
|
|
|
|
F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
|
|
|
|
{
|
2022-06-04 15:29:51 -04:00
|
|
|
// Overwrite the PC -- whatever the interpreter does to it does not make any sense anyway.
|
2023-03-30 18:08:09 +00:00
|
|
|
self.ecx.frame_mut().loc = Left(location);
|
2022-03-08 17:20:31 +00:00
|
|
|
match f(self) {
|
|
|
|
Ok(val) => Some(val),
|
|
|
|
Err(error) => {
|
|
|
|
trace!("InterpCx operation failed: {:?}", error);
|
|
|
|
// Some errors shouldn't come up because creating them causes
|
|
|
|
// an allocation, which we should avoid. When that happens,
|
|
|
|
// dedicated error variants should be introduced instead.
|
|
|
|
assert!(
|
|
|
|
!error.kind().formatted_string(),
|
|
|
|
"const-prop encountered formatting error: {}",
|
|
|
|
error
|
|
|
|
);
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the value, if any, of evaluating `c`.
|
2023-03-30 18:08:09 +00:00
|
|
|
fn eval_constant(&mut self, c: &Constant<'tcx>, location: Location) -> Option<OpTy<'tcx>> {
|
2022-03-08 17:20:31 +00:00
|
|
|
// FIXME we need to revisit this for #67176
|
|
|
|
if c.needs_subst() {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
2023-04-04 10:39:26 +00:00
|
|
|
// Normalization needed b/c const prop lint runs in
|
|
|
|
// `mir_drops_elaborated_and_const_checked`, which happens before
|
|
|
|
// optimized MIR. Only after optimizing the MIR can we guarantee
|
|
|
|
// that the `RevealAll` pass has happened and that the body's consts
|
|
|
|
// are normalized, so any call to resolve before that needs to be
|
|
|
|
// manually normalized.
|
|
|
|
let val = self.tcx.try_normalize_erasing_regions(self.param_env, c.literal).ok()?;
|
|
|
|
|
2023-03-30 18:08:09 +00:00
|
|
|
self.use_ecx(location, |this| this.ecx.eval_mir_constant(&val, Some(c.span), None))
|
2022-03-08 17:20:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the value, if any, of evaluating `place`.
|
2023-03-30 18:08:09 +00:00
|
|
|
fn eval_place(&mut self, place: Place<'tcx>, location: Location) -> Option<OpTy<'tcx>> {
|
2022-03-08 17:20:31 +00:00
|
|
|
trace!("eval_place(place={:?})", place);
|
2023-03-30 18:08:09 +00:00
|
|
|
self.use_ecx(location, |this| this.ecx.eval_place_to_op(place, None))
|
2022-03-08 17:20:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the value, if any, of evaluating `op`. Calls upon `eval_constant`
|
|
|
|
/// or `eval_place`, depending on the variant of `Operand` used.
|
2023-03-30 18:08:09 +00:00
|
|
|
fn eval_operand(&mut self, op: &Operand<'tcx>, location: Location) -> Option<OpTy<'tcx>> {
|
2022-03-08 17:20:31 +00:00
|
|
|
match *op {
|
2023-03-30 18:08:09 +00:00
|
|
|
Operand::Constant(ref c) => self.eval_constant(c, location),
|
|
|
|
Operand::Move(place) | Operand::Copy(place) => self.eval_place(place, location),
|
2022-03-08 17:20:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn report_assert_as_lint(
|
|
|
|
&self,
|
|
|
|
lint: &'static lint::Lint,
|
2023-03-30 18:08:09 +00:00
|
|
|
location: Location,
|
2022-03-08 17:20:31 +00:00
|
|
|
message: &'static str,
|
|
|
|
panic: AssertKind<impl std::fmt::Debug>,
|
|
|
|
) {
|
2023-03-30 18:08:09 +00:00
|
|
|
let source_info = self.body().source_info(location);
|
|
|
|
if let Some(lint_root) = self.lint_root(*source_info) {
|
2022-09-16 11:01:02 +04:00
|
|
|
self.tcx.struct_span_lint_hir(lint, lint_root, source_info.span, message, |lint| {
|
|
|
|
lint.span_label(source_info.span, format!("{:?}", panic))
|
2022-03-08 17:20:31 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-30 18:08:09 +00:00
|
|
|
fn check_unary_op(&mut self, op: UnOp, arg: &Operand<'tcx>, location: Location) -> Option<()> {
|
|
|
|
if let (val, true) = self.use_ecx(location, |this| {
|
2022-03-08 17:20:31 +00:00
|
|
|
let val = this.ecx.read_immediate(&this.ecx.eval_operand(arg, None)?)?;
|
|
|
|
let (_res, overflow, _ty) = this.ecx.overflowing_unary_op(op, &val)?;
|
|
|
|
Ok((val, overflow))
|
|
|
|
})? {
|
|
|
|
// `AssertKind` only has an `OverflowNeg` variant, so make sure that is
|
|
|
|
// appropriate to use.
|
|
|
|
assert_eq!(op, UnOp::Neg, "Neg is the only UnOp that can overflow");
|
|
|
|
self.report_assert_as_lint(
|
|
|
|
lint::builtin::ARITHMETIC_OVERFLOW,
|
2023-03-30 18:08:09 +00:00
|
|
|
location,
|
2022-03-08 17:20:31 +00:00
|
|
|
"this arithmetic operation will overflow",
|
|
|
|
AssertKind::OverflowNeg(val.to_const_int()),
|
|
|
|
);
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
Some(())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn check_binary_op(
|
|
|
|
&mut self,
|
|
|
|
op: BinOp,
|
|
|
|
left: &Operand<'tcx>,
|
|
|
|
right: &Operand<'tcx>,
|
2023-03-30 18:08:09 +00:00
|
|
|
location: Location,
|
2022-03-08 17:20:31 +00:00
|
|
|
) -> Option<()> {
|
2023-03-30 18:08:09 +00:00
|
|
|
let r = self.use_ecx(location, |this| {
|
2022-06-04 15:29:51 -04:00
|
|
|
this.ecx.read_immediate(&this.ecx.eval_operand(right, None)?)
|
|
|
|
});
|
2023-03-30 18:08:09 +00:00
|
|
|
let l = self
|
|
|
|
.use_ecx(location, |this| this.ecx.read_immediate(&this.ecx.eval_operand(left, None)?));
|
2022-03-08 17:20:31 +00:00
|
|
|
// Check for exceeding shifts *even if* we cannot evaluate the LHS.
|
2023-01-30 12:01:09 +00:00
|
|
|
if matches!(op, BinOp::Shr | BinOp::Shl) {
|
2022-07-15 22:58:20 -04:00
|
|
|
let r = r.clone()?;
|
2022-03-08 17:20:31 +00:00
|
|
|
// We need the type of the LHS. We cannot use `place_layout` as that is the type
|
|
|
|
// of the result, which for checked binops is not the same!
|
2023-03-30 18:01:42 +00:00
|
|
|
let left_ty = left.ty(self.local_decls(), self.tcx);
|
2022-03-08 17:20:31 +00:00
|
|
|
let left_size = self.ecx.layout_of(left_ty).ok()?.size;
|
|
|
|
let right_size = r.layout.size;
|
2022-08-01 19:05:20 -04:00
|
|
|
let r_bits = r.to_scalar().to_bits(right_size).ok();
|
2022-03-08 17:20:31 +00:00
|
|
|
if r_bits.map_or(false, |b| b >= left_size.bits() as u128) {
|
2023-03-30 18:08:09 +00:00
|
|
|
debug!("check_binary_op: reporting assert for {:?}", location);
|
2022-03-08 17:20:31 +00:00
|
|
|
self.report_assert_as_lint(
|
|
|
|
lint::builtin::ARITHMETIC_OVERFLOW,
|
2023-03-30 18:08:09 +00:00
|
|
|
location,
|
2022-03-08 17:20:31 +00:00
|
|
|
"this arithmetic operation will overflow",
|
|
|
|
AssertKind::Overflow(
|
|
|
|
op,
|
|
|
|
match l {
|
|
|
|
Some(l) => l.to_const_int(),
|
|
|
|
// Invent a dummy value, the diagnostic ignores it anyway
|
|
|
|
None => ConstInt::new(
|
|
|
|
ScalarInt::try_from_uint(1_u8, left_size).unwrap(),
|
|
|
|
left_ty.is_signed(),
|
|
|
|
left_ty.is_ptr_sized_integral(),
|
|
|
|
),
|
|
|
|
},
|
|
|
|
r.to_const_int(),
|
|
|
|
),
|
|
|
|
);
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-15 22:58:20 -04:00
|
|
|
if let (Some(l), Some(r)) = (l, r) {
|
2022-03-08 17:20:31 +00:00
|
|
|
// The remaining operators are handled through `overflowing_binary_op`.
|
2023-03-30 18:08:09 +00:00
|
|
|
if self.use_ecx(location, |this| {
|
2022-07-15 22:58:20 -04:00
|
|
|
let (_res, overflow, _ty) = this.ecx.overflowing_binary_op(op, &l, &r)?;
|
2022-03-08 17:20:31 +00:00
|
|
|
Ok(overflow)
|
|
|
|
})? {
|
|
|
|
self.report_assert_as_lint(
|
|
|
|
lint::builtin::ARITHMETIC_OVERFLOW,
|
2023-03-30 18:08:09 +00:00
|
|
|
location,
|
2022-03-08 17:20:31 +00:00
|
|
|
"this arithmetic operation will overflow",
|
|
|
|
AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
|
|
|
|
);
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Some(())
|
|
|
|
}
|
|
|
|
|
2023-03-30 18:08:09 +00:00
|
|
|
fn check_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) -> Option<()> {
|
2022-03-08 17:20:31 +00:00
|
|
|
// Perform any special handling for specific Rvalue types.
|
|
|
|
// Generally, checks here fall into one of two categories:
|
|
|
|
// 1. Additional checking to provide useful lints to the user
|
|
|
|
// - In this case, we will do some validation and then fall through to the
|
|
|
|
// end of the function which evals the assignment.
|
|
|
|
// 2. Working around bugs in other parts of the compiler
|
|
|
|
// - In this case, we'll return `None` from this function to stop evaluation.
|
|
|
|
match rvalue {
|
|
|
|
// Additional checking: give lints to the user if an overflow would occur.
|
|
|
|
// We do this here and not in the `Assert` terminator as that terminator is
|
|
|
|
// only sometimes emitted (overflow checks can be disabled), but we want to always
|
|
|
|
// lint.
|
|
|
|
Rvalue::UnaryOp(op, arg) => {
|
|
|
|
trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
|
2023-03-30 18:08:09 +00:00
|
|
|
self.check_unary_op(*op, arg, location)?;
|
2022-03-08 17:20:31 +00:00
|
|
|
}
|
|
|
|
Rvalue::BinaryOp(op, box (left, right)) => {
|
|
|
|
trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
|
2023-03-30 18:08:09 +00:00
|
|
|
self.check_binary_op(*op, left, right, location)?;
|
2022-03-08 17:20:31 +00:00
|
|
|
}
|
|
|
|
Rvalue::CheckedBinaryOp(op, box (left, right)) => {
|
|
|
|
trace!(
|
|
|
|
"checking CheckedBinaryOp(op = {:?}, left = {:?}, right = {:?})",
|
|
|
|
op,
|
|
|
|
left,
|
|
|
|
right
|
|
|
|
);
|
2023-03-30 18:08:09 +00:00
|
|
|
self.check_binary_op(*op, left, right, location)?;
|
2022-03-08 17:20:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Do not try creating references (#67862)
|
|
|
|
Rvalue::AddressOf(_, place) | Rvalue::Ref(_, _, place) => {
|
|
|
|
trace!("skipping AddressOf | Ref for {:?}", place);
|
|
|
|
|
|
|
|
// This may be creating mutable references or immutable references to cells.
|
|
|
|
// If that happens, the pointed to value could be mutated via that reference.
|
|
|
|
// Since we aren't tracking references, the const propagator loses track of what
|
|
|
|
// value the local has right now.
|
|
|
|
// Thus, all locals that have their reference taken
|
|
|
|
// must not take part in propagation.
|
|
|
|
Self::remove_const(&mut self.ecx, place.local);
|
|
|
|
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
Rvalue::ThreadLocalRef(def_id) => {
|
|
|
|
trace!("skipping ThreadLocalRef({:?})", def_id);
|
|
|
|
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
// There's no other checking to do at this time.
|
|
|
|
Rvalue::Aggregate(..)
|
|
|
|
| Rvalue::Use(..)
|
2022-06-13 16:37:41 +03:00
|
|
|
| Rvalue::CopyForDeref(..)
|
2022-03-08 17:20:31 +00:00
|
|
|
| Rvalue::Repeat(..)
|
|
|
|
| Rvalue::Len(..)
|
|
|
|
| Rvalue::Cast(..)
|
|
|
|
| Rvalue::ShallowInitBox(..)
|
|
|
|
| Rvalue::Discriminant(..)
|
|
|
|
| Rvalue::NullaryOp(..) => {}
|
|
|
|
}
|
|
|
|
|
|
|
|
// FIXME we need to revisit this for #67176
|
|
|
|
if rvalue.needs_subst() {
|
|
|
|
return None;
|
|
|
|
}
|
2023-03-30 18:01:42 +00:00
|
|
|
if !rvalue.ty(self.local_decls(), self.tcx).is_sized(self.tcx, self.param_env) {
|
2022-08-07 10:36:42 -04:00
|
|
|
// the interpreter doesn't support unsized locals (only unsized arguments),
|
|
|
|
// but rustc does (in a kinda broken way), so we have to skip them here
|
|
|
|
return None;
|
|
|
|
}
|
2022-03-08 17:20:31 +00:00
|
|
|
|
2023-03-07 16:34:11 +00:00
|
|
|
Some(())
|
|
|
|
}
|
|
|
|
|
2023-03-30 18:19:20 +00:00
|
|
|
fn check_assertion(
|
|
|
|
&mut self,
|
|
|
|
expected: bool,
|
|
|
|
msg: &AssertKind<Operand<'tcx>>,
|
|
|
|
cond: &Operand<'tcx>,
|
|
|
|
location: Location,
|
|
|
|
) -> Option<!> {
|
2023-04-15 20:18:30 +02:00
|
|
|
let value = &self.eval_operand(&cond, location)?;
|
2023-03-30 18:19:20 +00:00
|
|
|
trace!("assertion on {:?} should be {:?}", value, expected);
|
|
|
|
|
|
|
|
let expected = Scalar::from_bool(expected);
|
|
|
|
let value_const = self.use_ecx(location, |this| this.ecx.read_scalar(&value))?;
|
|
|
|
|
|
|
|
if expected != value_const {
|
|
|
|
// Poison all places this operand references so that further code
|
|
|
|
// doesn't use the invalid value
|
2023-03-30 18:40:47 +00:00
|
|
|
if let Some(place) = cond.place() {
|
|
|
|
Self::remove_const(&mut self.ecx, place.local);
|
2023-03-30 18:19:20 +00:00
|
|
|
}
|
2023-03-30 18:40:47 +00:00
|
|
|
|
2023-03-30 18:19:20 +00:00
|
|
|
enum DbgVal<T> {
|
|
|
|
Val(T),
|
|
|
|
Underscore,
|
|
|
|
}
|
|
|
|
impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
|
|
|
|
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
match self {
|
|
|
|
Self::Val(val) => val.fmt(fmt),
|
|
|
|
Self::Underscore => fmt.write_str("_"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
let mut eval_to_int = |op| {
|
|
|
|
// This can be `None` if the lhs wasn't const propagated and we just
|
|
|
|
// triggered the assert on the value of the rhs.
|
|
|
|
self.eval_operand(op, location)
|
|
|
|
.and_then(|op| self.ecx.read_immediate(&op).ok())
|
|
|
|
.map_or(DbgVal::Underscore, |op| DbgVal::Val(op.to_const_int()))
|
|
|
|
};
|
|
|
|
let msg = match msg {
|
|
|
|
AssertKind::DivisionByZero(op) => AssertKind::DivisionByZero(eval_to_int(op)),
|
|
|
|
AssertKind::RemainderByZero(op) => AssertKind::RemainderByZero(eval_to_int(op)),
|
|
|
|
AssertKind::Overflow(bin_op @ (BinOp::Div | BinOp::Rem), op1, op2) => {
|
|
|
|
// Division overflow is *UB* in the MIR, and different than the
|
|
|
|
// other overflow checks.
|
|
|
|
AssertKind::Overflow(*bin_op, eval_to_int(op1), eval_to_int(op2))
|
|
|
|
}
|
|
|
|
AssertKind::BoundsCheck { ref len, ref index } => {
|
|
|
|
let len = eval_to_int(len);
|
|
|
|
let index = eval_to_int(index);
|
|
|
|
AssertKind::BoundsCheck { len, index }
|
|
|
|
}
|
|
|
|
// Remaining overflow errors are already covered by checks on the binary operators.
|
|
|
|
AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => return None,
|
|
|
|
// Need proper const propagator for these.
|
|
|
|
_ => return None,
|
|
|
|
};
|
|
|
|
self.report_assert_as_lint(
|
|
|
|
lint::builtin::UNCONDITIONAL_PANIC,
|
|
|
|
location,
|
|
|
|
"this operation will panic at runtime",
|
|
|
|
msg,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
None
|
|
|
|
}
|
|
|
|
|
2023-03-13 17:43:14 +00:00
|
|
|
fn ensure_not_propagated(&self, local: Local) {
|
2023-03-07 16:34:11 +00:00
|
|
|
if cfg!(debug_assertions) {
|
|
|
|
assert!(
|
|
|
|
self.get_const(local.into()).is_none()
|
|
|
|
|| self
|
2023-03-30 18:01:42 +00:00
|
|
|
.layout_of(self.local_decls()[local].ty)
|
2023-03-07 16:34:11 +00:00
|
|
|
.map_or(true, |layout| layout.is_zst()),
|
|
|
|
"failed to remove values for `{local:?}`, value={:?}",
|
|
|
|
self.get_const(local.into()),
|
|
|
|
)
|
|
|
|
}
|
2022-03-08 17:20:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-11 14:52:58 +00:00
|
|
|
impl<'tcx> Visitor<'tcx> for ConstPropagator<'_, 'tcx> {
|
|
|
|
fn visit_body(&mut self, body: &Body<'tcx>) {
|
2023-03-30 18:40:47 +00:00
|
|
|
while let Some(bb) = self.worklist.pop() {
|
|
|
|
if !self.visited_blocks.insert(bb) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
let data = &body.basic_blocks[bb];
|
2022-03-08 17:20:31 +00:00
|
|
|
self.visit_basic_block_data(bb, data);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-11 14:52:58 +00:00
|
|
|
fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
|
2022-03-08 17:20:31 +00:00
|
|
|
self.super_operand(operand, location);
|
|
|
|
}
|
|
|
|
|
2022-03-11 14:52:58 +00:00
|
|
|
fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
|
2022-03-08 17:20:31 +00:00
|
|
|
trace!("visit_constant: {:?}", constant);
|
|
|
|
self.super_constant(constant, location);
|
2023-03-30 18:08:09 +00:00
|
|
|
self.eval_constant(constant, location);
|
2022-03-08 17:20:31 +00:00
|
|
|
}
|
|
|
|
|
2023-03-07 16:34:11 +00:00
|
|
|
fn visit_assign(&mut self, place: &Place<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
|
|
|
|
self.super_assign(place, rvalue, location);
|
|
|
|
|
2023-03-30 18:08:09 +00:00
|
|
|
let Some(()) = self.check_rvalue(rvalue, location) else { return };
|
2023-03-07 16:34:11 +00:00
|
|
|
|
|
|
|
match self.ecx.machine.can_const_prop[place.local] {
|
|
|
|
// Do nothing if the place is indirect.
|
|
|
|
_ if place.is_indirect() => {}
|
|
|
|
ConstPropMode::NoPropagation => self.ensure_not_propagated(place.local),
|
|
|
|
ConstPropMode::OnlyInsideOwnBlock | ConstPropMode::FullConstProp => {
|
|
|
|
if self
|
2023-03-30 18:08:09 +00:00
|
|
|
.use_ecx(location, |this| this.ecx.eval_rvalue_into_place(rvalue, *place))
|
2023-03-07 16:34:11 +00:00
|
|
|
.is_none()
|
|
|
|
{
|
2023-03-07 14:41:13 +00:00
|
|
|
// Const prop failed, so erase the destination, ensuring that whatever happens
|
|
|
|
// from here on, does not know about the previous value.
|
|
|
|
// This is important in case we have
|
|
|
|
// ```rust
|
|
|
|
// let mut x = 42;
|
|
|
|
// x = SOME_MUTABLE_STATIC;
|
|
|
|
// // x must now be uninit
|
|
|
|
// ```
|
|
|
|
// FIXME: we overzealously erase the entire local, because that's easier to
|
|
|
|
// implement.
|
|
|
|
trace!(
|
|
|
|
"propagation into {:?} failed.
|
|
|
|
Nuking the entire site from orbit, it's the only way to be sure",
|
|
|
|
place,
|
|
|
|
);
|
|
|
|
Self::remove_const(&mut self.ecx, place.local);
|
2022-03-08 17:20:31 +00:00
|
|
|
}
|
2023-03-07 14:41:13 +00:00
|
|
|
}
|
2023-03-07 16:34:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-11 14:52:58 +00:00
|
|
|
fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
|
2022-03-08 17:20:31 +00:00
|
|
|
trace!("visit_statement: {:?}", statement);
|
2023-03-07 16:34:11 +00:00
|
|
|
|
2023-03-07 17:12:42 +00:00
|
|
|
// We want to evaluate operands before any change to the assigned-to value,
|
|
|
|
// so we recurse first.
|
2023-03-07 16:34:11 +00:00
|
|
|
self.super_statement(statement, location);
|
|
|
|
|
|
|
|
match statement.kind {
|
2023-03-07 14:41:13 +00:00
|
|
|
StatementKind::SetDiscriminant { ref place, .. } => {
|
|
|
|
match self.ecx.machine.can_const_prop[place.local] {
|
2023-03-07 16:34:11 +00:00
|
|
|
// Do nothing if the place is indirect.
|
|
|
|
_ if place.is_indirect() => {}
|
|
|
|
ConstPropMode::NoPropagation => self.ensure_not_propagated(place.local),
|
2023-03-07 14:41:13 +00:00
|
|
|
ConstPropMode::FullConstProp | ConstPropMode::OnlyInsideOwnBlock => {
|
2023-03-30 18:08:09 +00:00
|
|
|
if self.use_ecx(location, |this| this.ecx.statement(statement)).is_some() {
|
2023-03-07 14:41:13 +00:00
|
|
|
trace!("propped discriminant into {:?}", place);
|
2022-03-08 17:20:31 +00:00
|
|
|
} else {
|
|
|
|
Self::remove_const(&mut self.ecx, place.local);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-03-07 14:41:13 +00:00
|
|
|
StatementKind::StorageLive(local) => {
|
|
|
|
let frame = self.ecx.frame_mut();
|
|
|
|
frame.locals[local].value =
|
|
|
|
LocalValue::Live(interpret::Operand::Immediate(interpret::Immediate::Uninit));
|
|
|
|
}
|
|
|
|
StatementKind::StorageDead(local) => {
|
|
|
|
let frame = self.ecx.frame_mut();
|
|
|
|
frame.locals[local].value = LocalValue::Dead;
|
2022-03-08 17:20:31 +00:00
|
|
|
}
|
2023-03-07 14:41:13 +00:00
|
|
|
_ => {}
|
2022-03-08 17:20:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-11 14:52:58 +00:00
|
|
|
fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
|
2022-03-08 17:20:31 +00:00
|
|
|
self.super_terminator(terminator, location);
|
2022-03-11 14:52:58 +00:00
|
|
|
match &terminator.kind {
|
|
|
|
TerminatorKind::Assert { expected, ref msg, ref cond, .. } => {
|
2023-03-30 18:19:20 +00:00
|
|
|
self.check_assertion(*expected, msg, cond, location);
|
2022-03-08 17:20:31 +00:00
|
|
|
}
|
2023-03-30 18:40:47 +00:00
|
|
|
TerminatorKind::SwitchInt { ref discr, ref targets } => {
|
|
|
|
if let Some(ref value) = self.eval_operand(&discr, location)
|
|
|
|
&& let Some(value_const) = self.use_ecx(location, |this| this.ecx.read_scalar(&value))
|
|
|
|
&& let Ok(constant) = value_const.try_to_int()
|
|
|
|
&& let Ok(constant) = constant.to_bits(constant.size())
|
|
|
|
{
|
2023-04-04 17:14:53 +00:00
|
|
|
// We managed to evaluate the discriminant, so we know we only need to visit
|
|
|
|
// one target.
|
2023-03-30 18:40:47 +00:00
|
|
|
let target = targets.target_for_value(constant);
|
|
|
|
self.worklist.push(target);
|
|
|
|
return;
|
|
|
|
}
|
2023-04-04 17:14:53 +00:00
|
|
|
// We failed to evaluate the discriminant, fallback to visiting all successors.
|
2023-03-30 18:40:47 +00:00
|
|
|
}
|
2022-03-08 17:20:31 +00:00
|
|
|
// None of these have Operands to const-propagate.
|
|
|
|
TerminatorKind::Goto { .. }
|
|
|
|
| TerminatorKind::Resume
|
2022-10-31 01:01:24 +00:00
|
|
|
| TerminatorKind::Terminate
|
2022-03-08 17:20:31 +00:00
|
|
|
| TerminatorKind::Return
|
|
|
|
| TerminatorKind::Unreachable
|
|
|
|
| TerminatorKind::Drop { .. }
|
|
|
|
| TerminatorKind::Yield { .. }
|
|
|
|
| TerminatorKind::GeneratorDrop
|
|
|
|
| TerminatorKind::FalseEdge { .. }
|
|
|
|
| TerminatorKind::FalseUnwind { .. }
|
2022-03-11 14:52:58 +00:00
|
|
|
| TerminatorKind::Call { .. }
|
2022-03-08 17:20:31 +00:00
|
|
|
| TerminatorKind::InlineAsm { .. } => {}
|
|
|
|
}
|
2023-03-30 18:40:47 +00:00
|
|
|
|
|
|
|
self.worklist.extend(terminator.successors());
|
2023-03-07 14:31:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn visit_basic_block_data(&mut self, block: BasicBlock, data: &BasicBlockData<'tcx>) {
|
|
|
|
self.super_basic_block_data(block, data);
|
2022-03-08 17:20:31 +00:00
|
|
|
|
|
|
|
// We remove all Locals which are restricted in propagation to their containing blocks and
|
|
|
|
// which were modified in the current block.
|
|
|
|
// Take it out of the ecx so we can get a mutable reference to the ecx for `remove_const`.
|
2023-03-13 17:43:14 +00:00
|
|
|
let mut written_only_inside_own_block_locals =
|
|
|
|
std::mem::take(&mut self.ecx.machine.written_only_inside_own_block_locals);
|
|
|
|
|
|
|
|
// This loop can get very hot for some bodies: it check each local in each bb.
|
|
|
|
// To avoid this quadratic behaviour, we only clear the locals that were modified inside
|
|
|
|
// the current block.
|
|
|
|
for local in written_only_inside_own_block_locals.drain() {
|
|
|
|
debug_assert_eq!(
|
|
|
|
self.ecx.machine.can_const_prop[local],
|
|
|
|
ConstPropMode::OnlyInsideOwnBlock
|
|
|
|
);
|
|
|
|
Self::remove_const(&mut self.ecx, local);
|
|
|
|
}
|
|
|
|
self.ecx.machine.written_only_inside_own_block_locals =
|
|
|
|
written_only_inside_own_block_locals;
|
|
|
|
|
2023-03-19 08:59:11 +00:00
|
|
|
if cfg!(debug_assertions) {
|
|
|
|
for (local, &mode) in self.ecx.machine.can_const_prop.iter_enumerated() {
|
|
|
|
match mode {
|
|
|
|
ConstPropMode::FullConstProp => {}
|
|
|
|
ConstPropMode::NoPropagation | ConstPropMode::OnlyInsideOwnBlock => {
|
|
|
|
self.ensure_not_propagated(local);
|
|
|
|
}
|
2023-03-07 15:20:57 +00:00
|
|
|
}
|
2022-03-08 17:20:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|