]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/transform/const_prop.rs
BPF: review fixes
[rust.git] / compiler / rustc_mir / src / transform / const_prop.rs
1 //! Propagates constants for early reporting of statically known
2 //! assertion failures
3
4 use std::cell::Cell;
5
6 use rustc_ast::Mutability;
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_hir::def::DefKind;
9 use rustc_hir::HirId;
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,
14 };
15 use rustc_middle::mir::{
16     AssertKind, BasicBlock, BinOp, Body, Constant, ConstantKind, Local, LocalDecl, LocalKind,
17     Location, Operand, Place, Rvalue, SourceInfo, SourceScope, SourceScopeData, Statement,
18     StatementKind, Terminator, TerminatorKind, UnOp, RETURN_PLACE,
19 };
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,
24 };
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_target::spec::abi::Abi;
29 use rustc_trait_selection::traits;
30
31 use crate::const_eval::ConstEvalErr;
32 use crate::interpret::{
33     self, compile_time_machine, AllocId, Allocation, ConstValue, CtfeValidationMode, Frame, ImmTy,
34     Immediate, InterpCx, InterpResult, LocalState, LocalValue, MemPlace, Memory, MemoryKind, OpTy,
35     Operand as InterpOperand, PlaceTy, Pointer, Scalar, ScalarMaybeUninit, StackPopCleanup,
36 };
37 use crate::transform::MirPass;
38
39 /// The maximum number of bytes that we'll allocate space for a local or the return value.
40 /// Needed for #66397, because otherwise we eval into large places and that can cause OOM or just
41 /// Severely regress performance.
42 const MAX_ALLOC_LIMIT: u64 = 1024;
43
44 /// Macro for machine-specific `InterpError` without allocation.
45 /// (These will never be shown to the user, but they help diagnose ICEs.)
46 macro_rules! throw_machine_stop_str {
47     ($($tt:tt)*) => {{
48         // We make a new local type for it. The type itself does not carry any information,
49         // but its vtable (for the `MachineStopType` trait) does.
50         struct Zst;
51         // Printing this type shows the desired string.
52         impl std::fmt::Display for Zst {
53             fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54                 write!(f, $($tt)*)
55             }
56         }
57         impl rustc_middle::mir::interpret::MachineStopType for Zst {}
58         throw_machine_stop!(Zst)
59     }};
60 }
61
62 pub struct ConstProp;
63
64 impl<'tcx> MirPass<'tcx> for ConstProp {
65     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
66         // will be evaluated by miri and produce its errors there
67         if body.source.promoted.is_some() {
68             return;
69         }
70
71         use rustc_middle::hir::map::blocks::FnLikeNode;
72         let def_id = body.source.def_id().expect_local();
73         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
74
75         let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some();
76         let is_assoc_const = tcx.def_kind(def_id.to_def_id()) == DefKind::AssocConst;
77
78         // Only run const prop on functions, methods, closures and associated constants
79         if !is_fn_like && !is_assoc_const {
80             // skip anon_const/statics/consts because they'll be evaluated by miri anyway
81             trace!("ConstProp skipped for {:?}", def_id);
82             return;
83         }
84
85         let is_generator = tcx.type_of(def_id.to_def_id()).is_generator();
86         // FIXME(welseywiser) const prop doesn't work on generators because of query cycles
87         // computing their layout.
88         if is_generator {
89             trace!("ConstProp skipped for generator {:?}", def_id);
90             return;
91         }
92
93         // Check if it's even possible to satisfy the 'where' clauses
94         // for this item.
95         // This branch will never be taken for any normal function.
96         // However, it's possible to `#!feature(trivial_bounds)]` to write
97         // a function with impossible to satisfy clauses, e.g.:
98         // `fn foo() where String: Copy {}`
99         //
100         // We don't usually need to worry about this kind of case,
101         // since we would get a compilation error if the user tried
102         // to call it. However, since we can do const propagation
103         // even without any calls to the function, we need to make
104         // sure that it even makes sense to try to evaluate the body.
105         // If there are unsatisfiable where clauses, then all bets are
106         // off, and we just give up.
107         //
108         // We manually filter the predicates, skipping anything that's not
109         // "global". We are in a potentially generic context
110         // (e.g. we are evaluating a function without substituting generic
111         // parameters, so this filtering serves two purposes:
112         //
113         // 1. We skip evaluating any predicates that we would
114         // never be able prove are unsatisfiable (e.g. `<T as Foo>`
115         // 2. We avoid trying to normalize predicates involving generic
116         // parameters (e.g. `<T as Foo>::MyItem`). This can confuse
117         // the normalization code (leading to cycle errors), since
118         // it's usually never invoked in this way.
119         let predicates = tcx
120             .predicates_of(def_id.to_def_id())
121             .predicates
122             .iter()
123             .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
124         if traits::impossible_predicates(
125             tcx,
126             traits::elaborate_predicates(tcx, predicates).map(|o| o.predicate).collect(),
127         ) {
128             trace!("ConstProp skipped for {:?}: found unsatisfiable predicates", def_id);
129             return;
130         }
131
132         trace!("ConstProp starting for {:?}", def_id);
133
134         let dummy_body = &Body::new(
135             body.source,
136             body.basic_blocks().clone(),
137             body.source_scopes.clone(),
138             body.local_decls.clone(),
139             Default::default(),
140             body.arg_count,
141             Default::default(),
142             body.span,
143             body.generator_kind(),
144         );
145
146         // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
147         // constants, instead of just checking for const-folding succeeding.
148         // That would require an uniform one-def no-mutation analysis
149         // and RPO (or recursing when needing the value of a local).
150         let mut optimization_finder = ConstPropagator::new(body, dummy_body, tcx);
151         optimization_finder.visit_body(body);
152
153         trace!("ConstProp done for {:?}", def_id);
154     }
155 }
156
157 struct ConstPropMachine<'mir, 'tcx> {
158     /// The virtual call stack.
159     stack: Vec<Frame<'mir, 'tcx, (), ()>>,
160     /// `OnlyInsideOwnBlock` locals that were written in the current block get erased at the end.
161     written_only_inside_own_block_locals: FxHashSet<Local>,
162     /// Locals that need to be cleared after every block terminates.
163     only_propagate_inside_block_locals: BitSet<Local>,
164     can_const_prop: IndexVec<Local, ConstPropMode>,
165 }
166
167 impl<'mir, 'tcx> ConstPropMachine<'mir, 'tcx> {
168     fn new(
169         only_propagate_inside_block_locals: BitSet<Local>,
170         can_const_prop: IndexVec<Local, ConstPropMode>,
171     ) -> Self {
172         Self {
173             stack: Vec::new(),
174             written_only_inside_own_block_locals: Default::default(),
175             only_propagate_inside_block_locals,
176             can_const_prop,
177         }
178     }
179 }
180
181 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine<'mir, 'tcx> {
182     compile_time_machine!(<'mir, 'tcx>);
183
184     type MemoryKind = !;
185
186     type MemoryExtra = ();
187
188     fn load_mir(
189         _ecx: &InterpCx<'mir, 'tcx, Self>,
190         _instance: ty::InstanceDef<'tcx>,
191     ) -> InterpResult<'tcx, &'tcx Body<'tcx>> {
192         throw_machine_stop_str!("calling functions isn't supported in ConstProp")
193     }
194
195     fn find_mir_or_eval_fn(
196         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
197         _instance: ty::Instance<'tcx>,
198         _abi: Abi,
199         _args: &[OpTy<'tcx>],
200         _ret: Option<(&PlaceTy<'tcx>, BasicBlock)>,
201         _unwind: Option<BasicBlock>,
202     ) -> InterpResult<'tcx, Option<&'mir Body<'tcx>>> {
203         Ok(None)
204     }
205
206     fn call_intrinsic(
207         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
208         _instance: ty::Instance<'tcx>,
209         _args: &[OpTy<'tcx>],
210         _ret: Option<(&PlaceTy<'tcx>, BasicBlock)>,
211         _unwind: Option<BasicBlock>,
212     ) -> InterpResult<'tcx> {
213         throw_machine_stop_str!("calling intrinsics isn't supported in ConstProp")
214     }
215
216     fn assert_panic(
217         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
218         _msg: &rustc_middle::mir::AssertMessage<'tcx>,
219         _unwind: Option<rustc_middle::mir::BasicBlock>,
220     ) -> InterpResult<'tcx> {
221         bug!("panics terminators are not evaluated in ConstProp")
222     }
223
224     fn ptr_to_int(_mem: &Memory<'mir, 'tcx, Self>, _ptr: Pointer) -> InterpResult<'tcx, u64> {
225         throw_unsup!(ReadPointerAsBytes)
226     }
227
228     fn binary_ptr_op(
229         _ecx: &InterpCx<'mir, 'tcx, Self>,
230         _bin_op: BinOp,
231         _left: &ImmTy<'tcx>,
232         _right: &ImmTy<'tcx>,
233     ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
234         // We can't do this because aliasing of memory can differ between const eval and llvm
235         throw_machine_stop_str!("pointer arithmetic or comparisons aren't supported in ConstProp")
236     }
237
238     fn box_alloc(
239         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
240         _dest: &PlaceTy<'tcx>,
241     ) -> InterpResult<'tcx> {
242         throw_machine_stop_str!("can't const prop heap allocations")
243     }
244
245     fn access_local(
246         _ecx: &InterpCx<'mir, 'tcx, Self>,
247         frame: &Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>,
248         local: Local,
249     ) -> InterpResult<'tcx, InterpOperand<Self::PointerTag>> {
250         let l = &frame.locals[local];
251
252         if l.value == LocalValue::Uninitialized {
253             throw_machine_stop_str!("tried to access an uninitialized local")
254         }
255
256         l.access()
257     }
258
259     fn access_local_mut<'a>(
260         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
261         frame: usize,
262         local: Local,
263     ) -> InterpResult<'tcx, Result<&'a mut LocalValue<Self::PointerTag>, MemPlace<Self::PointerTag>>>
264     {
265         if ecx.machine.can_const_prop[local] == ConstPropMode::NoPropagation {
266             throw_machine_stop_str!("tried to write to a local that is marked as not propagatable")
267         }
268         if frame == 0 && ecx.machine.only_propagate_inside_block_locals.contains(local) {
269             trace!(
270                 "mutating local {:?} which is restricted to its block. \
271                 Will remove it from const-prop after block is finished.",
272                 local
273             );
274             ecx.machine.written_only_inside_own_block_locals.insert(local);
275         }
276         ecx.machine.stack[frame].locals[local].access_mut()
277     }
278
279     fn before_access_global(
280         _memory_extra: &(),
281         _alloc_id: AllocId,
282         allocation: &Allocation<Self::PointerTag, Self::AllocExtra>,
283         _static_def_id: Option<DefId>,
284         is_write: bool,
285     ) -> InterpResult<'tcx> {
286         if is_write {
287             throw_machine_stop_str!("can't write to global");
288         }
289         // If the static allocation is mutable, then we can't const prop it as its content
290         // might be different at runtime.
291         if allocation.mutability == Mutability::Mut {
292             throw_machine_stop_str!("can't access mutable globals in ConstProp");
293         }
294
295         Ok(())
296     }
297
298     #[inline(always)]
299     fn init_frame_extra(
300         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
301         frame: Frame<'mir, 'tcx>,
302     ) -> InterpResult<'tcx, Frame<'mir, 'tcx>> {
303         Ok(frame)
304     }
305
306     #[inline(always)]
307     fn stack(
308         ecx: &'a InterpCx<'mir, 'tcx, Self>,
309     ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
310         &ecx.machine.stack
311     }
312
313     #[inline(always)]
314     fn stack_mut(
315         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
316     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
317         &mut ecx.machine.stack
318     }
319 }
320
321 /// Finds optimization opportunities on the MIR.
322 struct ConstPropagator<'mir, 'tcx> {
323     ecx: InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>,
324     tcx: TyCtxt<'tcx>,
325     param_env: ParamEnv<'tcx>,
326     // FIXME(eddyb) avoid cloning these two fields more than once,
327     // by accessing them through `ecx` instead.
328     source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
329     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
330     // Because we have `MutVisitor` we can't obtain the `SourceInfo` from a `Location`. So we store
331     // the last known `SourceInfo` here and just keep revisiting it.
332     source_info: Option<SourceInfo>,
333 }
334
335 impl<'mir, 'tcx> LayoutOf for ConstPropagator<'mir, 'tcx> {
336     type Ty = Ty<'tcx>;
337     type TyAndLayout = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
338
339     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
340         self.tcx.layout_of(self.param_env.and(ty))
341     }
342 }
343
344 impl<'mir, 'tcx> HasDataLayout for ConstPropagator<'mir, 'tcx> {
345     #[inline]
346     fn data_layout(&self) -> &TargetDataLayout {
347         &self.tcx.data_layout
348     }
349 }
350
351 impl<'mir, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'mir, 'tcx> {
352     #[inline]
353     fn tcx(&self) -> TyCtxt<'tcx> {
354         self.tcx
355     }
356 }
357
358 impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
359     fn new(
360         body: &Body<'tcx>,
361         dummy_body: &'mir Body<'tcx>,
362         tcx: TyCtxt<'tcx>,
363     ) -> ConstPropagator<'mir, 'tcx> {
364         let def_id = body.source.def_id();
365         let substs = &InternalSubsts::identity_for_item(tcx, def_id);
366         let param_env = tcx.param_env_reveal_all_normalized(def_id);
367
368         let span = tcx.def_span(def_id);
369         // FIXME: `CanConstProp::check` computes the layout of all locals, return those layouts
370         // so we can write them to `ecx.frame_mut().locals.layout, reducing the duplication in
371         // `layout_of` query invocations.
372         let can_const_prop = CanConstProp::check(tcx, param_env, body);
373         let mut only_propagate_inside_block_locals = BitSet::new_empty(can_const_prop.len());
374         for (l, mode) in can_const_prop.iter_enumerated() {
375             if *mode == ConstPropMode::OnlyInsideOwnBlock {
376                 only_propagate_inside_block_locals.insert(l);
377             }
378         }
379         let mut ecx = InterpCx::new(
380             tcx,
381             span,
382             param_env,
383             ConstPropMachine::new(only_propagate_inside_block_locals, can_const_prop),
384             (),
385         );
386
387         let ret = ecx
388             .layout_of(body.return_ty().subst(tcx, substs))
389             .ok()
390             // Don't bother allocating memory for ZST types which have no values
391             // or for large values.
392             .filter(|ret_layout| {
393                 !ret_layout.is_zst() && ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT)
394             })
395             .map(|ret_layout| ecx.allocate(ret_layout, MemoryKind::Stack).into());
396
397         ecx.push_stack_frame(
398             Instance::new(def_id, substs),
399             dummy_body,
400             ret.as_ref(),
401             StackPopCleanup::None { cleanup: false },
402         )
403         .expect("failed to push initial stack frame");
404
405         ConstPropagator {
406             ecx,
407             tcx,
408             param_env,
409             // FIXME(eddyb) avoid cloning these two fields more than once,
410             // by accessing them through `ecx` instead.
411             source_scopes: body.source_scopes.clone(),
412             //FIXME(wesleywiser) we can't steal this because `Visitor::super_visit_body()` needs it
413             local_decls: body.local_decls.clone(),
414             source_info: None,
415         }
416     }
417
418     fn get_const(&self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
419         let op = match self.ecx.eval_place_to_op(place, None) {
420             Ok(op) => op,
421             Err(e) => {
422                 trace!("get_const failed: {}", e);
423                 return None;
424             }
425         };
426
427         // Try to read the local as an immediate so that if it is representable as a scalar, we can
428         // handle it as such, but otherwise, just return the value as is.
429         Some(match self.ecx.try_read_immediate(&op) {
430             Ok(Ok(imm)) => imm.into(),
431             _ => op,
432         })
433     }
434
435     /// Remove `local` from the pool of `Locals`. Allows writing to them,
436     /// but not reading from them anymore.
437     fn remove_const(ecx: &mut InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>, local: Local) {
438         ecx.frame_mut().locals[local] =
439             LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) };
440     }
441
442     fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
443         source_info.scope.lint_root(&self.source_scopes)
444     }
445
446     fn use_ecx<F, T>(&mut self, f: F) -> Option<T>
447     where
448         F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
449     {
450         match f(self) {
451             Ok(val) => Some(val),
452             Err(error) => {
453                 trace!("InterpCx operation failed: {:?}", error);
454                 // Some errors shouldn't come up because creating them causes
455                 // an allocation, which we should avoid. When that happens,
456                 // dedicated error variants should be introduced instead.
457                 assert!(
458                     !error.kind().formatted_string(),
459                     "const-prop encountered formatting error: {}",
460                     error
461                 );
462                 None
463             }
464         }
465     }
466
467     /// Returns the value, if any, of evaluating `c`.
468     fn eval_constant(&mut self, c: &Constant<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
469         // FIXME we need to revisit this for #67176
470         if c.needs_subst() {
471             return None;
472         }
473
474         match self.ecx.mir_const_to_op(&c.literal, None) {
475             Ok(op) => Some(op),
476             Err(error) => {
477                 let tcx = self.ecx.tcx.at(c.span);
478                 let err = ConstEvalErr::new(&self.ecx, error, Some(c.span));
479                 if let Some(lint_root) = self.lint_root(source_info) {
480                     let lint_only = match c.literal {
481                         ConstantKind::Ty(ct) => match ct.val {
482                             // Promoteds must lint and not error as the user didn't ask for them
483                             ConstKind::Unevaluated(ty::Unevaluated {
484                                 def: _,
485                                 substs: _,
486                                 promoted: Some(_),
487                             }) => true,
488                             // Out of backwards compatibility we cannot report hard errors in unused
489                             // generic functions using associated constants of the generic parameters.
490                             _ => c.literal.needs_subst(),
491                         },
492                         ConstantKind::Val(_, ty) => ty.needs_subst(),
493                     };
494                     if lint_only {
495                         // Out of backwards compatibility we cannot report hard errors in unused
496                         // generic functions using associated constants of the generic parameters.
497                         err.report_as_lint(tcx, "erroneous constant used", lint_root, Some(c.span));
498                     } else {
499                         err.report_as_error(tcx, "erroneous constant used");
500                     }
501                 } else {
502                     err.report_as_error(tcx, "erroneous constant used");
503                 }
504                 None
505             }
506         }
507     }
508
509     /// Returns the value, if any, of evaluating `place`.
510     fn eval_place(&mut self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
511         trace!("eval_place(place={:?})", place);
512         self.use_ecx(|this| this.ecx.eval_place_to_op(place, None))
513     }
514
515     /// Returns the value, if any, of evaluating `op`. Calls upon `eval_constant`
516     /// or `eval_place`, depending on the variant of `Operand` used.
517     fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
518         match *op {
519             Operand::Constant(ref c) => self.eval_constant(c, source_info),
520             Operand::Move(place) | Operand::Copy(place) => self.eval_place(place),
521         }
522     }
523
524     fn report_assert_as_lint(
525         &self,
526         lint: &'static lint::Lint,
527         source_info: SourceInfo,
528         message: &'static str,
529         panic: AssertKind<impl std::fmt::Debug>,
530     ) -> Option<()> {
531         let lint_root = self.lint_root(source_info)?;
532         self.tcx.struct_span_lint_hir(lint, lint_root, source_info.span, |lint| {
533             let mut err = lint.build(message);
534             err.span_label(source_info.span, format!("{:?}", panic));
535             err.emit()
536         });
537         None
538     }
539
540     fn check_unary_op(
541         &mut self,
542         op: UnOp,
543         arg: &Operand<'tcx>,
544         source_info: SourceInfo,
545     ) -> Option<()> {
546         if let (val, true) = self.use_ecx(|this| {
547             let val = this.ecx.read_immediate(&this.ecx.eval_operand(arg, None)?)?;
548             let (_res, overflow, _ty) = this.ecx.overflowing_unary_op(op, &val)?;
549             Ok((val, overflow))
550         })? {
551             // `AssertKind` only has an `OverflowNeg` variant, so make sure that is
552             // appropriate to use.
553             assert_eq!(op, UnOp::Neg, "Neg is the only UnOp that can overflow");
554             self.report_assert_as_lint(
555                 lint::builtin::ARITHMETIC_OVERFLOW,
556                 source_info,
557                 "this arithmetic operation will overflow",
558                 AssertKind::OverflowNeg(val.to_const_int()),
559             )?;
560         }
561
562         Some(())
563     }
564
565     fn check_binary_op(
566         &mut self,
567         op: BinOp,
568         left: &Operand<'tcx>,
569         right: &Operand<'tcx>,
570         source_info: SourceInfo,
571     ) -> Option<()> {
572         let r = self.use_ecx(|this| this.ecx.read_immediate(&this.ecx.eval_operand(right, None)?));
573         let l = self.use_ecx(|this| this.ecx.read_immediate(&this.ecx.eval_operand(left, None)?));
574         // Check for exceeding shifts *even if* we cannot evaluate the LHS.
575         if op == BinOp::Shr || op == BinOp::Shl {
576             let r = r?;
577             // We need the type of the LHS. We cannot use `place_layout` as that is the type
578             // of the result, which for checked binops is not the same!
579             let left_ty = left.ty(&self.local_decls, self.tcx);
580             let left_size = self.ecx.layout_of(left_ty).ok()?.size;
581             let right_size = r.layout.size;
582             let r_bits = r.to_scalar().ok();
583             // This is basically `force_bits`.
584             let r_bits = r_bits.and_then(|r| r.to_bits_or_ptr(right_size, &self.tcx).ok());
585             if r_bits.map_or(false, |b| b >= left_size.bits() as u128) {
586                 debug!("check_binary_op: reporting assert for {:?}", source_info);
587                 self.report_assert_as_lint(
588                     lint::builtin::ARITHMETIC_OVERFLOW,
589                     source_info,
590                     "this arithmetic operation will overflow",
591                     AssertKind::Overflow(
592                         op,
593                         match l {
594                             Some(l) => l.to_const_int(),
595                             // Invent a dummy value, the diagnostic ignores it anyway
596                             None => ConstInt::new(
597                                 ScalarInt::try_from_uint(1_u8, left_size).unwrap(),
598                                 left_ty.is_signed(),
599                                 left_ty.is_ptr_sized_integral(),
600                             ),
601                         },
602                         r.to_const_int(),
603                     ),
604                 )?;
605             }
606         }
607
608         if let (Some(l), Some(r)) = (&l, &r) {
609             // The remaining operators are handled through `overflowing_binary_op`.
610             if self.use_ecx(|this| {
611                 let (_res, overflow, _ty) = this.ecx.overflowing_binary_op(op, l, r)?;
612                 Ok(overflow)
613             })? {
614                 self.report_assert_as_lint(
615                     lint::builtin::ARITHMETIC_OVERFLOW,
616                     source_info,
617                     "this arithmetic operation will overflow",
618                     AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
619                 )?;
620             }
621         }
622         Some(())
623     }
624
625     fn propagate_operand(&mut self, operand: &mut Operand<'tcx>) {
626         match *operand {
627             Operand::Copy(l) | Operand::Move(l) => {
628                 if let Some(value) = self.get_const(l) {
629                     if self.should_const_prop(&value) {
630                         // FIXME(felix91gr): this code only handles `Scalar` cases.
631                         // For now, we're not handling `ScalarPair` cases because
632                         // doing so here would require a lot of code duplication.
633                         // We should hopefully generalize `Operand` handling into a fn,
634                         // and use it to do const-prop here and everywhere else
635                         // where it makes sense.
636                         if let interpret::Operand::Immediate(interpret::Immediate::Scalar(
637                             ScalarMaybeUninit::Scalar(scalar),
638                         )) = *value
639                         {
640                             *operand = self.operand_from_scalar(
641                                 scalar,
642                                 value.layout.ty,
643                                 self.source_info.unwrap().span,
644                             );
645                         }
646                     }
647                 }
648             }
649             Operand::Constant(_) => (),
650         }
651     }
652
653     fn const_prop(
654         &mut self,
655         rvalue: &Rvalue<'tcx>,
656         source_info: SourceInfo,
657         place: Place<'tcx>,
658     ) -> Option<()> {
659         // Perform any special handling for specific Rvalue types.
660         // Generally, checks here fall into one of two categories:
661         //   1. Additional checking to provide useful lints to the user
662         //        - In this case, we will do some validation and then fall through to the
663         //          end of the function which evals the assignment.
664         //   2. Working around bugs in other parts of the compiler
665         //        - In this case, we'll return `None` from this function to stop evaluation.
666         match rvalue {
667             // Additional checking: give lints to the user if an overflow would occur.
668             // We do this here and not in the `Assert` terminator as that terminator is
669             // only sometimes emitted (overflow checks can be disabled), but we want to always
670             // lint.
671             Rvalue::UnaryOp(op, arg) => {
672                 trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
673                 self.check_unary_op(*op, arg, source_info)?;
674             }
675             Rvalue::BinaryOp(op, box (left, right)) => {
676                 trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
677                 self.check_binary_op(*op, left, right, source_info)?;
678             }
679             Rvalue::CheckedBinaryOp(op, box (left, right)) => {
680                 trace!(
681                     "checking CheckedBinaryOp(op = {:?}, left = {:?}, right = {:?})",
682                     op,
683                     left,
684                     right
685                 );
686                 self.check_binary_op(*op, left, right, source_info)?;
687             }
688
689             // Do not try creating references (#67862)
690             Rvalue::AddressOf(_, place) | Rvalue::Ref(_, _, place) => {
691                 trace!("skipping AddressOf | Ref for {:?}", place);
692
693                 // This may be creating mutable references or immutable references to cells.
694                 // If that happens, the pointed to value could be mutated via that reference.
695                 // Since we aren't tracking references, the const propagator loses track of what
696                 // value the local has right now.
697                 // Thus, all locals that have their reference taken
698                 // must not take part in propagation.
699                 Self::remove_const(&mut self.ecx, place.local);
700
701                 return None;
702             }
703             Rvalue::ThreadLocalRef(def_id) => {
704                 trace!("skipping ThreadLocalRef({:?})", def_id);
705
706                 return None;
707             }
708
709             // There's no other checking to do at this time.
710             Rvalue::Aggregate(..)
711             | Rvalue::Use(..)
712             | Rvalue::Repeat(..)
713             | Rvalue::Len(..)
714             | Rvalue::Cast(..)
715             | Rvalue::Discriminant(..)
716             | Rvalue::NullaryOp(..) => {}
717         }
718
719         // FIXME we need to revisit this for #67176
720         if rvalue.needs_subst() {
721             return None;
722         }
723
724         if self.tcx.sess.mir_opt_level() >= 4 {
725             self.eval_rvalue_with_identities(rvalue, place)
726         } else {
727             self.use_ecx(|this| this.ecx.eval_rvalue_into_place(rvalue, place))
728         }
729     }
730
731     // Attempt to use albegraic identities to eliminate constant expressions
732     fn eval_rvalue_with_identities(
733         &mut self,
734         rvalue: &Rvalue<'tcx>,
735         place: Place<'tcx>,
736     ) -> Option<()> {
737         self.use_ecx(|this| {
738             match rvalue {
739                 Rvalue::BinaryOp(op, box (left, right))
740                 | Rvalue::CheckedBinaryOp(op, box (left, right)) => {
741                     let l = this.ecx.eval_operand(left, None);
742                     let r = this.ecx.eval_operand(right, None);
743
744                     let const_arg = match (l, r) {
745                         (Ok(ref x), Err(_)) | (Err(_), Ok(ref x)) => this.ecx.read_immediate(x)?,
746                         (Err(e), Err(_)) => return Err(e),
747                         (Ok(_), Ok(_)) => {
748                             this.ecx.eval_rvalue_into_place(rvalue, place)?;
749                             return Ok(());
750                         }
751                     };
752
753                     let arg_value =
754                         this.ecx.force_bits(const_arg.to_scalar()?, const_arg.layout.size)?;
755                     let dest = this.ecx.eval_place(place)?;
756
757                     match op {
758                         BinOp::BitAnd => {
759                             if arg_value == 0 {
760                                 this.ecx.write_immediate(*const_arg, &dest)?;
761                             }
762                         }
763                         BinOp::BitOr => {
764                             if arg_value == const_arg.layout.size.truncate(u128::MAX)
765                                 || (const_arg.layout.ty.is_bool() && arg_value == 1)
766                             {
767                                 this.ecx.write_immediate(*const_arg, &dest)?;
768                             }
769                         }
770                         BinOp::Mul => {
771                             if const_arg.layout.ty.is_integral() && arg_value == 0 {
772                                 if let Rvalue::CheckedBinaryOp(_, _) = rvalue {
773                                     let val = Immediate::ScalarPair(
774                                         const_arg.to_scalar()?.into(),
775                                         Scalar::from_bool(false).into(),
776                                     );
777                                     this.ecx.write_immediate(val, &dest)?;
778                                 } else {
779                                     this.ecx.write_immediate(*const_arg, &dest)?;
780                                 }
781                             }
782                         }
783                         _ => {
784                             this.ecx.eval_rvalue_into_place(rvalue, place)?;
785                         }
786                     }
787                 }
788                 _ => {
789                     this.ecx.eval_rvalue_into_place(rvalue, place)?;
790                 }
791             }
792
793             Ok(())
794         })
795     }
796
797     /// Creates a new `Operand::Constant` from a `Scalar` value
798     fn operand_from_scalar(&self, scalar: Scalar, ty: Ty<'tcx>, span: Span) -> Operand<'tcx> {
799         Operand::Constant(Box::new(Constant {
800             span,
801             user_ty: None,
802             literal: ty::Const::from_scalar(self.tcx, scalar, ty).into(),
803         }))
804     }
805
806     fn replace_with_const(
807         &mut self,
808         rval: &mut Rvalue<'tcx>,
809         value: &OpTy<'tcx>,
810         source_info: SourceInfo,
811     ) {
812         if let Rvalue::Use(Operand::Constant(c)) = rval {
813             match c.literal {
814                 ConstantKind::Ty(c) if matches!(c.val, ConstKind::Unevaluated(..)) => {}
815                 _ => {
816                     trace!("skipping replace of Rvalue::Use({:?} because it is already a const", c);
817                     return;
818                 }
819             }
820         }
821
822         trace!("attempting to replace {:?} with {:?}", rval, value);
823         if let Err(e) = self.ecx.const_validate_operand(
824             value,
825             vec![],
826             // FIXME: is ref tracking too expensive?
827             // FIXME: what is the point of ref tracking if we do not even check the tracked refs?
828             &mut interpret::RefTracking::empty(),
829             CtfeValidationMode::Regular,
830         ) {
831             trace!("validation error, attempt failed: {:?}", e);
832             return;
833         }
834
835         // FIXME> figure out what to do when try_read_immediate fails
836         let imm = self.use_ecx(|this| this.ecx.try_read_immediate(value));
837
838         if let Some(Ok(imm)) = imm {
839             match *imm {
840                 interpret::Immediate::Scalar(ScalarMaybeUninit::Scalar(scalar)) => {
841                     *rval = Rvalue::Use(self.operand_from_scalar(
842                         scalar,
843                         value.layout.ty,
844                         source_info.span,
845                     ));
846                 }
847                 Immediate::ScalarPair(
848                     ScalarMaybeUninit::Scalar(_),
849                     ScalarMaybeUninit::Scalar(_),
850                 ) => {
851                     // Found a value represented as a pair. For now only do const-prop if the type
852                     // of `rvalue` is also a tuple with two scalars.
853                     // FIXME: enable the general case stated above ^.
854                     let ty = &value.layout.ty;
855                     // Only do it for tuples
856                     if let ty::Tuple(substs) = ty.kind() {
857                         // Only do it if tuple is also a pair with two scalars
858                         if substs.len() == 2 {
859                             let alloc = self.use_ecx(|this| {
860                                 let ty1 = substs[0].expect_ty();
861                                 let ty2 = substs[1].expect_ty();
862                                 let ty_is_scalar = |ty| {
863                                     this.ecx.layout_of(ty).ok().map(|layout| layout.abi.is_scalar())
864                                         == Some(true)
865                                 };
866                                 if ty_is_scalar(ty1) && ty_is_scalar(ty2) {
867                                     let alloc = this
868                                         .ecx
869                                         .intern_with_temp_alloc(value.layout, |ecx, dest| {
870                                             ecx.write_immediate_to_mplace(*imm, dest)
871                                         })
872                                         .unwrap();
873                                     Ok(Some(alloc))
874                                 } else {
875                                     Ok(None)
876                                 }
877                             });
878
879                             if let Some(Some(alloc)) = alloc {
880                                 // Assign entire constant in a single statement.
881                                 // We can't use aggregates, as we run after the aggregate-lowering `MirPhase`.
882                                 *rval = Rvalue::Use(Operand::Constant(Box::new(Constant {
883                                     span: source_info.span,
884                                     user_ty: None,
885                                     literal: self
886                                         .ecx
887                                         .tcx
888                                         .mk_const(ty::Const {
889                                             ty,
890                                             val: ty::ConstKind::Value(ConstValue::ByRef {
891                                                 alloc,
892                                                 offset: Size::ZERO,
893                                             }),
894                                         })
895                                         .into(),
896                                 })));
897                             }
898                         }
899                     }
900                 }
901                 // Scalars or scalar pairs that contain undef values are assumed to not have
902                 // successfully evaluated and are thus not propagated.
903                 _ => {}
904             }
905         }
906     }
907
908     /// Returns `true` if and only if this `op` should be const-propagated into.
909     fn should_const_prop(&mut self, op: &OpTy<'tcx>) -> bool {
910         let mir_opt_level = self.tcx.sess.mir_opt_level();
911
912         if mir_opt_level == 0 {
913             return false;
914         }
915
916         if !self.tcx.consider_optimizing(|| format!("ConstantPropagation - OpTy: {:?}", op)) {
917             return false;
918         }
919
920         match **op {
921             interpret::Operand::Immediate(Immediate::Scalar(ScalarMaybeUninit::Scalar(s))) => {
922                 s.is_bits()
923             }
924             interpret::Operand::Immediate(Immediate::ScalarPair(
925                 ScalarMaybeUninit::Scalar(l),
926                 ScalarMaybeUninit::Scalar(r),
927             )) => l.is_bits() && r.is_bits(),
928             _ => false,
929         }
930     }
931 }
932
933 /// The mode that `ConstProp` is allowed to run in for a given `Local`.
934 #[derive(Clone, Copy, Debug, PartialEq)]
935 enum ConstPropMode {
936     /// The `Local` can be propagated into and reads of this `Local` can also be propagated.
937     FullConstProp,
938     /// The `Local` can only be propagated into and from its own block.
939     OnlyInsideOwnBlock,
940     /// The `Local` can be propagated into but reads cannot be propagated.
941     OnlyPropagateInto,
942     /// The `Local` cannot be part of propagation at all. Any statement
943     /// referencing it either for reading or writing will not get propagated.
944     NoPropagation,
945 }
946
947 struct CanConstProp {
948     can_const_prop: IndexVec<Local, ConstPropMode>,
949     // False at the beginning. Once set, no more assignments are allowed to that local.
950     found_assignment: BitSet<Local>,
951     // Cache of locals' information
952     local_kinds: IndexVec<Local, LocalKind>,
953 }
954
955 impl CanConstProp {
956     /// Returns true if `local` can be propagated
957     fn check(
958         tcx: TyCtxt<'tcx>,
959         param_env: ParamEnv<'tcx>,
960         body: &Body<'tcx>,
961     ) -> IndexVec<Local, ConstPropMode> {
962         let mut cpv = CanConstProp {
963             can_const_prop: IndexVec::from_elem(ConstPropMode::FullConstProp, &body.local_decls),
964             found_assignment: BitSet::new_empty(body.local_decls.len()),
965             local_kinds: IndexVec::from_fn_n(
966                 |local| body.local_kind(local),
967                 body.local_decls.len(),
968             ),
969         };
970         for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
971             let ty = body.local_decls[local].ty;
972             match tcx.layout_of(param_env.and(ty)) {
973                 Ok(layout) if layout.size < Size::from_bytes(MAX_ALLOC_LIMIT) => {}
974                 // Either the layout fails to compute, then we can't use this local anyway
975                 // or the local is too large, then we don't want to.
976                 _ => {
977                     *val = ConstPropMode::NoPropagation;
978                     continue;
979                 }
980             }
981             // Cannot use args at all
982             // Cannot use locals because if x < y { y - x } else { x - y } would
983             //        lint for x != y
984             // FIXME(oli-obk): lint variables until they are used in a condition
985             // FIXME(oli-obk): lint if return value is constant
986             if cpv.local_kinds[local] == LocalKind::Arg {
987                 *val = ConstPropMode::OnlyPropagateInto;
988                 trace!(
989                     "local {:?} can't be const propagated because it's a function argument",
990                     local
991                 );
992             } else if cpv.local_kinds[local] == LocalKind::Var {
993                 *val = ConstPropMode::OnlyInsideOwnBlock;
994                 trace!(
995                     "local {:?} will only be propagated inside its block, because it's a user variable",
996                     local
997                 );
998             }
999         }
1000         cpv.visit_body(&body);
1001         cpv.can_const_prop
1002     }
1003 }
1004
1005 impl<'tcx> Visitor<'tcx> for CanConstProp {
1006     fn visit_local(&mut self, &local: &Local, context: PlaceContext, _: Location) {
1007         use rustc_middle::mir::visit::PlaceContext::*;
1008         match context {
1009             // Projections are fine, because `&mut foo.x` will be caught by
1010             // `MutatingUseContext::Borrow` elsewhere.
1011             MutatingUse(MutatingUseContext::Projection)
1012             // These are just stores, where the storing is not propagatable, but there may be later
1013             // mutations of the same local via `Store`
1014             | MutatingUse(MutatingUseContext::Call)
1015             // Actual store that can possibly even propagate a value
1016             | MutatingUse(MutatingUseContext::Store) => {
1017                 if !self.found_assignment.insert(local) {
1018                     match &mut self.can_const_prop[local] {
1019                         // If the local can only get propagated in its own block, then we don't have
1020                         // to worry about multiple assignments, as we'll nuke the const state at the
1021                         // end of the block anyway, and inside the block we overwrite previous
1022                         // states as applicable.
1023                         ConstPropMode::OnlyInsideOwnBlock => {}
1024                         ConstPropMode::NoPropagation => {}
1025                         ConstPropMode::OnlyPropagateInto => {}
1026                         other @ ConstPropMode::FullConstProp => {
1027                             trace!(
1028                                 "local {:?} can't be propagated because of multiple assignments. Previous state: {:?}",
1029                                 local, other,
1030                             );
1031                             *other = ConstPropMode::OnlyInsideOwnBlock;
1032                         }
1033                     }
1034                 }
1035             }
1036             // Reading constants is allowed an arbitrary number of times
1037             NonMutatingUse(NonMutatingUseContext::Copy)
1038             | NonMutatingUse(NonMutatingUseContext::Move)
1039             | NonMutatingUse(NonMutatingUseContext::Inspect)
1040             | NonMutatingUse(NonMutatingUseContext::Projection)
1041             | NonUse(_) => {}
1042
1043             // These could be propagated with a smarter analysis or just some careful thinking about
1044             // whether they'd be fine right now.
1045             MutatingUse(MutatingUseContext::AsmOutput)
1046             | MutatingUse(MutatingUseContext::Yield)
1047             | MutatingUse(MutatingUseContext::Drop)
1048             | MutatingUse(MutatingUseContext::Retag)
1049             // These can't ever be propagated under any scheme, as we can't reason about indirect
1050             // mutation.
1051             | NonMutatingUse(NonMutatingUseContext::SharedBorrow)
1052             | NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
1053             | NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
1054             | NonMutatingUse(NonMutatingUseContext::AddressOf)
1055             | MutatingUse(MutatingUseContext::Borrow)
1056             | MutatingUse(MutatingUseContext::AddressOf) => {
1057                 trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
1058                 self.can_const_prop[local] = ConstPropMode::NoPropagation;
1059             }
1060         }
1061     }
1062 }
1063
1064 impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> {
1065     fn tcx(&self) -> TyCtxt<'tcx> {
1066         self.tcx
1067     }
1068
1069     fn visit_body(&mut self, body: &mut Body<'tcx>) {
1070         for (bb, data) in body.basic_blocks_mut().iter_enumerated_mut() {
1071             self.visit_basic_block_data(bb, data);
1072         }
1073     }
1074
1075     fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
1076         self.super_operand(operand, location);
1077
1078         // Only const prop copies and moves on `mir_opt_level=3` as doing so
1079         // currently slightly increases compile time in some cases.
1080         if self.tcx.sess.mir_opt_level() >= 3 {
1081             self.propagate_operand(operand)
1082         }
1083     }
1084
1085     fn visit_constant(&mut self, constant: &mut Constant<'tcx>, location: Location) {
1086         trace!("visit_constant: {:?}", constant);
1087         self.super_constant(constant, location);
1088         self.eval_constant(constant, self.source_info.unwrap());
1089     }
1090
1091     fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
1092         trace!("visit_statement: {:?}", statement);
1093         let source_info = statement.source_info;
1094         self.source_info = Some(source_info);
1095         if let StatementKind::Assign(box (place, ref mut rval)) = statement.kind {
1096             let can_const_prop = self.ecx.machine.can_const_prop[place.local];
1097             if let Some(()) = self.const_prop(rval, source_info, place) {
1098                 // This will return None if the above `const_prop` invocation only "wrote" a
1099                 // type whose creation requires no write. E.g. a generator whose initial state
1100                 // consists solely of uninitialized memory (so it doesn't capture any locals).
1101                 if let Some(ref value) = self.get_const(place) {
1102                     if self.should_const_prop(value) {
1103                         trace!("replacing {:?} with {:?}", rval, value);
1104                         self.replace_with_const(rval, value, source_info);
1105                         if can_const_prop == ConstPropMode::FullConstProp
1106                             || can_const_prop == ConstPropMode::OnlyInsideOwnBlock
1107                         {
1108                             trace!("propagated into {:?}", place);
1109                         }
1110                     }
1111                 }
1112                 match can_const_prop {
1113                     ConstPropMode::OnlyInsideOwnBlock => {
1114                         trace!(
1115                             "found local restricted to its block. \
1116                                 Will remove it from const-prop after block is finished. Local: {:?}",
1117                             place.local
1118                         );
1119                     }
1120                     ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
1121                         trace!("can't propagate into {:?}", place);
1122                         if place.local != RETURN_PLACE {
1123                             Self::remove_const(&mut self.ecx, place.local);
1124                         }
1125                     }
1126                     ConstPropMode::FullConstProp => {}
1127                 }
1128             } else {
1129                 // Const prop failed, so erase the destination, ensuring that whatever happens
1130                 // from here on, does not know about the previous value.
1131                 // This is important in case we have
1132                 // ```rust
1133                 // let mut x = 42;
1134                 // x = SOME_MUTABLE_STATIC;
1135                 // // x must now be uninit
1136                 // ```
1137                 // FIXME: we overzealously erase the entire local, because that's easier to
1138                 // implement.
1139                 trace!(
1140                     "propagation into {:?} failed.
1141                         Nuking the entire site from orbit, it's the only way to be sure",
1142                     place,
1143                 );
1144                 Self::remove_const(&mut self.ecx, place.local);
1145             }
1146         } else {
1147             match statement.kind {
1148                 StatementKind::SetDiscriminant { ref place, .. } => {
1149                     match self.ecx.machine.can_const_prop[place.local] {
1150                         ConstPropMode::FullConstProp | ConstPropMode::OnlyInsideOwnBlock => {
1151                             if self.use_ecx(|this| this.ecx.statement(statement)).is_some() {
1152                                 trace!("propped discriminant into {:?}", place);
1153                             } else {
1154                                 Self::remove_const(&mut self.ecx, place.local);
1155                             }
1156                         }
1157                         ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
1158                             Self::remove_const(&mut self.ecx, place.local);
1159                         }
1160                     }
1161                 }
1162                 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
1163                     let frame = self.ecx.frame_mut();
1164                     frame.locals[local].value =
1165                         if let StatementKind::StorageLive(_) = statement.kind {
1166                             LocalValue::Uninitialized
1167                         } else {
1168                             LocalValue::Dead
1169                         };
1170                 }
1171                 _ => {}
1172             }
1173         }
1174
1175         self.super_statement(statement, location);
1176     }
1177
1178     fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
1179         let source_info = terminator.source_info;
1180         self.source_info = Some(source_info);
1181         self.super_terminator(terminator, location);
1182         match &mut terminator.kind {
1183             TerminatorKind::Assert { expected, ref msg, ref mut cond, .. } => {
1184                 if let Some(ref value) = self.eval_operand(&cond, source_info) {
1185                     trace!("assertion on {:?} should be {:?}", value, expected);
1186                     let expected = ScalarMaybeUninit::from(Scalar::from_bool(*expected));
1187                     let value_const = self.ecx.read_scalar(&value).unwrap();
1188                     if expected != value_const {
1189                         enum DbgVal<T> {
1190                             Val(T),
1191                             Underscore,
1192                         }
1193                         impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
1194                             fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1195                                 match self {
1196                                     Self::Val(val) => val.fmt(fmt),
1197                                     Self::Underscore => fmt.write_str("_"),
1198                                 }
1199                             }
1200                         }
1201                         let mut eval_to_int = |op| {
1202                             // This can be `None` if the lhs wasn't const propagated and we just
1203                             // triggered the assert on the value of the rhs.
1204                             match self.eval_operand(op, source_info) {
1205                                 Some(op) => DbgVal::Val(
1206                                     self.ecx.read_immediate(&op).unwrap().to_const_int(),
1207                                 ),
1208                                 None => DbgVal::Underscore,
1209                             }
1210                         };
1211                         let msg = match msg {
1212                             AssertKind::DivisionByZero(op) => {
1213                                 Some(AssertKind::DivisionByZero(eval_to_int(op)))
1214                             }
1215                             AssertKind::RemainderByZero(op) => {
1216                                 Some(AssertKind::RemainderByZero(eval_to_int(op)))
1217                             }
1218                             AssertKind::BoundsCheck { ref len, ref index } => {
1219                                 let len = eval_to_int(len);
1220                                 let index = eval_to_int(index);
1221                                 Some(AssertKind::BoundsCheck { len, index })
1222                             }
1223                             // Overflow is are already covered by checks on the binary operators.
1224                             AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => None,
1225                             // Need proper const propagator for these.
1226                             _ => None,
1227                         };
1228                         // Poison all places this operand references so that further code
1229                         // doesn't use the invalid value
1230                         match cond {
1231                             Operand::Move(ref place) | Operand::Copy(ref place) => {
1232                                 Self::remove_const(&mut self.ecx, place.local);
1233                             }
1234                             Operand::Constant(_) => {}
1235                         }
1236                         if let Some(msg) = msg {
1237                             self.report_assert_as_lint(
1238                                 lint::builtin::UNCONDITIONAL_PANIC,
1239                                 source_info,
1240                                 "this operation will panic at runtime",
1241                                 msg,
1242                             );
1243                         }
1244                     } else {
1245                         if self.should_const_prop(value) {
1246                             if let ScalarMaybeUninit::Scalar(scalar) = value_const {
1247                                 *cond = self.operand_from_scalar(
1248                                     scalar,
1249                                     self.tcx.types.bool,
1250                                     source_info.span,
1251                                 );
1252                             }
1253                         }
1254                     }
1255                 }
1256             }
1257             TerminatorKind::SwitchInt { ref mut discr, .. } => {
1258                 // FIXME: This is currently redundant with `visit_operand`, but sadly
1259                 // always visiting operands currently causes a perf regression in LLVM codegen, so
1260                 // `visit_operand` currently only runs for propagates places for `mir_opt_level=4`.
1261                 self.propagate_operand(discr)
1262             }
1263             // None of these have Operands to const-propagate.
1264             TerminatorKind::Goto { .. }
1265             | TerminatorKind::Resume
1266             | TerminatorKind::Abort
1267             | TerminatorKind::Return
1268             | TerminatorKind::Unreachable
1269             | TerminatorKind::Drop { .. }
1270             | TerminatorKind::DropAndReplace { .. }
1271             | TerminatorKind::Yield { .. }
1272             | TerminatorKind::GeneratorDrop
1273             | TerminatorKind::FalseEdge { .. }
1274             | TerminatorKind::FalseUnwind { .. }
1275             | TerminatorKind::InlineAsm { .. } => {}
1276             // Every argument in our function calls have already been propagated in `visit_operand`.
1277             //
1278             // NOTE: because LLVM codegen gives slight performance regressions with it, so this is
1279             // gated on `mir_opt_level=3`.
1280             TerminatorKind::Call { .. } => {}
1281         }
1282
1283         // We remove all Locals which are restricted in propagation to their containing blocks and
1284         // which were modified in the current block.
1285         // Take it out of the ecx so we can get a mutable reference to the ecx for `remove_const`.
1286         let mut locals = std::mem::take(&mut self.ecx.machine.written_only_inside_own_block_locals);
1287         for &local in locals.iter() {
1288             Self::remove_const(&mut self.ecx, local);
1289         }
1290         locals.clear();
1291         // Put it back so we reuse the heap of the storage
1292         self.ecx.machine.written_only_inside_own_block_locals = locals;
1293         if cfg!(debug_assertions) {
1294             // Ensure we are correctly erasing locals with the non-debug-assert logic.
1295             for local in self.ecx.machine.only_propagate_inside_block_locals.iter() {
1296                 assert!(
1297                     self.get_const(local.into()).is_none()
1298                         || self
1299                             .layout_of(self.local_decls[local].ty)
1300                             .map_or(true, |layout| layout.is_zst())
1301                 )
1302             }
1303         }
1304     }
1305 }