]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/const_prop.rs
Auto merge of #75488 - ssomers:btree_revert_75257, r=Mark-Simulacrum
[rust.git] / src / librustc_mir / 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::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     AggregateKind, AssertKind, BasicBlock, BinOp, Body, ClearCrossCrate, Constant, Local,
18     LocalDecl, LocalKind, Location, Operand, Place, Rvalue, SourceInfo, SourceScope,
19     SourceScopeData, Statement, StatementKind, Terminator, TerminatorKind, UnOp, RETURN_PLACE,
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, Frame, ImmTy, Immediate, InterpCx,
32     LocalState, LocalValue, MemPlace, Memory, MemoryKind, OpTy, Operand as InterpOperand, PlaceTy,
33     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(one),
828                     ScalarMaybeUninit::Scalar(two),
829                 ) => {
830                     // Found a value represented as a pair. For now only do cont-prop if type of
831                     // Rvalue is also a pair with two scalars. The more general case is more
832                     // complicated to implement so we'll do it later.
833                     // FIXME: implement the general case stated above ^.
834                     let ty = &value.layout.ty.kind;
835                     // Only do it for tuples
836                     if let ty::Tuple(substs) = ty {
837                         // Only do it if tuple is also a pair with two scalars
838                         if substs.len() == 2 {
839                             let opt_ty1_ty2 = self.use_ecx(|this| {
840                                 let ty1 = substs[0].expect_ty();
841                                 let ty2 = substs[1].expect_ty();
842                                 let ty_is_scalar = |ty| {
843                                     this.ecx.layout_of(ty).ok().map(|layout| layout.abi.is_scalar())
844                                         == Some(true)
845                                 };
846                                 if ty_is_scalar(ty1) && ty_is_scalar(ty2) {
847                                     Ok(Some((ty1, ty2)))
848                                 } else {
849                                     Ok(None)
850                                 }
851                             });
852
853                             if let Some(Some((ty1, ty2))) = opt_ty1_ty2 {
854                                 *rval = Rvalue::Aggregate(
855                                     Box::new(AggregateKind::Tuple),
856                                     vec![
857                                         self.operand_from_scalar(one, ty1, source_info.span),
858                                         self.operand_from_scalar(two, ty2, source_info.span),
859                                     ],
860                                 );
861                             }
862                         }
863                     }
864                 }
865                 _ => {}
866             }
867         }
868     }
869
870     /// Returns `true` if and only if this `op` should be const-propagated into.
871     fn should_const_prop(&mut self, op: OpTy<'tcx>) -> bool {
872         let mir_opt_level = self.tcx.sess.opts.debugging_opts.mir_opt_level;
873
874         if mir_opt_level == 0 {
875             return false;
876         }
877
878         match *op {
879             interpret::Operand::Immediate(Immediate::Scalar(ScalarMaybeUninit::Scalar(s))) => {
880                 s.is_bits()
881             }
882             interpret::Operand::Immediate(Immediate::ScalarPair(
883                 ScalarMaybeUninit::Scalar(l),
884                 ScalarMaybeUninit::Scalar(r),
885             )) => l.is_bits() && r.is_bits(),
886             _ => false,
887         }
888     }
889 }
890
891 /// The mode that `ConstProp` is allowed to run in for a given `Local`.
892 #[derive(Clone, Copy, Debug, PartialEq)]
893 enum ConstPropMode {
894     /// The `Local` can be propagated into and reads of this `Local` can also be propagated.
895     FullConstProp,
896     /// The `Local` can only be propagated into and from its own block.
897     OnlyInsideOwnBlock,
898     /// The `Local` can be propagated into but reads cannot be propagated.
899     OnlyPropagateInto,
900     /// The `Local` cannot be part of propagation at all. Any statement
901     /// referencing it either for reading or writing will not get propagated.
902     NoPropagation,
903 }
904
905 struct CanConstProp {
906     can_const_prop: IndexVec<Local, ConstPropMode>,
907     // False at the beginning. Once set, no more assignments are allowed to that local.
908     found_assignment: BitSet<Local>,
909     // Cache of locals' information
910     local_kinds: IndexVec<Local, LocalKind>,
911 }
912
913 impl CanConstProp {
914     /// Returns true if `local` can be propagated
915     fn check(
916         tcx: TyCtxt<'tcx>,
917         param_env: ParamEnv<'tcx>,
918         body: &Body<'tcx>,
919     ) -> IndexVec<Local, ConstPropMode> {
920         let mut cpv = CanConstProp {
921             can_const_prop: IndexVec::from_elem(ConstPropMode::FullConstProp, &body.local_decls),
922             found_assignment: BitSet::new_empty(body.local_decls.len()),
923             local_kinds: IndexVec::from_fn_n(
924                 |local| body.local_kind(local),
925                 body.local_decls.len(),
926             ),
927         };
928         for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
929             let ty = body.local_decls[local].ty;
930             match tcx.layout_of(param_env.and(ty)) {
931                 Ok(layout) if layout.size < Size::from_bytes(MAX_ALLOC_LIMIT) => {}
932                 // Either the layout fails to compute, then we can't use this local anyway
933                 // or the local is too large, then we don't want to.
934                 _ => {
935                     *val = ConstPropMode::NoPropagation;
936                     continue;
937                 }
938             }
939             // Cannot use args at all
940             // Cannot use locals because if x < y { y - x } else { x - y } would
941             //        lint for x != y
942             // FIXME(oli-obk): lint variables until they are used in a condition
943             // FIXME(oli-obk): lint if return value is constant
944             if cpv.local_kinds[local] == LocalKind::Arg {
945                 *val = ConstPropMode::OnlyPropagateInto;
946                 trace!(
947                     "local {:?} can't be const propagated because it's a function argument",
948                     local
949                 );
950             } else if cpv.local_kinds[local] == LocalKind::Var {
951                 *val = ConstPropMode::OnlyInsideOwnBlock;
952                 trace!(
953                     "local {:?} will only be propagated inside its block, because it's a user variable",
954                     local
955                 );
956             }
957         }
958         cpv.visit_body(&body);
959         cpv.can_const_prop
960     }
961 }
962
963 impl<'tcx> Visitor<'tcx> for CanConstProp {
964     fn visit_local(&mut self, &local: &Local, context: PlaceContext, _: Location) {
965         use rustc_middle::mir::visit::PlaceContext::*;
966         match context {
967             // Projections are fine, because `&mut foo.x` will be caught by
968             // `MutatingUseContext::Borrow` elsewhere.
969             MutatingUse(MutatingUseContext::Projection)
970             // These are just stores, where the storing is not propagatable, but there may be later
971             // mutations of the same local via `Store`
972             | MutatingUse(MutatingUseContext::Call)
973             // Actual store that can possibly even propagate a value
974             | MutatingUse(MutatingUseContext::Store) => {
975                 if !self.found_assignment.insert(local) {
976                     match &mut self.can_const_prop[local] {
977                         // If the local can only get propagated in its own block, then we don't have
978                         // to worry about multiple assignments, as we'll nuke the const state at the
979                         // end of the block anyway, and inside the block we overwrite previous
980                         // states as applicable.
981                         ConstPropMode::OnlyInsideOwnBlock => {}
982                         ConstPropMode::NoPropagation => {}
983                         ConstPropMode::OnlyPropagateInto => {}
984                         other @ ConstPropMode::FullConstProp => {
985                             trace!(
986                                 "local {:?} can't be propagated because of multiple assignments. Previous state: {:?}",
987                                 local, other,
988                             );
989                             *other = ConstPropMode::OnlyInsideOwnBlock;
990                         }
991                     }
992                 }
993             }
994             // Reading constants is allowed an arbitrary number of times
995             NonMutatingUse(NonMutatingUseContext::Copy)
996             | NonMutatingUse(NonMutatingUseContext::Move)
997             | NonMutatingUse(NonMutatingUseContext::Inspect)
998             | NonMutatingUse(NonMutatingUseContext::Projection)
999             | NonUse(_) => {}
1000
1001             // These could be propagated with a smarter analysis or just some careful thinking about
1002             // whether they'd be fine right now.
1003             MutatingUse(MutatingUseContext::AsmOutput)
1004             | MutatingUse(MutatingUseContext::Yield)
1005             | MutatingUse(MutatingUseContext::Drop)
1006             | MutatingUse(MutatingUseContext::Retag)
1007             // These can't ever be propagated under any scheme, as we can't reason about indirect
1008             // mutation.
1009             | NonMutatingUse(NonMutatingUseContext::SharedBorrow)
1010             | NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
1011             | NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
1012             | NonMutatingUse(NonMutatingUseContext::AddressOf)
1013             | MutatingUse(MutatingUseContext::Borrow)
1014             | MutatingUse(MutatingUseContext::AddressOf) => {
1015                 trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
1016                 self.can_const_prop[local] = ConstPropMode::NoPropagation;
1017             }
1018         }
1019     }
1020 }
1021
1022 impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> {
1023     fn tcx(&self) -> TyCtxt<'tcx> {
1024         self.tcx
1025     }
1026
1027     fn visit_body(&mut self, body: &mut Body<'tcx>) {
1028         for (bb, data) in body.basic_blocks_mut().iter_enumerated_mut() {
1029             self.visit_basic_block_data(bb, data);
1030         }
1031     }
1032
1033     fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
1034         self.super_operand(operand, location);
1035
1036         // Only const prop copies and moves on `mir_opt_level=3` as doing so
1037         // currently increases compile time.
1038         if self.tcx.sess.opts.debugging_opts.mir_opt_level >= 3 {
1039             self.propagate_operand(operand)
1040         }
1041     }
1042
1043     fn visit_constant(&mut self, constant: &mut Constant<'tcx>, location: Location) {
1044         trace!("visit_constant: {:?}", constant);
1045         self.super_constant(constant, location);
1046         self.eval_constant(constant, self.source_info.unwrap());
1047     }
1048
1049     fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
1050         trace!("visit_statement: {:?}", statement);
1051         let source_info = statement.source_info;
1052         self.source_info = Some(source_info);
1053         if let StatementKind::Assign(box (place, ref mut rval)) = statement.kind {
1054             let can_const_prop = self.ecx.machine.can_const_prop[place.local];
1055             if let Some(()) = self.const_prop(rval, source_info, place) {
1056                 // This will return None if the above `const_prop` invocation only "wrote" a
1057                 // type whose creation requires no write. E.g. a generator whose initial state
1058                 // consists solely of uninitialized memory (so it doesn't capture any locals).
1059                 if let Some(value) = self.get_const(place) {
1060                     if self.should_const_prop(value) {
1061                         trace!("replacing {:?} with {:?}", rval, value);
1062                         self.replace_with_const(rval, value, source_info);
1063                         if can_const_prop == ConstPropMode::FullConstProp
1064                             || can_const_prop == ConstPropMode::OnlyInsideOwnBlock
1065                         {
1066                             trace!("propagated into {:?}", place);
1067                         }
1068                     }
1069                 }
1070                 match can_const_prop {
1071                     ConstPropMode::OnlyInsideOwnBlock => {
1072                         trace!(
1073                             "found local restricted to its block. \
1074                                 Will remove it from const-prop after block is finished. Local: {:?}",
1075                             place.local
1076                         );
1077                     }
1078                     ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
1079                         trace!("can't propagate into {:?}", place);
1080                         if place.local != RETURN_PLACE {
1081                             Self::remove_const(&mut self.ecx, place.local);
1082                         }
1083                     }
1084                     ConstPropMode::FullConstProp => {}
1085                 }
1086             } else {
1087                 // Const prop failed, so erase the destination, ensuring that whatever happens
1088                 // from here on, does not know about the previous value.
1089                 // This is important in case we have
1090                 // ```rust
1091                 // let mut x = 42;
1092                 // x = SOME_MUTABLE_STATIC;
1093                 // // x must now be uninit
1094                 // ```
1095                 // FIXME: we overzealously erase the entire local, because that's easier to
1096                 // implement.
1097                 trace!(
1098                     "propagation into {:?} failed.
1099                         Nuking the entire site from orbit, it's the only way to be sure",
1100                     place,
1101                 );
1102                 Self::remove_const(&mut self.ecx, place.local);
1103             }
1104         } else {
1105             match statement.kind {
1106                 StatementKind::SetDiscriminant { ref place, .. } => {
1107                     match self.ecx.machine.can_const_prop[place.local] {
1108                         ConstPropMode::FullConstProp | ConstPropMode::OnlyInsideOwnBlock => {
1109                             if self.use_ecx(|this| this.ecx.statement(statement)).is_some() {
1110                                 trace!("propped discriminant into {:?}", place);
1111                             } else {
1112                                 Self::remove_const(&mut self.ecx, place.local);
1113                             }
1114                         }
1115                         ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
1116                             Self::remove_const(&mut self.ecx, place.local);
1117                         }
1118                     }
1119                 }
1120                 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
1121                     let frame = self.ecx.frame_mut();
1122                     frame.locals[local].value =
1123                         if let StatementKind::StorageLive(_) = statement.kind {
1124                             LocalValue::Uninitialized
1125                         } else {
1126                             LocalValue::Dead
1127                         };
1128                 }
1129                 _ => {}
1130             }
1131         }
1132
1133         self.super_statement(statement, location);
1134     }
1135
1136     fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
1137         let source_info = terminator.source_info;
1138         self.source_info = Some(source_info);
1139         self.super_terminator(terminator, location);
1140         match &mut terminator.kind {
1141             TerminatorKind::Assert { expected, ref msg, ref mut cond, .. } => {
1142                 if let Some(value) = self.eval_operand(&cond, source_info) {
1143                     trace!("assertion on {:?} should be {:?}", value, expected);
1144                     let expected = ScalarMaybeUninit::from(Scalar::from_bool(*expected));
1145                     let value_const = self.ecx.read_scalar(value).unwrap();
1146                     if expected != value_const {
1147                         enum DbgVal<T> {
1148                             Val(T),
1149                             Underscore,
1150                         }
1151                         impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
1152                             fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1153                                 match self {
1154                                     Self::Val(val) => val.fmt(fmt),
1155                                     Self::Underscore => fmt.write_str("_"),
1156                                 }
1157                             }
1158                         }
1159                         let mut eval_to_int = |op| {
1160                             // This can be `None` if the lhs wasn't const propagated and we just
1161                             // triggered the assert on the value of the rhs.
1162                             match self.eval_operand(op, source_info) {
1163                                 Some(op) => {
1164                                     DbgVal::Val(self.ecx.read_immediate(op).unwrap().to_const_int())
1165                                 }
1166                                 None => DbgVal::Underscore,
1167                             }
1168                         };
1169                         let msg = match msg {
1170                             AssertKind::DivisionByZero(op) => {
1171                                 Some(AssertKind::DivisionByZero(eval_to_int(op)))
1172                             }
1173                             AssertKind::RemainderByZero(op) => {
1174                                 Some(AssertKind::RemainderByZero(eval_to_int(op)))
1175                             }
1176                             AssertKind::BoundsCheck { ref len, ref index } => {
1177                                 let len = eval_to_int(len);
1178                                 let index = eval_to_int(index);
1179                                 Some(AssertKind::BoundsCheck { len, index })
1180                             }
1181                             // Overflow is are already covered by checks on the binary operators.
1182                             AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => None,
1183                             // Need proper const propagator for these.
1184                             _ => None,
1185                         };
1186                         // Poison all places this operand references so that further code
1187                         // doesn't use the invalid value
1188                         match cond {
1189                             Operand::Move(ref place) | Operand::Copy(ref place) => {
1190                                 Self::remove_const(&mut self.ecx, place.local);
1191                             }
1192                             Operand::Constant(_) => {}
1193                         }
1194                         if let Some(msg) = msg {
1195                             self.report_assert_as_lint(
1196                                 lint::builtin::UNCONDITIONAL_PANIC,
1197                                 source_info,
1198                                 "this operation will panic at runtime",
1199                                 msg,
1200                             );
1201                         }
1202                     } else {
1203                         if self.should_const_prop(value) {
1204                             if let ScalarMaybeUninit::Scalar(scalar) = value_const {
1205                                 *cond = self.operand_from_scalar(
1206                                     scalar,
1207                                     self.tcx.types.bool,
1208                                     source_info.span,
1209                                 );
1210                             }
1211                         }
1212                     }
1213                 }
1214             }
1215             TerminatorKind::SwitchInt { ref mut discr, .. } => {
1216                 // FIXME: This is currently redundant with `visit_operand`, but sadly
1217                 // always visiting operands currently causes a perf regression in LLVM codegen, so
1218                 // `visit_operand` currently only runs for propagates places for `mir_opt_level=3`.
1219                 self.propagate_operand(discr)
1220             }
1221             // None of these have Operands to const-propagate.
1222             TerminatorKind::Goto { .. }
1223             | TerminatorKind::Resume
1224             | TerminatorKind::Abort
1225             | TerminatorKind::Return
1226             | TerminatorKind::Unreachable
1227             | TerminatorKind::Drop { .. }
1228             | TerminatorKind::DropAndReplace { .. }
1229             | TerminatorKind::Yield { .. }
1230             | TerminatorKind::GeneratorDrop
1231             | TerminatorKind::FalseEdge { .. }
1232             | TerminatorKind::FalseUnwind { .. }
1233             | TerminatorKind::InlineAsm { .. } => {}
1234             // Every argument in our function calls have already been propagated in `visit_operand`.
1235             //
1236             // NOTE: because LLVM codegen gives performance regressions with it, so this is gated
1237             // on `mir_opt_level=3`.
1238             TerminatorKind::Call { .. } => {}
1239         }
1240
1241         // We remove all Locals which are restricted in propagation to their containing blocks and
1242         // which were modified in the current block.
1243         // Take it out of the ecx so we can get a mutable reference to the ecx for `remove_const`.
1244         let mut locals = std::mem::take(&mut self.ecx.machine.written_only_inside_own_block_locals);
1245         for &local in locals.iter() {
1246             Self::remove_const(&mut self.ecx, local);
1247         }
1248         locals.clear();
1249         // Put it back so we reuse the heap of the storage
1250         self.ecx.machine.written_only_inside_own_block_locals = locals;
1251         if cfg!(debug_assertions) {
1252             // Ensure we are correctly erasing locals with the non-debug-assert logic.
1253             for local in self.ecx.machine.only_propagate_inside_block_locals.iter() {
1254                 assert!(
1255                     self.get_const(local.into()).is_none()
1256                         || self
1257                             .layout_of(self.local_decls[local].ty)
1258                             .map_or(true, |layout| layout.is_zst())
1259                 )
1260             }
1261         }
1262     }
1263 }