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