1use std::fmt::Debug;
6
7use rustc_abi::{BackendRepr, FieldIdx, HasDataLayout, Size, TargetDataLayout, VariantIdx};
8use rustc_const_eval::const_eval::DummyMachine;
9use rustc_const_eval::interpret::{ImmTy, InterpCx, InterpResult, Projectable, Scalar, interp_ok};
10use rustc_data_structures::fx::FxHashSet;
11use rustc_hir::def::DefKind;
12use rustc_hir::{HirId, find_attr};
13use rustc_index::IndexVec;
14use rustc_index::bit_set::DenseBitSet;
15use rustc_middle::bug;
16use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor};
17use rustc_middle::mir::*;
18use rustc_middle::ty::layout::{LayoutError, LayoutOf, LayoutOfHelpers, TyAndLayout};
19use rustc_middle::ty::{
20 self, ConstInt, GenericArgKind, GenericParamDefKind, ScalarInt, Ty, TyCtxt, TypeVisitableExt,
21 Unnormalized,
22};
23use rustc_session::lint::builtin::UNCONDITIONAL_PANIC;
24use rustc_span::Span;
25use tracing::{debug, instrument, trace};
26
27use crate::diagnostics::{AssertLint, AssertLintKind, ConstNIsZero};
28
29pub(super) struct KnownPanicsLint;
30
31impl<'tcx> crate::MirLint<'tcx> for KnownPanicsLint {
32 fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
33 if body.tainted_by_errors.is_some() {
34 return;
35 }
36
37 let def_id = body.source.def_id().expect_local();
38 let def_kind = tcx.def_kind(def_id);
39 let is_fn_like = def_kind.is_fn_like();
40 let is_assoc_const = matches!(def_kind, DefKind::AssocConst { .. });
41
42 if !is_fn_like && !is_assoc_const {
44 trace!("KnownPanicsLint skipped for {:?}", def_id);
46 return;
47 }
48
49 if tcx.is_coroutine(def_id.to_def_id()) {
52 trace!("KnownPanicsLint skipped for coroutine {:?}", def_id);
53 return;
54 }
55
56 trace!("KnownPanicsLint starting for {:?}", def_id);
57
58 let mut linter = ConstPropagator::new(body, tcx);
59 linter.visit_body(body);
60
61 trace!("KnownPanicsLint done for {:?}", def_id);
62 }
63}
64
65struct ConstPropagator<'mir, 'tcx> {
68 ecx: InterpCx<'tcx, DummyMachine>,
69 tcx: TyCtxt<'tcx>,
70 typing_env: ty::TypingEnv<'tcx>,
71 worklist: Vec<BasicBlock>,
72 visited_blocks: DenseBitSet<BasicBlock>,
73 locals: IndexVec<Local, Value<'tcx>>,
74 body: &'mir Body<'tcx>,
75 written_only_inside_own_block_locals: FxHashSet<Local>,
76 can_const_prop: IndexVec<Local, ConstPropMode>,
77}
78
79#[derive(Debug, Clone)]
80enum Value<'tcx> {
81 Immediate(ImmTy<'tcx>),
82 Aggregate { variant: VariantIdx, fields: IndexVec<FieldIdx, Value<'tcx>> },
83 Uninit,
84}
85
86impl<'tcx> From<ImmTy<'tcx>> for Value<'tcx> {
87 fn from(v: ImmTy<'tcx>) -> Self {
88 Self::Immediate(v)
89 }
90}
91
92impl<'tcx> Value<'tcx> {
93 fn project(
94 &self,
95 proj: &[PlaceElem<'tcx>],
96 prop: &ConstPropagator<'_, 'tcx>,
97 ) -> Option<&Value<'tcx>> {
98 let mut this = self;
99 for proj in proj {
100 this = match (*proj, this) {
101 (PlaceElem::Field(idx, _), Value::Aggregate { fields, .. }) => {
102 fields.get(idx).unwrap_or(&Value::Uninit)
103 }
104 (PlaceElem::Index(idx), Value::Aggregate { fields, .. }) => {
105 let idx = prop.get_const(idx.into())?.immediate()?;
106 let idx = prop.ecx.read_target_usize(idx).discard_err()?.try_into().ok()?;
107 if idx <= FieldIdx::MAX_AS_U32 {
108 fields.get(FieldIdx::from_u32(idx)).unwrap_or(&Value::Uninit)
109 } else {
110 return None;
111 }
112 }
113 (
114 PlaceElem::ConstantIndex { offset, min_length: _, from_end: false },
115 Value::Aggregate { fields, .. },
116 ) => fields
117 .get(FieldIdx::from_u32(offset.try_into().ok()?))
118 .unwrap_or(&Value::Uninit),
119 _ => return None,
120 };
121 }
122 Some(this)
123 }
124
125 fn project_mut(&mut self, proj: &[PlaceElem<'_>]) -> Option<&mut Value<'tcx>> {
126 let mut this = self;
127 for proj in proj {
128 this = match (proj, this) {
129 (PlaceElem::Field(idx, _), Value::Aggregate { fields, .. }) => {
130 fields.ensure_contains_elem(*idx, || Value::Uninit)
131 }
132 (PlaceElem::Field(..), val @ Value::Uninit) => {
133 *val =
134 Value::Aggregate { variant: VariantIdx::ZERO, fields: Default::default() };
135 val.project_mut(&[*proj])?
136 }
137 _ => return None,
138 };
139 }
140 Some(this)
141 }
142
143 fn immediate(&self) -> Option<&ImmTy<'tcx>> {
144 match self {
145 Value::Immediate(op) => Some(op),
146 _ => None,
147 }
148 }
149}
150
151impl<'tcx> LayoutOfHelpers<'tcx> for ConstPropagator<'_, 'tcx> {
152 type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
153
154 #[inline]
155 fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
156 err
157 }
158}
159
160impl HasDataLayout for ConstPropagator<'_, '_> {
161 #[inline]
162 fn data_layout(&self) -> &TargetDataLayout {
163 &self.tcx.data_layout
164 }
165}
166
167impl<'tcx> ty::layout::HasTyCtxt<'tcx> for ConstPropagator<'_, 'tcx> {
168 #[inline]
169 fn tcx(&self) -> TyCtxt<'tcx> {
170 self.tcx
171 }
172}
173
174impl<'tcx> ty::layout::HasTypingEnv<'tcx> for ConstPropagator<'_, 'tcx> {
175 #[inline]
176 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
177 self.typing_env
178 }
179}
180
181impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
182 fn new(body: &'mir Body<'tcx>, tcx: TyCtxt<'tcx>) -> ConstPropagator<'mir, 'tcx> {
183 let def_id = body.source.def_id();
184 let typing_env = ty::TypingEnv::post_analysis(tcx, body.source.def_id());
187 let can_const_prop = CanConstProp::check(tcx, typing_env, body);
188 let ecx = InterpCx::new(tcx, tcx.def_span(def_id), typing_env, DummyMachine);
189
190 ConstPropagator {
191 ecx,
192 tcx,
193 typing_env,
194 worklist: vec![START_BLOCK],
195 visited_blocks: DenseBitSet::new_empty(body.basic_blocks.len()),
196 locals: IndexVec::from_elem_n(Value::Uninit, body.local_decls.len()),
197 body,
198 can_const_prop,
199 written_only_inside_own_block_locals: Default::default(),
200 }
201 }
202
203 fn local_decls(&self) -> &'mir LocalDecls<'tcx> {
204 &self.body.local_decls
205 }
206
207 fn get_const(&self, place: Place<'tcx>) -> Option<&Value<'tcx>> {
208 self.locals[place.local].project(&place.projection, self)
209 }
210
211 fn remove_const(&mut self, local: Local) {
214 self.locals[local] = Value::Uninit;
215 self.written_only_inside_own_block_locals.remove(&local);
216 }
217
218 fn access_mut(&mut self, place: &Place<'_>) -> Option<&mut Value<'tcx>> {
219 match self.can_const_prop[place.local] {
220 ConstPropMode::NoPropagation => return None,
221 ConstPropMode::OnlyInsideOwnBlock => {
222 self.written_only_inside_own_block_locals.insert(place.local);
223 }
224 ConstPropMode::FullConstProp => {}
225 }
226 self.locals[place.local].project_mut(place.projection)
227 }
228
229 fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
230 source_info.scope.lint_root(&self.body.source_scopes)
231 }
232
233 fn use_ecx<F, T>(&mut self, f: F) -> Option<T>
234 where
235 F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
236 {
237 f(self)
238 .inspect_err_info(|err| {
239 trace!("InterpCx operation failed: {:?}", err);
240 assert!(
244 !err.kind().formatted_string(),
245 "known panics lint encountered formatting error: {}",
246 err.to_string(),
247 );
248 })
249 .discard_err()
250 }
251
252 fn eval_constant(&mut self, c: &ConstOperand<'tcx>) -> Option<ImmTy<'tcx>> {
254 if c.has_param() {
256 return None;
257 }
258
259 let val = self
266 .tcx
267 .try_normalize_erasing_regions(self.typing_env, Unnormalized::new_wip(c.const_))
268 .ok()?;
269
270 self.use_ecx(|this| this.ecx.eval_mir_constant(&val, c.span, None))?
271 .as_mplace_or_imm()
272 .right()
273 }
274
275 #[instrument(level = "trace", skip(self), ret)]
277 fn eval_place(&mut self, place: Place<'tcx>) -> Option<ImmTy<'tcx>> {
278 match self.get_const(place)? {
279 Value::Immediate(imm) => Some(imm.clone()),
280 Value::Aggregate { .. } => None,
281 Value::Uninit => None,
282 }
283 }
284
285 fn eval_operand(&mut self, op: &Operand<'tcx>) -> Option<ImmTy<'tcx>> {
288 match *op {
289 Operand::RuntimeChecks(_) => None,
290 Operand::Constant(ref c) => self.eval_constant(c),
291 Operand::Move(place) | Operand::Copy(place) => self.eval_place(place),
292 }
293 }
294
295 fn report_assert_as_lint(
296 &self,
297 location: Location,
298 lint_kind: AssertLintKind,
299 assert_kind: AssertKind<impl Debug>,
300 ) {
301 let source_info = self.body.source_info(location);
302 if let Some(lint_root) = self.lint_root(*source_info) {
303 let span = source_info.span;
304 self.tcx.emit_node_span_lint(
305 lint_kind.lint(),
306 lint_root,
307 span,
308 AssertLint { span, assert_kind, lint_kind },
309 );
310 }
311 }
312
313 fn check_unary_op(&mut self, op: UnOp, arg: &Operand<'tcx>, location: Location) -> Option<()> {
314 let arg = self.eval_operand(arg)?;
315 if op == UnOp::Neg && arg.layout.ty.is_integral() {
317 let (arg, overflow) = self.use_ecx(|this| {
319 let arg = this.ecx.read_immediate(&arg)?;
320 let (_res, overflow) = this
321 .ecx
322 .binary_op(BinOp::SubWithOverflow, &ImmTy::from_int(0, arg.layout), &arg)?
323 .to_scalar_pair();
324 interp_ok((arg, overflow.to_bool()?))
325 })?;
326 if overflow {
327 self.report_assert_as_lint(
328 location,
329 AssertLintKind::ArithmeticOverflow,
330 AssertKind::OverflowNeg(arg.to_const_int()),
331 );
332 return None;
333 }
334 }
335
336 Some(())
337 }
338
339 fn check_binary_op(
340 &mut self,
341 op: BinOp,
342 left: &Operand<'tcx>,
343 right: &Operand<'tcx>,
344 location: Location,
345 ) -> Option<()> {
346 let r =
347 self.eval_operand(right).and_then(|r| self.use_ecx(|this| this.ecx.read_immediate(&r)));
348 let l =
349 self.eval_operand(left).and_then(|l| self.use_ecx(|this| this.ecx.read_immediate(&l)));
350 if matches!(op, BinOp::Shr | BinOp::Shl) {
352 let r = r.clone()?;
353 let left_ty = left.ty(self.local_decls(), self.tcx);
356 let left_size = self.ecx.layout_of(left_ty).ok()?.size;
357 let right_size = r.layout.size;
358 let r_bits = r.to_scalar().to_bits(right_size).discard_err();
359 if r_bits.is_some_and(|b| b >= left_size.bits() as u128) {
360 debug!("check_binary_op: reporting assert for {:?}", location);
361 let panic = AssertKind::Overflow(
362 op,
363 ConstInt::new(
365 ScalarInt::try_from_uint(1_u8, left_size).unwrap(),
366 left_ty.is_signed(),
367 left_ty.is_ptr_sized_integral(),
368 ),
369 r.to_const_int(),
370 );
371 self.report_assert_as_lint(location, AssertLintKind::ArithmeticOverflow, panic);
372 return None;
373 }
374 }
375
376 let op = op.wrapping_to_overflowing().unwrap_or(op);
382 if let (Some(l), Some(r)) = (l, r)
384 && l.layout.ty.is_integral()
385 && op.is_overflowing()
386 && self.use_ecx(|this| {
387 let (_res, overflow) = this.ecx.binary_op(op, &l, &r)?.to_scalar_pair();
388 overflow.to_bool()
389 })?
390 {
391 self.report_assert_as_lint(
392 location,
393 AssertLintKind::ArithmeticOverflow,
394 AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
395 );
396 return None;
397 }
398
399 Some(())
400 }
401
402 fn check_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) -> Option<()> {
403 match rvalue {
411 Rvalue::UnaryOp(op, arg) => {
416 trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
417 self.check_unary_op(*op, arg, location)?;
418 }
419 Rvalue::BinaryOp(op, (left, right)) => {
420 trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
421 self.check_binary_op(*op, left, right, location)?;
422 }
423
424 Rvalue::RawPtr(_, place) | Rvalue::Ref(_, _, place) | Rvalue::Reborrow(_, _, place) => {
426 trace!("skipping RawPtr | Ref | Reborrow for {:?}", place);
427
428 self.remove_const(place.local);
435
436 return None;
437 }
438 Rvalue::ThreadLocalRef(def_id) => {
439 trace!("skipping ThreadLocalRef({:?})", def_id);
440
441 return None;
442 }
443
444 Rvalue::Aggregate(..)
446 | Rvalue::Use(..)
447 | Rvalue::CopyForDeref(..)
448 | Rvalue::Repeat(..)
449 | Rvalue::Cast(..)
450 | Rvalue::Discriminant(..)
451 | Rvalue::WrapUnsafeBinder(..) => {}
452 }
453
454 if rvalue.has_param() {
456 return None;
457 }
458 if !rvalue.ty(self.local_decls(), self.tcx).is_sized(self.tcx, self.typing_env) {
459 return None;
462 }
463
464 Some(())
465 }
466
467 fn check_assertion(
468 &mut self,
469 expected: bool,
470 msg: &AssertKind<Operand<'tcx>>,
471 cond: &Operand<'tcx>,
472 location: Location,
473 ) {
474 let Some(value) = &self.eval_operand(cond) else { return };
475 trace!("assertion on {:?} should be {:?}", value, expected);
476
477 let expected = Scalar::from_bool(expected);
478 let Some(value_const) = self.use_ecx(|this| this.ecx.read_scalar(value)) else { return };
479
480 if expected != value_const {
481 if let Some(place) = cond.place() {
484 self.remove_const(place.local);
485 }
486
487 enum DbgVal<T> {
488 Val(T),
489 Underscore,
490 }
491 impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
492 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
493 match self {
494 Self::Val(val) => val.fmt(fmt),
495 Self::Underscore => fmt.write_str("_"),
496 }
497 }
498 }
499 let mut eval_to_int = |op| {
500 self.eval_operand(op)
503 .and_then(|op| self.ecx.read_immediate(&op).discard_err())
504 .map_or(DbgVal::Underscore, |op| DbgVal::Val(op.to_const_int()))
505 };
506 let msg = match msg {
507 AssertKind::DivisionByZero(op) => AssertKind::DivisionByZero(eval_to_int(op)),
508 AssertKind::RemainderByZero(op) => AssertKind::RemainderByZero(eval_to_int(op)),
509 AssertKind::Overflow(bin_op @ (BinOp::Div | BinOp::Rem), op1, op2) => {
510 AssertKind::Overflow(*bin_op, eval_to_int(op1), eval_to_int(op2))
513 }
514 AssertKind::BoundsCheck { len, index } => {
515 let len = eval_to_int(len);
516 let index = eval_to_int(index);
517 AssertKind::BoundsCheck { len, index }
518 }
519 AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => return,
521 _ => return,
523 };
524 self.report_assert_as_lint(location, AssertLintKind::UnconditionalPanic, msg);
525 }
526 }
527
528 fn ensure_not_propagated(&self, local: Local) {
529 if cfg!(debug_assertions) {
530 let val = self.get_const(local.into());
531 assert!(
532 matches!(val, Some(Value::Uninit))
533 || self
534 .layout_of(self.local_decls()[local].ty)
535 .map_or(true, |layout| layout.is_zst()),
536 "failed to remove values for `{local:?}`, value={val:?}",
537 )
538 }
539 }
540
541 #[instrument(level = "trace", skip(self), ret)]
542 fn eval_rvalue(&mut self, rvalue: &Rvalue<'tcx>, dest: &Place<'tcx>) -> Option<()> {
543 if !dest.projection.is_empty() {
544 return None;
545 }
546 use rustc_middle::mir::Rvalue::*;
547 let layout = self.ecx.layout_of(dest.ty(self.body, self.tcx).ty).ok()?;
548 trace!(?layout);
549
550 let val: Value<'_> = match *rvalue {
551 ThreadLocalRef(_) => return None,
552
553 Use(ref operand, _) | WrapUnsafeBinder(ref operand, _) => {
554 self.eval_operand(operand)?.into()
555 }
556
557 CopyForDeref(place) | Reborrow(_, _, place) => self.eval_place(place)?.into(),
558
559 BinaryOp(bin_op, (ref left, ref right)) => {
560 let left = self.eval_operand(left)?;
561 let left = self.use_ecx(|this| this.ecx.read_immediate(&left))?;
562
563 let right = self.eval_operand(right)?;
564 let right = self.use_ecx(|this| this.ecx.read_immediate(&right))?;
565
566 let val = self.use_ecx(|this| this.ecx.binary_op(bin_op, &left, &right))?;
567 if matches!(val.layout.backend_repr, BackendRepr::ScalarPair { .. }) {
568 let (val, overflow) = val.to_pair(&self.ecx);
571 Value::Aggregate {
572 variant: VariantIdx::ZERO,
573 fields: [val.into(), overflow.into()].into_iter().collect(),
574 }
575 } else {
576 val.into()
577 }
578 }
579
580 UnaryOp(un_op, ref operand) => {
581 let operand = self.eval_operand(operand)?;
582 let val = self.use_ecx(|this| this.ecx.read_immediate(&operand))?;
583
584 let val = self.use_ecx(|this| this.ecx.unary_op(un_op, &val))?;
585 val.into()
586 }
587
588 Aggregate(ref kind, ref fields) => Value::Aggregate {
589 fields: fields
590 .iter()
591 .map(|field| self.eval_operand(field).map_or(Value::Uninit, Value::Immediate))
592 .collect(),
593 variant: match **kind {
594 AggregateKind::Adt(_, variant, _, _, _) => variant,
595 AggregateKind::Array(_)
596 | AggregateKind::Tuple
597 | AggregateKind::RawPtr(_, _)
598 | AggregateKind::Closure(_, _)
599 | AggregateKind::Coroutine(_, _)
600 | AggregateKind::CoroutineClosure(_, _) => VariantIdx::ZERO,
601 },
602 },
603
604 Repeat(ref op, n) => {
605 trace!(?op, ?n);
606 return None;
607 }
608
609 Ref(..) | RawPtr(..) => return None,
610
611 Cast(ref kind, ref value, to) => match kind {
612 CastKind::IntToInt | CastKind::IntToFloat => {
613 let value = self.eval_operand(value)?;
614 let value = self.ecx.read_immediate(&value).discard_err()?;
615 let to = self.ecx.layout_of(to).ok()?;
616 let res = self.ecx.int_to_int_or_float(&value, to).discard_err()?;
617 res.into()
618 }
619 CastKind::FloatToFloat | CastKind::FloatToInt => {
620 let value = self.eval_operand(value)?;
621 let value = self.ecx.read_immediate(&value).discard_err()?;
622 let to = self.ecx.layout_of(to).ok()?;
623 let res = self.ecx.float_to_float_or_int(&value, to).discard_err()?;
624 res.into()
625 }
626 CastKind::Transmute | CastKind::Subtype => {
627 let value = self.eval_operand(value)?;
628 let to = self.ecx.layout_of(to).ok()?;
629 match (value.layout.backend_repr, to.backend_repr) {
632 (BackendRepr::Scalar(..), BackendRepr::Scalar(..)) => {}
633 (BackendRepr::ScalarPair { .. }, BackendRepr::ScalarPair { .. }) => {}
634 _ => return None,
635 }
636
637 value.offset(Size::ZERO, to, &self.ecx).discard_err()?.into()
638 }
639 _ => return None,
640 },
641
642 Discriminant(place) => {
643 let variant = match self.get_const(place)? {
644 Value::Immediate(op) => {
645 let op = op.clone();
646 self.use_ecx(|this| this.ecx.read_discriminant(&op))?
647 }
648 Value::Aggregate { variant, .. } => *variant,
649 Value::Uninit => return None,
650 };
651 let imm = self.use_ecx(|this| {
652 this.ecx.discriminant_for_variant(
653 place.ty(this.local_decls(), this.tcx).ty,
654 variant,
655 )
656 })?;
657 imm.into()
658 }
659 };
660 trace!(?val);
661
662 *self.access_mut(dest)? = val;
663
664 Some(())
665 }
666}
667
668impl<'tcx> Visitor<'tcx> for ConstPropagator<'_, 'tcx> {
669 fn visit_body(&mut self, body: &Body<'tcx>) {
670 while let Some(bb) = self.worklist.pop() {
671 if !self.visited_blocks.insert(bb) {
672 continue;
673 }
674
675 let data = &body.basic_blocks[bb];
676 self.visit_basic_block_data(bb, data);
677 }
678 }
679
680 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
681 self.super_operand(operand, location);
682 }
683
684 fn visit_const_operand(&mut self, constant: &ConstOperand<'tcx>, location: Location) {
685 trace!("visit_const_operand: {:?}", constant);
686 self.super_const_operand(constant, location);
687 self.eval_constant(constant);
688 }
689
690 fn visit_assign(&mut self, place: &Place<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
691 self.super_assign(place, rvalue, location);
692
693 let Some(()) = self.check_rvalue(rvalue, location) else { return };
694
695 match self.can_const_prop[place.local] {
696 _ if place.is_indirect() => {}
698 ConstPropMode::NoPropagation => self.ensure_not_propagated(place.local),
699 ConstPropMode::OnlyInsideOwnBlock | ConstPropMode::FullConstProp => {
700 if self.eval_rvalue(rvalue, place).is_none() {
701 trace!(
712 "propagation into {:?} failed.
713 Nuking the entire site from orbit, it's the only way to be sure",
714 place,
715 );
716 self.remove_const(place.local);
717 }
718 }
719 }
720 }
721
722 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
723 trace!("visit_statement: {:?}", statement);
724
725 self.super_statement(statement, location);
728
729 match statement.kind {
730 StatementKind::SetDiscriminant { ref place, variant_index } => {
731 match self.can_const_prop[place.local] {
732 _ if place.is_indirect() => {}
734 ConstPropMode::NoPropagation => self.ensure_not_propagated(place.local),
735 ConstPropMode::FullConstProp | ConstPropMode::OnlyInsideOwnBlock => {
736 match self.access_mut(place) {
737 Some(Value::Aggregate { variant, .. }) => *variant = variant_index,
738 _ => self.remove_const(place.local),
739 }
740 }
741 }
742 }
743 StatementKind::StorageLive(local) => {
744 self.remove_const(local);
745 }
746 StatementKind::StorageDead(local) => {
747 self.remove_const(local);
748 }
749 _ => {}
750 }
751 }
752
753 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
754 self.super_terminator(terminator, location);
755 match &terminator.kind {
756 TerminatorKind::Assert { expected, msg, cond, .. } => {
757 self.check_assertion(*expected, msg, cond, location);
758 }
759 TerminatorKind::SwitchInt { discr, targets } => {
760 if let Some(ref value) = self.eval_operand(discr)
761 && let Some(value_const) = self.use_ecx(|this| this.ecx.read_scalar(value))
762 && let Some(constant) = value_const.to_bits(value_const.size()).discard_err()
763 {
764 let target = targets.target_for_value(constant);
767 self.worklist.push(target);
768 return;
769 }
770 }
772 TerminatorKind::Call { func, args: _, .. } => {
773 if let Some((def_id, generic_args)) = func.const_fn_def() {
774 for (index, arg) in generic_args.iter().enumerate() {
775 if let GenericArgKind::Const(ct) = arg.kind() {
776 let generics = self.tcx.generics_of(def_id);
777 let param_def = generics.param_at(index, self.tcx);
778
779 if let GenericParamDefKind::Const { .. } = param_def.kind
780 && find_attr!(self.tcx, param_def.def_id, RustcPanicsWhenZero)
781 && let Some(0) = ct.try_to_target_usize(self.tcx)
782 {
783 let source_info = self.body.source_info(location);
788 if let Some(lint_root) = self.lint_root(*source_info) {
789 self.tcx.emit_node_span_lint(
790 UNCONDITIONAL_PANIC,
791 lint_root,
792 source_info.span,
793 ConstNIsZero {
794 const_param_span: source_info.span,
795 const_param_name: param_def.name,
796 },
797 );
798 }
799 }
800 }
801 }
802 }
803 }
804 TerminatorKind::Goto { .. }
806 | TerminatorKind::UnwindResume
807 | TerminatorKind::UnwindTerminate(_)
808 | TerminatorKind::Return
809 | TerminatorKind::TailCall { .. }
810 | TerminatorKind::Unreachable
811 | TerminatorKind::Drop { .. }
812 | TerminatorKind::Yield { .. }
813 | TerminatorKind::CoroutineDrop
814 | TerminatorKind::FalseEdge { .. }
815 | TerminatorKind::FalseUnwind { .. }
816 | TerminatorKind::InlineAsm { .. } => {}
817 }
818
819 self.worklist.extend(terminator.successors());
820 }
821
822 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &BasicBlockData<'tcx>) {
823 self.super_basic_block_data(block, data);
824
825 let mut written_only_inside_own_block_locals =
829 std::mem::take(&mut self.written_only_inside_own_block_locals);
830
831 #[allow(rustc::potential_query_instability)]
836 for local in written_only_inside_own_block_locals.drain() {
837 debug_assert_eq!(self.can_const_prop[local], ConstPropMode::OnlyInsideOwnBlock);
838 self.remove_const(local);
839 }
840 self.written_only_inside_own_block_locals = written_only_inside_own_block_locals;
841
842 if cfg!(debug_assertions) {
843 for (local, &mode) in self.can_const_prop.iter_enumerated() {
844 match mode {
845 ConstPropMode::FullConstProp => {}
846 ConstPropMode::NoPropagation | ConstPropMode::OnlyInsideOwnBlock => {
847 self.ensure_not_propagated(local);
848 }
849 }
850 }
851 }
852 }
853}
854
855const MAX_ALLOC_LIMIT: u64 = 1024;
859
860#[derive(Clone, Copy, Debug, PartialEq)]
862enum ConstPropMode {
863 FullConstProp,
865 OnlyInsideOwnBlock,
867 NoPropagation,
870}
871
872struct CanConstProp {
875 can_const_prop: IndexVec<Local, ConstPropMode>,
876 found_assignment: DenseBitSet<Local>,
878}
879
880impl CanConstProp {
881 fn check<'tcx>(
883 tcx: TyCtxt<'tcx>,
884 typing_env: ty::TypingEnv<'tcx>,
885 body: &Body<'tcx>,
886 ) -> IndexVec<Local, ConstPropMode> {
887 let mut cpv = CanConstProp {
888 can_const_prop: IndexVec::from_elem(ConstPropMode::FullConstProp, &body.local_decls),
889 found_assignment: DenseBitSet::new_empty(body.local_decls.len()),
890 };
891 for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
892 let ty = body.local_decls[local].ty;
893 if ty.is_async_drop_in_place_coroutine(tcx) {
894 *val = ConstPropMode::NoPropagation;
899 continue;
900 } else if ty.is_union() {
901 *val = ConstPropMode::NoPropagation;
905 } else {
906 match tcx.layout_of(typing_env.as_query_input(ty)) {
907 Ok(layout) if layout.size < Size::from_bytes(MAX_ALLOC_LIMIT) => {}
908 _ => {
911 *val = ConstPropMode::NoPropagation;
912 continue;
913 }
914 }
915 }
916 }
917 for arg in body.args_iter() {
919 cpv.found_assignment.insert(arg);
920 }
921 cpv.visit_body(body);
922 cpv.can_const_prop
923 }
924}
925
926impl<'tcx> Visitor<'tcx> for CanConstProp {
927 fn visit_place(&mut self, place: &Place<'tcx>, mut context: PlaceContext, loc: Location) {
928 use rustc_middle::mir::visit::PlaceContext::*;
929
930 if place.projection.first() == Some(&PlaceElem::Deref) {
932 context = NonMutatingUse(NonMutatingUseContext::Copy);
933 }
934
935 self.visit_local(place.local, context, loc);
936 self.visit_projection(place.as_ref(), context, loc);
937 }
938
939 fn visit_local(&mut self, local: Local, context: PlaceContext, _: Location) {
940 use rustc_middle::mir::visit::PlaceContext::*;
941 match context {
942 | MutatingUse(MutatingUseContext::Call)
945 | MutatingUse(MutatingUseContext::AsmOutput)
946 | MutatingUse(MutatingUseContext::Store)
948 | MutatingUse(MutatingUseContext::SetDiscriminant) => {
949 if !self.found_assignment.insert(local) {
950 match &mut self.can_const_prop[local] {
951 ConstPropMode::OnlyInsideOwnBlock => {}
956 ConstPropMode::NoPropagation => {}
957 other @ ConstPropMode::FullConstProp => {
958 trace!(
959 "local {:?} can't be propagated because of multiple assignments. Previous state: {:?}",
960 local, other,
961 );
962 *other = ConstPropMode::OnlyInsideOwnBlock;
963 }
964 }
965 }
966 }
967 NonMutatingUse(NonMutatingUseContext::Copy)
969 | NonMutatingUse(NonMutatingUseContext::Move)
970 | NonMutatingUse(NonMutatingUseContext::Inspect)
971 | NonMutatingUse(NonMutatingUseContext::PlaceMention)
972 | NonUse(_) => {}
973
974 MutatingUse(MutatingUseContext::Yield)
977 | MutatingUse(MutatingUseContext::Drop)
978 | NonMutatingUse(NonMutatingUseContext::SharedBorrow)
981 | NonMutatingUse(NonMutatingUseContext::FakeBorrow)
982 | NonMutatingUse(NonMutatingUseContext::RawBorrow)
983 | MutatingUse(MutatingUseContext::Borrow)
984 | MutatingUse(MutatingUseContext::RawBorrow) => {
985 trace!("local {:?} can't be propagated because it's used: {:?}", local, context);
986 self.can_const_prop[local] = ConstPropMode::NoPropagation;
987 }
988 MutatingUse(MutatingUseContext::Projection)
989 | NonMutatingUse(NonMutatingUseContext::Projection) => {
990 bug!("visit_place should not pass {context:?} for {local:?}")
991 }
992 }
993 }
994}