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: &'a InterpCx<'mir, 'tcx, Self>,
287 ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
293 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
294 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
295 &mut ecx.machine.stack
299 /// Finds optimization opportunities on the MIR.
300 struct ConstPropagator<'mir, 'tcx> {
301 ecx: InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>,
303 param_env: ParamEnv<'tcx>,
304 // FIXME(eddyb) avoid cloning these two fields more than once,
305 // by accessing them through `ecx` instead.
306 source_scopes: IndexVec<SourceScope, SourceScopeData>,
307 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
308 // Because we have `MutVisitor` we can't obtain the `SourceInfo` from a `Location`. So we store
309 // the last known `SourceInfo` here and just keep revisiting it.
310 source_info: Option<SourceInfo>,
313 impl<'mir, 'tcx> LayoutOf for ConstPropagator<'mir, 'tcx> {
315 type TyAndLayout = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
317 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
318 self.tcx.layout_of(self.param_env.and(ty))
322 impl<'mir, 'tcx> HasDataLayout for ConstPropagator<'mir, 'tcx> {
324 fn data_layout(&self) -> &TargetDataLayout {
325 &self.tcx.data_layout
329 impl<'mir, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'mir, 'tcx> {
331 fn tcx(&self) -> TyCtxt<'tcx> {
336 impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
339 dummy_body: &'mir Body<'tcx>,
341 source: MirSource<'tcx>,
342 ) -> ConstPropagator<'mir, 'tcx> {
343 let def_id = source.def_id();
344 let substs = &InternalSubsts::identity_for_item(tcx, def_id);
345 let param_env = tcx.param_env_reveal_all_normalized(def_id);
347 let span = tcx.def_span(def_id);
348 // FIXME: `CanConstProp::check` computes the layout of all locals, return those layouts
349 // so we can write them to `ecx.frame_mut().locals.layout, reducing the duplication in
350 // `layout_of` query invocations.
351 let can_const_prop = CanConstProp::check(tcx, param_env, body);
352 let mut only_propagate_inside_block_locals = BitSet::new_empty(can_const_prop.len());
353 for (l, mode) in can_const_prop.iter_enumerated() {
354 if *mode == ConstPropMode::OnlyInsideOwnBlock {
355 only_propagate_inside_block_locals.insert(l);
358 let mut ecx = InterpCx::new(
362 ConstPropMachine::new(only_propagate_inside_block_locals, can_const_prop),
367 .layout_of(body.return_ty().subst(tcx, substs))
369 // Don't bother allocating memory for ZST types which have no values
370 // or for large values.
371 .filter(|ret_layout| {
372 !ret_layout.is_zst() && ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT)
374 .map(|ret_layout| ecx.allocate(ret_layout, MemoryKind::Stack));
376 ecx.push_stack_frame(
377 Instance::new(def_id, substs),
380 StackPopCleanup::None { cleanup: false },
382 .expect("failed to push initial stack frame");
388 // FIXME(eddyb) avoid cloning these two fields more than once,
389 // by accessing them through `ecx` instead.
390 source_scopes: body.source_scopes.clone(),
391 //FIXME(wesleywiser) we can't steal this because `Visitor::super_visit_body()` needs it
392 local_decls: body.local_decls.clone(),
397 fn get_const(&self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
398 let op = match self.ecx.eval_place_to_op(place, None) {
401 trace!("get_const failed: {}", e);
406 // Try to read the local as an immediate so that if it is representable as a scalar, we can
407 // handle it as such, but otherwise, just return the value as is.
408 Some(match self.ecx.try_read_immediate(op) {
409 Ok(Ok(imm)) => imm.into(),
414 /// Remove `local` from the pool of `Locals`. Allows writing to them,
415 /// but not reading from them anymore.
416 fn remove_const(ecx: &mut InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>, local: Local) {
417 ecx.frame_mut().locals[local] =
418 LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) };
421 fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
422 match &self.source_scopes[source_info.scope].local_data {
423 ClearCrossCrate::Set(data) => Some(data.lint_root),
424 ClearCrossCrate::Clear => None,
428 fn use_ecx<F, T>(&mut self, f: F) -> Option<T>
430 F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
433 Ok(val) => Some(val),
435 trace!("InterpCx operation failed: {:?}", error);
436 // Some errors shouldn't come up because creating them causes
437 // an allocation, which we should avoid. When that happens,
438 // dedicated error variants should be introduced instead.
440 !error.kind.allocates(),
441 "const-prop encountered allocating error: {}",
449 /// Returns the value, if any, of evaluating `c`.
450 fn eval_constant(&mut self, c: &Constant<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
451 // FIXME we need to revisit this for #67176
456 match self.ecx.const_to_op(c.literal, None) {
459 let tcx = self.ecx.tcx.at(c.span);
460 let err = ConstEvalErr::new(&self.ecx, error, Some(c.span));
461 if let Some(lint_root) = self.lint_root(source_info) {
462 let lint_only = match c.literal.val {
463 // Promoteds must lint and not error as the user didn't ask for them
464 ConstKind::Unevaluated(_, _, Some(_)) => true,
465 // Out of backwards compatibility we cannot report hard errors in unused
466 // generic functions using associated constants of the generic parameters.
467 _ => c.literal.needs_subst(),
470 // Out of backwards compatibility we cannot report hard errors in unused
471 // generic functions using associated constants of the generic parameters.
472 err.report_as_lint(tcx, "erroneous constant used", lint_root, Some(c.span));
474 err.report_as_error(tcx, "erroneous constant used");
477 err.report_as_error(tcx, "erroneous constant used");
484 /// Returns the value, if any, of evaluating `place`.
485 fn eval_place(&mut self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
486 trace!("eval_place(place={:?})", place);
487 self.use_ecx(|this| this.ecx.eval_place_to_op(place, None))
490 /// Returns the value, if any, of evaluating `op`. Calls upon `eval_constant`
491 /// or `eval_place`, depending on the variant of `Operand` used.
492 fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
494 Operand::Constant(ref c) => self.eval_constant(c, source_info),
495 Operand::Move(place) | Operand::Copy(place) => self.eval_place(place),
499 fn report_assert_as_lint(
501 lint: &'static lint::Lint,
502 source_info: SourceInfo,
503 message: &'static str,
504 panic: AssertKind<impl std::fmt::Debug>,
506 let lint_root = self.lint_root(source_info)?;
507 self.tcx.struct_span_lint_hir(lint, lint_root, source_info.span, |lint| {
508 let mut err = lint.build(message);
509 err.span_label(source_info.span, format!("{:?}", panic));
519 source_info: SourceInfo,
521 if let (val, true) = self.use_ecx(|this| {
522 let val = this.ecx.read_immediate(this.ecx.eval_operand(arg, None)?)?;
523 let (_res, overflow, _ty) = this.ecx.overflowing_unary_op(op, val)?;
526 // `AssertKind` only has an `OverflowNeg` variant, so make sure that is
527 // appropriate to use.
528 assert_eq!(op, UnOp::Neg, "Neg is the only UnOp that can overflow");
529 self.report_assert_as_lint(
530 lint::builtin::ARITHMETIC_OVERFLOW,
532 "this arithmetic operation will overflow",
533 AssertKind::OverflowNeg(val.to_const_int()),
543 left: &Operand<'tcx>,
544 right: &Operand<'tcx>,
545 source_info: SourceInfo,
547 let r = self.use_ecx(|this| this.ecx.read_immediate(this.ecx.eval_operand(right, None)?));
548 let l = self.use_ecx(|this| this.ecx.read_immediate(this.ecx.eval_operand(left, None)?));
549 // Check for exceeding shifts *even if* we cannot evaluate the LHS.
550 if op == BinOp::Shr || op == BinOp::Shl {
552 // We need the type of the LHS. We cannot use `place_layout` as that is the type
553 // of the result, which for checked binops is not the same!
554 let left_ty = left.ty(&self.local_decls, self.tcx);
555 let left_size = self.ecx.layout_of(left_ty).ok()?.size;
556 let right_size = r.layout.size;
557 let r_bits = r.to_scalar().ok();
558 // This is basically `force_bits`.
559 let r_bits = r_bits.and_then(|r| r.to_bits_or_ptr(right_size, &self.tcx).ok());
560 if r_bits.map_or(false, |b| b >= left_size.bits() as u128) {
561 debug!("check_binary_op: reporting assert for {:?}", source_info);
562 self.report_assert_as_lint(
563 lint::builtin::ARITHMETIC_OVERFLOW,
565 "this arithmetic operation will overflow",
566 AssertKind::Overflow(
569 Some(l) => l.to_const_int(),
570 // Invent a dummy value, the diagnostic ignores it anyway
571 None => ConstInt::new(
575 left_ty.is_ptr_sized_integral(),
584 if let (Some(l), Some(r)) = (l, r) {
585 // The remaining operators are handled through `overflowing_binary_op`.
586 if self.use_ecx(|this| {
587 let (_res, overflow, _ty) = this.ecx.overflowing_binary_op(op, l, r)?;
590 self.report_assert_as_lint(
591 lint::builtin::ARITHMETIC_OVERFLOW,
593 "this arithmetic operation will overflow",
594 AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
601 fn propagate_operand(&mut self, operand: &mut Operand<'tcx>) {
603 Operand::Copy(l) | Operand::Move(l) => {
604 if let Some(value) = self.get_const(l) {
605 if self.should_const_prop(value) {
606 // FIXME(felix91gr): this code only handles `Scalar` cases.
607 // For now, we're not handling `ScalarPair` cases because
608 // doing so here would require a lot of code duplication.
609 // We should hopefully generalize `Operand` handling into a fn,
610 // and use it to do const-prop here and everywhere else
611 // where it makes sense.
612 if let interpret::Operand::Immediate(interpret::Immediate::Scalar(
613 ScalarMaybeUninit::Scalar(scalar),
616 *operand = self.operand_from_scalar(
619 self.source_info.unwrap().span,
625 Operand::Constant(_) => (),
631 rvalue: &Rvalue<'tcx>,
632 source_info: SourceInfo,
635 // Perform any special handling for specific Rvalue types.
636 // Generally, checks here fall into one of two categories:
637 // 1. Additional checking to provide useful lints to the user
638 // - In this case, we will do some validation and then fall through to the
639 // end of the function which evals the assignment.
640 // 2. Working around bugs in other parts of the compiler
641 // - In this case, we'll return `None` from this function to stop evaluation.
643 // Additional checking: give lints to the user if an overflow would occur.
644 // We do this here and not in the `Assert` terminator as that terminator is
645 // only sometimes emitted (overflow checks can be disabled), but we want to always
647 Rvalue::UnaryOp(op, arg) => {
648 trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
649 self.check_unary_op(*op, arg, source_info)?;
651 Rvalue::BinaryOp(op, left, right) => {
652 trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
653 self.check_binary_op(*op, left, right, source_info)?;
655 Rvalue::CheckedBinaryOp(op, left, right) => {
657 "checking CheckedBinaryOp(op = {:?}, left = {:?}, right = {:?})",
662 self.check_binary_op(*op, left, right, source_info)?;
665 // Do not try creating references (#67862)
666 Rvalue::AddressOf(_, place) | Rvalue::Ref(_, _, place) => {
667 trace!("skipping AddressOf | Ref for {:?}", place);
669 // This may be creating mutable references or immutable references to cells.
670 // If that happens, the pointed to value could be mutated via that reference.
671 // Since we aren't tracking references, the const propagator loses track of what
672 // value the local has right now.
673 // Thus, all locals that have their reference taken
674 // must not take part in propagation.
675 Self::remove_const(&mut self.ecx, place.local);
679 Rvalue::ThreadLocalRef(def_id) => {
680 trace!("skipping ThreadLocalRef({:?})", def_id);
685 // There's no other checking to do at this time.
686 Rvalue::Aggregate(..)
691 | Rvalue::Discriminant(..)
692 | Rvalue::NullaryOp(..) => {}
695 // FIXME we need to revisit this for #67176
696 if rvalue.needs_subst() {
700 if self.tcx.sess.opts.debugging_opts.mir_opt_level >= 3 {
701 self.eval_rvalue_with_identities(rvalue, place)
703 self.use_ecx(|this| this.ecx.eval_rvalue_into_place(rvalue, place))
707 // Attempt to use albegraic identities to eliminate constant expressions
708 fn eval_rvalue_with_identities(
710 rvalue: &Rvalue<'tcx>,
713 self.use_ecx(|this| {
715 Rvalue::BinaryOp(op, left, right) | Rvalue::CheckedBinaryOp(op, left, right) => {
716 let l = this.ecx.eval_operand(left, None);
717 let r = this.ecx.eval_operand(right, None);
719 let const_arg = match (l, r) {
720 (Ok(x), Err(_)) | (Err(_), Ok(x)) => this.ecx.read_immediate(x)?,
721 (Err(e), Err(_)) => return Err(e),
723 this.ecx.eval_rvalue_into_place(rvalue, place)?;
729 this.ecx.force_bits(const_arg.to_scalar()?, const_arg.layout.size)?;
730 let dest = this.ecx.eval_place(place)?;
735 this.ecx.write_immediate(*const_arg, dest)?;
739 if arg_value == truncate(u128::MAX, const_arg.layout.size)
740 || (const_arg.layout.ty.is_bool() && arg_value == 1)
742 this.ecx.write_immediate(*const_arg, dest)?;
746 if const_arg.layout.ty.is_integral() && arg_value == 0 {
747 if let Rvalue::CheckedBinaryOp(_, _, _) = rvalue {
748 let val = Immediate::ScalarPair(
749 const_arg.to_scalar()?.into(),
750 Scalar::from_bool(false).into(),
752 this.ecx.write_immediate(val, dest)?;
754 this.ecx.write_immediate(*const_arg, dest)?;
759 this.ecx.eval_rvalue_into_place(rvalue, place)?;
764 this.ecx.eval_rvalue_into_place(rvalue, place)?;
772 /// Creates a new `Operand::Constant` from a `Scalar` value
773 fn operand_from_scalar(&self, scalar: Scalar, ty: Ty<'tcx>, span: Span) -> Operand<'tcx> {
774 Operand::Constant(Box::new(Constant {
777 literal: ty::Const::from_scalar(self.tcx, scalar, ty),
781 fn replace_with_const(
783 rval: &mut Rvalue<'tcx>,
785 source_info: SourceInfo,
787 if let Rvalue::Use(Operand::Constant(c)) = rval {
788 if !matches!(c.literal.val, ConstKind::Unevaluated(..)) {
789 trace!("skipping replace of Rvalue::Use({:?} because it is already a const", c);
794 trace!("attepting to replace {:?} with {:?}", rval, value);
795 if let Err(e) = self.ecx.const_validate_operand(
798 // FIXME: is ref tracking too expensive?
799 &mut interpret::RefTracking::empty(),
800 /*may_ref_to_static*/ true,
802 trace!("validation error, attempt failed: {:?}", e);
806 // FIXME> figure out what to do when try_read_immediate fails
807 let imm = self.use_ecx(|this| this.ecx.try_read_immediate(value));
809 if let Some(Ok(imm)) = imm {
811 interpret::Immediate::Scalar(ScalarMaybeUninit::Scalar(scalar)) => {
812 *rval = Rvalue::Use(self.operand_from_scalar(
818 Immediate::ScalarPair(
819 ScalarMaybeUninit::Scalar(one),
820 ScalarMaybeUninit::Scalar(two),
822 // Found a value represented as a pair. For now only do cont-prop if type of
823 // Rvalue is also a pair with two scalars. The more general case is more
824 // complicated to implement so we'll do it later.
825 // FIXME: implement the general case stated above ^.
826 let ty = &value.layout.ty.kind;
827 // Only do it for tuples
828 if let ty::Tuple(substs) = ty {
829 // Only do it if tuple is also a pair with two scalars
830 if substs.len() == 2 {
831 let opt_ty1_ty2 = self.use_ecx(|this| {
832 let ty1 = substs[0].expect_ty();
833 let ty2 = substs[1].expect_ty();
834 let ty_is_scalar = |ty| {
835 this.ecx.layout_of(ty).ok().map(|layout| layout.abi.is_scalar())
838 if ty_is_scalar(ty1) && ty_is_scalar(ty2) {
845 if let Some(Some((ty1, ty2))) = opt_ty1_ty2 {
846 *rval = Rvalue::Aggregate(
847 Box::new(AggregateKind::Tuple),
849 self.operand_from_scalar(one, ty1, source_info.span),
850 self.operand_from_scalar(two, ty2, source_info.span),
862 /// Returns `true` if and only if this `op` should be const-propagated into.
863 fn should_const_prop(&mut self, op: OpTy<'tcx>) -> bool {
864 let mir_opt_level = self.tcx.sess.opts.debugging_opts.mir_opt_level;
866 if mir_opt_level == 0 {
871 interpret::Operand::Immediate(Immediate::Scalar(ScalarMaybeUninit::Scalar(s))) => {
874 interpret::Operand::Immediate(Immediate::ScalarPair(
875 ScalarMaybeUninit::Scalar(l),
876 ScalarMaybeUninit::Scalar(r),
877 )) => l.is_bits() && r.is_bits(),
883 /// The mode that `ConstProp` is allowed to run in for a given `Local`.
884 #[derive(Clone, Copy, Debug, PartialEq)]
886 /// The `Local` can be propagated into and reads of this `Local` can also be propagated.
888 /// The `Local` can only be propagated into and from its own block.
890 /// The `Local` can be propagated into but reads cannot be propagated.
892 /// The `Local` cannot be part of propagation at all. Any statement
893 /// referencing it either for reading or writing will not get propagated.
897 struct CanConstProp {
898 can_const_prop: IndexVec<Local, ConstPropMode>,
899 // False at the beginning. Once set, no more assignments are allowed to that local.
900 found_assignment: BitSet<Local>,
901 // Cache of locals' information
902 local_kinds: IndexVec<Local, LocalKind>,
906 /// Returns true if `local` can be propagated
909 param_env: ParamEnv<'tcx>,
911 ) -> IndexVec<Local, ConstPropMode> {
912 let mut cpv = CanConstProp {
913 can_const_prop: IndexVec::from_elem(ConstPropMode::FullConstProp, &body.local_decls),
914 found_assignment: BitSet::new_empty(body.local_decls.len()),
915 local_kinds: IndexVec::from_fn_n(
916 |local| body.local_kind(local),
917 body.local_decls.len(),
920 for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
921 let ty = body.local_decls[local].ty;
922 match tcx.layout_of(param_env.and(ty)) {
923 Ok(layout) if layout.size < Size::from_bytes(MAX_ALLOC_LIMIT) => {}
924 // Either the layout fails to compute, then we can't use this local anyway
925 // or the local is too large, then we don't want to.
927 *val = ConstPropMode::NoPropagation;
931 // Cannot use args at all
932 // Cannot use locals because if x < y { y - x } else { x - y } would
934 // FIXME(oli-obk): lint variables until they are used in a condition
935 // FIXME(oli-obk): lint if return value is constant
936 if cpv.local_kinds[local] == LocalKind::Arg {
937 *val = ConstPropMode::OnlyPropagateInto;
939 "local {:?} can't be const propagated because it's a function argument",
942 } else if cpv.local_kinds[local] == LocalKind::Var {
943 *val = ConstPropMode::OnlyInsideOwnBlock;
945 "local {:?} will only be propagated inside its block, because it's a user variable",
950 cpv.visit_body(&body);
955 impl<'tcx> Visitor<'tcx> for CanConstProp {
956 fn visit_local(&mut self, &local: &Local, context: PlaceContext, _: Location) {
957 use rustc_middle::mir::visit::PlaceContext::*;
959 // Projections are fine, because `&mut foo.x` will be caught by
960 // `MutatingUseContext::Borrow` elsewhere.
961 MutatingUse(MutatingUseContext::Projection)
962 // These are just stores, where the storing is not propagatable, but there may be later
963 // mutations of the same local via `Store`
964 | MutatingUse(MutatingUseContext::Call)
965 // Actual store that can possibly even propagate a value
966 | MutatingUse(MutatingUseContext::Store) => {
967 if !self.found_assignment.insert(local) {
968 match &mut self.can_const_prop[local] {
969 // If the local can only get propagated in its own block, then we don't have
970 // to worry about multiple assignments, as we'll nuke the const state at the
971 // end of the block anyway, and inside the block we overwrite previous
972 // states as applicable.
973 ConstPropMode::OnlyInsideOwnBlock => {}
974 ConstPropMode::NoPropagation => {}
975 ConstPropMode::OnlyPropagateInto => {}
976 other @ ConstPropMode::FullConstProp => {
978 "local {:?} can't be propagated because of multiple assignments. Previous state: {:?}",
981 *other = ConstPropMode::OnlyInsideOwnBlock;
986 // Reading constants is allowed an arbitrary number of times
987 NonMutatingUse(NonMutatingUseContext::Copy)
988 | NonMutatingUse(NonMutatingUseContext::Move)
989 | NonMutatingUse(NonMutatingUseContext::Inspect)
990 | NonMutatingUse(NonMutatingUseContext::Projection)
993 // These could be propagated with a smarter analysis or just some careful thinking about
994 // whether they'd be fine right now.
995 MutatingUse(MutatingUseContext::AsmOutput)
996 | MutatingUse(MutatingUseContext::Yield)
997 | MutatingUse(MutatingUseContext::Drop)
998 | MutatingUse(MutatingUseContext::Retag)
999 // These can't ever be propagated under any scheme, as we can't reason about indirect
1001 | NonMutatingUse(NonMutatingUseContext::SharedBorrow)
1002 | NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
1003 | NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
1004 | NonMutatingUse(NonMutatingUseContext::AddressOf)
1005 | MutatingUse(MutatingUseContext::Borrow)
1006 | MutatingUse(MutatingUseContext::AddressOf) => {
1007 trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
1008 self.can_const_prop[local] = ConstPropMode::NoPropagation;
1014 impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> {
1015 fn tcx(&self) -> TyCtxt<'tcx> {
1019 fn visit_body(&mut self, body: &mut Body<'tcx>) {
1020 for (bb, data) in body.basic_blocks_mut().iter_enumerated_mut() {
1021 self.visit_basic_block_data(bb, data);
1025 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
1026 self.super_operand(operand, location);
1028 // Only const prop copies and moves on `mir_opt_level=3` as doing so
1029 // currently increases compile time.
1030 if self.tcx.sess.opts.debugging_opts.mir_opt_level >= 3 {
1031 self.propagate_operand(operand)
1035 fn visit_constant(&mut self, constant: &mut Constant<'tcx>, location: Location) {
1036 trace!("visit_constant: {:?}", constant);
1037 self.super_constant(constant, location);
1038 self.eval_constant(constant, self.source_info.unwrap());
1041 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
1042 trace!("visit_statement: {:?}", statement);
1043 let source_info = statement.source_info;
1044 self.source_info = Some(source_info);
1045 if let StatementKind::Assign(box (place, ref mut rval)) = statement.kind {
1046 let can_const_prop = self.ecx.machine.can_const_prop[place.local];
1047 if let Some(()) = self.const_prop(rval, source_info, place) {
1048 // This will return None if the above `const_prop` invocation only "wrote" a
1049 // type whose creation requires no write. E.g. a generator whose initial state
1050 // consists solely of uninitialized memory (so it doesn't capture any locals).
1051 if let Some(value) = self.get_const(place) {
1052 if self.should_const_prop(value) {
1053 trace!("replacing {:?} with {:?}", rval, value);
1054 self.replace_with_const(rval, value, source_info);
1055 if can_const_prop == ConstPropMode::FullConstProp
1056 || can_const_prop == ConstPropMode::OnlyInsideOwnBlock
1058 trace!("propagated into {:?}", place);
1062 match can_const_prop {
1063 ConstPropMode::OnlyInsideOwnBlock => {
1065 "found local restricted to its block. \
1066 Will remove it from const-prop after block is finished. Local: {:?}",
1070 ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
1071 trace!("can't propagate into {:?}", place);
1072 if place.local != RETURN_PLACE {
1073 Self::remove_const(&mut self.ecx, place.local);
1076 ConstPropMode::FullConstProp => {}
1079 // Const prop failed, so erase the destination, ensuring that whatever happens
1080 // from here on, does not know about the previous value.
1081 // This is important in case we have
1084 // x = SOME_MUTABLE_STATIC;
1085 // // x must now be uninit
1087 // FIXME: we overzealously erase the entire local, because that's easier to
1090 "propagation into {:?} failed.
1091 Nuking the entire site from orbit, it's the only way to be sure",
1094 Self::remove_const(&mut self.ecx, place.local);
1097 match statement.kind {
1098 StatementKind::SetDiscriminant { ref place, .. } => {
1099 match self.ecx.machine.can_const_prop[place.local] {
1100 ConstPropMode::FullConstProp | ConstPropMode::OnlyInsideOwnBlock => {
1101 if self.use_ecx(|this| this.ecx.statement(statement)).is_some() {
1102 trace!("propped discriminant into {:?}", place);
1104 Self::remove_const(&mut self.ecx, place.local);
1107 ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
1108 Self::remove_const(&mut self.ecx, place.local);
1112 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
1113 let frame = self.ecx.frame_mut();
1114 frame.locals[local].value =
1115 if let StatementKind::StorageLive(_) = statement.kind {
1116 LocalValue::Uninitialized
1125 self.super_statement(statement, location);
1128 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
1129 let source_info = terminator.source_info;
1130 self.source_info = Some(source_info);
1131 self.super_terminator(terminator, location);
1132 match &mut terminator.kind {
1133 TerminatorKind::Assert { expected, ref msg, ref mut cond, .. } => {
1134 if let Some(value) = self.eval_operand(&cond, source_info) {
1135 trace!("assertion on {:?} should be {:?}", value, expected);
1136 let expected = ScalarMaybeUninit::from(Scalar::from_bool(*expected));
1137 let value_const = self.ecx.read_scalar(value).unwrap();
1138 if expected != value_const {
1143 impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
1144 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1146 Self::Val(val) => val.fmt(fmt),
1147 Self::Underscore => fmt.write_str("_"),
1151 let mut eval_to_int = |op| {
1152 // This can be `None` if the lhs wasn't const propagated and we just
1153 // triggered the assert on the value of the rhs.
1154 match self.eval_operand(op, source_info) {
1156 DbgVal::Val(self.ecx.read_immediate(op).unwrap().to_const_int())
1158 None => DbgVal::Underscore,
1161 let msg = match msg {
1162 AssertKind::DivisionByZero(op) => {
1163 Some(AssertKind::DivisionByZero(eval_to_int(op)))
1165 AssertKind::RemainderByZero(op) => {
1166 Some(AssertKind::RemainderByZero(eval_to_int(op)))
1168 AssertKind::BoundsCheck { ref len, ref index } => {
1169 let len = eval_to_int(len);
1170 let index = eval_to_int(index);
1171 Some(AssertKind::BoundsCheck { len, index })
1173 // Overflow is are already covered by checks on the binary operators.
1174 AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => None,
1175 // Need proper const propagator for these.
1178 // Poison all places this operand references so that further code
1179 // doesn't use the invalid value
1181 Operand::Move(ref place) | Operand::Copy(ref place) => {
1182 Self::remove_const(&mut self.ecx, place.local);
1184 Operand::Constant(_) => {}
1186 if let Some(msg) = msg {
1187 self.report_assert_as_lint(
1188 lint::builtin::UNCONDITIONAL_PANIC,
1190 "this operation will panic at runtime",
1195 if self.should_const_prop(value) {
1196 if let ScalarMaybeUninit::Scalar(scalar) = value_const {
1197 *cond = self.operand_from_scalar(
1199 self.tcx.types.bool,
1207 TerminatorKind::SwitchInt { ref mut discr, .. } => {
1208 // FIXME: This is currently redundant with `visit_operand`, but sadly
1209 // always visiting operands currently causes a perf regression in LLVM codegen, so
1210 // `visit_operand` currently only runs for propagates places for `mir_opt_level=3`.
1211 self.propagate_operand(discr)
1213 // None of these have Operands to const-propagate.
1214 TerminatorKind::Goto { .. }
1215 | TerminatorKind::Resume
1216 | TerminatorKind::Abort
1217 | TerminatorKind::Return
1218 | TerminatorKind::Unreachable
1219 | TerminatorKind::Drop { .. }
1220 | TerminatorKind::DropAndReplace { .. }
1221 | TerminatorKind::Yield { .. }
1222 | TerminatorKind::GeneratorDrop
1223 | TerminatorKind::FalseEdge { .. }
1224 | TerminatorKind::FalseUnwind { .. }
1225 | TerminatorKind::InlineAsm { .. } => {}
1226 // Every argument in our function calls have already been propagated in `visit_operand`.
1228 // NOTE: because LLVM codegen gives performance regressions with it, so this is gated
1229 // on `mir_opt_level=3`.
1230 TerminatorKind::Call { .. } => {}
1233 // We remove all Locals which are restricted in propagation to their containing blocks and
1234 // which were modified in the current block.
1235 // Take it out of the ecx so we can get a mutable reference to the ecx for `remove_const`.
1236 let mut locals = std::mem::take(&mut self.ecx.machine.written_only_inside_own_block_locals);
1237 for &local in locals.iter() {
1238 Self::remove_const(&mut self.ecx, local);
1241 // Put it back so we reuse the heap of the storage
1242 self.ecx.machine.written_only_inside_own_block_locals = locals;
1243 if cfg!(debug_assertions) {
1244 // Ensure we are correctly erasing locals with the non-debug-assert logic.
1245 for local in self.ecx.machine.only_propagate_inside_block_locals.iter() {
1247 self.get_const(local.into()).is_none()
1249 .layout_of(self.local_decls[local].ty)
1250 .map_or(true, |layout| layout.is_zst())