]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/const_prop_lint.rs
Merge commit 'e9d1a0a7b0b28dd422f1a790ccde532acafbf193' into sync_cg_clif-2022-08-24
[rust.git] / compiler / rustc_mir_transform / src / const_prop_lint.rs
1 //! Propagates constants for early reporting of statically known
2 //! assertion failures
3
4 use crate::const_prop::CanConstProp;
5 use crate::const_prop::ConstPropMachine;
6 use crate::const_prop::ConstPropMode;
7 use crate::MirLint;
8 use rustc_const_eval::const_eval::ConstEvalErr;
9 use rustc_const_eval::interpret::{
10     self, InterpCx, InterpResult, LocalState, LocalValue, MemoryKind, OpTy, Scalar,
11     ScalarMaybeUninit, StackPopCleanup,
12 };
13 use rustc_hir::def::DefKind;
14 use rustc_hir::HirId;
15 use rustc_index::bit_set::BitSet;
16 use rustc_index::vec::IndexVec;
17 use rustc_middle::mir::visit::Visitor;
18 use rustc_middle::mir::{
19     AssertKind, BinOp, Body, Constant, ConstantKind, Local, LocalDecl, Location, Operand, Place,
20     Rvalue, SourceInfo, SourceScope, SourceScopeData, Statement, StatementKind, Terminator,
21     TerminatorKind, UnOp, RETURN_PLACE,
22 };
23 use rustc_middle::ty::layout::{LayoutError, LayoutOf, LayoutOfHelpers, TyAndLayout};
24 use rustc_middle::ty::subst::{InternalSubsts, Subst};
25 use rustc_middle::ty::{
26     self, ConstInt, ConstKind, Instance, ParamEnv, ScalarInt, Ty, TyCtxt, TypeVisitable,
27 };
28 use rustc_session::lint;
29 use rustc_span::Span;
30 use rustc_target::abi::{HasDataLayout, Size, TargetDataLayout};
31 use rustc_trait_selection::traits;
32 use std::cell::Cell;
33
34 /// The maximum number of bytes that we'll allocate space for a local or the return value.
35 /// Needed for #66397, because otherwise we eval into large places and that can cause OOM or just
36 /// Severely regress performance.
37 const MAX_ALLOC_LIMIT: u64 = 1024;
38 pub struct ConstProp;
39
40 impl<'tcx> MirLint<'tcx> for ConstProp {
41     fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
42         // will be evaluated by miri and produce its errors there
43         if body.source.promoted.is_some() {
44             return;
45         }
46
47         let def_id = body.source.def_id().expect_local();
48         let is_fn_like = tcx.def_kind(def_id).is_fn_like();
49         let is_assoc_const = tcx.def_kind(def_id) == DefKind::AssocConst;
50
51         // Only run const prop on functions, methods, closures and associated constants
52         if !is_fn_like && !is_assoc_const {
53             // skip anon_const/statics/consts because they'll be evaluated by miri anyway
54             trace!("ConstProp skipped for {:?}", def_id);
55             return;
56         }
57
58         let is_generator = tcx.type_of(def_id.to_def_id()).is_generator();
59         // FIXME(welseywiser) const prop doesn't work on generators because of query cycles
60         // computing their layout.
61         if is_generator {
62             trace!("ConstProp skipped for generator {:?}", def_id);
63             return;
64         }
65
66         // Check if it's even possible to satisfy the 'where' clauses
67         // for this item.
68         // This branch will never be taken for any normal function.
69         // However, it's possible to `#!feature(trivial_bounds)]` to write
70         // a function with impossible to satisfy clauses, e.g.:
71         // `fn foo() where String: Copy {}`
72         //
73         // We don't usually need to worry about this kind of case,
74         // since we would get a compilation error if the user tried
75         // to call it. However, since we can do const propagation
76         // even without any calls to the function, we need to make
77         // sure that it even makes sense to try to evaluate the body.
78         // If there are unsatisfiable where clauses, then all bets are
79         // off, and we just give up.
80         //
81         // We manually filter the predicates, skipping anything that's not
82         // "global". We are in a potentially generic context
83         // (e.g. we are evaluating a function without substituting generic
84         // parameters, so this filtering serves two purposes:
85         //
86         // 1. We skip evaluating any predicates that we would
87         // never be able prove are unsatisfiable (e.g. `<T as Foo>`
88         // 2. We avoid trying to normalize predicates involving generic
89         // parameters (e.g. `<T as Foo>::MyItem`). This can confuse
90         // the normalization code (leading to cycle errors), since
91         // it's usually never invoked in this way.
92         let predicates = tcx
93             .predicates_of(def_id.to_def_id())
94             .predicates
95             .iter()
96             .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
97         if traits::impossible_predicates(
98             tcx,
99             traits::elaborate_predicates(tcx, predicates).map(|o| o.predicate).collect(),
100         ) {
101             trace!("ConstProp skipped for {:?}: found unsatisfiable predicates", def_id);
102             return;
103         }
104
105         trace!("ConstProp starting for {:?}", def_id);
106
107         let dummy_body = &Body::new(
108             body.source,
109             body.basic_blocks().clone(),
110             body.source_scopes.clone(),
111             body.local_decls.clone(),
112             Default::default(),
113             body.arg_count,
114             Default::default(),
115             body.span,
116             body.generator_kind(),
117             body.tainted_by_errors,
118         );
119
120         // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
121         // constants, instead of just checking for const-folding succeeding.
122         // That would require a uniform one-def no-mutation analysis
123         // and RPO (or recursing when needing the value of a local).
124         let mut optimization_finder = ConstPropagator::new(body, dummy_body, tcx);
125         optimization_finder.visit_body(body);
126
127         trace!("ConstProp done for {:?}", def_id);
128     }
129 }
130
131 /// Finds optimization opportunities on the MIR.
132 struct ConstPropagator<'mir, 'tcx> {
133     ecx: InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>,
134     tcx: TyCtxt<'tcx>,
135     param_env: ParamEnv<'tcx>,
136     source_scopes: &'mir IndexVec<SourceScope, SourceScopeData<'tcx>>,
137     local_decls: &'mir IndexVec<Local, LocalDecl<'tcx>>,
138     // Because we have `MutVisitor` we can't obtain the `SourceInfo` from a `Location`. So we store
139     // the last known `SourceInfo` here and just keep revisiting it.
140     source_info: Option<SourceInfo>,
141 }
142
143 impl<'tcx> LayoutOfHelpers<'tcx> for ConstPropagator<'_, 'tcx> {
144     type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
145
146     #[inline]
147     fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
148         err
149     }
150 }
151
152 impl HasDataLayout for ConstPropagator<'_, '_> {
153     #[inline]
154     fn data_layout(&self) -> &TargetDataLayout {
155         &self.tcx.data_layout
156     }
157 }
158
159 impl<'tcx> ty::layout::HasTyCtxt<'tcx> for ConstPropagator<'_, 'tcx> {
160     #[inline]
161     fn tcx(&self) -> TyCtxt<'tcx> {
162         self.tcx
163     }
164 }
165
166 impl<'tcx> ty::layout::HasParamEnv<'tcx> for ConstPropagator<'_, 'tcx> {
167     #[inline]
168     fn param_env(&self) -> ty::ParamEnv<'tcx> {
169         self.param_env
170     }
171 }
172
173 impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
174     fn new(
175         body: &Body<'tcx>,
176         dummy_body: &'mir Body<'tcx>,
177         tcx: TyCtxt<'tcx>,
178     ) -> ConstPropagator<'mir, 'tcx> {
179         let def_id = body.source.def_id();
180         let substs = &InternalSubsts::identity_for_item(tcx, def_id);
181         let param_env = tcx.param_env_reveal_all_normalized(def_id);
182
183         let can_const_prop = CanConstProp::check(tcx, param_env, body);
184         let mut only_propagate_inside_block_locals = BitSet::new_empty(can_const_prop.len());
185         for (l, mode) in can_const_prop.iter_enumerated() {
186             if *mode == ConstPropMode::OnlyInsideOwnBlock {
187                 only_propagate_inside_block_locals.insert(l);
188             }
189         }
190         let mut ecx = InterpCx::new(
191             tcx,
192             tcx.def_span(def_id),
193             param_env,
194             ConstPropMachine::new(only_propagate_inside_block_locals, can_const_prop),
195         );
196
197         let ret_layout = ecx
198             .layout_of(body.bound_return_ty().subst(tcx, substs))
199             .ok()
200             // Don't bother allocating memory for large values.
201             // I don't know how return types can seem to be unsized but this happens in the
202             // `type/type-unsatisfiable.rs` test.
203             .filter(|ret_layout| {
204                 !ret_layout.is_unsized() && ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT)
205             })
206             .unwrap_or_else(|| ecx.layout_of(tcx.types.unit).unwrap());
207
208         let ret = ecx
209             .allocate(ret_layout, MemoryKind::Stack)
210             .expect("couldn't perform small allocation")
211             .into();
212
213         ecx.push_stack_frame(
214             Instance::new(def_id, substs),
215             dummy_body,
216             &ret,
217             StackPopCleanup::Root { cleanup: false },
218         )
219         .expect("failed to push initial stack frame");
220
221         ConstPropagator {
222             ecx,
223             tcx,
224             param_env,
225             source_scopes: &dummy_body.source_scopes,
226             local_decls: &dummy_body.local_decls,
227             source_info: None,
228         }
229     }
230
231     fn get_const(&self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
232         let op = match self.ecx.eval_place_to_op(place, None) {
233             Ok(op) => op,
234             Err(e) => {
235                 trace!("get_const failed: {}", e);
236                 return None;
237             }
238         };
239
240         // Try to read the local as an immediate so that if it is representable as a scalar, we can
241         // handle it as such, but otherwise, just return the value as is.
242         Some(match self.ecx.read_immediate_raw(&op, /*force*/ false) {
243             Ok(Ok(imm)) => imm.into(),
244             _ => op,
245         })
246     }
247
248     /// Remove `local` from the pool of `Locals`. Allows writing to them,
249     /// but not reading from them anymore.
250     fn remove_const(ecx: &mut InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>, local: Local) {
251         ecx.frame_mut().locals[local] = LocalState {
252             value: LocalValue::Live(interpret::Operand::Immediate(interpret::Immediate::Uninit)),
253             layout: Cell::new(None),
254         };
255     }
256
257     fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
258         source_info.scope.lint_root(self.source_scopes)
259     }
260
261     fn use_ecx<F, T>(&mut self, source_info: SourceInfo, f: F) -> Option<T>
262     where
263         F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
264     {
265         // Overwrite the PC -- whatever the interpreter does to it does not make any sense anyway.
266         self.ecx.frame_mut().loc = Err(source_info.span);
267         match f(self) {
268             Ok(val) => Some(val),
269             Err(error) => {
270                 trace!("InterpCx operation failed: {:?}", error);
271                 // Some errors shouldn't come up because creating them causes
272                 // an allocation, which we should avoid. When that happens,
273                 // dedicated error variants should be introduced instead.
274                 assert!(
275                     !error.kind().formatted_string(),
276                     "const-prop encountered formatting error: {}",
277                     error
278                 );
279                 None
280             }
281         }
282     }
283
284     /// Returns the value, if any, of evaluating `c`.
285     fn eval_constant(&mut self, c: &Constant<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
286         // FIXME we need to revisit this for #67176
287         if c.needs_subst() {
288             return None;
289         }
290
291         match self.ecx.mir_const_to_op(&c.literal, None) {
292             Ok(op) => Some(op),
293             Err(error) => {
294                 let tcx = self.ecx.tcx.at(c.span);
295                 let err = ConstEvalErr::new(&self.ecx, error, Some(c.span));
296                 if let Some(lint_root) = self.lint_root(source_info) {
297                     let lint_only = match c.literal {
298                         ConstantKind::Ty(ct) => match ct.kind() {
299                             // Promoteds must lint and not error as the user didn't ask for them
300                             ConstKind::Unevaluated(ty::Unevaluated {
301                                 def: _,
302                                 substs: _,
303                                 promoted: Some(_),
304                             }) => true,
305                             // Out of backwards compatibility we cannot report hard errors in unused
306                             // generic functions using associated constants of the generic parameters.
307                             _ => c.literal.needs_subst(),
308                         },
309                         ConstantKind::Val(_, ty) => ty.needs_subst(),
310                     };
311                     if lint_only {
312                         // Out of backwards compatibility we cannot report hard errors in unused
313                         // generic functions using associated constants of the generic parameters.
314                         err.report_as_lint(tcx, "erroneous constant used", lint_root, Some(c.span));
315                     } else {
316                         err.report_as_error(tcx, "erroneous constant used");
317                     }
318                 } else {
319                     err.report_as_error(tcx, "erroneous constant used");
320                 }
321                 None
322             }
323         }
324     }
325
326     /// Returns the value, if any, of evaluating `place`.
327     fn eval_place(&mut self, place: Place<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
328         trace!("eval_place(place={:?})", place);
329         self.use_ecx(source_info, |this| this.ecx.eval_place_to_op(place, None))
330     }
331
332     /// Returns the value, if any, of evaluating `op`. Calls upon `eval_constant`
333     /// or `eval_place`, depending on the variant of `Operand` used.
334     fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
335         match *op {
336             Operand::Constant(ref c) => self.eval_constant(c, source_info),
337             Operand::Move(place) | Operand::Copy(place) => self.eval_place(place, source_info),
338         }
339     }
340
341     fn report_assert_as_lint(
342         &self,
343         lint: &'static lint::Lint,
344         source_info: SourceInfo,
345         message: &'static str,
346         panic: AssertKind<impl std::fmt::Debug>,
347     ) {
348         if let Some(lint_root) = self.lint_root(source_info) {
349             self.tcx.struct_span_lint_hir(lint, lint_root, source_info.span, |lint| {
350                 let mut err = lint.build(message);
351                 err.span_label(source_info.span, format!("{:?}", panic));
352                 err.emit();
353             });
354         }
355     }
356
357     fn check_unary_op(
358         &mut self,
359         op: UnOp,
360         arg: &Operand<'tcx>,
361         source_info: SourceInfo,
362     ) -> Option<()> {
363         if let (val, true) = self.use_ecx(source_info, |this| {
364             let val = this.ecx.read_immediate(&this.ecx.eval_operand(arg, None)?)?;
365             let (_res, overflow, _ty) = this.ecx.overflowing_unary_op(op, &val)?;
366             Ok((val, overflow))
367         })? {
368             // `AssertKind` only has an `OverflowNeg` variant, so make sure that is
369             // appropriate to use.
370             assert_eq!(op, UnOp::Neg, "Neg is the only UnOp that can overflow");
371             self.report_assert_as_lint(
372                 lint::builtin::ARITHMETIC_OVERFLOW,
373                 source_info,
374                 "this arithmetic operation will overflow",
375                 AssertKind::OverflowNeg(val.to_const_int()),
376             );
377             return None;
378         }
379
380         Some(())
381     }
382
383     fn check_binary_op(
384         &mut self,
385         op: BinOp,
386         left: &Operand<'tcx>,
387         right: &Operand<'tcx>,
388         source_info: SourceInfo,
389     ) -> Option<()> {
390         let r = self.use_ecx(source_info, |this| {
391             this.ecx.read_immediate(&this.ecx.eval_operand(right, None)?)
392         });
393         let l = self.use_ecx(source_info, |this| {
394             this.ecx.read_immediate(&this.ecx.eval_operand(left, None)?)
395         });
396         // Check for exceeding shifts *even if* we cannot evaluate the LHS.
397         if op == BinOp::Shr || op == BinOp::Shl {
398             let r = r.clone()?;
399             // We need the type of the LHS. We cannot use `place_layout` as that is the type
400             // of the result, which for checked binops is not the same!
401             let left_ty = left.ty(self.local_decls, self.tcx);
402             let left_size = self.ecx.layout_of(left_ty).ok()?.size;
403             let right_size = r.layout.size;
404             let r_bits = r.to_scalar().ok();
405             let r_bits = r_bits.and_then(|r| r.to_bits(right_size).ok());
406             if r_bits.map_or(false, |b| b >= left_size.bits() as u128) {
407                 debug!("check_binary_op: reporting assert for {:?}", source_info);
408                 self.report_assert_as_lint(
409                     lint::builtin::ARITHMETIC_OVERFLOW,
410                     source_info,
411                     "this arithmetic operation will overflow",
412                     AssertKind::Overflow(
413                         op,
414                         match l {
415                             Some(l) => l.to_const_int(),
416                             // Invent a dummy value, the diagnostic ignores it anyway
417                             None => ConstInt::new(
418                                 ScalarInt::try_from_uint(1_u8, left_size).unwrap(),
419                                 left_ty.is_signed(),
420                                 left_ty.is_ptr_sized_integral(),
421                             ),
422                         },
423                         r.to_const_int(),
424                     ),
425                 );
426                 return None;
427             }
428         }
429
430         if let (Some(l), Some(r)) = (l, r) {
431             // The remaining operators are handled through `overflowing_binary_op`.
432             if self.use_ecx(source_info, |this| {
433                 let (_res, overflow, _ty) = this.ecx.overflowing_binary_op(op, &l, &r)?;
434                 Ok(overflow)
435             })? {
436                 self.report_assert_as_lint(
437                     lint::builtin::ARITHMETIC_OVERFLOW,
438                     source_info,
439                     "this arithmetic operation will overflow",
440                     AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
441                 );
442                 return None;
443             }
444         }
445         Some(())
446     }
447
448     fn const_prop(
449         &mut self,
450         rvalue: &Rvalue<'tcx>,
451         source_info: SourceInfo,
452         place: Place<'tcx>,
453     ) -> Option<()> {
454         // Perform any special handling for specific Rvalue types.
455         // Generally, checks here fall into one of two categories:
456         //   1. Additional checking to provide useful lints to the user
457         //        - In this case, we will do some validation and then fall through to the
458         //          end of the function which evals the assignment.
459         //   2. Working around bugs in other parts of the compiler
460         //        - In this case, we'll return `None` from this function to stop evaluation.
461         match rvalue {
462             // Additional checking: give lints to the user if an overflow would occur.
463             // We do this here and not in the `Assert` terminator as that terminator is
464             // only sometimes emitted (overflow checks can be disabled), but we want to always
465             // lint.
466             Rvalue::UnaryOp(op, arg) => {
467                 trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
468                 self.check_unary_op(*op, arg, source_info)?;
469             }
470             Rvalue::BinaryOp(op, box (left, right)) => {
471                 trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
472                 self.check_binary_op(*op, left, right, source_info)?;
473             }
474             Rvalue::CheckedBinaryOp(op, box (left, right)) => {
475                 trace!(
476                     "checking CheckedBinaryOp(op = {:?}, left = {:?}, right = {:?})",
477                     op,
478                     left,
479                     right
480                 );
481                 self.check_binary_op(*op, left, right, source_info)?;
482             }
483
484             // Do not try creating references (#67862)
485             Rvalue::AddressOf(_, place) | Rvalue::Ref(_, _, place) => {
486                 trace!("skipping AddressOf | Ref for {:?}", place);
487
488                 // This may be creating mutable references or immutable references to cells.
489                 // If that happens, the pointed to value could be mutated via that reference.
490                 // Since we aren't tracking references, the const propagator loses track of what
491                 // value the local has right now.
492                 // Thus, all locals that have their reference taken
493                 // must not take part in propagation.
494                 Self::remove_const(&mut self.ecx, place.local);
495
496                 return None;
497             }
498             Rvalue::ThreadLocalRef(def_id) => {
499                 trace!("skipping ThreadLocalRef({:?})", def_id);
500
501                 return None;
502             }
503
504             // There's no other checking to do at this time.
505             Rvalue::Aggregate(..)
506             | Rvalue::Use(..)
507             | Rvalue::CopyForDeref(..)
508             | Rvalue::Repeat(..)
509             | Rvalue::Len(..)
510             | Rvalue::Cast(..)
511             | Rvalue::ShallowInitBox(..)
512             | Rvalue::Discriminant(..)
513             | Rvalue::NullaryOp(..) => {}
514         }
515
516         // FIXME we need to revisit this for #67176
517         if rvalue.needs_subst() {
518             return None;
519         }
520
521         self.use_ecx(source_info, |this| this.ecx.eval_rvalue_into_place(rvalue, place))
522     }
523 }
524
525 impl<'tcx> Visitor<'tcx> for ConstPropagator<'_, 'tcx> {
526     fn visit_body(&mut self, body: &Body<'tcx>) {
527         for (bb, data) in body.basic_blocks().iter_enumerated() {
528             self.visit_basic_block_data(bb, data);
529         }
530     }
531
532     fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
533         self.super_operand(operand, location);
534     }
535
536     fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
537         trace!("visit_constant: {:?}", constant);
538         self.super_constant(constant, location);
539         self.eval_constant(constant, self.source_info.unwrap());
540     }
541
542     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
543         trace!("visit_statement: {:?}", statement);
544         let source_info = statement.source_info;
545         self.source_info = Some(source_info);
546         if let StatementKind::Assign(box (place, ref rval)) = statement.kind {
547             let can_const_prop = self.ecx.machine.can_const_prop[place.local];
548             if let Some(()) = self.const_prop(rval, source_info, place) {
549                 match can_const_prop {
550                     ConstPropMode::OnlyInsideOwnBlock => {
551                         trace!(
552                             "found local restricted to its block. \
553                                 Will remove it from const-prop after block is finished. Local: {:?}",
554                             place.local
555                         );
556                     }
557                     ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
558                         trace!("can't propagate into {:?}", place);
559                         if place.local != RETURN_PLACE {
560                             Self::remove_const(&mut self.ecx, place.local);
561                         }
562                     }
563                     ConstPropMode::FullConstProp => {}
564                 }
565             } else {
566                 // Const prop failed, so erase the destination, ensuring that whatever happens
567                 // from here on, does not know about the previous value.
568                 // This is important in case we have
569                 // ```rust
570                 // let mut x = 42;
571                 // x = SOME_MUTABLE_STATIC;
572                 // // x must now be uninit
573                 // ```
574                 // FIXME: we overzealously erase the entire local, because that's easier to
575                 // implement.
576                 trace!(
577                     "propagation into {:?} failed.
578                         Nuking the entire site from orbit, it's the only way to be sure",
579                     place,
580                 );
581                 Self::remove_const(&mut self.ecx, place.local);
582             }
583         } else {
584             match statement.kind {
585                 StatementKind::SetDiscriminant { ref place, .. } => {
586                     match self.ecx.machine.can_const_prop[place.local] {
587                         ConstPropMode::FullConstProp | ConstPropMode::OnlyInsideOwnBlock => {
588                             if self
589                                 .use_ecx(source_info, |this| this.ecx.statement(statement))
590                                 .is_some()
591                             {
592                                 trace!("propped discriminant into {:?}", place);
593                             } else {
594                                 Self::remove_const(&mut self.ecx, place.local);
595                             }
596                         }
597                         ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
598                             Self::remove_const(&mut self.ecx, place.local);
599                         }
600                     }
601                 }
602                 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
603                     let frame = self.ecx.frame_mut();
604                     frame.locals[local].value =
605                         if let StatementKind::StorageLive(_) = statement.kind {
606                             LocalValue::Live(interpret::Operand::Immediate(
607                                 interpret::Immediate::Uninit,
608                             ))
609                         } else {
610                             LocalValue::Dead
611                         };
612                 }
613                 _ => {}
614             }
615         }
616
617         self.super_statement(statement, location);
618     }
619
620     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
621         let source_info = terminator.source_info;
622         self.source_info = Some(source_info);
623         self.super_terminator(terminator, location);
624         match &terminator.kind {
625             TerminatorKind::Assert { expected, ref msg, ref cond, .. } => {
626                 if let Some(ref value) = self.eval_operand(&cond, source_info) {
627                     trace!("assertion on {:?} should be {:?}", value, expected);
628                     let expected = ScalarMaybeUninit::from(Scalar::from_bool(*expected));
629                     let value_const = self.ecx.read_scalar(&value).unwrap();
630                     if expected != value_const {
631                         enum DbgVal<T> {
632                             Val(T),
633                             Underscore,
634                         }
635                         impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
636                             fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
637                                 match self {
638                                     Self::Val(val) => val.fmt(fmt),
639                                     Self::Underscore => fmt.write_str("_"),
640                                 }
641                             }
642                         }
643                         let mut eval_to_int = |op| {
644                             // This can be `None` if the lhs wasn't const propagated and we just
645                             // triggered the assert on the value of the rhs.
646                             self.eval_operand(op, source_info).map_or(DbgVal::Underscore, |op| {
647                                 DbgVal::Val(self.ecx.read_immediate(&op).unwrap().to_const_int())
648                             })
649                         };
650                         let msg = match msg {
651                             AssertKind::DivisionByZero(op) => {
652                                 Some(AssertKind::DivisionByZero(eval_to_int(op)))
653                             }
654                             AssertKind::RemainderByZero(op) => {
655                                 Some(AssertKind::RemainderByZero(eval_to_int(op)))
656                             }
657                             AssertKind::Overflow(bin_op @ (BinOp::Div | BinOp::Rem), op1, op2) => {
658                                 // Division overflow is *UB* in the MIR, and different than the
659                                 // other overflow checks.
660                                 Some(AssertKind::Overflow(
661                                     *bin_op,
662                                     eval_to_int(op1),
663                                     eval_to_int(op2),
664                                 ))
665                             }
666                             AssertKind::BoundsCheck { ref len, ref index } => {
667                                 let len = eval_to_int(len);
668                                 let index = eval_to_int(index);
669                                 Some(AssertKind::BoundsCheck { len, index })
670                             }
671                             // Remaining overflow errors are already covered by checks on the binary operators.
672                             AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => None,
673                             // Need proper const propagator for these.
674                             _ => None,
675                         };
676                         // Poison all places this operand references so that further code
677                         // doesn't use the invalid value
678                         match cond {
679                             Operand::Move(ref place) | Operand::Copy(ref place) => {
680                                 Self::remove_const(&mut self.ecx, place.local);
681                             }
682                             Operand::Constant(_) => {}
683                         }
684                         if let Some(msg) = msg {
685                             self.report_assert_as_lint(
686                                 lint::builtin::UNCONDITIONAL_PANIC,
687                                 source_info,
688                                 "this operation will panic at runtime",
689                                 msg,
690                             );
691                         }
692                     }
693                 }
694             }
695             // None of these have Operands to const-propagate.
696             TerminatorKind::Goto { .. }
697             | TerminatorKind::Resume
698             | TerminatorKind::Abort
699             | TerminatorKind::Return
700             | TerminatorKind::Unreachable
701             | TerminatorKind::Drop { .. }
702             | TerminatorKind::DropAndReplace { .. }
703             | TerminatorKind::Yield { .. }
704             | TerminatorKind::GeneratorDrop
705             | TerminatorKind::FalseEdge { .. }
706             | TerminatorKind::FalseUnwind { .. }
707             | TerminatorKind::SwitchInt { .. }
708             | TerminatorKind::Call { .. }
709             | TerminatorKind::InlineAsm { .. } => {}
710         }
711
712         // We remove all Locals which are restricted in propagation to their containing blocks and
713         // which were modified in the current block.
714         // Take it out of the ecx so we can get a mutable reference to the ecx for `remove_const`.
715         let mut locals = std::mem::take(&mut self.ecx.machine.written_only_inside_own_block_locals);
716         for &local in locals.iter() {
717             Self::remove_const(&mut self.ecx, local);
718         }
719         locals.clear();
720         // Put it back so we reuse the heap of the storage
721         self.ecx.machine.written_only_inside_own_block_locals = locals;
722         if cfg!(debug_assertions) {
723             // Ensure we are correctly erasing locals with the non-debug-assert logic.
724             for local in self.ecx.machine.only_propagate_inside_block_locals.iter() {
725                 assert!(
726                     self.get_const(local.into()).is_none()
727                         || self
728                             .layout_of(self.local_decls[local].ty)
729                             .map_or(true, |layout| layout.is_zst())
730                 )
731             }
732         }
733     }
734 }