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