]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/const_prop_lint.rs
Merge remote-tracking branch 'origin/master' into mpk/add-long-error-message-for...
[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::Immediate;
10 use rustc_const_eval::interpret::{
11     self, InterpCx, InterpResult, LocalState, LocalValue, MemoryKind, OpTy, Scalar, 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) => {
234                 if matches!(*op, interpret::Operand::Immediate(Immediate::Uninit)) {
235                     // Make sure nobody accidentally uses this value.
236                     return None;
237                 }
238                 op
239             }
240             Err(e) => {
241                 trace!("get_const failed: {}", e);
242                 return None;
243             }
244         };
245
246         // Try to read the local as an immediate so that if it is representable as a scalar, we can
247         // handle it as such, but otherwise, just return the value as is.
248         Some(match self.ecx.read_immediate_raw(&op) {
249             Ok(Ok(imm)) => imm.into(),
250             _ => op,
251         })
252     }
253
254     /// Remove `local` from the pool of `Locals`. Allows writing to them,
255     /// but not reading from them anymore.
256     fn remove_const(ecx: &mut InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>, local: Local) {
257         ecx.frame_mut().locals[local] = LocalState {
258             value: LocalValue::Live(interpret::Operand::Immediate(interpret::Immediate::Uninit)),
259             layout: Cell::new(None),
260         };
261     }
262
263     fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
264         source_info.scope.lint_root(self.source_scopes)
265     }
266
267     fn use_ecx<F, T>(&mut self, source_info: SourceInfo, f: F) -> Option<T>
268     where
269         F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
270     {
271         // Overwrite the PC -- whatever the interpreter does to it does not make any sense anyway.
272         self.ecx.frame_mut().loc = Err(source_info.span);
273         match f(self) {
274             Ok(val) => Some(val),
275             Err(error) => {
276                 trace!("InterpCx operation failed: {:?}", error);
277                 // Some errors shouldn't come up because creating them causes
278                 // an allocation, which we should avoid. When that happens,
279                 // dedicated error variants should be introduced instead.
280                 assert!(
281                     !error.kind().formatted_string(),
282                     "const-prop encountered formatting error: {}",
283                     error
284                 );
285                 None
286             }
287         }
288     }
289
290     /// Returns the value, if any, of evaluating `c`.
291     fn eval_constant(&mut self, c: &Constant<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
292         // FIXME we need to revisit this for #67176
293         if c.needs_subst() {
294             return None;
295         }
296
297         match self.ecx.mir_const_to_op(&c.literal, None) {
298             Ok(op) => Some(op),
299             Err(error) => {
300                 let tcx = self.ecx.tcx.at(c.span);
301                 let err = ConstEvalErr::new(&self.ecx, error, Some(c.span));
302                 if let Some(lint_root) = self.lint_root(source_info) {
303                     let lint_only = match c.literal {
304                         ConstantKind::Ty(ct) => match ct.kind() {
305                             // Promoteds must lint and not error as the user didn't ask for them
306                             ConstKind::Unevaluated(ty::Unevaluated {
307                                 def: _,
308                                 substs: _,
309                                 promoted: Some(_),
310                             }) => true,
311                             // Out of backwards compatibility we cannot report hard errors in unused
312                             // generic functions using associated constants of the generic parameters.
313                             _ => c.literal.needs_subst(),
314                         },
315                         ConstantKind::Val(_, ty) => ty.needs_subst(),
316                     };
317                     if lint_only {
318                         // Out of backwards compatibility we cannot report hard errors in unused
319                         // generic functions using associated constants of the generic parameters.
320                         err.report_as_lint(tcx, "erroneous constant used", lint_root, Some(c.span));
321                     } else {
322                         err.report_as_error(tcx, "erroneous constant used");
323                     }
324                 } else {
325                     err.report_as_error(tcx, "erroneous constant used");
326                 }
327                 None
328             }
329         }
330     }
331
332     /// Returns the value, if any, of evaluating `place`.
333     fn eval_place(&mut self, place: Place<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
334         trace!("eval_place(place={:?})", place);
335         self.use_ecx(source_info, |this| this.ecx.eval_place_to_op(place, None))
336     }
337
338     /// Returns the value, if any, of evaluating `op`. Calls upon `eval_constant`
339     /// or `eval_place`, depending on the variant of `Operand` used.
340     fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
341         match *op {
342             Operand::Constant(ref c) => self.eval_constant(c, source_info),
343             Operand::Move(place) | Operand::Copy(place) => self.eval_place(place, source_info),
344         }
345     }
346
347     fn report_assert_as_lint(
348         &self,
349         lint: &'static lint::Lint,
350         source_info: SourceInfo,
351         message: &'static str,
352         panic: AssertKind<impl std::fmt::Debug>,
353     ) {
354         if let Some(lint_root) = self.lint_root(source_info) {
355             self.tcx.struct_span_lint_hir(lint, lint_root, source_info.span, |lint| {
356                 let mut err = lint.build(message);
357                 err.span_label(source_info.span, format!("{:?}", panic));
358                 err.emit();
359             });
360         }
361     }
362
363     fn check_unary_op(
364         &mut self,
365         op: UnOp,
366         arg: &Operand<'tcx>,
367         source_info: SourceInfo,
368     ) -> Option<()> {
369         if let (val, true) = self.use_ecx(source_info, |this| {
370             let val = this.ecx.read_immediate(&this.ecx.eval_operand(arg, None)?)?;
371             let (_res, overflow, _ty) = this.ecx.overflowing_unary_op(op, &val)?;
372             Ok((val, overflow))
373         })? {
374             // `AssertKind` only has an `OverflowNeg` variant, so make sure that is
375             // appropriate to use.
376             assert_eq!(op, UnOp::Neg, "Neg is the only UnOp that can overflow");
377             self.report_assert_as_lint(
378                 lint::builtin::ARITHMETIC_OVERFLOW,
379                 source_info,
380                 "this arithmetic operation will overflow",
381                 AssertKind::OverflowNeg(val.to_const_int()),
382             );
383             return None;
384         }
385
386         Some(())
387     }
388
389     fn check_binary_op(
390         &mut self,
391         op: BinOp,
392         left: &Operand<'tcx>,
393         right: &Operand<'tcx>,
394         source_info: SourceInfo,
395     ) -> Option<()> {
396         let r = self.use_ecx(source_info, |this| {
397             this.ecx.read_immediate(&this.ecx.eval_operand(right, None)?)
398         });
399         let l = self.use_ecx(source_info, |this| {
400             this.ecx.read_immediate(&this.ecx.eval_operand(left, None)?)
401         });
402         // Check for exceeding shifts *even if* we cannot evaluate the LHS.
403         if op == BinOp::Shr || op == BinOp::Shl {
404             let r = r.clone()?;
405             // We need the type of the LHS. We cannot use `place_layout` as that is the type
406             // of the result, which for checked binops is not the same!
407             let left_ty = left.ty(self.local_decls, self.tcx);
408             let left_size = self.ecx.layout_of(left_ty).ok()?.size;
409             let right_size = r.layout.size;
410             let r_bits = r.to_scalar().to_bits(right_size).ok();
411             if r_bits.map_or(false, |b| b >= left_size.bits() as u128) {
412                 debug!("check_binary_op: reporting assert for {:?}", source_info);
413                 self.report_assert_as_lint(
414                     lint::builtin::ARITHMETIC_OVERFLOW,
415                     source_info,
416                     "this arithmetic operation will overflow",
417                     AssertKind::Overflow(
418                         op,
419                         match l {
420                             Some(l) => l.to_const_int(),
421                             // Invent a dummy value, the diagnostic ignores it anyway
422                             None => ConstInt::new(
423                                 ScalarInt::try_from_uint(1_u8, left_size).unwrap(),
424                                 left_ty.is_signed(),
425                                 left_ty.is_ptr_sized_integral(),
426                             ),
427                         },
428                         r.to_const_int(),
429                     ),
430                 );
431                 return None;
432             }
433         }
434
435         if let (Some(l), Some(r)) = (l, r) {
436             // The remaining operators are handled through `overflowing_binary_op`.
437             if self.use_ecx(source_info, |this| {
438                 let (_res, overflow, _ty) = this.ecx.overflowing_binary_op(op, &l, &r)?;
439                 Ok(overflow)
440             })? {
441                 self.report_assert_as_lint(
442                     lint::builtin::ARITHMETIC_OVERFLOW,
443                     source_info,
444                     "this arithmetic operation will overflow",
445                     AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
446                 );
447                 return None;
448             }
449         }
450         Some(())
451     }
452
453     fn const_prop(
454         &mut self,
455         rvalue: &Rvalue<'tcx>,
456         source_info: SourceInfo,
457         place: Place<'tcx>,
458     ) -> Option<()> {
459         // Perform any special handling for specific Rvalue types.
460         // Generally, checks here fall into one of two categories:
461         //   1. Additional checking to provide useful lints to the user
462         //        - In this case, we will do some validation and then fall through to the
463         //          end of the function which evals the assignment.
464         //   2. Working around bugs in other parts of the compiler
465         //        - In this case, we'll return `None` from this function to stop evaluation.
466         match rvalue {
467             // Additional checking: give lints to the user if an overflow would occur.
468             // We do this here and not in the `Assert` terminator as that terminator is
469             // only sometimes emitted (overflow checks can be disabled), but we want to always
470             // lint.
471             Rvalue::UnaryOp(op, arg) => {
472                 trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
473                 self.check_unary_op(*op, arg, source_info)?;
474             }
475             Rvalue::BinaryOp(op, box (left, right)) => {
476                 trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
477                 self.check_binary_op(*op, left, right, source_info)?;
478             }
479             Rvalue::CheckedBinaryOp(op, box (left, right)) => {
480                 trace!(
481                     "checking CheckedBinaryOp(op = {:?}, left = {:?}, right = {:?})",
482                     op,
483                     left,
484                     right
485                 );
486                 self.check_binary_op(*op, left, right, source_info)?;
487             }
488
489             // Do not try creating references (#67862)
490             Rvalue::AddressOf(_, place) | Rvalue::Ref(_, _, place) => {
491                 trace!("skipping AddressOf | Ref for {:?}", place);
492
493                 // This may be creating mutable references or immutable references to cells.
494                 // If that happens, the pointed to value could be mutated via that reference.
495                 // Since we aren't tracking references, the const propagator loses track of what
496                 // value the local has right now.
497                 // Thus, all locals that have their reference taken
498                 // must not take part in propagation.
499                 Self::remove_const(&mut self.ecx, place.local);
500
501                 return None;
502             }
503             Rvalue::ThreadLocalRef(def_id) => {
504                 trace!("skipping ThreadLocalRef({:?})", def_id);
505
506                 return None;
507             }
508
509             // There's no other checking to do at this time.
510             Rvalue::Aggregate(..)
511             | Rvalue::Use(..)
512             | Rvalue::CopyForDeref(..)
513             | Rvalue::Repeat(..)
514             | Rvalue::Len(..)
515             | Rvalue::Cast(..)
516             | Rvalue::ShallowInitBox(..)
517             | Rvalue::Discriminant(..)
518             | Rvalue::NullaryOp(..) => {}
519         }
520
521         // FIXME we need to revisit this for #67176
522         if rvalue.needs_subst() {
523             return None;
524         }
525         if !rvalue
526             .ty(&self.ecx.frame().body.local_decls, *self.ecx.tcx)
527             .is_sized(self.ecx.tcx, self.param_env)
528         {
529             // the interpreter doesn't support unsized locals (only unsized arguments),
530             // but rustc does (in a kinda broken way), so we have to skip them here
531             return None;
532         }
533
534         self.use_ecx(source_info, |this| this.ecx.eval_rvalue_into_place(rvalue, place))
535     }
536 }
537
538 impl<'tcx> Visitor<'tcx> for ConstPropagator<'_, 'tcx> {
539     fn visit_body(&mut self, body: &Body<'tcx>) {
540         for (bb, data) in body.basic_blocks.iter_enumerated() {
541             self.visit_basic_block_data(bb, data);
542         }
543     }
544
545     fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
546         self.super_operand(operand, location);
547     }
548
549     fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
550         trace!("visit_constant: {:?}", constant);
551         self.super_constant(constant, location);
552         self.eval_constant(constant, self.source_info.unwrap());
553     }
554
555     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
556         trace!("visit_statement: {:?}", statement);
557         let source_info = statement.source_info;
558         self.source_info = Some(source_info);
559         if let StatementKind::Assign(box (place, ref rval)) = statement.kind {
560             let can_const_prop = self.ecx.machine.can_const_prop[place.local];
561             if let Some(()) = self.const_prop(rval, source_info, place) {
562                 match can_const_prop {
563                     ConstPropMode::OnlyInsideOwnBlock => {
564                         trace!(
565                             "found local restricted to its block. \
566                                 Will remove it from const-prop after block is finished. Local: {:?}",
567                             place.local
568                         );
569                     }
570                     ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
571                         trace!("can't propagate into {:?}", place);
572                         if place.local != RETURN_PLACE {
573                             Self::remove_const(&mut self.ecx, place.local);
574                         }
575                     }
576                     ConstPropMode::FullConstProp => {}
577                 }
578             } else {
579                 // Const prop failed, so erase the destination, ensuring that whatever happens
580                 // from here on, does not know about the previous value.
581                 // This is important in case we have
582                 // ```rust
583                 // let mut x = 42;
584                 // x = SOME_MUTABLE_STATIC;
585                 // // x must now be uninit
586                 // ```
587                 // FIXME: we overzealously erase the entire local, because that's easier to
588                 // implement.
589                 trace!(
590                     "propagation into {:?} failed.
591                         Nuking the entire site from orbit, it's the only way to be sure",
592                     place,
593                 );
594                 Self::remove_const(&mut self.ecx, place.local);
595             }
596         } else {
597             match statement.kind {
598                 StatementKind::SetDiscriminant { ref place, .. } => {
599                     match self.ecx.machine.can_const_prop[place.local] {
600                         ConstPropMode::FullConstProp | ConstPropMode::OnlyInsideOwnBlock => {
601                             if self
602                                 .use_ecx(source_info, |this| this.ecx.statement(statement))
603                                 .is_some()
604                             {
605                                 trace!("propped discriminant into {:?}", place);
606                             } else {
607                                 Self::remove_const(&mut self.ecx, place.local);
608                             }
609                         }
610                         ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
611                             Self::remove_const(&mut self.ecx, place.local);
612                         }
613                     }
614                 }
615                 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
616                     let frame = self.ecx.frame_mut();
617                     frame.locals[local].value =
618                         if let StatementKind::StorageLive(_) = statement.kind {
619                             LocalValue::Live(interpret::Operand::Immediate(
620                                 interpret::Immediate::Uninit,
621                             ))
622                         } else {
623                             LocalValue::Dead
624                         };
625                 }
626                 _ => {}
627             }
628         }
629
630         self.super_statement(statement, location);
631     }
632
633     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
634         let source_info = terminator.source_info;
635         self.source_info = Some(source_info);
636         self.super_terminator(terminator, location);
637         match &terminator.kind {
638             TerminatorKind::Assert { expected, ref msg, ref cond, .. } => {
639                 if let Some(ref value) = self.eval_operand(&cond, source_info) {
640                     trace!("assertion on {:?} should be {:?}", value, expected);
641                     let expected = Scalar::from_bool(*expected);
642                     let Ok(value_const) = self.ecx.read_scalar(&value) else {
643                         // FIXME should be used use_ecx rather than a local match... but we have
644                         // quite a few of these read_scalar/read_immediate that need fixing.
645                         return
646                     };
647                     if expected != value_const {
648                         enum DbgVal<T> {
649                             Val(T),
650                             Underscore,
651                         }
652                         impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
653                             fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
654                                 match self {
655                                     Self::Val(val) => val.fmt(fmt),
656                                     Self::Underscore => fmt.write_str("_"),
657                                 }
658                             }
659                         }
660                         let mut eval_to_int = |op| {
661                             // This can be `None` if the lhs wasn't const propagated and we just
662                             // triggered the assert on the value of the rhs.
663                             self.eval_operand(op, source_info)
664                                 .and_then(|op| self.ecx.read_immediate(&op).ok())
665                                 .map_or(DbgVal::Underscore, |op| DbgVal::Val(op.to_const_int()))
666                         };
667                         let msg = match msg {
668                             AssertKind::DivisionByZero(op) => {
669                                 Some(AssertKind::DivisionByZero(eval_to_int(op)))
670                             }
671                             AssertKind::RemainderByZero(op) => {
672                                 Some(AssertKind::RemainderByZero(eval_to_int(op)))
673                             }
674                             AssertKind::Overflow(bin_op @ (BinOp::Div | BinOp::Rem), op1, op2) => {
675                                 // Division overflow is *UB* in the MIR, and different than the
676                                 // other overflow checks.
677                                 Some(AssertKind::Overflow(
678                                     *bin_op,
679                                     eval_to_int(op1),
680                                     eval_to_int(op2),
681                                 ))
682                             }
683                             AssertKind::BoundsCheck { ref len, ref index } => {
684                                 let len = eval_to_int(len);
685                                 let index = eval_to_int(index);
686                                 Some(AssertKind::BoundsCheck { len, index })
687                             }
688                             // Remaining overflow errors are already covered by checks on the binary operators.
689                             AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => None,
690                             // Need proper const propagator for these.
691                             _ => None,
692                         };
693                         // Poison all places this operand references so that further code
694                         // doesn't use the invalid value
695                         match cond {
696                             Operand::Move(ref place) | Operand::Copy(ref place) => {
697                                 Self::remove_const(&mut self.ecx, place.local);
698                             }
699                             Operand::Constant(_) => {}
700                         }
701                         if let Some(msg) = msg {
702                             self.report_assert_as_lint(
703                                 lint::builtin::UNCONDITIONAL_PANIC,
704                                 source_info,
705                                 "this operation will panic at runtime",
706                                 msg,
707                             );
708                         }
709                     }
710                 }
711             }
712             // None of these have Operands to const-propagate.
713             TerminatorKind::Goto { .. }
714             | TerminatorKind::Resume
715             | TerminatorKind::Abort
716             | TerminatorKind::Return
717             | TerminatorKind::Unreachable
718             | TerminatorKind::Drop { .. }
719             | TerminatorKind::DropAndReplace { .. }
720             | TerminatorKind::Yield { .. }
721             | TerminatorKind::GeneratorDrop
722             | TerminatorKind::FalseEdge { .. }
723             | TerminatorKind::FalseUnwind { .. }
724             | TerminatorKind::SwitchInt { .. }
725             | TerminatorKind::Call { .. }
726             | TerminatorKind::InlineAsm { .. } => {}
727         }
728
729         // We remove all Locals which are restricted in propagation to their containing blocks and
730         // which were modified in the current block.
731         // Take it out of the ecx so we can get a mutable reference to the ecx for `remove_const`.
732         let mut locals = std::mem::take(&mut self.ecx.machine.written_only_inside_own_block_locals);
733         for &local in locals.iter() {
734             Self::remove_const(&mut self.ecx, local);
735         }
736         locals.clear();
737         // Put it back so we reuse the heap of the storage
738         self.ecx.machine.written_only_inside_own_block_locals = locals;
739         if cfg!(debug_assertions) {
740             // Ensure we are correctly erasing locals with the non-debug-assert logic.
741             for local in self.ecx.machine.only_propagate_inside_block_locals.iter() {
742                 assert!(
743                     self.get_const(local.into()).is_none()
744                         || self
745                             .layout_of(self.local_decls[local].ty)
746                             .map_or(true, |layout| layout.is_zst())
747                 )
748             }
749         }
750     }
751 }