1 //! Propagates constants for early reporting of statically known
6 use rustc_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::visit::{
13 MutVisitor, MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor,
15 use rustc_middle::mir::{
16 AssertKind, BasicBlock, BinOp, Body, ClearCrossCrate, Constant, Local, LocalDecl, LocalKind,
17 Location, Operand, Place, Rvalue, SourceInfo, SourceScope, SourceScopeData, Statement,
18 StatementKind, Terminator, TerminatorKind, UnOp, RETURN_PLACE,
20 use rustc_middle::ty::layout::{HasTyCtxt, LayoutError, TyAndLayout};
21 use rustc_middle::ty::subst::{InternalSubsts, Subst};
22 use rustc_middle::ty::{
23 self, ConstInt, ConstKind, Instance, ParamEnv, ScalarInt, Ty, TyCtxt, TypeFoldable,
25 use rustc_session::lint;
26 use rustc_span::{def_id::DefId, Span};
27 use rustc_target::abi::{HasDataLayout, LayoutOf, Size, TargetDataLayout};
28 use rustc_trait_selection::traits;
30 use crate::const_eval::ConstEvalErr;
31 use crate::interpret::{
32 self, compile_time_machine, AllocId, Allocation, ConstValue, CtfeValidationMode, Frame, ImmTy,
33 Immediate, InterpCx, InterpResult, LocalState, LocalValue, MemPlace, Memory, MemoryKind, OpTy,
34 Operand as InterpOperand, PlaceTy, Pointer, Scalar, ScalarMaybeUninit, StackPopCleanup,
36 use crate::transform::MirPass;
38 /// The maximum number of bytes that we'll allocate space for a local or the return value.
39 /// Needed for #66397, because otherwise we eval into large places and that can cause OOM or just
40 /// Severely regress performance.
41 const MAX_ALLOC_LIMIT: u64 = 1024;
43 /// Macro for machine-specific `InterpError` without allocation.
44 /// (These will never be shown to the user, but they help diagnose ICEs.)
45 macro_rules! throw_machine_stop_str {
47 // We make a new local type for it. The type itself does not carry any information,
48 // but its vtable (for the `MachineStopType` trait) does.
50 // Printing this type shows the desired string.
51 impl std::fmt::Display for Zst {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56 impl rustc_middle::mir::interpret::MachineStopType for Zst {}
57 throw_machine_stop!(Zst)
63 impl<'tcx> MirPass<'tcx> for ConstProp {
64 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
65 // will be evaluated by miri and produce its errors there
66 if body.source.promoted.is_some() {
70 use rustc_middle::hir::map::blocks::FnLikeNode;
71 let def_id = body.source.def_id().expect_local();
72 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
74 let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some();
75 let is_assoc_const = tcx.def_kind(def_id.to_def_id()) == DefKind::AssocConst;
77 // Only run const prop on functions, methods, closures and associated constants
78 if !is_fn_like && !is_assoc_const {
79 // skip anon_const/statics/consts because they'll be evaluated by miri anyway
80 trace!("ConstProp skipped for {:?}", def_id);
84 let is_generator = tcx.type_of(def_id.to_def_id()).is_generator();
85 // FIXME(welseywiser) const prop doesn't work on generators because of query cycles
86 // computing their layout.
88 trace!("ConstProp skipped for generator {:?}", def_id);
92 // Check if it's even possible to satisfy the 'where' clauses
94 // This branch will never be taken for any normal function.
95 // However, it's possible to `#!feature(trivial_bounds)]` to write
96 // a function with impossible to satisfy clauses, e.g.:
97 // `fn foo() where String: Copy {}`
99 // We don't usually need to worry about this kind of case,
100 // since we would get a compilation error if the user tried
101 // to call it. However, since we can do const propagation
102 // even without any calls to the function, we need to make
103 // sure that it even makes sense to try to evaluate the body.
104 // If there are unsatisfiable where clauses, then all bets are
105 // off, and we just give up.
107 // We manually filter the predicates, skipping anything that's not
108 // "global". We are in a potentially generic context
109 // (e.g. we are evaluating a function without substituting generic
110 // parameters, so this filtering serves two purposes:
112 // 1. We skip evaluating any predicates that we would
113 // never be able prove are unsatisfiable (e.g. `<T as Foo>`
114 // 2. We avoid trying to normalize predicates involving generic
115 // parameters (e.g. `<T as Foo>::MyItem`). This can confuse
116 // the normalization code (leading to cycle errors), since
117 // it's usually never invoked in this way.
119 .predicates_of(def_id.to_def_id())
122 .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
123 if traits::impossible_predicates(
125 traits::elaborate_predicates(tcx, predicates).map(|o| o.predicate).collect(),
127 trace!("ConstProp skipped for {:?}: found unsatisfiable predicates", def_id);
131 trace!("ConstProp starting for {:?}", def_id);
133 let dummy_body = &Body::new(
135 body.basic_blocks().clone(),
136 body.source_scopes.clone(),
137 body.local_decls.clone(),
141 tcx.def_span(def_id),
145 // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
146 // constants, instead of just checking for const-folding succeeding.
147 // That would require an uniform one-def no-mutation analysis
148 // and RPO (or recursing when needing the value of a local).
149 let mut optimization_finder = ConstPropagator::new(body, dummy_body, tcx);
150 optimization_finder.visit_body(body);
152 trace!("ConstProp done for {:?}", def_id);
156 struct ConstPropMachine<'mir, 'tcx> {
157 /// The virtual call stack.
158 stack: Vec<Frame<'mir, 'tcx, (), ()>>,
159 /// `OnlyInsideOwnBlock` locals that were written in the current block get erased at the end.
160 written_only_inside_own_block_locals: FxHashSet<Local>,
161 /// Locals that need to be cleared after every block terminates.
162 only_propagate_inside_block_locals: BitSet<Local>,
163 can_const_prop: IndexVec<Local, ConstPropMode>,
166 impl<'mir, 'tcx> ConstPropMachine<'mir, 'tcx> {
168 only_propagate_inside_block_locals: BitSet<Local>,
169 can_const_prop: IndexVec<Local, ConstPropMode>,
173 written_only_inside_own_block_locals: Default::default(),
174 only_propagate_inside_block_locals,
180 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine<'mir, 'tcx> {
181 compile_time_machine!(<'mir, 'tcx>);
183 type MemoryExtra = ();
185 fn find_mir_or_eval_fn(
186 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
187 _instance: ty::Instance<'tcx>,
188 _args: &[OpTy<'tcx>],
189 _ret: Option<(PlaceTy<'tcx>, BasicBlock)>,
190 _unwind: Option<BasicBlock>,
191 ) -> InterpResult<'tcx, Option<&'mir Body<'tcx>>> {
196 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
197 _instance: ty::Instance<'tcx>,
198 _args: &[OpTy<'tcx>],
199 _ret: Option<(PlaceTy<'tcx>, BasicBlock)>,
200 _unwind: Option<BasicBlock>,
201 ) -> InterpResult<'tcx> {
202 throw_machine_stop_str!("calling intrinsics isn't supported in ConstProp")
206 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
207 _msg: &rustc_middle::mir::AssertMessage<'tcx>,
208 _unwind: Option<rustc_middle::mir::BasicBlock>,
209 ) -> InterpResult<'tcx> {
210 bug!("panics terminators are not evaluated in ConstProp")
213 fn ptr_to_int(_mem: &Memory<'mir, 'tcx, Self>, _ptr: Pointer) -> InterpResult<'tcx, u64> {
214 throw_unsup!(ReadPointerAsBytes)
218 _ecx: &InterpCx<'mir, 'tcx, Self>,
222 ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
223 // We can't do this because aliasing of memory can differ between const eval and llvm
224 throw_machine_stop_str!("pointer arithmetic or comparisons aren't supported in ConstProp")
228 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
229 _dest: PlaceTy<'tcx>,
230 ) -> InterpResult<'tcx> {
231 throw_machine_stop_str!("can't const prop heap allocations")
235 _ecx: &InterpCx<'mir, 'tcx, Self>,
236 frame: &Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>,
238 ) -> InterpResult<'tcx, InterpOperand<Self::PointerTag>> {
239 let l = &frame.locals[local];
241 if l.value == LocalValue::Uninitialized {
242 throw_machine_stop_str!("tried to access an uninitialized local")
248 fn access_local_mut<'a>(
249 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
252 ) -> InterpResult<'tcx, Result<&'a mut LocalValue<Self::PointerTag>, MemPlace<Self::PointerTag>>>
254 if ecx.machine.can_const_prop[local] == ConstPropMode::NoPropagation {
255 throw_machine_stop_str!("tried to write to a local that is marked as not propagatable")
257 if frame == 0 && ecx.machine.only_propagate_inside_block_locals.contains(local) {
259 "mutating local {:?} which is restricted to its block. \
260 Will remove it from const-prop after block is finished.",
263 ecx.machine.written_only_inside_own_block_locals.insert(local);
265 ecx.machine.stack[frame].locals[local].access_mut()
268 fn before_access_global(
271 allocation: &Allocation<Self::PointerTag, Self::AllocExtra>,
272 _static_def_id: Option<DefId>,
274 ) -> InterpResult<'tcx> {
276 throw_machine_stop_str!("can't write to global");
278 // If the static allocation is mutable, then we can't const prop it as its content
279 // might be different at runtime.
280 if allocation.mutability == Mutability::Mut {
281 throw_machine_stop_str!("can't access mutable globals in ConstProp");
289 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
290 frame: Frame<'mir, 'tcx>,
291 ) -> InterpResult<'tcx, Frame<'mir, 'tcx>> {
297 ecx: &'a InterpCx<'mir, 'tcx, Self>,
298 ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
304 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
305 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
306 &mut ecx.machine.stack
310 /// Finds optimization opportunities on the MIR.
311 struct ConstPropagator<'mir, 'tcx> {
312 ecx: InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>,
314 param_env: ParamEnv<'tcx>,
315 // FIXME(eddyb) avoid cloning these two fields more than once,
316 // by accessing them through `ecx` instead.
317 source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
318 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
319 // Because we have `MutVisitor` we can't obtain the `SourceInfo` from a `Location`. So we store
320 // the last known `SourceInfo` here and just keep revisiting it.
321 source_info: Option<SourceInfo>,
324 impl<'mir, 'tcx> LayoutOf for ConstPropagator<'mir, 'tcx> {
326 type TyAndLayout = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
328 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
329 self.tcx.layout_of(self.param_env.and(ty))
333 impl<'mir, 'tcx> HasDataLayout for ConstPropagator<'mir, 'tcx> {
335 fn data_layout(&self) -> &TargetDataLayout {
336 &self.tcx.data_layout
340 impl<'mir, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'mir, 'tcx> {
342 fn tcx(&self) -> TyCtxt<'tcx> {
347 impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
350 dummy_body: &'mir Body<'tcx>,
352 ) -> ConstPropagator<'mir, 'tcx> {
353 let def_id = body.source.def_id();
354 let substs = &InternalSubsts::identity_for_item(tcx, def_id);
355 let param_env = tcx.param_env_reveal_all_normalized(def_id);
357 let span = tcx.def_span(def_id);
358 // FIXME: `CanConstProp::check` computes the layout of all locals, return those layouts
359 // so we can write them to `ecx.frame_mut().locals.layout, reducing the duplication in
360 // `layout_of` query invocations.
361 let can_const_prop = CanConstProp::check(tcx, param_env, body);
362 let mut only_propagate_inside_block_locals = BitSet::new_empty(can_const_prop.len());
363 for (l, mode) in can_const_prop.iter_enumerated() {
364 if *mode == ConstPropMode::OnlyInsideOwnBlock {
365 only_propagate_inside_block_locals.insert(l);
368 let mut ecx = InterpCx::new(
372 ConstPropMachine::new(only_propagate_inside_block_locals, can_const_prop),
377 .layout_of(body.return_ty().subst(tcx, substs))
379 // Don't bother allocating memory for ZST types which have no values
380 // or for large values.
381 .filter(|ret_layout| {
382 !ret_layout.is_zst() && ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT)
384 .map(|ret_layout| ecx.allocate(ret_layout, MemoryKind::Stack));
386 ecx.push_stack_frame(
387 Instance::new(def_id, substs),
390 StackPopCleanup::None { cleanup: false },
392 .expect("failed to push initial stack frame");
398 // FIXME(eddyb) avoid cloning these two fields more than once,
399 // by accessing them through `ecx` instead.
400 source_scopes: body.source_scopes.clone(),
401 //FIXME(wesleywiser) we can't steal this because `Visitor::super_visit_body()` needs it
402 local_decls: body.local_decls.clone(),
407 fn get_const(&self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
408 let op = match self.ecx.eval_place_to_op(place, None) {
411 trace!("get_const failed: {}", e);
416 // Try to read the local as an immediate so that if it is representable as a scalar, we can
417 // handle it as such, but otherwise, just return the value as is.
418 Some(match self.ecx.try_read_immediate(op) {
419 Ok(Ok(imm)) => imm.into(),
424 /// Remove `local` from the pool of `Locals`. Allows writing to them,
425 /// but not reading from them anymore.
426 fn remove_const(ecx: &mut InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>, local: Local) {
427 ecx.frame_mut().locals[local] =
428 LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) };
431 fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
432 match &self.source_scopes[source_info.scope].local_data {
433 ClearCrossCrate::Set(data) => Some(data.lint_root),
434 ClearCrossCrate::Clear => None,
438 fn use_ecx<F, T>(&mut self, f: F) -> Option<T>
440 F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
443 Ok(val) => Some(val),
445 trace!("InterpCx operation failed: {:?}", error);
446 // Some errors shouldn't come up because creating them causes
447 // an allocation, which we should avoid. When that happens,
448 // dedicated error variants should be introduced instead.
450 !error.kind.allocates(),
451 "const-prop encountered allocating error: {}",
459 /// Returns the value, if any, of evaluating `c`.
460 fn eval_constant(&mut self, c: &Constant<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
461 // FIXME we need to revisit this for #67176
466 match self.ecx.const_to_op(c.literal, None) {
469 let tcx = self.ecx.tcx.at(c.span);
470 let err = ConstEvalErr::new(&self.ecx, error, Some(c.span));
471 if let Some(lint_root) = self.lint_root(source_info) {
472 let lint_only = match c.literal.val {
473 // Promoteds must lint and not error as the user didn't ask for them
474 ConstKind::Unevaluated(_, _, Some(_)) => true,
475 // Out of backwards compatibility we cannot report hard errors in unused
476 // generic functions using associated constants of the generic parameters.
477 _ => c.literal.needs_subst(),
480 // Out of backwards compatibility we cannot report hard errors in unused
481 // generic functions using associated constants of the generic parameters.
482 err.report_as_lint(tcx, "erroneous constant used", lint_root, Some(c.span));
484 err.report_as_error(tcx, "erroneous constant used");
487 err.report_as_error(tcx, "erroneous constant used");
494 /// Returns the value, if any, of evaluating `place`.
495 fn eval_place(&mut self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
496 trace!("eval_place(place={:?})", place);
497 self.use_ecx(|this| this.ecx.eval_place_to_op(place, None))
500 /// Returns the value, if any, of evaluating `op`. Calls upon `eval_constant`
501 /// or `eval_place`, depending on the variant of `Operand` used.
502 fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
504 Operand::Constant(ref c) => self.eval_constant(c, source_info),
505 Operand::Move(place) | Operand::Copy(place) => self.eval_place(place),
509 fn report_assert_as_lint(
511 lint: &'static lint::Lint,
512 source_info: SourceInfo,
513 message: &'static str,
514 panic: AssertKind<impl std::fmt::Debug>,
516 let lint_root = self.lint_root(source_info)?;
517 self.tcx.struct_span_lint_hir(lint, lint_root, source_info.span, |lint| {
518 let mut err = lint.build(message);
519 err.span_label(source_info.span, format!("{:?}", panic));
529 source_info: SourceInfo,
531 if let (val, true) = self.use_ecx(|this| {
532 let val = this.ecx.read_immediate(this.ecx.eval_operand(arg, None)?)?;
533 let (_res, overflow, _ty) = this.ecx.overflowing_unary_op(op, val)?;
536 // `AssertKind` only has an `OverflowNeg` variant, so make sure that is
537 // appropriate to use.
538 assert_eq!(op, UnOp::Neg, "Neg is the only UnOp that can overflow");
539 self.report_assert_as_lint(
540 lint::builtin::ARITHMETIC_OVERFLOW,
542 "this arithmetic operation will overflow",
543 AssertKind::OverflowNeg(val.to_const_int()),
553 left: &Operand<'tcx>,
554 right: &Operand<'tcx>,
555 source_info: SourceInfo,
557 let r = self.use_ecx(|this| this.ecx.read_immediate(this.ecx.eval_operand(right, None)?));
558 let l = self.use_ecx(|this| this.ecx.read_immediate(this.ecx.eval_operand(left, None)?));
559 // Check for exceeding shifts *even if* we cannot evaluate the LHS.
560 if op == BinOp::Shr || op == BinOp::Shl {
562 // We need the type of the LHS. We cannot use `place_layout` as that is the type
563 // of the result, which for checked binops is not the same!
564 let left_ty = left.ty(&self.local_decls, self.tcx);
565 let left_size = self.ecx.layout_of(left_ty).ok()?.size;
566 let right_size = r.layout.size;
567 let r_bits = r.to_scalar().ok();
568 // This is basically `force_bits`.
569 let r_bits = r_bits.and_then(|r| r.to_bits_or_ptr(right_size, &self.tcx).ok());
570 if r_bits.map_or(false, |b| b >= left_size.bits() as u128) {
571 debug!("check_binary_op: reporting assert for {:?}", source_info);
572 self.report_assert_as_lint(
573 lint::builtin::ARITHMETIC_OVERFLOW,
575 "this arithmetic operation will overflow",
576 AssertKind::Overflow(
579 Some(l) => l.to_const_int(),
580 // Invent a dummy value, the diagnostic ignores it anyway
581 None => ConstInt::new(
582 ScalarInt::try_from_uint(1_u8, left_size).unwrap(),
584 left_ty.is_ptr_sized_integral(),
593 if let (Some(l), Some(r)) = (l, r) {
594 // The remaining operators are handled through `overflowing_binary_op`.
595 if self.use_ecx(|this| {
596 let (_res, overflow, _ty) = this.ecx.overflowing_binary_op(op, l, r)?;
599 self.report_assert_as_lint(
600 lint::builtin::ARITHMETIC_OVERFLOW,
602 "this arithmetic operation will overflow",
603 AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
610 fn propagate_operand(&mut self, operand: &mut Operand<'tcx>) {
612 Operand::Copy(l) | Operand::Move(l) => {
613 if let Some(value) = self.get_const(l) {
614 if self.should_const_prop(value) {
615 // FIXME(felix91gr): this code only handles `Scalar` cases.
616 // For now, we're not handling `ScalarPair` cases because
617 // doing so here would require a lot of code duplication.
618 // We should hopefully generalize `Operand` handling into a fn,
619 // and use it to do const-prop here and everywhere else
620 // where it makes sense.
621 if let interpret::Operand::Immediate(interpret::Immediate::Scalar(
622 ScalarMaybeUninit::Scalar(scalar),
625 *operand = self.operand_from_scalar(
628 self.source_info.unwrap().span,
634 Operand::Constant(_) => (),
640 rvalue: &Rvalue<'tcx>,
641 source_info: SourceInfo,
644 // Perform any special handling for specific Rvalue types.
645 // Generally, checks here fall into one of two categories:
646 // 1. Additional checking to provide useful lints to the user
647 // - In this case, we will do some validation and then fall through to the
648 // end of the function which evals the assignment.
649 // 2. Working around bugs in other parts of the compiler
650 // - In this case, we'll return `None` from this function to stop evaluation.
652 // Additional checking: give lints to the user if an overflow would occur.
653 // We do this here and not in the `Assert` terminator as that terminator is
654 // only sometimes emitted (overflow checks can be disabled), but we want to always
656 Rvalue::UnaryOp(op, arg) => {
657 trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
658 self.check_unary_op(*op, arg, source_info)?;
660 Rvalue::BinaryOp(op, left, right) => {
661 trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
662 self.check_binary_op(*op, left, right, source_info)?;
664 Rvalue::CheckedBinaryOp(op, left, right) => {
666 "checking CheckedBinaryOp(op = {:?}, left = {:?}, right = {:?})",
671 self.check_binary_op(*op, left, right, source_info)?;
674 // Do not try creating references (#67862)
675 Rvalue::AddressOf(_, place) | Rvalue::Ref(_, _, place) => {
676 trace!("skipping AddressOf | Ref for {:?}", place);
678 // This may be creating mutable references or immutable references to cells.
679 // If that happens, the pointed to value could be mutated via that reference.
680 // Since we aren't tracking references, the const propagator loses track of what
681 // value the local has right now.
682 // Thus, all locals that have their reference taken
683 // must not take part in propagation.
684 Self::remove_const(&mut self.ecx, place.local);
688 Rvalue::ThreadLocalRef(def_id) => {
689 trace!("skipping ThreadLocalRef({:?})", def_id);
694 // There's no other checking to do at this time.
695 Rvalue::Aggregate(..)
700 | Rvalue::Discriminant(..)
701 | Rvalue::NullaryOp(..) => {}
704 // FIXME we need to revisit this for #67176
705 if rvalue.needs_subst() {
709 if self.tcx.sess.opts.debugging_opts.mir_opt_level >= 3 {
710 self.eval_rvalue_with_identities(rvalue, place)
712 self.use_ecx(|this| this.ecx.eval_rvalue_into_place(rvalue, place))
716 // Attempt to use albegraic identities to eliminate constant expressions
717 fn eval_rvalue_with_identities(
719 rvalue: &Rvalue<'tcx>,
722 self.use_ecx(|this| {
724 Rvalue::BinaryOp(op, left, right) | Rvalue::CheckedBinaryOp(op, left, right) => {
725 let l = this.ecx.eval_operand(left, None);
726 let r = this.ecx.eval_operand(right, None);
728 let const_arg = match (l, r) {
729 (Ok(x), Err(_)) | (Err(_), Ok(x)) => this.ecx.read_immediate(x)?,
730 (Err(e), Err(_)) => return Err(e),
732 this.ecx.eval_rvalue_into_place(rvalue, place)?;
738 this.ecx.force_bits(const_arg.to_scalar()?, const_arg.layout.size)?;
739 let dest = this.ecx.eval_place(place)?;
744 this.ecx.write_immediate(*const_arg, dest)?;
748 if arg_value == const_arg.layout.size.truncate(u128::MAX)
749 || (const_arg.layout.ty.is_bool() && arg_value == 1)
751 this.ecx.write_immediate(*const_arg, dest)?;
755 if const_arg.layout.ty.is_integral() && arg_value == 0 {
756 if let Rvalue::CheckedBinaryOp(_, _, _) = rvalue {
757 let val = Immediate::ScalarPair(
758 const_arg.to_scalar()?.into(),
759 Scalar::from_bool(false).into(),
761 this.ecx.write_immediate(val, dest)?;
763 this.ecx.write_immediate(*const_arg, dest)?;
768 this.ecx.eval_rvalue_into_place(rvalue, place)?;
773 this.ecx.eval_rvalue_into_place(rvalue, place)?;
781 /// Creates a new `Operand::Constant` from a `Scalar` value
782 fn operand_from_scalar(&self, scalar: Scalar, ty: Ty<'tcx>, span: Span) -> Operand<'tcx> {
783 Operand::Constant(Box::new(Constant {
786 literal: ty::Const::from_scalar(self.tcx, scalar, ty),
790 fn replace_with_const(
792 rval: &mut Rvalue<'tcx>,
794 source_info: SourceInfo,
796 if let Rvalue::Use(Operand::Constant(c)) = rval {
797 if !matches!(c.literal.val, ConstKind::Unevaluated(..)) {
798 trace!("skipping replace of Rvalue::Use({:?} because it is already a const", c);
803 trace!("attepting to replace {:?} with {:?}", rval, value);
804 if let Err(e) = self.ecx.const_validate_operand(
807 // FIXME: is ref tracking too expensive?
808 // FIXME: what is the point of ref tracking if we do not even check the tracked refs?
809 &mut interpret::RefTracking::empty(),
810 CtfeValidationMode::Regular,
812 trace!("validation error, attempt failed: {:?}", e);
816 // FIXME> figure out what to do when try_read_immediate fails
817 let imm = self.use_ecx(|this| this.ecx.try_read_immediate(value));
819 if let Some(Ok(imm)) = imm {
821 interpret::Immediate::Scalar(ScalarMaybeUninit::Scalar(scalar)) => {
822 *rval = Rvalue::Use(self.operand_from_scalar(
828 Immediate::ScalarPair(
829 ScalarMaybeUninit::Scalar(_),
830 ScalarMaybeUninit::Scalar(_),
832 // Found a value represented as a pair. For now only do const-prop if the type
833 // of `rvalue` is also a tuple with two scalars.
834 // FIXME: enable the general case stated above ^.
835 let ty = &value.layout.ty;
836 // Only do it for tuples
837 if let ty::Tuple(substs) = ty.kind() {
838 // Only do it if tuple is also a pair with two scalars
839 if substs.len() == 2 {
840 let alloc = self.use_ecx(|this| {
841 let ty1 = substs[0].expect_ty();
842 let ty2 = substs[1].expect_ty();
843 let ty_is_scalar = |ty| {
844 this.ecx.layout_of(ty).ok().map(|layout| layout.abi.is_scalar())
847 if ty_is_scalar(ty1) && ty_is_scalar(ty2) {
850 .intern_with_temp_alloc(value.layout, |ecx, dest| {
851 ecx.write_immediate_to_mplace(*imm, dest)
860 if let Some(Some(alloc)) = alloc {
861 // Assign entire constant in a single statement.
862 // We can't use aggregates, as we run after the aggregate-lowering `MirPhase`.
863 *rval = Rvalue::Use(Operand::Constant(Box::new(Constant {
864 span: source_info.span,
866 literal: self.ecx.tcx.mk_const(ty::Const {
868 val: ty::ConstKind::Value(ConstValue::ByRef {
878 // Scalars or scalar pairs that contain undef values are assumed to not have
879 // successfully evaluated and are thus not propagated.
885 /// Returns `true` if and only if this `op` should be const-propagated into.
886 fn should_const_prop(&mut self, op: OpTy<'tcx>) -> bool {
887 let mir_opt_level = self.tcx.sess.opts.debugging_opts.mir_opt_level;
889 if mir_opt_level == 0 {
894 interpret::Operand::Immediate(Immediate::Scalar(ScalarMaybeUninit::Scalar(s))) => {
897 interpret::Operand::Immediate(Immediate::ScalarPair(
898 ScalarMaybeUninit::Scalar(l),
899 ScalarMaybeUninit::Scalar(r),
900 )) => l.is_bits() && r.is_bits(),
906 /// The mode that `ConstProp` is allowed to run in for a given `Local`.
907 #[derive(Clone, Copy, Debug, PartialEq)]
909 /// The `Local` can be propagated into and reads of this `Local` can also be propagated.
911 /// The `Local` can only be propagated into and from its own block.
913 /// The `Local` can be propagated into but reads cannot be propagated.
915 /// The `Local` cannot be part of propagation at all. Any statement
916 /// referencing it either for reading or writing will not get propagated.
920 struct CanConstProp {
921 can_const_prop: IndexVec<Local, ConstPropMode>,
922 // False at the beginning. Once set, no more assignments are allowed to that local.
923 found_assignment: BitSet<Local>,
924 // Cache of locals' information
925 local_kinds: IndexVec<Local, LocalKind>,
929 /// Returns true if `local` can be propagated
932 param_env: ParamEnv<'tcx>,
934 ) -> IndexVec<Local, ConstPropMode> {
935 let mut cpv = CanConstProp {
936 can_const_prop: IndexVec::from_elem(ConstPropMode::FullConstProp, &body.local_decls),
937 found_assignment: BitSet::new_empty(body.local_decls.len()),
938 local_kinds: IndexVec::from_fn_n(
939 |local| body.local_kind(local),
940 body.local_decls.len(),
943 for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
944 let ty = body.local_decls[local].ty;
945 match tcx.layout_of(param_env.and(ty)) {
946 Ok(layout) if layout.size < Size::from_bytes(MAX_ALLOC_LIMIT) => {}
947 // Either the layout fails to compute, then we can't use this local anyway
948 // or the local is too large, then we don't want to.
950 *val = ConstPropMode::NoPropagation;
954 // Cannot use args at all
955 // Cannot use locals because if x < y { y - x } else { x - y } would
957 // FIXME(oli-obk): lint variables until they are used in a condition
958 // FIXME(oli-obk): lint if return value is constant
959 if cpv.local_kinds[local] == LocalKind::Arg {
960 *val = ConstPropMode::OnlyPropagateInto;
962 "local {:?} can't be const propagated because it's a function argument",
965 } else if cpv.local_kinds[local] == LocalKind::Var {
966 *val = ConstPropMode::OnlyInsideOwnBlock;
968 "local {:?} will only be propagated inside its block, because it's a user variable",
973 cpv.visit_body(&body);
978 impl<'tcx> Visitor<'tcx> for CanConstProp {
979 fn visit_local(&mut self, &local: &Local, context: PlaceContext, _: Location) {
980 use rustc_middle::mir::visit::PlaceContext::*;
982 // Projections are fine, because `&mut foo.x` will be caught by
983 // `MutatingUseContext::Borrow` elsewhere.
984 MutatingUse(MutatingUseContext::Projection)
985 // These are just stores, where the storing is not propagatable, but there may be later
986 // mutations of the same local via `Store`
987 | MutatingUse(MutatingUseContext::Call)
988 // Actual store that can possibly even propagate a value
989 | MutatingUse(MutatingUseContext::Store) => {
990 if !self.found_assignment.insert(local) {
991 match &mut self.can_const_prop[local] {
992 // If the local can only get propagated in its own block, then we don't have
993 // to worry about multiple assignments, as we'll nuke the const state at the
994 // end of the block anyway, and inside the block we overwrite previous
995 // states as applicable.
996 ConstPropMode::OnlyInsideOwnBlock => {}
997 ConstPropMode::NoPropagation => {}
998 ConstPropMode::OnlyPropagateInto => {}
999 other @ ConstPropMode::FullConstProp => {
1001 "local {:?} can't be propagated because of multiple assignments. Previous state: {:?}",
1004 *other = ConstPropMode::OnlyInsideOwnBlock;
1009 // Reading constants is allowed an arbitrary number of times
1010 NonMutatingUse(NonMutatingUseContext::Copy)
1011 | NonMutatingUse(NonMutatingUseContext::Move)
1012 | NonMutatingUse(NonMutatingUseContext::Inspect)
1013 | NonMutatingUse(NonMutatingUseContext::Projection)
1016 // These could be propagated with a smarter analysis or just some careful thinking about
1017 // whether they'd be fine right now.
1018 MutatingUse(MutatingUseContext::AsmOutput)
1019 | MutatingUse(MutatingUseContext::Yield)
1020 | MutatingUse(MutatingUseContext::Drop)
1021 | MutatingUse(MutatingUseContext::Retag)
1022 // These can't ever be propagated under any scheme, as we can't reason about indirect
1024 | NonMutatingUse(NonMutatingUseContext::SharedBorrow)
1025 | NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
1026 | NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
1027 | NonMutatingUse(NonMutatingUseContext::AddressOf)
1028 | MutatingUse(MutatingUseContext::Borrow)
1029 | MutatingUse(MutatingUseContext::AddressOf) => {
1030 trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
1031 self.can_const_prop[local] = ConstPropMode::NoPropagation;
1037 impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> {
1038 fn tcx(&self) -> TyCtxt<'tcx> {
1042 fn visit_body(&mut self, body: &mut Body<'tcx>) {
1043 for (bb, data) in body.basic_blocks_mut().iter_enumerated_mut() {
1044 self.visit_basic_block_data(bb, data);
1048 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
1049 self.super_operand(operand, location);
1051 // Only const prop copies and moves on `mir_opt_level=2` as doing so
1052 // currently slightly increases compile time in some cases.
1053 if self.tcx.sess.opts.debugging_opts.mir_opt_level >= 2 {
1054 self.propagate_operand(operand)
1058 fn visit_constant(&mut self, constant: &mut Constant<'tcx>, location: Location) {
1059 trace!("visit_constant: {:?}", constant);
1060 self.super_constant(constant, location);
1061 self.eval_constant(constant, self.source_info.unwrap());
1064 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
1065 trace!("visit_statement: {:?}", statement);
1066 let source_info = statement.source_info;
1067 self.source_info = Some(source_info);
1068 if let StatementKind::Assign(box (place, ref mut rval)) = statement.kind {
1069 let can_const_prop = self.ecx.machine.can_const_prop[place.local];
1070 if let Some(()) = self.const_prop(rval, source_info, place) {
1071 // This will return None if the above `const_prop` invocation only "wrote" a
1072 // type whose creation requires no write. E.g. a generator whose initial state
1073 // consists solely of uninitialized memory (so it doesn't capture any locals).
1074 if let Some(value) = self.get_const(place) {
1075 if self.should_const_prop(value) {
1076 trace!("replacing {:?} with {:?}", rval, value);
1077 self.replace_with_const(rval, value, source_info);
1078 if can_const_prop == ConstPropMode::FullConstProp
1079 || can_const_prop == ConstPropMode::OnlyInsideOwnBlock
1081 trace!("propagated into {:?}", place);
1085 match can_const_prop {
1086 ConstPropMode::OnlyInsideOwnBlock => {
1088 "found local restricted to its block. \
1089 Will remove it from const-prop after block is finished. Local: {:?}",
1093 ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
1094 trace!("can't propagate into {:?}", place);
1095 if place.local != RETURN_PLACE {
1096 Self::remove_const(&mut self.ecx, place.local);
1099 ConstPropMode::FullConstProp => {}
1102 // Const prop failed, so erase the destination, ensuring that whatever happens
1103 // from here on, does not know about the previous value.
1104 // This is important in case we have
1107 // x = SOME_MUTABLE_STATIC;
1108 // // x must now be uninit
1110 // FIXME: we overzealously erase the entire local, because that's easier to
1113 "propagation into {:?} failed.
1114 Nuking the entire site from orbit, it's the only way to be sure",
1117 Self::remove_const(&mut self.ecx, place.local);
1120 match statement.kind {
1121 StatementKind::SetDiscriminant { ref place, .. } => {
1122 match self.ecx.machine.can_const_prop[place.local] {
1123 ConstPropMode::FullConstProp | ConstPropMode::OnlyInsideOwnBlock => {
1124 if self.use_ecx(|this| this.ecx.statement(statement)).is_some() {
1125 trace!("propped discriminant into {:?}", place);
1127 Self::remove_const(&mut self.ecx, place.local);
1130 ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
1131 Self::remove_const(&mut self.ecx, place.local);
1135 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
1136 let frame = self.ecx.frame_mut();
1137 frame.locals[local].value =
1138 if let StatementKind::StorageLive(_) = statement.kind {
1139 LocalValue::Uninitialized
1148 self.super_statement(statement, location);
1151 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
1152 let source_info = terminator.source_info;
1153 self.source_info = Some(source_info);
1154 self.super_terminator(terminator, location);
1155 match &mut terminator.kind {
1156 TerminatorKind::Assert { expected, ref msg, ref mut cond, .. } => {
1157 if let Some(value) = self.eval_operand(&cond, source_info) {
1158 trace!("assertion on {:?} should be {:?}", value, expected);
1159 let expected = ScalarMaybeUninit::from(Scalar::from_bool(*expected));
1160 let value_const = self.ecx.read_scalar(value).unwrap();
1161 if expected != value_const {
1166 impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
1167 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1169 Self::Val(val) => val.fmt(fmt),
1170 Self::Underscore => fmt.write_str("_"),
1174 let mut eval_to_int = |op| {
1175 // This can be `None` if the lhs wasn't const propagated and we just
1176 // triggered the assert on the value of the rhs.
1177 match self.eval_operand(op, source_info) {
1179 DbgVal::Val(self.ecx.read_immediate(op).unwrap().to_const_int())
1181 None => DbgVal::Underscore,
1184 let msg = match msg {
1185 AssertKind::DivisionByZero(op) => {
1186 Some(AssertKind::DivisionByZero(eval_to_int(op)))
1188 AssertKind::RemainderByZero(op) => {
1189 Some(AssertKind::RemainderByZero(eval_to_int(op)))
1191 AssertKind::BoundsCheck { ref len, ref index } => {
1192 let len = eval_to_int(len);
1193 let index = eval_to_int(index);
1194 Some(AssertKind::BoundsCheck { len, index })
1196 // Overflow is are already covered by checks on the binary operators.
1197 AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => None,
1198 // Need proper const propagator for these.
1201 // Poison all places this operand references so that further code
1202 // doesn't use the invalid value
1204 Operand::Move(ref place) | Operand::Copy(ref place) => {
1205 Self::remove_const(&mut self.ecx, place.local);
1207 Operand::Constant(_) => {}
1209 if let Some(msg) = msg {
1210 self.report_assert_as_lint(
1211 lint::builtin::UNCONDITIONAL_PANIC,
1213 "this operation will panic at runtime",
1218 if self.should_const_prop(value) {
1219 if let ScalarMaybeUninit::Scalar(scalar) = value_const {
1220 *cond = self.operand_from_scalar(
1222 self.tcx.types.bool,
1230 TerminatorKind::SwitchInt { ref mut discr, .. } => {
1231 // FIXME: This is currently redundant with `visit_operand`, but sadly
1232 // always visiting operands currently causes a perf regression in LLVM codegen, so
1233 // `visit_operand` currently only runs for propagates places for `mir_opt_level=3`.
1234 self.propagate_operand(discr)
1236 // None of these have Operands to const-propagate.
1237 TerminatorKind::Goto { .. }
1238 | TerminatorKind::Resume
1239 | TerminatorKind::Abort
1240 | TerminatorKind::Return
1241 | TerminatorKind::Unreachable
1242 | TerminatorKind::Drop { .. }
1243 | TerminatorKind::DropAndReplace { .. }
1244 | TerminatorKind::Yield { .. }
1245 | TerminatorKind::GeneratorDrop
1246 | TerminatorKind::FalseEdge { .. }
1247 | TerminatorKind::FalseUnwind { .. }
1248 | TerminatorKind::InlineAsm { .. } => {}
1249 // Every argument in our function calls have already been propagated in `visit_operand`.
1251 // NOTE: because LLVM codegen gives slight performance regressions with it, so this is
1252 // gated on `mir_opt_level=2`.
1253 TerminatorKind::Call { .. } => {}
1256 // We remove all Locals which are restricted in propagation to their containing blocks and
1257 // which were modified in the current block.
1258 // Take it out of the ecx so we can get a mutable reference to the ecx for `remove_const`.
1259 let mut locals = std::mem::take(&mut self.ecx.machine.written_only_inside_own_block_locals);
1260 for &local in locals.iter() {
1261 Self::remove_const(&mut self.ecx, local);
1264 // Put it back so we reuse the heap of the storage
1265 self.ecx.machine.written_only_inside_own_block_locals = locals;
1266 if cfg!(debug_assertions) {
1267 // Ensure we are correctly erasing locals with the non-debug-assert logic.
1268 for local in self.ecx.machine.only_propagate_inside_block_locals.iter() {
1270 self.get_const(local.into()).is_none()
1272 .layout_of(self.local_decls[local].ty)
1273 .map_or(true, |layout| layout.is_zst())