1 //! Propagates constants for early reporting of statically known
6 use rustc_ast::ast::Mutability;
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_hir::def::DefKind;
10 use rustc_index::bit_set::BitSet;
11 use rustc_index::vec::IndexVec;
12 use rustc_middle::mir::interpret::{InterpResult, Scalar};
13 use rustc_middle::mir::visit::{
14 MutVisitor, MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor,
16 use rustc_middle::mir::{
17 AggregateKind, AssertKind, BasicBlock, BinOp, Body, ClearCrossCrate, Constant, Local,
18 LocalDecl, LocalKind, Location, Operand, Place, Rvalue, SourceInfo, SourceScope,
19 SourceScopeData, Statement, StatementKind, Terminator, TerminatorKind, UnOp, RETURN_PLACE,
21 use rustc_middle::ty::layout::{HasTyCtxt, LayoutError, TyAndLayout};
22 use rustc_middle::ty::subst::{InternalSubsts, Subst};
23 use rustc_middle::ty::{self, ConstInt, ConstKind, Instance, ParamEnv, Ty, TyCtxt, TypeFoldable};
24 use rustc_session::lint;
25 use rustc_span::{def_id::DefId, Span};
26 use rustc_target::abi::{HasDataLayout, LayoutOf, Size, TargetDataLayout};
27 use rustc_trait_selection::traits;
29 use crate::const_eval::ConstEvalErr;
30 use crate::interpret::{
31 self, compile_time_machine, truncate, AllocId, Allocation, Frame, ImmTy, Immediate, InterpCx,
32 LocalState, LocalValue, MemPlace, Memory, MemoryKind, OpTy, Operand as InterpOperand, PlaceTy,
33 Pointer, ScalarMaybeUninit, StackPopCleanup,
35 use crate::transform::{MirPass, MirSource};
37 /// The maximum number of bytes that we'll allocate space for a local or the return value.
38 /// Needed for #66397, because otherwise we eval into large places and that can cause OOM or just
39 /// Severely regress performance.
40 const MAX_ALLOC_LIMIT: u64 = 1024;
42 /// Macro for machine-specific `InterpError` without allocation.
43 /// (These will never be shown to the user, but they help diagnose ICEs.)
44 macro_rules! throw_machine_stop_str {
46 // We make a new local type for it. The type itself does not carry any information,
47 // but its vtable (for the `MachineStopType` trait) does.
49 // Printing this type shows the desired string.
50 impl std::fmt::Display for Zst {
51 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55 impl rustc_middle::mir::interpret::MachineStopType for Zst {}
56 throw_machine_stop!(Zst)
62 impl<'tcx> MirPass<'tcx> for ConstProp {
63 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>) {
64 // will be evaluated by miri and produce its errors there
65 if source.promoted.is_some() {
69 use rustc_middle::hir::map::blocks::FnLikeNode;
70 let hir_id = tcx.hir().as_local_hir_id(source.def_id().expect_local());
72 let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some();
73 let is_assoc_const = tcx.def_kind(source.def_id()) == DefKind::AssocConst;
75 // Only run const prop on functions, methods, closures and associated constants
76 if !is_fn_like && !is_assoc_const {
77 // skip anon_const/statics/consts because they'll be evaluated by miri anyway
78 trace!("ConstProp skipped for {:?}", source.def_id());
82 let is_generator = tcx.type_of(source.def_id()).is_generator();
83 // FIXME(welseywiser) const prop doesn't work on generators because of query cycles
84 // computing their layout.
86 trace!("ConstProp skipped for generator {:?}", source.def_id());
90 // Check if it's even possible to satisfy the 'where' clauses
92 // This branch will never be taken for any normal function.
93 // However, it's possible to `#!feature(trivial_bounds)]` to write
94 // a function with impossible to satisfy clauses, e.g.:
95 // `fn foo() where String: Copy {}`
97 // We don't usually need to worry about this kind of case,
98 // since we would get a compilation error if the user tried
99 // to call it. However, since we can do const propagation
100 // even without any calls to the function, we need to make
101 // sure that it even makes sense to try to evaluate the body.
102 // If there are unsatisfiable where clauses, then all bets are
103 // off, and we just give up.
105 // We manually filter the predicates, skipping anything that's not
106 // "global". We are in a potentially generic context
107 // (e.g. we are evaluating a function without substituting generic
108 // parameters, so this filtering serves two purposes:
110 // 1. We skip evaluating any predicates that we would
111 // never be able prove are unsatisfiable (e.g. `<T as Foo>`
112 // 2. We avoid trying to normalize predicates involving generic
113 // parameters (e.g. `<T as Foo>::MyItem`). This can confuse
114 // the normalization code (leading to cycle errors), since
115 // it's usually never invoked in this way.
117 .predicates_of(source.def_id())
120 .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
121 if traits::impossible_predicates(
123 traits::elaborate_predicates(tcx, predicates).map(|o| o.predicate).collect(),
125 trace!("ConstProp skipped for {:?}: found unsatisfiable predicates", source.def_id());
129 trace!("ConstProp starting for {:?}", source.def_id());
131 let dummy_body = &Body::new(
132 body.basic_blocks().clone(),
133 body.source_scopes.clone(),
134 body.local_decls.clone(),
138 tcx.def_span(source.def_id()),
142 // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
143 // constants, instead of just checking for const-folding succeeding.
144 // That would require an uniform one-def no-mutation analysis
145 // and RPO (or recursing when needing the value of a local).
146 let mut optimization_finder = ConstPropagator::new(body, dummy_body, tcx, source);
147 optimization_finder.visit_body(body);
149 trace!("ConstProp done for {:?}", source.def_id());
153 struct ConstPropMachine<'mir, 'tcx> {
154 /// The virtual call stack.
155 stack: Vec<Frame<'mir, 'tcx, (), ()>>,
156 /// `OnlyInsideOwnBlock` locals that were written in the current block get erased at the end.
157 written_only_inside_own_block_locals: FxHashSet<Local>,
158 /// Locals that need to be cleared after every block terminates.
159 only_propagate_inside_block_locals: BitSet<Local>,
160 can_const_prop: IndexVec<Local, ConstPropMode>,
163 impl<'mir, 'tcx> ConstPropMachine<'mir, 'tcx> {
165 only_propagate_inside_block_locals: BitSet<Local>,
166 can_const_prop: IndexVec<Local, ConstPropMode>,
170 written_only_inside_own_block_locals: Default::default(),
171 only_propagate_inside_block_locals,
177 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine<'mir, 'tcx> {
178 compile_time_machine!(<'mir, 'tcx>);
180 type MemoryExtra = ();
182 fn find_mir_or_eval_fn(
183 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
184 _instance: ty::Instance<'tcx>,
185 _args: &[OpTy<'tcx>],
186 _ret: Option<(PlaceTy<'tcx>, BasicBlock)>,
187 _unwind: Option<BasicBlock>,
188 ) -> InterpResult<'tcx, Option<&'mir Body<'tcx>>> {
193 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
194 _instance: ty::Instance<'tcx>,
195 _args: &[OpTy<'tcx>],
196 _ret: Option<(PlaceTy<'tcx>, BasicBlock)>,
197 _unwind: Option<BasicBlock>,
198 ) -> InterpResult<'tcx> {
199 throw_machine_stop_str!("calling intrinsics isn't supported in ConstProp")
203 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
204 _msg: &rustc_middle::mir::AssertMessage<'tcx>,
205 _unwind: Option<rustc_middle::mir::BasicBlock>,
206 ) -> InterpResult<'tcx> {
207 bug!("panics terminators are not evaluated in ConstProp")
210 fn ptr_to_int(_mem: &Memory<'mir, 'tcx, Self>, _ptr: Pointer) -> InterpResult<'tcx, u64> {
211 throw_unsup!(ReadPointerAsBytes)
215 _ecx: &InterpCx<'mir, 'tcx, Self>,
219 ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
220 // We can't do this because aliasing of memory can differ between const eval and llvm
221 throw_machine_stop_str!("pointer arithmetic or comparisons aren't supported in ConstProp")
225 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
226 _dest: PlaceTy<'tcx>,
227 ) -> InterpResult<'tcx> {
228 throw_machine_stop_str!("can't const prop heap allocations")
232 _ecx: &InterpCx<'mir, 'tcx, Self>,
233 frame: &Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>,
235 ) -> InterpResult<'tcx, InterpOperand<Self::PointerTag>> {
236 let l = &frame.locals[local];
238 if l.value == LocalValue::Uninitialized {
239 throw_machine_stop_str!("tried to access an uninitialized local")
245 fn access_local_mut<'a>(
246 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
249 ) -> InterpResult<'tcx, Result<&'a mut LocalValue<Self::PointerTag>, MemPlace<Self::PointerTag>>>
251 if ecx.machine.can_const_prop[local] == ConstPropMode::NoPropagation {
252 throw_machine_stop_str!("tried to write to a local that is marked as not propagatable")
254 if frame == 0 && ecx.machine.only_propagate_inside_block_locals.contains(local) {
256 "mutating local {:?} which is restricted to its block. \
257 Will remove it from const-prop after block is finished.",
260 ecx.machine.written_only_inside_own_block_locals.insert(local);
262 ecx.machine.stack[frame].locals[local].access_mut()
265 fn before_access_global(
268 allocation: &Allocation<Self::PointerTag, Self::AllocExtra>,
269 _static_def_id: Option<DefId>,
271 ) -> InterpResult<'tcx> {
273 throw_machine_stop_str!("can't write to global");
275 // If the static allocation is mutable, then we can't const prop it as its content
276 // might be different at runtime.
277 if allocation.mutability == Mutability::Mut {
278 throw_machine_stop_str!("can't access mutable globals in ConstProp");
286 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
287 frame: Frame<'mir, 'tcx>,
288 ) -> InterpResult<'tcx, Frame<'mir, 'tcx>> {
294 ecx: &'a InterpCx<'mir, 'tcx, Self>,
295 ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
301 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
302 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
303 &mut ecx.machine.stack
307 /// Finds optimization opportunities on the MIR.
308 struct ConstPropagator<'mir, 'tcx> {
309 ecx: InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>,
311 param_env: ParamEnv<'tcx>,
312 // FIXME(eddyb) avoid cloning these two fields more than once,
313 // by accessing them through `ecx` instead.
314 source_scopes: IndexVec<SourceScope, SourceScopeData>,
315 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
316 // Because we have `MutVisitor` we can't obtain the `SourceInfo` from a `Location`. So we store
317 // the last known `SourceInfo` here and just keep revisiting it.
318 source_info: Option<SourceInfo>,
321 impl<'mir, 'tcx> LayoutOf for ConstPropagator<'mir, 'tcx> {
323 type TyAndLayout = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
325 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
326 self.tcx.layout_of(self.param_env.and(ty))
330 impl<'mir, 'tcx> HasDataLayout for ConstPropagator<'mir, 'tcx> {
332 fn data_layout(&self) -> &TargetDataLayout {
333 &self.tcx.data_layout
337 impl<'mir, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'mir, 'tcx> {
339 fn tcx(&self) -> TyCtxt<'tcx> {
344 impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
347 dummy_body: &'mir Body<'tcx>,
349 source: MirSource<'tcx>,
350 ) -> ConstPropagator<'mir, 'tcx> {
351 let def_id = source.def_id();
352 let substs = &InternalSubsts::identity_for_item(tcx, def_id);
353 let param_env = tcx.param_env_reveal_all_normalized(def_id);
355 let span = tcx.def_span(def_id);
356 // FIXME: `CanConstProp::check` computes the layout of all locals, return those layouts
357 // so we can write them to `ecx.frame_mut().locals.layout, reducing the duplication in
358 // `layout_of` query invocations.
359 let can_const_prop = CanConstProp::check(tcx, param_env, body);
360 let mut only_propagate_inside_block_locals = BitSet::new_empty(can_const_prop.len());
361 for (l, mode) in can_const_prop.iter_enumerated() {
362 if *mode == ConstPropMode::OnlyInsideOwnBlock {
363 only_propagate_inside_block_locals.insert(l);
366 let mut ecx = InterpCx::new(
370 ConstPropMachine::new(only_propagate_inside_block_locals, can_const_prop),
375 .layout_of(body.return_ty().subst(tcx, substs))
377 // Don't bother allocating memory for ZST types which have no values
378 // or for large values.
379 .filter(|ret_layout| {
380 !ret_layout.is_zst() && ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT)
382 .map(|ret_layout| ecx.allocate(ret_layout, MemoryKind::Stack));
384 ecx.push_stack_frame(
385 Instance::new(def_id, substs),
388 StackPopCleanup::None { cleanup: false },
390 .expect("failed to push initial stack frame");
396 // FIXME(eddyb) avoid cloning these two fields more than once,
397 // by accessing them through `ecx` instead.
398 source_scopes: body.source_scopes.clone(),
399 //FIXME(wesleywiser) we can't steal this because `Visitor::super_visit_body()` needs it
400 local_decls: body.local_decls.clone(),
405 fn get_const(&self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
406 let op = match self.ecx.eval_place_to_op(place, None) {
409 trace!("get_const failed: {}", e);
414 // Try to read the local as an immediate so that if it is representable as a scalar, we can
415 // handle it as such, but otherwise, just return the value as is.
416 Some(match self.ecx.try_read_immediate(op) {
417 Ok(Ok(imm)) => imm.into(),
422 /// Remove `local` from the pool of `Locals`. Allows writing to them,
423 /// but not reading from them anymore.
424 fn remove_const(ecx: &mut InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>, local: Local) {
425 ecx.frame_mut().locals[local] =
426 LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) };
429 fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
430 match &self.source_scopes[source_info.scope].local_data {
431 ClearCrossCrate::Set(data) => Some(data.lint_root),
432 ClearCrossCrate::Clear => None,
436 fn use_ecx<F, T>(&mut self, f: F) -> Option<T>
438 F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
441 Ok(val) => Some(val),
443 trace!("InterpCx operation failed: {:?}", error);
444 // Some errors shouldn't come up because creating them causes
445 // an allocation, which we should avoid. When that happens,
446 // dedicated error variants should be introduced instead.
448 !error.kind.allocates(),
449 "const-prop encountered allocating error: {}",
457 /// Returns the value, if any, of evaluating `c`.
458 fn eval_constant(&mut self, c: &Constant<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
459 // FIXME we need to revisit this for #67176
464 match self.ecx.const_to_op(c.literal, None) {
467 let tcx = self.ecx.tcx.at(c.span);
468 let err = ConstEvalErr::new(&self.ecx, error, Some(c.span));
469 if let Some(lint_root) = self.lint_root(source_info) {
470 let lint_only = match c.literal.val {
471 // Promoteds must lint and not error as the user didn't ask for them
472 ConstKind::Unevaluated(_, _, Some(_)) => true,
473 // Out of backwards compatibility we cannot report hard errors in unused
474 // generic functions using associated constants of the generic parameters.
475 _ => c.literal.needs_subst(),
478 // Out of backwards compatibility we cannot report hard errors in unused
479 // generic functions using associated constants of the generic parameters.
480 err.report_as_lint(tcx, "erroneous constant used", lint_root, Some(c.span));
482 err.report_as_error(tcx, "erroneous constant used");
485 err.report_as_error(tcx, "erroneous constant used");
492 /// Returns the value, if any, of evaluating `place`.
493 fn eval_place(&mut self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
494 trace!("eval_place(place={:?})", place);
495 self.use_ecx(|this| this.ecx.eval_place_to_op(place, None))
498 /// Returns the value, if any, of evaluating `op`. Calls upon `eval_constant`
499 /// or `eval_place`, depending on the variant of `Operand` used.
500 fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
502 Operand::Constant(ref c) => self.eval_constant(c, source_info),
503 Operand::Move(place) | Operand::Copy(place) => self.eval_place(place),
507 fn report_assert_as_lint(
509 lint: &'static lint::Lint,
510 source_info: SourceInfo,
511 message: &'static str,
512 panic: AssertKind<impl std::fmt::Debug>,
514 let lint_root = self.lint_root(source_info)?;
515 self.tcx.struct_span_lint_hir(lint, lint_root, source_info.span, |lint| {
516 let mut err = lint.build(message);
517 err.span_label(source_info.span, format!("{:?}", panic));
527 source_info: SourceInfo,
529 if let (val, true) = self.use_ecx(|this| {
530 let val = this.ecx.read_immediate(this.ecx.eval_operand(arg, None)?)?;
531 let (_res, overflow, _ty) = this.ecx.overflowing_unary_op(op, val)?;
534 // `AssertKind` only has an `OverflowNeg` variant, so make sure that is
535 // appropriate to use.
536 assert_eq!(op, UnOp::Neg, "Neg is the only UnOp that can overflow");
537 self.report_assert_as_lint(
538 lint::builtin::ARITHMETIC_OVERFLOW,
540 "this arithmetic operation will overflow",
541 AssertKind::OverflowNeg(val.to_const_int()),
551 left: &Operand<'tcx>,
552 right: &Operand<'tcx>,
553 source_info: SourceInfo,
555 let r = self.use_ecx(|this| this.ecx.read_immediate(this.ecx.eval_operand(right, None)?));
556 let l = self.use_ecx(|this| this.ecx.read_immediate(this.ecx.eval_operand(left, None)?));
557 // Check for exceeding shifts *even if* we cannot evaluate the LHS.
558 if op == BinOp::Shr || op == BinOp::Shl {
560 // We need the type of the LHS. We cannot use `place_layout` as that is the type
561 // of the result, which for checked binops is not the same!
562 let left_ty = left.ty(&self.local_decls, self.tcx);
563 let left_size = self.ecx.layout_of(left_ty).ok()?.size;
564 let right_size = r.layout.size;
565 let r_bits = r.to_scalar().ok();
566 // This is basically `force_bits`.
567 let r_bits = r_bits.and_then(|r| r.to_bits_or_ptr(right_size, &self.tcx).ok());
568 if r_bits.map_or(false, |b| b >= left_size.bits() as u128) {
569 debug!("check_binary_op: reporting assert for {:?}", source_info);
570 self.report_assert_as_lint(
571 lint::builtin::ARITHMETIC_OVERFLOW,
573 "this arithmetic operation will overflow",
574 AssertKind::Overflow(
577 Some(l) => l.to_const_int(),
578 // Invent a dummy value, the diagnostic ignores it anyway
579 None => ConstInt::new(
583 left_ty.is_ptr_sized_integral(),
592 if let (Some(l), Some(r)) = (l, r) {
593 // The remaining operators are handled through `overflowing_binary_op`.
594 if self.use_ecx(|this| {
595 let (_res, overflow, _ty) = this.ecx.overflowing_binary_op(op, l, r)?;
598 self.report_assert_as_lint(
599 lint::builtin::ARITHMETIC_OVERFLOW,
601 "this arithmetic operation will overflow",
602 AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
609 fn propagate_operand(&mut self, operand: &mut Operand<'tcx>) {
611 Operand::Copy(l) | Operand::Move(l) => {
612 if let Some(value) = self.get_const(l) {
613 if self.should_const_prop(value) {
614 // FIXME(felix91gr): this code only handles `Scalar` cases.
615 // For now, we're not handling `ScalarPair` cases because
616 // doing so here would require a lot of code duplication.
617 // We should hopefully generalize `Operand` handling into a fn,
618 // and use it to do const-prop here and everywhere else
619 // where it makes sense.
620 if let interpret::Operand::Immediate(interpret::Immediate::Scalar(
621 ScalarMaybeUninit::Scalar(scalar),
624 *operand = self.operand_from_scalar(
627 self.source_info.unwrap().span,
633 Operand::Constant(_) => (),
639 rvalue: &Rvalue<'tcx>,
640 source_info: SourceInfo,
643 // Perform any special handling for specific Rvalue types.
644 // Generally, checks here fall into one of two categories:
645 // 1. Additional checking to provide useful lints to the user
646 // - In this case, we will do some validation and then fall through to the
647 // end of the function which evals the assignment.
648 // 2. Working around bugs in other parts of the compiler
649 // - In this case, we'll return `None` from this function to stop evaluation.
651 // Additional checking: give lints to the user if an overflow would occur.
652 // We do this here and not in the `Assert` terminator as that terminator is
653 // only sometimes emitted (overflow checks can be disabled), but we want to always
655 Rvalue::UnaryOp(op, arg) => {
656 trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
657 self.check_unary_op(*op, arg, source_info)?;
659 Rvalue::BinaryOp(op, left, right) => {
660 trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
661 self.check_binary_op(*op, left, right, source_info)?;
663 Rvalue::CheckedBinaryOp(op, left, right) => {
665 "checking CheckedBinaryOp(op = {:?}, left = {:?}, right = {:?})",
670 self.check_binary_op(*op, left, right, source_info)?;
673 // Do not try creating references (#67862)
674 Rvalue::AddressOf(_, place) | Rvalue::Ref(_, _, place) => {
675 trace!("skipping AddressOf | Ref for {:?}", place);
677 // This may be creating mutable references or immutable references to cells.
678 // If that happens, the pointed to value could be mutated via that reference.
679 // Since we aren't tracking references, the const propagator loses track of what
680 // value the local has right now.
681 // Thus, all locals that have their reference taken
682 // must not take part in propagation.
683 Self::remove_const(&mut self.ecx, place.local);
687 Rvalue::ThreadLocalRef(def_id) => {
688 trace!("skipping ThreadLocalRef({:?})", def_id);
693 // There's no other checking to do at this time.
694 Rvalue::Aggregate(..)
699 | Rvalue::Discriminant(..)
700 | Rvalue::NullaryOp(..) => {}
703 // FIXME we need to revisit this for #67176
704 if rvalue.needs_subst() {
708 if self.tcx.sess.opts.debugging_opts.mir_opt_level >= 3 {
709 self.eval_rvalue_with_identities(rvalue, place)
711 self.use_ecx(|this| this.ecx.eval_rvalue_into_place(rvalue, place))
715 // Attempt to use albegraic identities to eliminate constant expressions
716 fn eval_rvalue_with_identities(
718 rvalue: &Rvalue<'tcx>,
721 self.use_ecx(|this| {
723 Rvalue::BinaryOp(op, left, right) | Rvalue::CheckedBinaryOp(op, left, right) => {
724 let l = this.ecx.eval_operand(left, None);
725 let r = this.ecx.eval_operand(right, None);
727 let const_arg = match (l, r) {
728 (Ok(x), Err(_)) | (Err(_), Ok(x)) => this.ecx.read_immediate(x)?,
729 (Err(e), Err(_)) => return Err(e),
731 this.ecx.eval_rvalue_into_place(rvalue, place)?;
737 this.ecx.force_bits(const_arg.to_scalar()?, const_arg.layout.size)?;
738 let dest = this.ecx.eval_place(place)?;
743 this.ecx.write_immediate(*const_arg, dest)?;
747 if arg_value == truncate(u128::MAX, const_arg.layout.size)
748 || (const_arg.layout.ty.is_bool() && arg_value == 1)
750 this.ecx.write_immediate(*const_arg, dest)?;
754 if const_arg.layout.ty.is_integral() && arg_value == 0 {
755 if let Rvalue::CheckedBinaryOp(_, _, _) = rvalue {
756 let val = Immediate::ScalarPair(
757 const_arg.to_scalar()?.into(),
758 Scalar::from_bool(false).into(),
760 this.ecx.write_immediate(val, dest)?;
762 this.ecx.write_immediate(*const_arg, dest)?;
767 this.ecx.eval_rvalue_into_place(rvalue, place)?;
772 this.ecx.eval_rvalue_into_place(rvalue, place)?;
780 /// Creates a new `Operand::Constant` from a `Scalar` value
781 fn operand_from_scalar(&self, scalar: Scalar, ty: Ty<'tcx>, span: Span) -> Operand<'tcx> {
782 Operand::Constant(Box::new(Constant {
785 literal: ty::Const::from_scalar(self.tcx, scalar, ty),
789 fn replace_with_const(
791 rval: &mut Rvalue<'tcx>,
793 source_info: SourceInfo,
795 if let Rvalue::Use(Operand::Constant(c)) = rval {
796 if !matches!(c.literal.val, ConstKind::Unevaluated(..)) {
797 trace!("skipping replace of Rvalue::Use({:?} because it is already a const", c);
802 trace!("attepting to replace {:?} with {:?}", rval, value);
803 if let Err(e) = self.ecx.const_validate_operand(
806 // FIXME: is ref tracking too expensive?
807 &mut interpret::RefTracking::empty(),
808 /*may_ref_to_static*/ true,
810 trace!("validation error, attempt failed: {:?}", e);
814 // FIXME> figure out what to do when try_read_immediate fails
815 let imm = self.use_ecx(|this| this.ecx.try_read_immediate(value));
817 if let Some(Ok(imm)) = imm {
819 interpret::Immediate::Scalar(ScalarMaybeUninit::Scalar(scalar)) => {
820 *rval = Rvalue::Use(self.operand_from_scalar(
826 Immediate::ScalarPair(
827 ScalarMaybeUninit::Scalar(one),
828 ScalarMaybeUninit::Scalar(two),
830 // Found a value represented as a pair. For now only do cont-prop if type of
831 // Rvalue is also a pair with two scalars. The more general case is more
832 // complicated to implement so we'll do it later.
833 // FIXME: implement the general case stated above ^.
834 let ty = &value.layout.ty.kind;
835 // Only do it for tuples
836 if let ty::Tuple(substs) = ty {
837 // Only do it if tuple is also a pair with two scalars
838 if substs.len() == 2 {
839 let opt_ty1_ty2 = self.use_ecx(|this| {
840 let ty1 = substs[0].expect_ty();
841 let ty2 = substs[1].expect_ty();
842 let ty_is_scalar = |ty| {
843 this.ecx.layout_of(ty).ok().map(|layout| layout.abi.is_scalar())
846 if ty_is_scalar(ty1) && ty_is_scalar(ty2) {
853 if let Some(Some((ty1, ty2))) = opt_ty1_ty2 {
854 *rval = Rvalue::Aggregate(
855 Box::new(AggregateKind::Tuple),
857 self.operand_from_scalar(one, ty1, source_info.span),
858 self.operand_from_scalar(two, ty2, source_info.span),
870 /// Returns `true` if and only if this `op` should be const-propagated into.
871 fn should_const_prop(&mut self, op: OpTy<'tcx>) -> bool {
872 let mir_opt_level = self.tcx.sess.opts.debugging_opts.mir_opt_level;
874 if mir_opt_level == 0 {
879 interpret::Operand::Immediate(Immediate::Scalar(ScalarMaybeUninit::Scalar(s))) => {
882 interpret::Operand::Immediate(Immediate::ScalarPair(
883 ScalarMaybeUninit::Scalar(l),
884 ScalarMaybeUninit::Scalar(r),
885 )) => l.is_bits() && r.is_bits(),
891 /// The mode that `ConstProp` is allowed to run in for a given `Local`.
892 #[derive(Clone, Copy, Debug, PartialEq)]
894 /// The `Local` can be propagated into and reads of this `Local` can also be propagated.
896 /// The `Local` can only be propagated into and from its own block.
898 /// The `Local` can be propagated into but reads cannot be propagated.
900 /// The `Local` cannot be part of propagation at all. Any statement
901 /// referencing it either for reading or writing will not get propagated.
905 struct CanConstProp {
906 can_const_prop: IndexVec<Local, ConstPropMode>,
907 // False at the beginning. Once set, no more assignments are allowed to that local.
908 found_assignment: BitSet<Local>,
909 // Cache of locals' information
910 local_kinds: IndexVec<Local, LocalKind>,
914 /// Returns true if `local` can be propagated
917 param_env: ParamEnv<'tcx>,
919 ) -> IndexVec<Local, ConstPropMode> {
920 let mut cpv = CanConstProp {
921 can_const_prop: IndexVec::from_elem(ConstPropMode::FullConstProp, &body.local_decls),
922 found_assignment: BitSet::new_empty(body.local_decls.len()),
923 local_kinds: IndexVec::from_fn_n(
924 |local| body.local_kind(local),
925 body.local_decls.len(),
928 for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
929 let ty = body.local_decls[local].ty;
930 match tcx.layout_of(param_env.and(ty)) {
931 Ok(layout) if layout.size < Size::from_bytes(MAX_ALLOC_LIMIT) => {}
932 // Either the layout fails to compute, then we can't use this local anyway
933 // or the local is too large, then we don't want to.
935 *val = ConstPropMode::NoPropagation;
939 // Cannot use args at all
940 // Cannot use locals because if x < y { y - x } else { x - y } would
942 // FIXME(oli-obk): lint variables until they are used in a condition
943 // FIXME(oli-obk): lint if return value is constant
944 if cpv.local_kinds[local] == LocalKind::Arg {
945 *val = ConstPropMode::OnlyPropagateInto;
947 "local {:?} can't be const propagated because it's a function argument",
950 } else if cpv.local_kinds[local] == LocalKind::Var {
951 *val = ConstPropMode::OnlyInsideOwnBlock;
953 "local {:?} will only be propagated inside its block, because it's a user variable",
958 cpv.visit_body(&body);
963 impl<'tcx> Visitor<'tcx> for CanConstProp {
964 fn visit_local(&mut self, &local: &Local, context: PlaceContext, _: Location) {
965 use rustc_middle::mir::visit::PlaceContext::*;
967 // Projections are fine, because `&mut foo.x` will be caught by
968 // `MutatingUseContext::Borrow` elsewhere.
969 MutatingUse(MutatingUseContext::Projection)
970 // These are just stores, where the storing is not propagatable, but there may be later
971 // mutations of the same local via `Store`
972 | MutatingUse(MutatingUseContext::Call)
973 // Actual store that can possibly even propagate a value
974 | MutatingUse(MutatingUseContext::Store) => {
975 if !self.found_assignment.insert(local) {
976 match &mut self.can_const_prop[local] {
977 // If the local can only get propagated in its own block, then we don't have
978 // to worry about multiple assignments, as we'll nuke the const state at the
979 // end of the block anyway, and inside the block we overwrite previous
980 // states as applicable.
981 ConstPropMode::OnlyInsideOwnBlock => {}
982 ConstPropMode::NoPropagation => {}
983 ConstPropMode::OnlyPropagateInto => {}
984 other @ ConstPropMode::FullConstProp => {
986 "local {:?} can't be propagated because of multiple assignments. Previous state: {:?}",
989 *other = ConstPropMode::OnlyInsideOwnBlock;
994 // Reading constants is allowed an arbitrary number of times
995 NonMutatingUse(NonMutatingUseContext::Copy)
996 | NonMutatingUse(NonMutatingUseContext::Move)
997 | NonMutatingUse(NonMutatingUseContext::Inspect)
998 | NonMutatingUse(NonMutatingUseContext::Projection)
1001 // These could be propagated with a smarter analysis or just some careful thinking about
1002 // whether they'd be fine right now.
1003 MutatingUse(MutatingUseContext::AsmOutput)
1004 | MutatingUse(MutatingUseContext::Yield)
1005 | MutatingUse(MutatingUseContext::Drop)
1006 | MutatingUse(MutatingUseContext::Retag)
1007 // These can't ever be propagated under any scheme, as we can't reason about indirect
1009 | NonMutatingUse(NonMutatingUseContext::SharedBorrow)
1010 | NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
1011 | NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
1012 | NonMutatingUse(NonMutatingUseContext::AddressOf)
1013 | MutatingUse(MutatingUseContext::Borrow)
1014 | MutatingUse(MutatingUseContext::AddressOf) => {
1015 trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
1016 self.can_const_prop[local] = ConstPropMode::NoPropagation;
1022 impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> {
1023 fn tcx(&self) -> TyCtxt<'tcx> {
1027 fn visit_body(&mut self, body: &mut Body<'tcx>) {
1028 for (bb, data) in body.basic_blocks_mut().iter_enumerated_mut() {
1029 self.visit_basic_block_data(bb, data);
1033 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
1034 self.super_operand(operand, location);
1036 // Only const prop copies and moves on `mir_opt_level=3` as doing so
1037 // currently increases compile time.
1038 if self.tcx.sess.opts.debugging_opts.mir_opt_level >= 3 {
1039 self.propagate_operand(operand)
1043 fn visit_constant(&mut self, constant: &mut Constant<'tcx>, location: Location) {
1044 trace!("visit_constant: {:?}", constant);
1045 self.super_constant(constant, location);
1046 self.eval_constant(constant, self.source_info.unwrap());
1049 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
1050 trace!("visit_statement: {:?}", statement);
1051 let source_info = statement.source_info;
1052 self.source_info = Some(source_info);
1053 if let StatementKind::Assign(box (place, ref mut rval)) = statement.kind {
1054 let can_const_prop = self.ecx.machine.can_const_prop[place.local];
1055 if let Some(()) = self.const_prop(rval, source_info, place) {
1056 // This will return None if the above `const_prop` invocation only "wrote" a
1057 // type whose creation requires no write. E.g. a generator whose initial state
1058 // consists solely of uninitialized memory (so it doesn't capture any locals).
1059 if let Some(value) = self.get_const(place) {
1060 if self.should_const_prop(value) {
1061 trace!("replacing {:?} with {:?}", rval, value);
1062 self.replace_with_const(rval, value, source_info);
1063 if can_const_prop == ConstPropMode::FullConstProp
1064 || can_const_prop == ConstPropMode::OnlyInsideOwnBlock
1066 trace!("propagated into {:?}", place);
1070 match can_const_prop {
1071 ConstPropMode::OnlyInsideOwnBlock => {
1073 "found local restricted to its block. \
1074 Will remove it from const-prop after block is finished. Local: {:?}",
1078 ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
1079 trace!("can't propagate into {:?}", place);
1080 if place.local != RETURN_PLACE {
1081 Self::remove_const(&mut self.ecx, place.local);
1084 ConstPropMode::FullConstProp => {}
1087 // Const prop failed, so erase the destination, ensuring that whatever happens
1088 // from here on, does not know about the previous value.
1089 // This is important in case we have
1092 // x = SOME_MUTABLE_STATIC;
1093 // // x must now be uninit
1095 // FIXME: we overzealously erase the entire local, because that's easier to
1098 "propagation into {:?} failed.
1099 Nuking the entire site from orbit, it's the only way to be sure",
1102 Self::remove_const(&mut self.ecx, place.local);
1105 match statement.kind {
1106 StatementKind::SetDiscriminant { ref place, .. } => {
1107 match self.ecx.machine.can_const_prop[place.local] {
1108 ConstPropMode::FullConstProp | ConstPropMode::OnlyInsideOwnBlock => {
1109 if self.use_ecx(|this| this.ecx.statement(statement)).is_some() {
1110 trace!("propped discriminant into {:?}", place);
1112 Self::remove_const(&mut self.ecx, place.local);
1115 ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
1116 Self::remove_const(&mut self.ecx, place.local);
1120 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
1121 let frame = self.ecx.frame_mut();
1122 frame.locals[local].value =
1123 if let StatementKind::StorageLive(_) = statement.kind {
1124 LocalValue::Uninitialized
1133 self.super_statement(statement, location);
1136 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
1137 let source_info = terminator.source_info;
1138 self.source_info = Some(source_info);
1139 self.super_terminator(terminator, location);
1140 match &mut terminator.kind {
1141 TerminatorKind::Assert { expected, ref msg, ref mut cond, .. } => {
1142 if let Some(value) = self.eval_operand(&cond, source_info) {
1143 trace!("assertion on {:?} should be {:?}", value, expected);
1144 let expected = ScalarMaybeUninit::from(Scalar::from_bool(*expected));
1145 let value_const = self.ecx.read_scalar(value).unwrap();
1146 if expected != value_const {
1151 impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
1152 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1154 Self::Val(val) => val.fmt(fmt),
1155 Self::Underscore => fmt.write_str("_"),
1159 let mut eval_to_int = |op| {
1160 // This can be `None` if the lhs wasn't const propagated and we just
1161 // triggered the assert on the value of the rhs.
1162 match self.eval_operand(op, source_info) {
1164 DbgVal::Val(self.ecx.read_immediate(op).unwrap().to_const_int())
1166 None => DbgVal::Underscore,
1169 let msg = match msg {
1170 AssertKind::DivisionByZero(op) => {
1171 Some(AssertKind::DivisionByZero(eval_to_int(op)))
1173 AssertKind::RemainderByZero(op) => {
1174 Some(AssertKind::RemainderByZero(eval_to_int(op)))
1176 AssertKind::BoundsCheck { ref len, ref index } => {
1177 let len = eval_to_int(len);
1178 let index = eval_to_int(index);
1179 Some(AssertKind::BoundsCheck { len, index })
1181 // Overflow is are already covered by checks on the binary operators.
1182 AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => None,
1183 // Need proper const propagator for these.
1186 // Poison all places this operand references so that further code
1187 // doesn't use the invalid value
1189 Operand::Move(ref place) | Operand::Copy(ref place) => {
1190 Self::remove_const(&mut self.ecx, place.local);
1192 Operand::Constant(_) => {}
1194 if let Some(msg) = msg {
1195 self.report_assert_as_lint(
1196 lint::builtin::UNCONDITIONAL_PANIC,
1198 "this operation will panic at runtime",
1203 if self.should_const_prop(value) {
1204 if let ScalarMaybeUninit::Scalar(scalar) = value_const {
1205 *cond = self.operand_from_scalar(
1207 self.tcx.types.bool,
1215 TerminatorKind::SwitchInt { ref mut discr, .. } => {
1216 // FIXME: This is currently redundant with `visit_operand`, but sadly
1217 // always visiting operands currently causes a perf regression in LLVM codegen, so
1218 // `visit_operand` currently only runs for propagates places for `mir_opt_level=3`.
1219 self.propagate_operand(discr)
1221 // None of these have Operands to const-propagate.
1222 TerminatorKind::Goto { .. }
1223 | TerminatorKind::Resume
1224 | TerminatorKind::Abort
1225 | TerminatorKind::Return
1226 | TerminatorKind::Unreachable
1227 | TerminatorKind::Drop { .. }
1228 | TerminatorKind::DropAndReplace { .. }
1229 | TerminatorKind::Yield { .. }
1230 | TerminatorKind::GeneratorDrop
1231 | TerminatorKind::FalseEdge { .. }
1232 | TerminatorKind::FalseUnwind { .. }
1233 | TerminatorKind::InlineAsm { .. } => {}
1234 // Every argument in our function calls have already been propagated in `visit_operand`.
1236 // NOTE: because LLVM codegen gives performance regressions with it, so this is gated
1237 // on `mir_opt_level=3`.
1238 TerminatorKind::Call { .. } => {}
1241 // We remove all Locals which are restricted in propagation to their containing blocks and
1242 // which were modified in the current block.
1243 // Take it out of the ecx so we can get a mutable reference to the ecx for `remove_const`.
1244 let mut locals = std::mem::take(&mut self.ecx.machine.written_only_inside_own_block_locals);
1245 for &local in locals.iter() {
1246 Self::remove_const(&mut self.ecx, local);
1249 // Put it back so we reuse the heap of the storage
1250 self.ecx.machine.written_only_inside_own_block_locals = locals;
1251 if cfg!(debug_assertions) {
1252 // Ensure we are correctly erasing locals with the non-debug-assert logic.
1253 for local in self.ecx.machine.only_propagate_inside_block_locals.iter() {
1255 self.get_const(local.into()).is_none()
1257 .layout_of(self.local_decls[local].ty)
1258 .map_or(true, |layout| layout.is_zst())