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