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