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