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