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::error_to_const_error;
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 return value.
38 const MAX_ALLOC_LIMIT: u64 = 1024;
40 /// Macro for machine-specific `InterpError` without allocation.
41 /// (These will never be shown to the user, but they help diagnose ICEs.)
42 macro_rules! throw_machine_stop_str {
44 // We make a new local type for it. The type itself does not carry any information,
45 // but its vtable (for the `MachineStopType` trait) does.
47 // Printing this type shows the desired string.
48 impl std::fmt::Display for Zst {
49 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 impl rustc_middle::mir::interpret::MachineStopType for Zst {}
54 throw_machine_stop!(Zst)
60 impl<'tcx> MirPass<'tcx> for ConstProp {
61 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>) {
62 // will be evaluated by miri and produce its errors there
63 if source.promoted.is_some() {
67 use rustc_middle::hir::map::blocks::FnLikeNode;
68 let hir_id = tcx.hir().as_local_hir_id(source.def_id().expect_local());
70 let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some();
71 let is_assoc_const = tcx.def_kind(source.def_id()) == DefKind::AssocConst;
73 // Only run const prop on functions, methods, closures and associated constants
74 if !is_fn_like && !is_assoc_const {
75 // skip anon_const/statics/consts because they'll be evaluated by miri anyway
76 trace!("ConstProp skipped for {:?}", source.def_id());
80 let is_generator = tcx.type_of(source.def_id()).is_generator();
81 // FIXME(welseywiser) const prop doesn't work on generators because of query cycles
82 // computing their layout.
84 trace!("ConstProp skipped for generator {:?}", source.def_id());
88 // Check if it's even possible to satisfy the 'where' clauses
90 // This branch will never be taken for any normal function.
91 // However, it's possible to `#!feature(trivial_bounds)]` to write
92 // a function with impossible to satisfy clauses, e.g.:
93 // `fn foo() where String: Copy {}`
95 // We don't usually need to worry about this kind of case,
96 // since we would get a compilation error if the user tried
97 // to call it. However, since we can do const propagation
98 // even without any calls to the function, we need to make
99 // sure that it even makes sense to try to evaluate the body.
100 // If there are unsatisfiable where clauses, then all bets are
101 // off, and we just give up.
103 // We manually filter the predicates, skipping anything that's not
104 // "global". We are in a potentially generic context
105 // (e.g. we are evaluating a function without substituting generic
106 // parameters, so this filtering serves two purposes:
108 // 1. We skip evaluating any predicates that we would
109 // never be able prove are unsatisfiable (e.g. `<T as Foo>`
110 // 2. We avoid trying to normalize predicates involving generic
111 // parameters (e.g. `<T as Foo>::MyItem`). This can confuse
112 // the normalization code (leading to cycle errors), since
113 // it's usually never invoked in this way.
115 .predicates_of(source.def_id())
118 .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
119 if traits::impossible_predicates(
121 traits::elaborate_predicates(tcx, predicates).map(|o| o.predicate).collect(),
123 trace!("ConstProp skipped for {:?}: found unsatisfiable predicates", source.def_id());
127 trace!("ConstProp starting for {:?}", source.def_id());
129 let dummy_body = &Body::new(
130 body.basic_blocks().clone(),
131 body.source_scopes.clone(),
132 body.local_decls.clone(),
136 tcx.def_span(source.def_id()),
140 // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
141 // constants, instead of just checking for const-folding succeeding.
142 // That would require an uniform one-def no-mutation analysis
143 // and RPO (or recursing when needing the value of a local).
144 let mut optimization_finder = ConstPropagator::new(body, dummy_body, tcx, source);
145 optimization_finder.visit_body(body);
147 trace!("ConstProp done for {:?}", source.def_id());
151 struct ConstPropMachine<'mir, 'tcx> {
152 /// The virtual call stack.
153 stack: Vec<Frame<'mir, 'tcx, (), ()>>,
154 /// `OnlyInsideOwnBlock` locals that were written in the current block get erased at the end.
155 written_only_inside_own_block_locals: FxHashSet<Local>,
156 /// Locals that need to be cleared after every block terminates.
157 only_propagate_inside_block_locals: BitSet<Local>,
160 impl<'mir, 'tcx> ConstPropMachine<'mir, 'tcx> {
161 fn new(only_propagate_inside_block_locals: BitSet<Local>) -> Self {
164 written_only_inside_own_block_locals: Default::default(),
165 only_propagate_inside_block_locals,
170 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine<'mir, 'tcx> {
171 compile_time_machine!(<'mir, 'tcx>);
173 type MemoryExtra = ();
175 fn find_mir_or_eval_fn(
176 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
177 _instance: ty::Instance<'tcx>,
178 _args: &[OpTy<'tcx>],
179 _ret: Option<(PlaceTy<'tcx>, BasicBlock)>,
180 _unwind: Option<BasicBlock>,
181 ) -> InterpResult<'tcx, Option<&'mir Body<'tcx>>> {
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> {
192 throw_machine_stop_str!("calling intrinsics isn't supported in ConstProp")
196 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
197 _msg: &rustc_middle::mir::AssertMessage<'tcx>,
198 _unwind: Option<rustc_middle::mir::BasicBlock>,
199 ) -> InterpResult<'tcx> {
200 bug!("panics terminators are not evaluated in ConstProp")
203 fn ptr_to_int(_mem: &Memory<'mir, 'tcx, Self>, _ptr: Pointer) -> InterpResult<'tcx, u64> {
204 throw_unsup!(ReadPointerAsBytes)
208 _ecx: &InterpCx<'mir, 'tcx, Self>,
212 ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
213 // We can't do this because aliasing of memory can differ between const eval and llvm
214 throw_machine_stop_str!("pointer arithmetic or comparisons aren't supported in ConstProp")
218 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
219 _dest: PlaceTy<'tcx>,
220 ) -> InterpResult<'tcx> {
221 throw_machine_stop_str!("can't const prop heap allocations")
225 _ecx: &InterpCx<'mir, 'tcx, Self>,
226 frame: &Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>,
228 ) -> InterpResult<'tcx, InterpOperand<Self::PointerTag>> {
229 let l = &frame.locals[local];
231 if l.value == LocalValue::Uninitialized {
232 throw_machine_stop_str!("tried to access an uninitialized local")
238 fn access_local_mut<'a>(
239 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
242 ) -> InterpResult<'tcx, Result<&'a mut LocalValue<Self::PointerTag>, MemPlace<Self::PointerTag>>>
244 if frame == 0 && ecx.machine.only_propagate_inside_block_locals.contains(local) {
245 ecx.machine.written_only_inside_own_block_locals.insert(local);
247 ecx.machine.stack[frame].locals[local].access_mut()
250 fn before_access_global(
253 allocation: &Allocation<Self::PointerTag, Self::AllocExtra>,
254 _static_def_id: Option<DefId>,
256 ) -> InterpResult<'tcx> {
258 throw_machine_stop_str!("can't write to global");
260 // If the static allocation is mutable, then we can't const prop it as its content
261 // might be different at runtime.
262 if allocation.mutability == Mutability::Mut {
263 throw_machine_stop_str!("can't access mutable globals in ConstProp");
271 ecx: &'a InterpCx<'mir, 'tcx, Self>,
272 ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
278 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
279 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
280 &mut ecx.machine.stack
284 /// Finds optimization opportunities on the MIR.
285 struct ConstPropagator<'mir, 'tcx> {
286 ecx: InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>,
288 can_const_prop: IndexVec<Local, ConstPropMode>,
289 param_env: ParamEnv<'tcx>,
290 // FIXME(eddyb) avoid cloning these two fields more than once,
291 // by accessing them through `ecx` instead.
292 source_scopes: IndexVec<SourceScope, SourceScopeData>,
293 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
294 // Because we have `MutVisitor` we can't obtain the `SourceInfo` from a `Location`. So we store
295 // the last known `SourceInfo` here and just keep revisiting it.
296 source_info: Option<SourceInfo>,
299 impl<'mir, 'tcx> LayoutOf for ConstPropagator<'mir, 'tcx> {
301 type TyAndLayout = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
303 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
304 self.tcx.layout_of(self.param_env.and(ty))
308 impl<'mir, 'tcx> HasDataLayout for ConstPropagator<'mir, 'tcx> {
310 fn data_layout(&self) -> &TargetDataLayout {
311 &self.tcx.data_layout
315 impl<'mir, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'mir, 'tcx> {
317 fn tcx(&self) -> TyCtxt<'tcx> {
322 impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
325 dummy_body: &'mir Body<'tcx>,
327 source: MirSource<'tcx>,
328 ) -> ConstPropagator<'mir, 'tcx> {
329 let def_id = source.def_id();
330 let substs = &InternalSubsts::identity_for_item(tcx, def_id);
331 let param_env = tcx.param_env_reveal_all_normalized(def_id);
333 let span = tcx.def_span(def_id);
334 let can_const_prop = CanConstProp::check(body);
335 let mut only_propagate_inside_block_locals = BitSet::new_empty(can_const_prop.len());
336 for (l, mode) in can_const_prop.iter_enumerated() {
337 if *mode == ConstPropMode::OnlyInsideOwnBlock {
338 only_propagate_inside_block_locals.insert(l);
341 let mut ecx = InterpCx::new(
345 ConstPropMachine::new(only_propagate_inside_block_locals),
350 .layout_of(body.return_ty().subst(tcx, substs))
352 // Don't bother allocating memory for ZST types which have no values
353 // or for large values.
354 .filter(|ret_layout| {
355 !ret_layout.is_zst() && ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT)
357 .map(|ret_layout| ecx.allocate(ret_layout, MemoryKind::Stack));
359 ecx.push_stack_frame(
360 Instance::new(def_id, substs),
363 StackPopCleanup::None { cleanup: false },
365 .expect("failed to push initial stack frame");
372 // FIXME(eddyb) avoid cloning these two fields more than once,
373 // by accessing them through `ecx` instead.
374 source_scopes: body.source_scopes.clone(),
375 //FIXME(wesleywiser) we can't steal this because `Visitor::super_visit_body()` needs it
376 local_decls: body.local_decls.clone(),
381 fn get_const(&self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
382 let op = match self.ecx.eval_place_to_op(place, None) {
385 trace!("get_const failed: {}", e);
390 // Try to read the local as an immediate so that if it is representable as a scalar, we can
391 // handle it as such, but otherwise, just return the value as is.
392 Some(match self.ecx.try_read_immediate(op) {
393 Ok(Ok(imm)) => imm.into(),
398 /// Remove `local` from the pool of `Locals`. Allows writing to them,
399 /// but not reading from them anymore.
400 fn remove_const(ecx: &mut InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>, local: Local) {
401 ecx.frame_mut().locals[local] =
402 LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) };
405 fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
406 match &self.source_scopes[source_info.scope].local_data {
407 ClearCrossCrate::Set(data) => Some(data.lint_root),
408 ClearCrossCrate::Clear => None,
412 fn use_ecx<F, T>(&mut self, f: F) -> Option<T>
414 F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
417 Ok(val) => Some(val),
419 // Some errors shouldn't come up because creating them causes
420 // an allocation, which we should avoid. When that happens,
421 // dedicated error variants should be introduced instead.
423 !error.kind.allocates(),
424 "const-prop encountered allocating error: {}",
432 /// Returns the value, if any, of evaluating `c`.
433 fn eval_constant(&mut self, c: &Constant<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
434 // FIXME we need to revisit this for #67176
439 match self.ecx.const_to_op(c.literal, None) {
442 let tcx = self.ecx.tcx.at(c.span);
443 let err = error_to_const_error(&self.ecx, error, Some(c.span));
444 if let Some(lint_root) = self.lint_root(source_info) {
445 let lint_only = match c.literal.val {
446 // Promoteds must lint and not error as the user didn't ask for them
447 ConstKind::Unevaluated(_, _, Some(_)) => true,
448 // Out of backwards compatibility we cannot report hard errors in unused
449 // generic functions using associated constants of the generic parameters.
450 _ => c.literal.needs_subst(),
453 // Out of backwards compatibility we cannot report hard errors in unused
454 // generic functions using associated constants of the generic parameters.
455 err.report_as_lint(tcx, "erroneous constant used", lint_root, Some(c.span));
457 err.report_as_error(tcx, "erroneous constant used");
460 err.report_as_error(tcx, "erroneous constant used");
467 /// Returns the value, if any, of evaluating `place`.
468 fn eval_place(&mut self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
469 trace!("eval_place(place={:?})", place);
470 self.use_ecx(|this| this.ecx.eval_place_to_op(place, None))
473 /// Returns the value, if any, of evaluating `op`. Calls upon `eval_constant`
474 /// or `eval_place`, depending on the variant of `Operand` used.
475 fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
477 Operand::Constant(ref c) => self.eval_constant(c, source_info),
478 Operand::Move(place) | Operand::Copy(place) => self.eval_place(place),
482 fn report_assert_as_lint(
484 lint: &'static lint::Lint,
485 source_info: SourceInfo,
486 message: &'static str,
487 panic: AssertKind<impl std::fmt::Debug>,
489 let lint_root = self.lint_root(source_info)?;
490 self.tcx.struct_span_lint_hir(lint, lint_root, source_info.span, |lint| {
491 let mut err = lint.build(message);
492 err.span_label(source_info.span, format!("{:?}", panic));
502 source_info: SourceInfo,
504 if let (val, true) = self.use_ecx(|this| {
505 let val = this.ecx.read_immediate(this.ecx.eval_operand(arg, None)?)?;
506 let (_res, overflow, _ty) = this.ecx.overflowing_unary_op(op, val)?;
509 // `AssertKind` only has an `OverflowNeg` variant, so make sure that is
510 // appropriate to use.
511 assert_eq!(op, UnOp::Neg, "Neg is the only UnOp that can overflow");
512 self.report_assert_as_lint(
513 lint::builtin::ARITHMETIC_OVERFLOW,
515 "this arithmetic operation will overflow",
516 AssertKind::OverflowNeg(val.to_const_int()),
526 left: &Operand<'tcx>,
527 right: &Operand<'tcx>,
528 source_info: SourceInfo,
530 let r = self.use_ecx(|this| this.ecx.read_immediate(this.ecx.eval_operand(right, None)?));
531 let l = self.use_ecx(|this| this.ecx.read_immediate(this.ecx.eval_operand(left, None)?));
532 // Check for exceeding shifts *even if* we cannot evaluate the LHS.
533 if op == BinOp::Shr || op == BinOp::Shl {
535 // We need the type of the LHS. We cannot use `place_layout` as that is the type
536 // of the result, which for checked binops is not the same!
537 let left_ty = left.ty(&self.local_decls, self.tcx);
538 let left_size = self.ecx.layout_of(left_ty).ok()?.size;
539 let right_size = r.layout.size;
540 let r_bits = r.to_scalar().ok();
541 // This is basically `force_bits`.
542 let r_bits = r_bits.and_then(|r| r.to_bits_or_ptr(right_size, &self.tcx).ok());
543 if r_bits.map_or(false, |b| b >= left_size.bits() as u128) {
544 debug!("check_binary_op: reporting assert for {:?}", source_info);
545 self.report_assert_as_lint(
546 lint::builtin::ARITHMETIC_OVERFLOW,
548 "this arithmetic operation will overflow",
549 AssertKind::Overflow(
552 Some(l) => l.to_const_int(),
553 // Invent a dummy value, the diagnostic ignores it anyway
554 None => ConstInt::new(
558 left_ty.is_ptr_sized_integral(),
567 if let (Some(l), Some(r)) = (l, r) {
568 // The remaining operators are handled through `overflowing_binary_op`.
569 if self.use_ecx(|this| {
570 let (_res, overflow, _ty) = this.ecx.overflowing_binary_op(op, l, r)?;
573 self.report_assert_as_lint(
574 lint::builtin::ARITHMETIC_OVERFLOW,
576 "this arithmetic operation will overflow",
577 AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
584 fn propagate_operand(&mut self, operand: &mut Operand<'tcx>) {
586 Operand::Copy(l) | Operand::Move(l) => {
587 if let Some(value) = self.get_const(l) {
588 if self.should_const_prop(value) {
589 // FIXME(felix91gr): this code only handles `Scalar` cases.
590 // For now, we're not handling `ScalarPair` cases because
591 // doing so here would require a lot of code duplication.
592 // We should hopefully generalize `Operand` handling into a fn,
593 // and use it to do const-prop here and everywhere else
594 // where it makes sense.
595 if let interpret::Operand::Immediate(interpret::Immediate::Scalar(
596 ScalarMaybeUninit::Scalar(scalar),
599 *operand = self.operand_from_scalar(
602 self.source_info.unwrap().span,
608 Operand::Constant(_) => (),
614 rvalue: &Rvalue<'tcx>,
615 place_layout: TyAndLayout<'tcx>,
616 source_info: SourceInfo,
619 // #66397: Don't try to eval into large places as that can cause an OOM
620 if place_layout.size >= Size::from_bytes(MAX_ALLOC_LIMIT) {
624 // Perform any special handling for specific Rvalue types.
625 // Generally, checks here fall into one of two categories:
626 // 1. Additional checking to provide useful lints to the user
627 // - In this case, we will do some validation and then fall through to the
628 // end of the function which evals the assignment.
629 // 2. Working around bugs in other parts of the compiler
630 // - In this case, we'll return `None` from this function to stop evaluation.
632 // Additional checking: give lints to the user if an overflow would occur.
633 // We do this here and not in the `Assert` terminator as that terminator is
634 // only sometimes emitted (overflow checks can be disabled), but we want to always
636 Rvalue::UnaryOp(op, arg) => {
637 trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
638 self.check_unary_op(*op, arg, source_info)?;
640 Rvalue::BinaryOp(op, left, right) => {
641 trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
642 self.check_binary_op(*op, left, right, source_info)?;
644 Rvalue::CheckedBinaryOp(op, left, right) => {
646 "checking CheckedBinaryOp(op = {:?}, left = {:?}, right = {:?})",
651 self.check_binary_op(*op, left, right, source_info)?;
654 // Do not try creating references (#67862)
655 Rvalue::AddressOf(_, place) | Rvalue::Ref(_, _, place) => {
656 trace!("skipping AddressOf | Ref for {:?}", place);
658 // This may be creating mutable references or immutable references to cells.
659 // If that happens, the pointed to value could be mutated via that reference.
660 // Since we aren't tracking references, the const propagator loses track of what
661 // value the local has right now.
662 // Thus, all locals that have their reference taken
663 // must not take part in propagation.
664 Self::remove_const(&mut self.ecx, place.local);
668 Rvalue::ThreadLocalRef(def_id) => {
669 trace!("skipping ThreadLocalRef({:?})", def_id);
674 // There's no other checking to do at this time.
675 Rvalue::Aggregate(..)
680 | Rvalue::Discriminant(..)
681 | Rvalue::NullaryOp(..) => {}
684 // FIXME we need to revisit this for #67176
685 if rvalue.needs_subst() {
689 if self.tcx.sess.opts.debugging_opts.mir_opt_level >= 3 {
690 self.eval_rvalue_with_identities(rvalue, place)
692 self.use_ecx(|this| this.ecx.eval_rvalue_into_place(rvalue, place))
696 // Attempt to use albegraic identities to eliminate constant expressions
697 fn eval_rvalue_with_identities(
699 rvalue: &Rvalue<'tcx>,
702 self.use_ecx(|this| {
704 Rvalue::BinaryOp(op, left, right) | Rvalue::CheckedBinaryOp(op, left, right) => {
705 let l = this.ecx.eval_operand(left, None);
706 let r = this.ecx.eval_operand(right, None);
708 let const_arg = match (l, r) {
709 (Ok(x), Err(_)) | (Err(_), Ok(x)) => this.ecx.read_immediate(x)?,
710 (Err(e), Err(_)) => return Err(e),
712 this.ecx.eval_rvalue_into_place(rvalue, place)?;
718 this.ecx.force_bits(const_arg.to_scalar()?, const_arg.layout.size)?;
719 let dest = this.ecx.eval_place(place)?;
724 this.ecx.write_immediate(*const_arg, dest)?;
728 if arg_value == truncate(u128::MAX, const_arg.layout.size)
729 || (const_arg.layout.ty.is_bool() && arg_value == 1)
731 this.ecx.write_immediate(*const_arg, dest)?;
735 if const_arg.layout.ty.is_integral() && arg_value == 0 {
736 if let Rvalue::CheckedBinaryOp(_, _, _) = rvalue {
737 let val = Immediate::ScalarPair(
738 const_arg.to_scalar()?.into(),
739 Scalar::from_bool(false).into(),
741 this.ecx.write_immediate(val, dest)?;
743 this.ecx.write_immediate(*const_arg, dest)?;
748 this.ecx.eval_rvalue_into_place(rvalue, place)?;
753 this.ecx.eval_rvalue_into_place(rvalue, place)?;
761 /// Creates a new `Operand::Constant` from a `Scalar` value
762 fn operand_from_scalar(&self, scalar: Scalar, ty: Ty<'tcx>, span: Span) -> Operand<'tcx> {
763 Operand::Constant(Box::new(Constant {
766 literal: ty::Const::from_scalar(self.tcx, scalar, ty),
770 fn replace_with_const(
772 rval: &mut Rvalue<'tcx>,
774 source_info: SourceInfo,
776 if let Rvalue::Use(Operand::Constant(c)) = rval {
777 if !matches!(c.literal.val, ConstKind::Unevaluated(..)) {
778 trace!("skipping replace of Rvalue::Use({:?} because it is already a const", c);
783 trace!("attepting to replace {:?} with {:?}", rval, value);
784 if let Err(e) = self.ecx.const_validate_operand(
787 // FIXME: is ref tracking too expensive?
788 &mut interpret::RefTracking::empty(),
789 /*may_ref_to_static*/ true,
791 trace!("validation error, attempt failed: {:?}", e);
795 // FIXME> figure out what to do when try_read_immediate fails
796 let imm = self.use_ecx(|this| this.ecx.try_read_immediate(value));
798 if let Some(Ok(imm)) = imm {
800 interpret::Immediate::Scalar(ScalarMaybeUninit::Scalar(scalar)) => {
801 *rval = Rvalue::Use(self.operand_from_scalar(
807 Immediate::ScalarPair(
808 ScalarMaybeUninit::Scalar(one),
809 ScalarMaybeUninit::Scalar(two),
811 // Found a value represented as a pair. For now only do cont-prop if type of
812 // Rvalue is also a pair with two scalars. The more general case is more
813 // complicated to implement so we'll do it later.
814 // FIXME: implement the general case stated above ^.
815 let ty = &value.layout.ty.kind;
816 // Only do it for tuples
817 if let ty::Tuple(substs) = ty {
818 // Only do it if tuple is also a pair with two scalars
819 if substs.len() == 2 {
820 let opt_ty1_ty2 = self.use_ecx(|this| {
821 let ty1 = substs[0].expect_ty();
822 let ty2 = substs[1].expect_ty();
823 let ty_is_scalar = |ty| {
824 this.ecx.layout_of(ty).ok().map(|layout| layout.abi.is_scalar())
827 if ty_is_scalar(ty1) && ty_is_scalar(ty2) {
834 if let Some(Some((ty1, ty2))) = opt_ty1_ty2 {
835 *rval = Rvalue::Aggregate(
836 Box::new(AggregateKind::Tuple),
838 self.operand_from_scalar(one, ty1, source_info.span),
839 self.operand_from_scalar(two, ty2, source_info.span),
851 /// Returns `true` if and only if this `op` should be const-propagated into.
852 fn should_const_prop(&mut self, op: OpTy<'tcx>) -> bool {
853 let mir_opt_level = self.tcx.sess.opts.debugging_opts.mir_opt_level;
855 if mir_opt_level == 0 {
860 interpret::Operand::Immediate(Immediate::Scalar(ScalarMaybeUninit::Scalar(s))) => {
863 interpret::Operand::Immediate(Immediate::ScalarPair(
864 ScalarMaybeUninit::Scalar(l),
865 ScalarMaybeUninit::Scalar(r),
866 )) => l.is_bits() && r.is_bits(),
872 /// The mode that `ConstProp` is allowed to run in for a given `Local`.
873 #[derive(Clone, Copy, Debug, PartialEq)]
875 /// The `Local` can be propagated into and reads of this `Local` can also be propagated.
877 /// The `Local` can only be propagated into and from its own block.
879 /// The `Local` can be propagated into but reads cannot be propagated.
881 /// The `Local` cannot be part of propagation at all. Any statement
882 /// referencing it either for reading or writing will not get propagated.
886 struct CanConstProp {
887 can_const_prop: IndexVec<Local, ConstPropMode>,
888 // False at the beginning. Once set, no more assignments are allowed to that local.
889 found_assignment: BitSet<Local>,
890 // Cache of locals' information
891 local_kinds: IndexVec<Local, LocalKind>,
895 /// Returns true if `local` can be propagated
896 fn check(body: &Body<'_>) -> IndexVec<Local, ConstPropMode> {
897 let mut cpv = CanConstProp {
898 can_const_prop: IndexVec::from_elem(ConstPropMode::FullConstProp, &body.local_decls),
899 found_assignment: BitSet::new_empty(body.local_decls.len()),
900 local_kinds: IndexVec::from_fn_n(
901 |local| body.local_kind(local),
902 body.local_decls.len(),
905 for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
906 // Cannot use args at all
907 // Cannot use locals because if x < y { y - x } else { x - y } would
909 // FIXME(oli-obk): lint variables until they are used in a condition
910 // FIXME(oli-obk): lint if return value is constant
911 if cpv.local_kinds[local] == LocalKind::Arg {
912 *val = ConstPropMode::OnlyPropagateInto;
914 "local {:?} can't be const propagated because it's a function argument",
917 } else if cpv.local_kinds[local] == LocalKind::Var {
918 *val = ConstPropMode::OnlyInsideOwnBlock;
920 "local {:?} will only be propagated inside its block, because it's a user variable",
925 cpv.visit_body(&body);
930 impl<'tcx> Visitor<'tcx> for CanConstProp {
931 fn visit_local(&mut self, &local: &Local, context: PlaceContext, _: Location) {
932 use rustc_middle::mir::visit::PlaceContext::*;
934 // Projections are fine, because `&mut foo.x` will be caught by
935 // `MutatingUseContext::Borrow` elsewhere.
936 MutatingUse(MutatingUseContext::Projection)
937 // These are just stores, where the storing is not propagatable, but there may be later
938 // mutations of the same local via `Store`
939 | MutatingUse(MutatingUseContext::Call)
940 // Actual store that can possibly even propagate a value
941 | MutatingUse(MutatingUseContext::Store) => {
942 if !self.found_assignment.insert(local) {
943 match &mut self.can_const_prop[local] {
944 // If the local can only get propagated in its own block, then we don't have
945 // to worry about multiple assignments, as we'll nuke the const state at the
946 // end of the block anyway, and inside the block we overwrite previous
947 // states as applicable.
948 ConstPropMode::OnlyInsideOwnBlock => {}
949 ConstPropMode::NoPropagation => {}
950 ConstPropMode::OnlyPropagateInto => {}
951 other @ ConstPropMode::FullConstProp => {
953 "local {:?} can't be propagated because of multiple assignments",
956 *other = ConstPropMode::OnlyPropagateInto;
961 // Reading constants is allowed an arbitrary number of times
962 NonMutatingUse(NonMutatingUseContext::Copy)
963 | NonMutatingUse(NonMutatingUseContext::Move)
964 | NonMutatingUse(NonMutatingUseContext::Inspect)
965 | NonMutatingUse(NonMutatingUseContext::Projection)
968 // These could be propagated with a smarter analysis or just some careful thinking about
969 // whether they'd be fine right now.
970 MutatingUse(MutatingUseContext::AsmOutput)
971 | MutatingUse(MutatingUseContext::Yield)
972 | MutatingUse(MutatingUseContext::Drop)
973 | MutatingUse(MutatingUseContext::Retag)
974 // These can't ever be propagated under any scheme, as we can't reason about indirect
976 | NonMutatingUse(NonMutatingUseContext::SharedBorrow)
977 | NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
978 | NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
979 | NonMutatingUse(NonMutatingUseContext::AddressOf)
980 | MutatingUse(MutatingUseContext::Borrow)
981 | MutatingUse(MutatingUseContext::AddressOf) => {
982 trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
983 self.can_const_prop[local] = ConstPropMode::NoPropagation;
989 impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> {
990 fn tcx(&self) -> TyCtxt<'tcx> {
994 fn visit_body(&mut self, body: &mut Body<'tcx>) {
995 for (bb, data) in body.basic_blocks_mut().iter_enumerated_mut() {
996 self.visit_basic_block_data(bb, data);
1000 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
1001 self.super_operand(operand, location);
1003 // Only const prop copies and moves on `mir_opt_level=3` as doing so
1004 // currently increases compile time.
1005 if self.tcx.sess.opts.debugging_opts.mir_opt_level >= 3 {
1006 self.propagate_operand(operand)
1010 fn visit_constant(&mut self, constant: &mut Constant<'tcx>, location: Location) {
1011 trace!("visit_constant: {:?}", constant);
1012 self.super_constant(constant, location);
1013 self.eval_constant(constant, self.source_info.unwrap());
1016 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
1017 trace!("visit_statement: {:?}", statement);
1018 let source_info = statement.source_info;
1019 self.source_info = Some(source_info);
1020 if let StatementKind::Assign(box (place, ref mut rval)) = statement.kind {
1021 let place_ty: Ty<'tcx> = place.ty(&self.local_decls, self.tcx).ty;
1022 if let Ok(place_layout) = self.tcx.layout_of(self.param_env.and(place_ty)) {
1023 let can_const_prop = self.can_const_prop[place.local];
1024 if let Some(()) = self.const_prop(rval, place_layout, source_info, place) {
1025 // This will return None if the above `const_prop` invocation only "wrote" a
1026 // type whose creation requires no write. E.g. a generator whose initial state
1027 // consists solely of uninitialized memory (so it doesn't capture any locals).
1028 if let Some(value) = self.get_const(place) {
1029 if self.should_const_prop(value) {
1030 trace!("replacing {:?} with {:?}", rval, value);
1031 self.replace_with_const(rval, value, source_info);
1032 if can_const_prop == ConstPropMode::FullConstProp
1033 || can_const_prop == ConstPropMode::OnlyInsideOwnBlock
1035 trace!("propagated into {:?}", place);
1039 match can_const_prop {
1040 ConstPropMode::OnlyInsideOwnBlock => {
1042 "found local restricted to its block. \
1043 Will remove it from const-prop after block is finished. Local: {:?}",
1047 ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
1048 trace!("can't propagate into {:?}", place);
1049 if place.local != RETURN_PLACE {
1050 Self::remove_const(&mut self.ecx, place.local);
1053 ConstPropMode::FullConstProp => {}
1056 // Const prop failed, so erase the destination, ensuring that whatever happens
1057 // from here on, does not know about the previous value.
1058 // This is important in case we have
1061 // x = SOME_MUTABLE_STATIC;
1062 // // x must now be undefined
1064 // FIXME: we overzealously erase the entire local, because that's easier to
1067 "propagation into {:?} failed.
1068 Nuking the entire site from orbit, it's the only way to be sure",
1071 Self::remove_const(&mut self.ecx, place.local);
1075 "cannot propagate into {:?}, because the type of the local is generic.",
1078 Self::remove_const(&mut self.ecx, place.local);
1081 match statement.kind {
1082 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
1083 let frame = self.ecx.frame_mut();
1084 frame.locals[local].value =
1085 if let StatementKind::StorageLive(_) = statement.kind {
1086 LocalValue::Uninitialized
1095 self.super_statement(statement, location);
1098 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
1099 let source_info = terminator.source_info;
1100 self.source_info = Some(source_info);
1101 self.super_terminator(terminator, location);
1102 match &mut terminator.kind {
1103 TerminatorKind::Assert { expected, ref msg, ref mut cond, .. } => {
1104 if let Some(value) = self.eval_operand(&cond, source_info) {
1105 trace!("assertion on {:?} should be {:?}", value, expected);
1106 let expected = ScalarMaybeUninit::from(Scalar::from_bool(*expected));
1107 let value_const = self.ecx.read_scalar(value).unwrap();
1108 if expected != value_const {
1113 impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
1114 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1116 Self::Val(val) => val.fmt(fmt),
1117 Self::Underscore => fmt.write_str("_"),
1121 let mut eval_to_int = |op| {
1122 // This can be `None` if the lhs wasn't const propagated and we just
1123 // triggered the assert on the value of the rhs.
1124 match self.eval_operand(op, source_info) {
1126 DbgVal::Val(self.ecx.read_immediate(op).unwrap().to_const_int())
1128 None => DbgVal::Underscore,
1131 let msg = match msg {
1132 AssertKind::DivisionByZero(op) => {
1133 Some(AssertKind::DivisionByZero(eval_to_int(op)))
1135 AssertKind::RemainderByZero(op) => {
1136 Some(AssertKind::RemainderByZero(eval_to_int(op)))
1138 AssertKind::BoundsCheck { ref len, ref index } => {
1139 let len = eval_to_int(len);
1140 let index = eval_to_int(index);
1141 Some(AssertKind::BoundsCheck { len, index })
1143 // Overflow is are already covered by checks on the binary operators.
1144 AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => None,
1145 // Need proper const propagator for these.
1148 // Poison all places this operand references so that further code
1149 // doesn't use the invalid value
1151 Operand::Move(ref place) | Operand::Copy(ref place) => {
1152 Self::remove_const(&mut self.ecx, place.local);
1154 Operand::Constant(_) => {}
1156 if let Some(msg) = msg {
1157 self.report_assert_as_lint(
1158 lint::builtin::UNCONDITIONAL_PANIC,
1160 "this operation will panic at runtime",
1165 if self.should_const_prop(value) {
1166 if let ScalarMaybeUninit::Scalar(scalar) = value_const {
1167 *cond = self.operand_from_scalar(
1169 self.tcx.types.bool,
1177 TerminatorKind::SwitchInt { ref mut discr, .. } => {
1178 // FIXME: This is currently redundant with `visit_operand`, but sadly
1179 // always visiting operands currently causes a perf regression in LLVM codegen, so
1180 // `visit_operand` currently only runs for propagates places for `mir_opt_level=3`.
1181 self.propagate_operand(discr)
1183 // None of these have Operands to const-propagate.
1184 TerminatorKind::Goto { .. }
1185 | TerminatorKind::Resume
1186 | TerminatorKind::Abort
1187 | TerminatorKind::Return
1188 | TerminatorKind::Unreachable
1189 | TerminatorKind::Drop { .. }
1190 | TerminatorKind::DropAndReplace { .. }
1191 | TerminatorKind::Yield { .. }
1192 | TerminatorKind::GeneratorDrop
1193 | TerminatorKind::FalseEdge { .. }
1194 | TerminatorKind::FalseUnwind { .. }
1195 | TerminatorKind::InlineAsm { .. } => {}
1196 // Every argument in our function calls have already been propagated in `visit_operand`.
1198 // NOTE: because LLVM codegen gives performance regressions with it, so this is gated
1199 // on `mir_opt_level=3`.
1200 TerminatorKind::Call { .. } => {}
1203 // We remove all Locals which are restricted in propagation to their containing blocks and
1204 // which were modified in the current block.
1205 // Take it out of the ecx so we can get a mutable reference to the ecx for `remove_const`.
1206 let mut locals = std::mem::take(&mut self.ecx.machine.written_only_inside_own_block_locals);
1207 for &local in locals.iter() {
1208 Self::remove_const(&mut self.ecx, local);
1211 // Put it back so we reuse the heap of the storage
1212 self.ecx.machine.written_only_inside_own_block_locals = locals;
1213 if cfg!(debug_assertions) {
1214 // Ensure we are correctly erasing locals with the non-debug-assert logic.
1215 for local in self.ecx.machine.only_propagate_inside_block_locals.iter() {
1217 self.get_const(local.into()).is_none()
1219 .layout_of(self.local_decls[local].ty)
1220 .map_or(true, |layout| layout.is_zst())