1 //! Propagates constants for early reporting of statically known
6 use either::{Left, Right};
8 use rustc_const_eval::interpret::Immediate;
9 use rustc_const_eval::interpret::{
10 self, InterpCx, InterpResult, LocalState, LocalValue, MemoryKind, OpTy, Scalar, StackPopCleanup,
12 use rustc_hir::def::DefKind;
14 use rustc_index::bit_set::BitSet;
15 use rustc_index::vec::IndexVec;
16 use rustc_middle::mir::visit::Visitor;
17 use rustc_middle::mir::{
18 AssertKind, BinOp, Body, Constant, Local, LocalDecl, Location, Operand, Place, Rvalue,
19 SourceInfo, SourceScope, SourceScopeData, Statement, StatementKind, Terminator, TerminatorKind,
22 use rustc_middle::ty::layout::{LayoutError, LayoutOf, LayoutOfHelpers, TyAndLayout};
23 use rustc_middle::ty::InternalSubsts;
24 use rustc_middle::ty::{self, ConstInt, Instance, ParamEnv, ScalarInt, Ty, TyCtxt, TypeVisitable};
25 use rustc_session::lint;
27 use rustc_target::abi::{HasDataLayout, Size, TargetDataLayout};
28 use rustc_trait_selection::traits;
30 use crate::const_prop::CanConstProp;
31 use crate::const_prop::ConstPropMachine;
32 use crate::const_prop::ConstPropMode;
35 /// The maximum number of bytes that we'll allocate space for a local or the return value.
36 /// Needed for #66397, because otherwise we eval into large places and that can cause OOM or just
37 /// Severely regress performance.
38 const MAX_ALLOC_LIMIT: u64 = 1024;
42 impl<'tcx> MirLint<'tcx> for ConstProp {
43 fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
44 // will be evaluated by miri and produce its errors there
45 if body.source.promoted.is_some() {
49 let def_id = body.source.def_id().expect_local();
50 let is_fn_like = tcx.def_kind(def_id).is_fn_like();
51 let is_assoc_const = tcx.def_kind(def_id) == DefKind::AssocConst;
53 // Only run const prop on functions, methods, closures and associated constants
54 if !is_fn_like && !is_assoc_const {
55 // skip anon_const/statics/consts because they'll be evaluated by miri anyway
56 trace!("ConstProp skipped for {:?}", def_id);
60 let is_generator = tcx.type_of(def_id.to_def_id()).is_generator();
61 // FIXME(welseywiser) const prop doesn't work on generators because of query cycles
62 // computing their layout.
64 trace!("ConstProp skipped for generator {:?}", def_id);
68 // Check if it's even possible to satisfy the 'where' clauses
70 // This branch will never be taken for any normal function.
71 // However, it's possible to `#!feature(trivial_bounds)]` to write
72 // a function with impossible to satisfy clauses, e.g.:
73 // `fn foo() where String: Copy {}`
75 // We don't usually need to worry about this kind of case,
76 // since we would get a compilation error if the user tried
77 // to call it. However, since we can do const propagation
78 // even without any calls to the function, we need to make
79 // sure that it even makes sense to try to evaluate the body.
80 // If there are unsatisfiable where clauses, then all bets are
81 // off, and we just give up.
83 // We manually filter the predicates, skipping anything that's not
84 // "global". We are in a potentially generic context
85 // (e.g. we are evaluating a function without substituting generic
86 // parameters, so this filtering serves two purposes:
88 // 1. We skip evaluating any predicates that we would
89 // never be able prove are unsatisfiable (e.g. `<T as Foo>`
90 // 2. We avoid trying to normalize predicates involving generic
91 // parameters (e.g. `<T as Foo>::MyItem`). This can confuse
92 // the normalization code (leading to cycle errors), since
93 // it's usually never invoked in this way.
95 .predicates_of(def_id.to_def_id())
98 .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
99 if traits::impossible_predicates(
101 traits::elaborate_predicates(tcx, predicates).map(|o| o.predicate).collect(),
103 trace!("ConstProp skipped for {:?}: found unsatisfiable predicates", def_id);
107 trace!("ConstProp starting for {:?}", def_id);
109 let dummy_body = &Body::new(
111 (*body.basic_blocks).clone(),
112 body.source_scopes.clone(),
113 body.local_decls.clone(),
118 body.generator_kind(),
119 body.tainted_by_errors,
122 // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
123 // constants, instead of just checking for const-folding succeeding.
124 // That would require a uniform one-def no-mutation analysis
125 // and RPO (or recursing when needing the value of a local).
126 let mut optimization_finder = ConstPropagator::new(body, dummy_body, tcx);
127 optimization_finder.visit_body(body);
129 trace!("ConstProp done for {:?}", def_id);
133 /// Finds optimization opportunities on the MIR.
134 struct ConstPropagator<'mir, 'tcx> {
135 ecx: InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>,
137 param_env: ParamEnv<'tcx>,
138 source_scopes: &'mir IndexVec<SourceScope, SourceScopeData<'tcx>>,
139 local_decls: &'mir IndexVec<Local, LocalDecl<'tcx>>,
140 // Because we have `MutVisitor` we can't obtain the `SourceInfo` from a `Location`. So we store
141 // the last known `SourceInfo` here and just keep revisiting it.
142 source_info: Option<SourceInfo>,
145 impl<'tcx> LayoutOfHelpers<'tcx> for ConstPropagator<'_, 'tcx> {
146 type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
149 fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
154 impl HasDataLayout for ConstPropagator<'_, '_> {
156 fn data_layout(&self) -> &TargetDataLayout {
157 &self.tcx.data_layout
161 impl<'tcx> ty::layout::HasTyCtxt<'tcx> for ConstPropagator<'_, 'tcx> {
163 fn tcx(&self) -> TyCtxt<'tcx> {
168 impl<'tcx> ty::layout::HasParamEnv<'tcx> for ConstPropagator<'_, 'tcx> {
170 fn param_env(&self) -> ty::ParamEnv<'tcx> {
175 impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
178 dummy_body: &'mir Body<'tcx>,
180 ) -> ConstPropagator<'mir, 'tcx> {
181 let def_id = body.source.def_id();
182 let substs = &InternalSubsts::identity_for_item(tcx, def_id);
183 let param_env = tcx.param_env_reveal_all_normalized(def_id);
185 let can_const_prop = CanConstProp::check(tcx, param_env, body);
186 let mut only_propagate_inside_block_locals = BitSet::new_empty(can_const_prop.len());
187 for (l, mode) in can_const_prop.iter_enumerated() {
188 if *mode == ConstPropMode::OnlyInsideOwnBlock {
189 only_propagate_inside_block_locals.insert(l);
192 let mut ecx = InterpCx::new(
194 tcx.def_span(def_id),
196 ConstPropMachine::new(only_propagate_inside_block_locals, can_const_prop),
200 .layout_of(body.bound_return_ty().subst(tcx, substs))
202 // Don't bother allocating memory for large values.
203 // I don't know how return types can seem to be unsized but this happens in the
204 // `type/type-unsatisfiable.rs` test.
205 .filter(|ret_layout| {
206 ret_layout.is_sized() && ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT)
208 .unwrap_or_else(|| ecx.layout_of(tcx.types.unit).unwrap());
211 .allocate(ret_layout, MemoryKind::Stack)
212 .expect("couldn't perform small allocation")
215 ecx.push_stack_frame(
216 Instance::new(def_id, substs),
219 StackPopCleanup::Root { cleanup: false },
221 .expect("failed to push initial stack frame");
227 source_scopes: &dummy_body.source_scopes,
228 local_decls: &dummy_body.local_decls,
233 fn get_const(&self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
234 let op = match self.ecx.eval_place_to_op(place, None) {
236 if matches!(*op, interpret::Operand::Immediate(Immediate::Uninit)) {
237 // Make sure nobody accidentally uses this value.
243 trace!("get_const failed: {}", e);
248 // Try to read the local as an immediate so that if it is representable as a scalar, we can
249 // handle it as such, but otherwise, just return the value as is.
250 Some(match self.ecx.read_immediate_raw(&op) {
251 Ok(Left(imm)) => imm.into(),
256 /// Remove `local` from the pool of `Locals`. Allows writing to them,
257 /// but not reading from them anymore.
258 fn remove_const(ecx: &mut InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>, local: Local) {
259 ecx.frame_mut().locals[local] = LocalState {
260 value: LocalValue::Live(interpret::Operand::Immediate(interpret::Immediate::Uninit)),
261 layout: Cell::new(None),
265 fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
266 source_info.scope.lint_root(self.source_scopes)
269 fn use_ecx<F, T>(&mut self, source_info: SourceInfo, f: F) -> Option<T>
271 F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
273 // Overwrite the PC -- whatever the interpreter does to it does not make any sense anyway.
274 self.ecx.frame_mut().loc = Right(source_info.span);
276 Ok(val) => Some(val),
278 trace!("InterpCx operation failed: {:?}", error);
279 // Some errors shouldn't come up because creating them causes
280 // an allocation, which we should avoid. When that happens,
281 // dedicated error variants should be introduced instead.
283 !error.kind().formatted_string(),
284 "const-prop encountered formatting error: {}",
292 /// Returns the value, if any, of evaluating `c`.
293 fn eval_constant(&mut self, c: &Constant<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
294 // FIXME we need to revisit this for #67176
299 self.use_ecx(source_info, |this| this.ecx.eval_mir_constant(&c.literal, Some(c.span), None))
302 /// Returns the value, if any, of evaluating `place`.
303 fn eval_place(&mut self, place: Place<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
304 trace!("eval_place(place={:?})", place);
305 self.use_ecx(source_info, |this| this.ecx.eval_place_to_op(place, None))
308 /// Returns the value, if any, of evaluating `op`. Calls upon `eval_constant`
309 /// or `eval_place`, depending on the variant of `Operand` used.
310 fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
312 Operand::Constant(ref c) => self.eval_constant(c, source_info),
313 Operand::Move(place) | Operand::Copy(place) => self.eval_place(place, source_info),
317 fn report_assert_as_lint(
319 lint: &'static lint::Lint,
320 source_info: SourceInfo,
321 message: &'static str,
322 panic: AssertKind<impl std::fmt::Debug>,
324 if let Some(lint_root) = self.lint_root(source_info) {
325 self.tcx.struct_span_lint_hir(lint, lint_root, source_info.span, message, |lint| {
326 lint.span_label(source_info.span, format!("{:?}", panic))
335 source_info: SourceInfo,
337 if let (val, true) = self.use_ecx(source_info, |this| {
338 let val = this.ecx.read_immediate(&this.ecx.eval_operand(arg, None)?)?;
339 let (_res, overflow, _ty) = this.ecx.overflowing_unary_op(op, &val)?;
342 // `AssertKind` only has an `OverflowNeg` variant, so make sure that is
343 // appropriate to use.
344 assert_eq!(op, UnOp::Neg, "Neg is the only UnOp that can overflow");
345 self.report_assert_as_lint(
346 lint::builtin::ARITHMETIC_OVERFLOW,
348 "this arithmetic operation will overflow",
349 AssertKind::OverflowNeg(val.to_const_int()),
360 left: &Operand<'tcx>,
361 right: &Operand<'tcx>,
362 source_info: SourceInfo,
364 let r = self.use_ecx(source_info, |this| {
365 this.ecx.read_immediate(&this.ecx.eval_operand(right, None)?)
367 let l = self.use_ecx(source_info, |this| {
368 this.ecx.read_immediate(&this.ecx.eval_operand(left, None)?)
370 // Check for exceeding shifts *even if* we cannot evaluate the LHS.
371 if op == BinOp::Shr || op == BinOp::Shl {
373 // We need the type of the LHS. We cannot use `place_layout` as that is the type
374 // of the result, which for checked binops is not the same!
375 let left_ty = left.ty(self.local_decls, self.tcx);
376 let left_size = self.ecx.layout_of(left_ty).ok()?.size;
377 let right_size = r.layout.size;
378 let r_bits = r.to_scalar().to_bits(right_size).ok();
379 if r_bits.map_or(false, |b| b >= left_size.bits() as u128) {
380 debug!("check_binary_op: reporting assert for {:?}", source_info);
381 self.report_assert_as_lint(
382 lint::builtin::ARITHMETIC_OVERFLOW,
384 "this arithmetic operation will overflow",
385 AssertKind::Overflow(
388 Some(l) => l.to_const_int(),
389 // Invent a dummy value, the diagnostic ignores it anyway
390 None => ConstInt::new(
391 ScalarInt::try_from_uint(1_u8, left_size).unwrap(),
393 left_ty.is_ptr_sized_integral(),
403 if let (Some(l), Some(r)) = (l, r) {
404 // The remaining operators are handled through `overflowing_binary_op`.
405 if self.use_ecx(source_info, |this| {
406 let (_res, overflow, _ty) = this.ecx.overflowing_binary_op(op, &l, &r)?;
409 self.report_assert_as_lint(
410 lint::builtin::ARITHMETIC_OVERFLOW,
412 "this arithmetic operation will overflow",
413 AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
423 rvalue: &Rvalue<'tcx>,
424 source_info: SourceInfo,
427 // Perform any special handling for specific Rvalue types.
428 // Generally, checks here fall into one of two categories:
429 // 1. Additional checking to provide useful lints to the user
430 // - In this case, we will do some validation and then fall through to the
431 // end of the function which evals the assignment.
432 // 2. Working around bugs in other parts of the compiler
433 // - In this case, we'll return `None` from this function to stop evaluation.
435 // Additional checking: give lints to the user if an overflow would occur.
436 // We do this here and not in the `Assert` terminator as that terminator is
437 // only sometimes emitted (overflow checks can be disabled), but we want to always
439 Rvalue::UnaryOp(op, arg) => {
440 trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
441 self.check_unary_op(*op, arg, source_info)?;
443 Rvalue::BinaryOp(op, box (left, right)) => {
444 trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
445 self.check_binary_op(*op, left, right, source_info)?;
447 Rvalue::CheckedBinaryOp(op, box (left, right)) => {
449 "checking CheckedBinaryOp(op = {:?}, left = {:?}, right = {:?})",
454 self.check_binary_op(*op, left, right, source_info)?;
457 // Do not try creating references (#67862)
458 Rvalue::AddressOf(_, place) | Rvalue::Ref(_, _, place) => {
459 trace!("skipping AddressOf | Ref for {:?}", place);
461 // This may be creating mutable references or immutable references to cells.
462 // If that happens, the pointed to value could be mutated via that reference.
463 // Since we aren't tracking references, the const propagator loses track of what
464 // value the local has right now.
465 // Thus, all locals that have their reference taken
466 // must not take part in propagation.
467 Self::remove_const(&mut self.ecx, place.local);
471 Rvalue::ThreadLocalRef(def_id) => {
472 trace!("skipping ThreadLocalRef({:?})", def_id);
477 // There's no other checking to do at this time.
478 Rvalue::Aggregate(..)
480 | Rvalue::CopyForDeref(..)
484 | Rvalue::ShallowInitBox(..)
485 | Rvalue::Discriminant(..)
486 | Rvalue::NullaryOp(..) => {}
489 // FIXME we need to revisit this for #67176
490 if rvalue.needs_subst() {
494 .ty(&self.ecx.frame().body.local_decls, *self.ecx.tcx)
495 .is_sized(*self.ecx.tcx, self.param_env)
497 // the interpreter doesn't support unsized locals (only unsized arguments),
498 // but rustc does (in a kinda broken way), so we have to skip them here
502 self.use_ecx(source_info, |this| this.ecx.eval_rvalue_into_place(rvalue, place))
506 impl<'tcx> Visitor<'tcx> for ConstPropagator<'_, 'tcx> {
507 fn visit_body(&mut self, body: &Body<'tcx>) {
508 for (bb, data) in body.basic_blocks.iter_enumerated() {
509 self.visit_basic_block_data(bb, data);
513 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
514 self.super_operand(operand, location);
517 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
518 trace!("visit_constant: {:?}", constant);
519 self.super_constant(constant, location);
520 self.eval_constant(constant, self.source_info.unwrap());
523 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
524 trace!("visit_statement: {:?}", statement);
525 let source_info = statement.source_info;
526 self.source_info = Some(source_info);
527 if let StatementKind::Assign(box (place, ref rval)) = statement.kind {
528 let can_const_prop = self.ecx.machine.can_const_prop[place.local];
529 if let Some(()) = self.const_prop(rval, source_info, place) {
530 match can_const_prop {
531 ConstPropMode::OnlyInsideOwnBlock => {
533 "found local restricted to its block. \
534 Will remove it from const-prop after block is finished. Local: {:?}",
538 ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
539 trace!("can't propagate into {:?}", place);
540 if place.local != RETURN_PLACE {
541 Self::remove_const(&mut self.ecx, place.local);
544 ConstPropMode::FullConstProp => {}
547 // Const prop failed, so erase the destination, ensuring that whatever happens
548 // from here on, does not know about the previous value.
549 // This is important in case we have
552 // x = SOME_MUTABLE_STATIC;
553 // // x must now be uninit
555 // FIXME: we overzealously erase the entire local, because that's easier to
558 "propagation into {:?} failed.
559 Nuking the entire site from orbit, it's the only way to be sure",
562 Self::remove_const(&mut self.ecx, place.local);
565 match statement.kind {
566 StatementKind::SetDiscriminant { ref place, .. } => {
567 match self.ecx.machine.can_const_prop[place.local] {
568 ConstPropMode::FullConstProp | ConstPropMode::OnlyInsideOwnBlock => {
570 .use_ecx(source_info, |this| this.ecx.statement(statement))
573 trace!("propped discriminant into {:?}", place);
575 Self::remove_const(&mut self.ecx, place.local);
578 ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
579 Self::remove_const(&mut self.ecx, place.local);
583 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
584 let frame = self.ecx.frame_mut();
585 frame.locals[local].value =
586 if let StatementKind::StorageLive(_) = statement.kind {
587 LocalValue::Live(interpret::Operand::Immediate(
588 interpret::Immediate::Uninit,
598 self.super_statement(statement, location);
601 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
602 let source_info = terminator.source_info;
603 self.source_info = Some(source_info);
604 self.super_terminator(terminator, location);
605 match &terminator.kind {
606 TerminatorKind::Assert { expected, ref msg, ref cond, .. } => {
607 if let Some(ref value) = self.eval_operand(&cond, source_info) {
608 trace!("assertion on {:?} should be {:?}", value, expected);
609 let expected = Scalar::from_bool(*expected);
610 let Ok(value_const) = self.ecx.read_scalar(&value) else {
611 // FIXME should be used use_ecx rather than a local match... but we have
612 // quite a few of these read_scalar/read_immediate that need fixing.
615 if expected != value_const {
620 impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
621 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
623 Self::Val(val) => val.fmt(fmt),
624 Self::Underscore => fmt.write_str("_"),
628 let mut eval_to_int = |op| {
629 // This can be `None` if the lhs wasn't const propagated and we just
630 // triggered the assert on the value of the rhs.
631 self.eval_operand(op, source_info)
632 .and_then(|op| self.ecx.read_immediate(&op).ok())
633 .map_or(DbgVal::Underscore, |op| DbgVal::Val(op.to_const_int()))
635 let msg = match msg {
636 AssertKind::DivisionByZero(op) => {
637 Some(AssertKind::DivisionByZero(eval_to_int(op)))
639 AssertKind::RemainderByZero(op) => {
640 Some(AssertKind::RemainderByZero(eval_to_int(op)))
642 AssertKind::Overflow(bin_op @ (BinOp::Div | BinOp::Rem), op1, op2) => {
643 // Division overflow is *UB* in the MIR, and different than the
644 // other overflow checks.
645 Some(AssertKind::Overflow(
651 AssertKind::BoundsCheck { ref len, ref index } => {
652 let len = eval_to_int(len);
653 let index = eval_to_int(index);
654 Some(AssertKind::BoundsCheck { len, index })
656 // Remaining overflow errors are already covered by checks on the binary operators.
657 AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => None,
658 // Need proper const propagator for these.
661 // Poison all places this operand references so that further code
662 // doesn't use the invalid value
664 Operand::Move(ref place) | Operand::Copy(ref place) => {
665 Self::remove_const(&mut self.ecx, place.local);
667 Operand::Constant(_) => {}
669 if let Some(msg) = msg {
670 self.report_assert_as_lint(
671 lint::builtin::UNCONDITIONAL_PANIC,
673 "this operation will panic at runtime",
680 // None of these have Operands to const-propagate.
681 TerminatorKind::Goto { .. }
682 | TerminatorKind::Resume
683 | TerminatorKind::Abort
684 | TerminatorKind::Return
685 | TerminatorKind::Unreachable
686 | TerminatorKind::Drop { .. }
687 | TerminatorKind::DropAndReplace { .. }
688 | TerminatorKind::Yield { .. }
689 | TerminatorKind::GeneratorDrop
690 | TerminatorKind::FalseEdge { .. }
691 | TerminatorKind::FalseUnwind { .. }
692 | TerminatorKind::SwitchInt { .. }
693 | TerminatorKind::Call { .. }
694 | TerminatorKind::InlineAsm { .. } => {}
697 // We remove all Locals which are restricted in propagation to their containing blocks and
698 // which were modified in the current block.
699 // Take it out of the ecx so we can get a mutable reference to the ecx for `remove_const`.
700 let mut locals = std::mem::take(&mut self.ecx.machine.written_only_inside_own_block_locals);
701 for &local in locals.iter() {
702 Self::remove_const(&mut self.ecx, local);
705 // Put it back so we reuse the heap of the storage
706 self.ecx.machine.written_only_inside_own_block_locals = locals;
707 if cfg!(debug_assertions) {
708 // Ensure we are correctly erasing locals with the non-debug-assert logic.
709 for local in self.ecx.machine.only_propagate_inside_block_locals.iter() {
711 self.get_const(local.into()).is_none()
713 .layout_of(self.local_decls[local].ty)
714 .map_or(true, |layout| layout.is_zst())