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