1use std::borrow::Cow;
88use std::hash::{Hash, Hasher};
89
90use either::Either;
91use hashbrown::hash_table::{Entry, HashTable};
92use itertools::Itertools as _;
93use rustc_abi::{self as abi, BackendRepr, FIRST_VARIANT, FieldIdx, Primitive, Size, VariantIdx};
94use rustc_arena::DroplessArena;
95use rustc_const_eval::const_eval::DummyMachine;
96use rustc_const_eval::interpret::{
97 ImmTy, Immediate, InterpCx, MemPlaceMeta, MemoryKind, OpTy, Projectable, Scalar,
98 intern_const_alloc_for_constprop,
99};
100use rustc_data_structures::fx::FxHasher;
101use rustc_data_structures::graph::dominators::Dominators;
102use rustc_hir::def::DefKind;
103use rustc_index::bit_set::DenseBitSet;
104use rustc_index::{IndexVec, newtype_index};
105use rustc_middle::bug;
106use rustc_middle::mir::interpret::GlobalAlloc;
107use rustc_middle::mir::visit::*;
108use rustc_middle::mir::*;
109use rustc_middle::ty::layout::HasTypingEnv;
110use rustc_middle::ty::{self, Ty, TyCtxt};
111use rustc_span::DUMMY_SP;
112use smallvec::SmallVec;
113use tracing::{debug, instrument, trace};
114
115use crate::ssa::SsaLocals;
116
117pub(super) struct GVN;
118
119impl<'tcx> crate::MirPass<'tcx> for GVN {
120 fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
121 sess.mir_opt_level() >= 2
122 }
123
124 #[instrument(level = "trace", skip(self, tcx, body))]
125 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
126 debug!(def_id = ?body.source.def_id());
127
128 let typing_env = body.typing_env(tcx);
129 let ssa = SsaLocals::new(tcx, body, typing_env);
130 let dominators = body.basic_blocks.dominators().clone();
132 let maybe_loop_headers = loops::maybe_loop_headers(body);
133
134 let arena = DroplessArena::default();
135 let mut state =
136 VnState::new(tcx, body, typing_env, &ssa, dominators, &body.local_decls, &arena);
137
138 for local in body.args_iter().filter(|&local| ssa.is_ssa(local)) {
139 let opaque = state.new_opaque(body.local_decls[local].ty);
140 state.assign(local, opaque);
141 }
142
143 let reverse_postorder = body.basic_blocks.reverse_postorder().to_vec();
144 for bb in reverse_postorder {
145 if maybe_loop_headers.contains(bb) {
148 state.invalidate_derefs();
149 }
150 let data = &mut body.basic_blocks.as_mut_preserves_cfg()[bb];
151 state.visit_basic_block_data(bb, data);
152 }
153
154 StorageRemover { tcx, reused_locals: state.reused_locals }.visit_body_preserves_cfg(body);
158 }
159
160 fn is_required(&self) -> bool {
161 false
162 }
163}
164
165newtype_index! {
166 #[debug_format = "_v{}"]
168 struct VnIndex {}
169}
170
171#[derive(Copy, Clone, Debug, Eq)]
175struct VnOpaque;
176impl PartialEq for VnOpaque {
177 fn eq(&self, _: &VnOpaque) -> bool {
178 unreachable!()
180 }
181}
182impl Hash for VnOpaque {
183 fn hash<T: Hasher>(&self, _: &mut T) {
184 unreachable!()
186 }
187}
188
189#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
190enum AddressKind {
191 Ref(BorrowKind),
192 Address(RawPtrKind),
193}
194
195#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
196enum AddressBase {
197 Local(Local),
199 Deref(VnIndex),
201}
202
203#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
204enum Value<'a, 'tcx> {
205 Opaque(VnOpaque),
209 Constant {
211 value: Const<'tcx>,
212 disambiguator: Option<VnOpaque>,
216 },
217
218 Aggregate(VariantIdx, &'a [VnIndex]),
222 Union(FieldIdx, VnIndex),
224 RawPtr {
226 pointer: VnIndex,
228 metadata: VnIndex,
230 },
231 Repeat(VnIndex, ty::Const<'tcx>),
233 Address {
235 base: AddressBase,
236 projection: &'a [ProjectionElem<VnIndex, Ty<'tcx>>],
239 kind: AddressKind,
240 provenance: VnOpaque,
242 },
243
244 Projection(VnIndex, ProjectionElem<VnIndex, ()>),
247 Discriminant(VnIndex),
249
250 NullaryOp(NullOp),
252 UnaryOp(UnOp, VnIndex),
253 BinaryOp(BinOp, VnIndex, VnIndex),
254 Cast {
255 kind: CastKind,
256 value: VnIndex,
257 },
258}
259
260struct ValueSet<'a, 'tcx> {
266 indices: HashTable<VnIndex>,
267 hashes: IndexVec<VnIndex, u64>,
268 values: IndexVec<VnIndex, Value<'a, 'tcx>>,
269 types: IndexVec<VnIndex, Ty<'tcx>>,
270}
271
272impl<'a, 'tcx> ValueSet<'a, 'tcx> {
273 fn new(num_values: usize) -> ValueSet<'a, 'tcx> {
274 ValueSet {
275 indices: HashTable::with_capacity(num_values),
276 hashes: IndexVec::with_capacity(num_values),
277 values: IndexVec::with_capacity(num_values),
278 types: IndexVec::with_capacity(num_values),
279 }
280 }
281
282 #[inline]
285 fn insert_unique(
286 &mut self,
287 ty: Ty<'tcx>,
288 value: impl FnOnce(VnOpaque) -> Value<'a, 'tcx>,
289 ) -> VnIndex {
290 let value = value(VnOpaque);
291
292 debug_assert!(match value {
293 Value::Opaque(_) | Value::Address { .. } => true,
294 Value::Constant { disambiguator, .. } => disambiguator.is_some(),
295 _ => false,
296 });
297
298 let index = self.hashes.push(0);
299 let _index = self.types.push(ty);
300 debug_assert_eq!(index, _index);
301 let _index = self.values.push(value);
302 debug_assert_eq!(index, _index);
303 index
304 }
305
306 #[allow(rustc::pass_by_value)] fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> (VnIndex, bool) {
310 debug_assert!(match value {
311 Value::Opaque(_) | Value::Address { .. } => false,
312 Value::Constant { disambiguator, .. } => disambiguator.is_none(),
313 _ => true,
314 });
315
316 let hash: u64 = {
317 let mut h = FxHasher::default();
318 value.hash(&mut h);
319 ty.hash(&mut h);
320 h.finish()
321 };
322
323 let eq = |index: &VnIndex| self.values[*index] == value && self.types[*index] == ty;
324 let hasher = |index: &VnIndex| self.hashes[*index];
325 match self.indices.entry(hash, eq, hasher) {
326 Entry::Occupied(entry) => {
327 let index = *entry.get();
328 (index, false)
329 }
330 Entry::Vacant(entry) => {
331 let index = self.hashes.push(hash);
332 entry.insert(index);
333 let _index = self.values.push(value);
334 debug_assert_eq!(index, _index);
335 let _index = self.types.push(ty);
336 debug_assert_eq!(index, _index);
337 (index, true)
338 }
339 }
340 }
341
342 #[inline]
344 fn value(&self, index: VnIndex) -> Value<'a, 'tcx> {
345 self.values[index]
346 }
347
348 #[inline]
350 fn ty(&self, index: VnIndex) -> Ty<'tcx> {
351 self.types[index]
352 }
353
354 #[inline]
356 fn forget(&mut self, index: VnIndex) {
357 self.values[index] = Value::Opaque(VnOpaque);
358 }
359}
360
361struct VnState<'body, 'a, 'tcx> {
362 tcx: TyCtxt<'tcx>,
363 ecx: InterpCx<'tcx, DummyMachine>,
364 local_decls: &'body LocalDecls<'tcx>,
365 is_coroutine: bool,
366 locals: IndexVec<Local, Option<VnIndex>>,
368 rev_locals: IndexVec<VnIndex, SmallVec<[Local; 1]>>,
371 values: ValueSet<'a, 'tcx>,
372 evaluated: IndexVec<VnIndex, Option<Option<&'a OpTy<'tcx>>>>,
377 derefs: Vec<VnIndex>,
379 ssa: &'body SsaLocals,
380 dominators: Dominators<BasicBlock>,
381 reused_locals: DenseBitSet<Local>,
382 arena: &'a DroplessArena,
383}
384
385impl<'body, 'a, 'tcx> VnState<'body, 'a, 'tcx> {
386 fn new(
387 tcx: TyCtxt<'tcx>,
388 body: &Body<'tcx>,
389 typing_env: ty::TypingEnv<'tcx>,
390 ssa: &'body SsaLocals,
391 dominators: Dominators<BasicBlock>,
392 local_decls: &'body LocalDecls<'tcx>,
393 arena: &'a DroplessArena,
394 ) -> Self {
395 let num_values =
400 2 * body.basic_blocks.iter().map(|bbdata| bbdata.statements.len()).sum::<usize>()
401 + 4 * body.basic_blocks.len();
402 VnState {
403 tcx,
404 ecx: InterpCx::new(tcx, DUMMY_SP, typing_env, DummyMachine),
405 local_decls,
406 is_coroutine: body.coroutine.is_some(),
407 locals: IndexVec::from_elem(None, local_decls),
408 rev_locals: IndexVec::with_capacity(num_values),
409 values: ValueSet::new(num_values),
410 evaluated: IndexVec::with_capacity(num_values),
411 derefs: Vec::new(),
412 ssa,
413 dominators,
414 reused_locals: DenseBitSet::new_empty(local_decls.len()),
415 arena,
416 }
417 }
418
419 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
420 self.ecx.typing_env()
421 }
422
423 #[instrument(level = "trace", skip(self), ret)]
424 fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> VnIndex {
425 let (index, new) = self.values.insert(ty, value);
426 if new {
427 let _index = self.evaluated.push(None);
429 debug_assert_eq!(index, _index);
430 let _index = self.rev_locals.push(SmallVec::new());
431 debug_assert_eq!(index, _index);
432 }
433 index
434 }
435
436 #[instrument(level = "trace", skip(self), ret)]
439 fn new_opaque(&mut self, ty: Ty<'tcx>) -> VnIndex {
440 let index = self.values.insert_unique(ty, Value::Opaque);
441 let _index = self.evaluated.push(Some(None));
442 debug_assert_eq!(index, _index);
443 let _index = self.rev_locals.push(SmallVec::new());
444 debug_assert_eq!(index, _index);
445 index
446 }
447
448 #[instrument(level = "trace", skip(self), ret)]
450 fn new_pointer(&mut self, place: Place<'tcx>, kind: AddressKind) -> Option<VnIndex> {
451 let pty = place.ty(self.local_decls, self.tcx).ty;
452 let ty = match kind {
453 AddressKind::Ref(bk) => {
454 Ty::new_ref(self.tcx, self.tcx.lifetimes.re_erased, pty, bk.to_mutbl_lossy())
455 }
456 AddressKind::Address(mutbl) => Ty::new_ptr(self.tcx, pty, mutbl.to_mutbl_lossy()),
457 };
458
459 let mut projection = place.projection.iter();
460 let base = if place.is_indirect_first_projection() {
461 let base = self.locals[place.local]?;
462 projection.next();
464 AddressBase::Deref(base)
465 } else {
466 AddressBase::Local(place.local)
467 };
468 let projection =
470 projection.map(|proj| proj.try_map(|index| self.locals[index], |ty| ty).ok_or(()));
471 let projection = self.arena.try_alloc_from_iter(projection).ok()?;
472
473 let index = self.values.insert_unique(ty, |provenance| Value::Address {
474 base,
475 projection,
476 kind,
477 provenance,
478 });
479 let _index = self.evaluated.push(None);
480 debug_assert_eq!(index, _index);
481 let _index = self.rev_locals.push(SmallVec::new());
482 debug_assert_eq!(index, _index);
483
484 Some(index)
485 }
486
487 #[instrument(level = "trace", skip(self), ret)]
488 fn insert_constant(&mut self, value: Const<'tcx>) -> VnIndex {
489 let (index, new) = if value.is_deterministic() {
490 let constant = Value::Constant { value, disambiguator: None };
492 self.values.insert(value.ty(), constant)
493 } else {
494 let index = self.values.insert_unique(value.ty(), |disambiguator| Value::Constant {
497 value,
498 disambiguator: Some(disambiguator),
499 });
500 (index, true)
501 };
502 if new {
503 let _index = self.evaluated.push(None);
504 debug_assert_eq!(index, _index);
505 let _index = self.rev_locals.push(SmallVec::new());
506 debug_assert_eq!(index, _index);
507 }
508 index
509 }
510
511 #[inline]
512 fn get(&self, index: VnIndex) -> Value<'a, 'tcx> {
513 self.values.value(index)
514 }
515
516 #[inline]
517 fn ty(&self, index: VnIndex) -> Ty<'tcx> {
518 self.values.ty(index)
519 }
520
521 #[instrument(level = "trace", skip(self))]
523 fn assign(&mut self, local: Local, value: VnIndex) {
524 debug_assert!(self.ssa.is_ssa(local));
525 self.locals[local] = Some(value);
526 self.rev_locals[value].push(local);
527 }
528
529 fn insert_bool(&mut self, flag: bool) -> VnIndex {
530 let value = Const::from_bool(self.tcx, flag);
532 debug_assert!(value.is_deterministic());
533 self.insert(self.tcx.types.bool, Value::Constant { value, disambiguator: None })
534 }
535
536 fn insert_scalar(&mut self, ty: Ty<'tcx>, scalar: Scalar) -> VnIndex {
537 let value = Const::from_scalar(self.tcx, scalar, ty);
539 debug_assert!(value.is_deterministic());
540 self.insert(ty, Value::Constant { value, disambiguator: None })
541 }
542
543 fn insert_tuple(&mut self, ty: Ty<'tcx>, values: &[VnIndex]) -> VnIndex {
544 self.insert(ty, Value::Aggregate(VariantIdx::ZERO, self.arena.alloc_slice(values)))
545 }
546
547 fn insert_deref(&mut self, ty: Ty<'tcx>, value: VnIndex) -> VnIndex {
548 let value = self.insert(ty, Value::Projection(value, ProjectionElem::Deref));
549 self.derefs.push(value);
550 value
551 }
552
553 fn invalidate_derefs(&mut self) {
554 for deref in std::mem::take(&mut self.derefs) {
555 self.values.forget(deref);
556 }
557 }
558
559 #[instrument(level = "trace", skip(self), ret)]
560 fn eval_to_const_inner(&mut self, value: VnIndex) -> Option<OpTy<'tcx>> {
561 use Value::*;
562 let ty = self.ty(value);
563 let ty = if !self.is_coroutine || ty.is_scalar() {
565 self.ecx.layout_of(ty).ok()?
566 } else {
567 return None;
568 };
569 let op = match self.get(value) {
570 _ if ty.is_zst() => ImmTy::uninit(ty).into(),
571
572 Opaque(_) => return None,
573
574 Repeat(value, _count) => {
579 let value = self.eval_to_const(value)?;
580 if value.is_immediate_uninit() {
581 ImmTy::uninit(ty).into()
582 } else {
583 return None;
584 }
585 }
586 Constant { ref value, disambiguator: _ } => {
587 self.ecx.eval_mir_constant(value, DUMMY_SP, None).discard_err()?
588 }
589 Aggregate(variant, ref fields) => {
590 let fields =
591 fields.iter().map(|&f| self.eval_to_const(f)).collect::<Option<Vec<_>>>()?;
592 let variant = if ty.ty.is_enum() { Some(variant) } else { None };
593 let (BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..)) = ty.backend_repr
594 else {
595 return None;
596 };
597 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
598 let variant_dest = if let Some(variant) = variant {
599 self.ecx.project_downcast(&dest, variant).discard_err()?
600 } else {
601 dest.clone()
602 };
603 for (field_index, op) in fields.into_iter().enumerate() {
604 let field_dest = self
605 .ecx
606 .project_field(&variant_dest, FieldIdx::from_usize(field_index))
607 .discard_err()?;
608 self.ecx.copy_op(op, &field_dest).discard_err()?;
609 }
610 self.ecx
611 .write_discriminant(variant.unwrap_or(FIRST_VARIANT), &dest)
612 .discard_err()?;
613 self.ecx
614 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
615 .discard_err()?;
616 dest.into()
617 }
618 Union(active_field, field) => {
619 let field = self.eval_to_const(field)?;
620 if field.layout.layout.is_zst() {
621 ImmTy::from_immediate(Immediate::Uninit, ty).into()
622 } else if matches!(
623 ty.backend_repr,
624 BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..)
625 ) {
626 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
627 let field_dest = self.ecx.project_field(&dest, active_field).discard_err()?;
628 self.ecx.copy_op(field, &field_dest).discard_err()?;
629 self.ecx
630 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
631 .discard_err()?;
632 dest.into()
633 } else {
634 return None;
635 }
636 }
637 RawPtr { pointer, metadata } => {
638 let pointer = self.eval_to_const(pointer)?;
639 let metadata = self.eval_to_const(metadata)?;
640
641 let data = self.ecx.read_pointer(pointer).discard_err()?;
643 let meta = if metadata.layout.is_zst() {
644 MemPlaceMeta::None
645 } else {
646 MemPlaceMeta::Meta(self.ecx.read_scalar(metadata).discard_err()?)
647 };
648 let ptr_imm = Immediate::new_pointer_with_meta(data, meta, &self.ecx);
649 ImmTy::from_immediate(ptr_imm, ty).into()
650 }
651
652 Projection(base, elem) => {
653 let base = self.eval_to_const(base)?;
654 let elem = elem.try_map(|_| None, |()| ty.ty)?;
657 self.ecx.project(base, elem).discard_err()?
658 }
659 Address { base, projection, .. } => {
660 debug_assert!(!projection.contains(&ProjectionElem::Deref));
661 let pointer = match base {
662 AddressBase::Deref(pointer) => self.eval_to_const(pointer)?,
663 AddressBase::Local(_) => return None,
665 };
666 let mut mplace = self.ecx.deref_pointer(pointer).discard_err()?;
667 for elem in projection {
668 let elem = elem.try_map(|_| None, |ty| ty)?;
671 mplace = self.ecx.project(&mplace, elem).discard_err()?;
672 }
673 let pointer = mplace.to_ref(&self.ecx);
674 ImmTy::from_immediate(pointer, ty).into()
675 }
676
677 Discriminant(base) => {
678 let base = self.eval_to_const(base)?;
679 let variant = self.ecx.read_discriminant(base).discard_err()?;
680 let discr_value =
681 self.ecx.discriminant_for_variant(base.layout.ty, variant).discard_err()?;
682 discr_value.into()
683 }
684 NullaryOp(NullOp::RuntimeChecks(_)) => return None,
685 UnaryOp(un_op, operand) => {
686 let operand = self.eval_to_const(operand)?;
687 let operand = self.ecx.read_immediate(operand).discard_err()?;
688 let val = self.ecx.unary_op(un_op, &operand).discard_err()?;
689 val.into()
690 }
691 BinaryOp(bin_op, lhs, rhs) => {
692 let lhs = self.eval_to_const(lhs)?;
693 let rhs = self.eval_to_const(rhs)?;
694 let lhs = self.ecx.read_immediate(lhs).discard_err()?;
695 let rhs = self.ecx.read_immediate(rhs).discard_err()?;
696 let val = self.ecx.binary_op(bin_op, &lhs, &rhs).discard_err()?;
697 val.into()
698 }
699 Cast { kind, value } => match kind {
700 CastKind::IntToInt | CastKind::IntToFloat => {
701 let value = self.eval_to_const(value)?;
702 let value = self.ecx.read_immediate(value).discard_err()?;
703 let res = self.ecx.int_to_int_or_float(&value, ty).discard_err()?;
704 res.into()
705 }
706 CastKind::FloatToFloat | CastKind::FloatToInt => {
707 let value = self.eval_to_const(value)?;
708 let value = self.ecx.read_immediate(value).discard_err()?;
709 let res = self.ecx.float_to_float_or_int(&value, ty).discard_err()?;
710 res.into()
711 }
712 CastKind::Transmute | CastKind::Subtype => {
713 let value = self.eval_to_const(value)?;
714 if value.as_mplace_or_imm().is_right() {
719 let can_transmute = match (value.layout.backend_repr, ty.backend_repr) {
720 (BackendRepr::Scalar(s1), BackendRepr::Scalar(s2)) => {
721 s1.size(&self.ecx) == s2.size(&self.ecx)
722 && !matches!(s1.primitive(), Primitive::Pointer(..))
723 }
724 (BackendRepr::ScalarPair(a1, b1), BackendRepr::ScalarPair(a2, b2)) => {
725 a1.size(&self.ecx) == a2.size(&self.ecx)
726 && b1.size(&self.ecx) == b2.size(&self.ecx)
727 && b1.align(&self.ecx) == b2.align(&self.ecx)
729 && !matches!(a1.primitive(), Primitive::Pointer(..))
731 && !matches!(b1.primitive(), Primitive::Pointer(..))
732 }
733 _ => false,
734 };
735 if !can_transmute {
736 return None;
737 }
738 }
739 value.offset(Size::ZERO, ty, &self.ecx).discard_err()?
740 }
741 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _) => {
742 let src = self.eval_to_const(value)?;
743 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
744 self.ecx.unsize_into(src, ty, &dest).discard_err()?;
745 self.ecx
746 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
747 .discard_err()?;
748 dest.into()
749 }
750 CastKind::FnPtrToPtr | CastKind::PtrToPtr => {
751 let src = self.eval_to_const(value)?;
752 let src = self.ecx.read_immediate(src).discard_err()?;
753 let ret = self.ecx.ptr_to_ptr(&src, ty).discard_err()?;
754 ret.into()
755 }
756 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::UnsafeFnPointer, _) => {
757 let src = self.eval_to_const(value)?;
758 let src = self.ecx.read_immediate(src).discard_err()?;
759 ImmTy::from_immediate(*src, ty).into()
760 }
761 _ => return None,
762 },
763 };
764 Some(op)
765 }
766
767 fn eval_to_const(&mut self, index: VnIndex) -> Option<&'a OpTy<'tcx>> {
768 if let Some(op) = self.evaluated[index] {
769 return op;
770 }
771 let op = self.eval_to_const_inner(index);
772 self.evaluated[index] = Some(self.arena.alloc(op).as_ref());
773 self.evaluated[index].unwrap()
774 }
775
776 #[instrument(level = "trace", skip(self), ret)]
778 fn dereference_address(
779 &mut self,
780 base: AddressBase,
781 projection: &[ProjectionElem<VnIndex, Ty<'tcx>>],
782 ) -> Option<VnIndex> {
783 let (mut place_ty, mut value) = match base {
784 AddressBase::Local(local) => {
786 let local = self.locals[local]?;
787 let place_ty = PlaceTy::from_ty(self.ty(local));
788 (place_ty, local)
789 }
790 AddressBase::Deref(reborrow) => {
792 let place_ty = PlaceTy::from_ty(self.ty(reborrow));
793 self.project(place_ty, reborrow, ProjectionElem::Deref)?
794 }
795 };
796 for &proj in projection {
797 (place_ty, value) = self.project(place_ty, value, proj)?;
798 }
799 Some(value)
800 }
801
802 #[instrument(level = "trace", skip(self), ret)]
803 fn project(
804 &mut self,
805 place_ty: PlaceTy<'tcx>,
806 value: VnIndex,
807 proj: ProjectionElem<VnIndex, Ty<'tcx>>,
808 ) -> Option<(PlaceTy<'tcx>, VnIndex)> {
809 let projection_ty = place_ty.projection_ty(self.tcx, proj);
810 let proj = match proj {
811 ProjectionElem::Deref => {
812 if let Some(Mutability::Not) = place_ty.ty.ref_mutability()
813 && projection_ty.ty.is_freeze(self.tcx, self.typing_env())
814 {
815 if let Value::Address { base, projection, .. } = self.get(value)
816 && let Some(value) = self.dereference_address(base, projection)
817 {
818 return Some((projection_ty, value));
819 }
820
821 return Some((projection_ty, self.insert_deref(projection_ty.ty, value)));
824 } else {
825 return None;
826 }
827 }
828 ProjectionElem::Downcast(name, index) => ProjectionElem::Downcast(name, index),
829 ProjectionElem::Field(f, _) => match self.get(value) {
830 Value::Aggregate(_, fields) => return Some((projection_ty, fields[f.as_usize()])),
831 Value::Union(active, field) if active == f => return Some((projection_ty, field)),
832 Value::Projection(outer_value, ProjectionElem::Downcast(_, read_variant))
833 if let Value::Aggregate(written_variant, fields) = self.get(outer_value)
834 && written_variant == read_variant =>
850 {
851 return Some((projection_ty, fields[f.as_usize()]));
852 }
853 _ => ProjectionElem::Field(f, ()),
854 },
855 ProjectionElem::Index(idx) => {
856 if let Value::Repeat(inner, _) = self.get(value) {
857 return Some((projection_ty, inner));
858 }
859 ProjectionElem::Index(idx)
860 }
861 ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
862 match self.get(value) {
863 Value::Repeat(inner, _) => {
864 return Some((projection_ty, inner));
865 }
866 Value::Aggregate(_, operands) => {
867 let offset = if from_end {
868 operands.len() - offset as usize
869 } else {
870 offset as usize
871 };
872 let value = operands.get(offset).copied()?;
873 return Some((projection_ty, value));
874 }
875 _ => {}
876 };
877 ProjectionElem::ConstantIndex { offset, min_length, from_end }
878 }
879 ProjectionElem::Subslice { from, to, from_end } => {
880 ProjectionElem::Subslice { from, to, from_end }
881 }
882 ProjectionElem::OpaqueCast(_) => ProjectionElem::OpaqueCast(()),
883 ProjectionElem::UnwrapUnsafeBinder(_) => ProjectionElem::UnwrapUnsafeBinder(()),
884 };
885
886 let value = self.insert(projection_ty.ty, Value::Projection(value, proj));
887 Some((projection_ty, value))
888 }
889
890 #[instrument(level = "trace", skip(self))]
892 fn simplify_place_projection(&mut self, place: &mut Place<'tcx>, location: Location) {
893 if place.is_indirect_first_projection()
896 && let Some(base) = self.locals[place.local]
897 && let Some(new_local) = self.try_as_local(base, location)
898 && place.local != new_local
899 {
900 place.local = new_local;
901 self.reused_locals.insert(new_local);
902 }
903
904 let mut projection = Cow::Borrowed(&place.projection[..]);
905
906 for i in 0..projection.len() {
907 let elem = projection[i];
908 if let ProjectionElem::Index(idx_local) = elem
909 && let Some(idx) = self.locals[idx_local]
910 {
911 if let Some(offset) = self.eval_to_const(idx)
912 && let Some(offset) = self.ecx.read_target_usize(offset).discard_err()
913 && let Some(min_length) = offset.checked_add(1)
914 {
915 projection.to_mut()[i] =
916 ProjectionElem::ConstantIndex { offset, min_length, from_end: false };
917 } else if let Some(new_idx_local) = self.try_as_local(idx, location)
918 && idx_local != new_idx_local
919 {
920 projection.to_mut()[i] = ProjectionElem::Index(new_idx_local);
921 self.reused_locals.insert(new_idx_local);
922 }
923 }
924 }
925
926 if Cow::is_owned(&projection) {
927 place.projection = self.tcx.mk_place_elems(&projection);
928 }
929
930 trace!(?place);
931 }
932
933 #[instrument(level = "trace", skip(self), ret)]
936 fn compute_place_value(
937 &mut self,
938 place: Place<'tcx>,
939 location: Location,
940 ) -> Result<VnIndex, PlaceRef<'tcx>> {
941 let mut place_ref = place.as_ref();
944
945 let Some(mut value) = self.locals[place.local] else { return Err(place_ref) };
947 let mut place_ty = PlaceTy::from_ty(self.local_decls[place.local].ty);
949 for (index, proj) in place.projection.iter().enumerate() {
950 if let Some(local) = self.try_as_local(value, location) {
951 place_ref = PlaceRef { local, projection: &place.projection[index..] };
955 }
956
957 let Some(proj) = proj.try_map(|value| self.locals[value], |ty| ty) else {
958 return Err(place_ref);
959 };
960 let Some(ty_and_value) = self.project(place_ty, value, proj) else {
961 return Err(place_ref);
962 };
963 (place_ty, value) = ty_and_value;
964 }
965
966 Ok(value)
967 }
968
969 #[instrument(level = "trace", skip(self), ret)]
972 fn simplify_place_value(
973 &mut self,
974 place: &mut Place<'tcx>,
975 location: Location,
976 ) -> Option<VnIndex> {
977 self.simplify_place_projection(place, location);
978
979 match self.compute_place_value(*place, location) {
980 Ok(value) => {
981 if let Some(new_place) = self.try_as_place(value, location, true)
982 && (new_place.local != place.local
983 || new_place.projection.len() < place.projection.len())
984 {
985 *place = new_place;
986 self.reused_locals.insert(new_place.local);
987 }
988 Some(value)
989 }
990 Err(place_ref) => {
991 if place_ref.local != place.local
992 || place_ref.projection.len() < place.projection.len()
993 {
994 *place = place_ref.project_deeper(&[], self.tcx);
996 self.reused_locals.insert(place_ref.local);
997 }
998 None
999 }
1000 }
1001 }
1002
1003 #[instrument(level = "trace", skip(self), ret)]
1004 fn simplify_operand(
1005 &mut self,
1006 operand: &mut Operand<'tcx>,
1007 location: Location,
1008 ) -> Option<VnIndex> {
1009 match *operand {
1010 Operand::Constant(ref constant) => Some(self.insert_constant(constant.const_)),
1011 Operand::Copy(ref mut place) | Operand::Move(ref mut place) => {
1012 let value = self.simplify_place_value(place, location)?;
1013 if let Some(const_) = self.try_as_constant(value) {
1014 *operand = Operand::Constant(Box::new(const_));
1015 }
1016 Some(value)
1017 }
1018 }
1019 }
1020
1021 #[instrument(level = "trace", skip(self), ret)]
1022 fn simplify_rvalue(
1023 &mut self,
1024 lhs: &Place<'tcx>,
1025 rvalue: &mut Rvalue<'tcx>,
1026 location: Location,
1027 ) -> Option<VnIndex> {
1028 let value = match *rvalue {
1029 Rvalue::Use(ref mut operand) => return self.simplify_operand(operand, location),
1031
1032 Rvalue::Repeat(ref mut op, amount) => {
1034 let op = self.simplify_operand(op, location)?;
1035 Value::Repeat(op, amount)
1036 }
1037 Rvalue::NullaryOp(op) => Value::NullaryOp(op),
1038 Rvalue::Aggregate(..) => return self.simplify_aggregate(lhs, rvalue, location),
1039 Rvalue::Ref(_, borrow_kind, ref mut place) => {
1040 self.simplify_place_projection(place, location);
1041 return self.new_pointer(*place, AddressKind::Ref(borrow_kind));
1042 }
1043 Rvalue::RawPtr(mutbl, ref mut place) => {
1044 self.simplify_place_projection(place, location);
1045 return self.new_pointer(*place, AddressKind::Address(mutbl));
1046 }
1047 Rvalue::WrapUnsafeBinder(ref mut op, _) => {
1048 let value = self.simplify_operand(op, location)?;
1049 Value::Cast { kind: CastKind::Transmute, value }
1050 }
1051
1052 Rvalue::Cast(ref mut kind, ref mut value, to) => {
1054 return self.simplify_cast(kind, value, to, location);
1055 }
1056 Rvalue::BinaryOp(op, box (ref mut lhs, ref mut rhs)) => {
1057 return self.simplify_binary(op, lhs, rhs, location);
1058 }
1059 Rvalue::UnaryOp(op, ref mut arg_op) => {
1060 return self.simplify_unary(op, arg_op, location);
1061 }
1062 Rvalue::Discriminant(ref mut place) => {
1063 let place = self.simplify_place_value(place, location)?;
1064 if let Some(discr) = self.simplify_discriminant(place) {
1065 return Some(discr);
1066 }
1067 Value::Discriminant(place)
1068 }
1069
1070 Rvalue::ThreadLocalRef(..) => return None,
1072 Rvalue::CopyForDeref(_) | Rvalue::ShallowInitBox(..) => {
1073 bug!("forbidden in runtime MIR: {rvalue:?}")
1074 }
1075 };
1076 let ty = rvalue.ty(self.local_decls, self.tcx);
1077 Some(self.insert(ty, value))
1078 }
1079
1080 fn simplify_discriminant(&mut self, place: VnIndex) -> Option<VnIndex> {
1081 let enum_ty = self.ty(place);
1082 if enum_ty.is_enum()
1083 && let Value::Aggregate(variant, _) = self.get(place)
1084 {
1085 let discr = self.ecx.discriminant_for_variant(enum_ty, variant).discard_err()?;
1086 return Some(self.insert_scalar(discr.layout.ty, discr.to_scalar()));
1087 }
1088
1089 None
1090 }
1091
1092 fn try_as_place_elem(
1093 &mut self,
1094 ty: Ty<'tcx>,
1095 proj: ProjectionElem<VnIndex, ()>,
1096 loc: Location,
1097 ) -> Option<PlaceElem<'tcx>> {
1098 proj.try_map(
1099 |value| {
1100 let local = self.try_as_local(value, loc)?;
1101 self.reused_locals.insert(local);
1102 Some(local)
1103 },
1104 |()| ty,
1105 )
1106 }
1107
1108 fn simplify_aggregate_to_copy(
1109 &mut self,
1110 ty: Ty<'tcx>,
1111 variant_index: VariantIdx,
1112 fields: &[VnIndex],
1113 ) -> Option<VnIndex> {
1114 let Some(&first_field) = fields.first() else { return None };
1115 let Value::Projection(copy_from_value, _) = self.get(first_field) else { return None };
1116
1117 if fields.iter().enumerate().any(|(index, &v)| {
1119 if let Value::Projection(pointer, ProjectionElem::Field(from_index, _)) = self.get(v)
1120 && copy_from_value == pointer
1121 && from_index.index() == index
1122 {
1123 return false;
1124 }
1125 true
1126 }) {
1127 return None;
1128 }
1129
1130 let mut copy_from_local_value = copy_from_value;
1131 if let Value::Projection(pointer, proj) = self.get(copy_from_value)
1132 && let ProjectionElem::Downcast(_, read_variant) = proj
1133 {
1134 if variant_index == read_variant {
1135 copy_from_local_value = pointer;
1137 } else {
1138 return None;
1140 }
1141 }
1142
1143 if self.ty(copy_from_local_value) == ty { Some(copy_from_local_value) } else { None }
1145 }
1146
1147 fn simplify_aggregate(
1148 &mut self,
1149 lhs: &Place<'tcx>,
1150 rvalue: &mut Rvalue<'tcx>,
1151 location: Location,
1152 ) -> Option<VnIndex> {
1153 let tcx = self.tcx;
1154 let ty = rvalue.ty(self.local_decls, tcx);
1155
1156 let Rvalue::Aggregate(box ref kind, ref mut field_ops) = *rvalue else { bug!() };
1157
1158 if field_ops.is_empty() {
1159 let is_zst = match *kind {
1160 AggregateKind::Array(..)
1161 | AggregateKind::Tuple
1162 | AggregateKind::Closure(..)
1163 | AggregateKind::CoroutineClosure(..) => true,
1164 AggregateKind::Adt(did, ..) => tcx.def_kind(did) != DefKind::Enum,
1166 AggregateKind::Coroutine(..) => false,
1168 AggregateKind::RawPtr(..) => bug!("MIR for RawPtr aggregate must have 2 fields"),
1169 };
1170
1171 if is_zst {
1172 return Some(self.insert_constant(Const::zero_sized(ty)));
1173 }
1174 }
1175
1176 let fields = self.arena.alloc_from_iter(field_ops.iter_mut().map(|op| {
1177 self.simplify_operand(op, location)
1178 .unwrap_or_else(|| self.new_opaque(op.ty(self.local_decls, self.tcx)))
1179 }));
1180
1181 let variant_index = match *kind {
1182 AggregateKind::Array(..) | AggregateKind::Tuple => {
1183 assert!(!field_ops.is_empty());
1184 FIRST_VARIANT
1185 }
1186 AggregateKind::Closure(..)
1187 | AggregateKind::CoroutineClosure(..)
1188 | AggregateKind::Coroutine(..) => FIRST_VARIANT,
1189 AggregateKind::Adt(_, variant_index, _, _, None) => variant_index,
1190 AggregateKind::Adt(_, _, _, _, Some(active_field)) => {
1192 let field = *fields.first()?;
1193 return Some(self.insert(ty, Value::Union(active_field, field)));
1194 }
1195 AggregateKind::RawPtr(..) => {
1196 assert_eq!(field_ops.len(), 2);
1197 let [mut pointer, metadata] = fields.try_into().unwrap();
1198
1199 let mut was_updated = false;
1201 while let Value::Cast { kind: CastKind::PtrToPtr, value: cast_value } =
1202 self.get(pointer)
1203 && let ty::RawPtr(from_pointee_ty, from_mtbl) = self.ty(cast_value).kind()
1204 && let ty::RawPtr(_, output_mtbl) = ty.kind()
1205 && from_mtbl == output_mtbl
1206 && from_pointee_ty.is_sized(self.tcx, self.typing_env())
1207 {
1208 pointer = cast_value;
1209 was_updated = true;
1210 }
1211
1212 if was_updated && let Some(op) = self.try_as_operand(pointer, location) {
1213 field_ops[FieldIdx::ZERO] = op;
1214 }
1215
1216 return Some(self.insert(ty, Value::RawPtr { pointer, metadata }));
1217 }
1218 };
1219
1220 if ty.is_array()
1221 && fields.len() > 4
1222 && let Ok(&first) = fields.iter().all_equal_value()
1223 {
1224 let len = ty::Const::from_target_usize(self.tcx, fields.len().try_into().unwrap());
1225 if let Some(op) = self.try_as_operand(first, location) {
1226 *rvalue = Rvalue::Repeat(op, len);
1227 }
1228 return Some(self.insert(ty, Value::Repeat(first, len)));
1229 }
1230
1231 if let Some(value) = self.simplify_aggregate_to_copy(ty, variant_index, &fields) {
1232 let allow_complex_projection =
1236 lhs.projection[..].iter().all(PlaceElem::is_stable_offset);
1237 if let Some(place) = self.try_as_place(value, location, allow_complex_projection) {
1238 self.reused_locals.insert(place.local);
1239 *rvalue = Rvalue::Use(Operand::Copy(place));
1240 }
1241 return Some(value);
1242 }
1243
1244 Some(self.insert(ty, Value::Aggregate(variant_index, fields)))
1245 }
1246
1247 #[instrument(level = "trace", skip(self), ret)]
1248 fn simplify_unary(
1249 &mut self,
1250 op: UnOp,
1251 arg_op: &mut Operand<'tcx>,
1252 location: Location,
1253 ) -> Option<VnIndex> {
1254 let mut arg_index = self.simplify_operand(arg_op, location)?;
1255 let arg_ty = self.ty(arg_index);
1256 let ret_ty = op.ty(self.tcx, arg_ty);
1257
1258 if op == UnOp::PtrMetadata {
1261 let mut was_updated = false;
1262 loop {
1263 arg_index = match self.get(arg_index) {
1264 Value::Cast { kind: CastKind::PtrToPtr, value: inner }
1273 if self.pointers_have_same_metadata(self.ty(inner), arg_ty) =>
1274 {
1275 inner
1276 }
1277
1278 Value::Cast {
1280 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1281 value: from,
1282 } if let Some(from) = self.ty(from).builtin_deref(true)
1283 && let ty::Array(_, len) = from.kind()
1284 && let Some(to) = self.ty(arg_index).builtin_deref(true)
1285 && let ty::Slice(..) = to.kind() =>
1286 {
1287 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1288 }
1289
1290 Value::Address { base: AddressBase::Deref(reborrowed), projection, .. }
1292 if projection.is_empty() =>
1293 {
1294 reborrowed
1295 }
1296
1297 _ => break,
1298 };
1299 was_updated = true;
1300 }
1301
1302 if was_updated && let Some(op) = self.try_as_operand(arg_index, location) {
1303 *arg_op = op;
1304 }
1305 }
1306
1307 let value = match (op, self.get(arg_index)) {
1308 (UnOp::Not, Value::UnaryOp(UnOp::Not, inner)) => return Some(inner),
1309 (UnOp::Neg, Value::UnaryOp(UnOp::Neg, inner)) => return Some(inner),
1310 (UnOp::Not, Value::BinaryOp(BinOp::Eq, lhs, rhs)) => {
1311 Value::BinaryOp(BinOp::Ne, lhs, rhs)
1312 }
1313 (UnOp::Not, Value::BinaryOp(BinOp::Ne, lhs, rhs)) => {
1314 Value::BinaryOp(BinOp::Eq, lhs, rhs)
1315 }
1316 (UnOp::PtrMetadata, Value::RawPtr { metadata, .. }) => return Some(metadata),
1317 (
1319 UnOp::PtrMetadata,
1320 Value::Cast {
1321 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1322 value: inner,
1323 },
1324 ) if let ty::Slice(..) = arg_ty.builtin_deref(true).unwrap().kind()
1325 && let ty::Array(_, len) = self.ty(inner).builtin_deref(true).unwrap().kind() =>
1326 {
1327 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1328 }
1329 _ => Value::UnaryOp(op, arg_index),
1330 };
1331 Some(self.insert(ret_ty, value))
1332 }
1333
1334 #[instrument(level = "trace", skip(self), ret)]
1335 fn simplify_binary(
1336 &mut self,
1337 op: BinOp,
1338 lhs_operand: &mut Operand<'tcx>,
1339 rhs_operand: &mut Operand<'tcx>,
1340 location: Location,
1341 ) -> Option<VnIndex> {
1342 let lhs = self.simplify_operand(lhs_operand, location);
1343 let rhs = self.simplify_operand(rhs_operand, location);
1344
1345 let mut lhs = lhs?;
1348 let mut rhs = rhs?;
1349
1350 let lhs_ty = self.ty(lhs);
1351
1352 if let BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge = op
1355 && lhs_ty.is_any_ptr()
1356 && let Value::Cast { kind: CastKind::PtrToPtr, value: lhs_value } = self.get(lhs)
1357 && let Value::Cast { kind: CastKind::PtrToPtr, value: rhs_value } = self.get(rhs)
1358 && let lhs_from = self.ty(lhs_value)
1359 && lhs_from == self.ty(rhs_value)
1360 && self.pointers_have_same_metadata(lhs_from, lhs_ty)
1361 {
1362 lhs = lhs_value;
1363 rhs = rhs_value;
1364 if let Some(lhs_op) = self.try_as_operand(lhs, location)
1365 && let Some(rhs_op) = self.try_as_operand(rhs, location)
1366 {
1367 *lhs_operand = lhs_op;
1368 *rhs_operand = rhs_op;
1369 }
1370 }
1371
1372 if let Some(value) = self.simplify_binary_inner(op, lhs_ty, lhs, rhs) {
1373 return Some(value);
1374 }
1375 let ty = op.ty(self.tcx, lhs_ty, self.ty(rhs));
1376 let value = Value::BinaryOp(op, lhs, rhs);
1377 Some(self.insert(ty, value))
1378 }
1379
1380 fn simplify_binary_inner(
1381 &mut self,
1382 op: BinOp,
1383 lhs_ty: Ty<'tcx>,
1384 lhs: VnIndex,
1385 rhs: VnIndex,
1386 ) -> Option<VnIndex> {
1387 let reasonable_ty =
1389 lhs_ty.is_integral() || lhs_ty.is_bool() || lhs_ty.is_char() || lhs_ty.is_any_ptr();
1390 if !reasonable_ty {
1391 return None;
1392 }
1393
1394 let layout = self.ecx.layout_of(lhs_ty).ok()?;
1395
1396 let mut as_bits = |value: VnIndex| {
1397 let constant = self.eval_to_const(value)?;
1398 if layout.backend_repr.is_scalar() {
1399 let scalar = self.ecx.read_scalar(constant).discard_err()?;
1400 scalar.to_bits(constant.layout.size).discard_err()
1401 } else {
1402 None
1404 }
1405 };
1406
1407 use Either::{Left, Right};
1409 let a = as_bits(lhs).map_or(Right(lhs), Left);
1410 let b = as_bits(rhs).map_or(Right(rhs), Left);
1411
1412 let result = match (op, a, b) {
1413 (
1415 BinOp::Add
1416 | BinOp::AddWithOverflow
1417 | BinOp::AddUnchecked
1418 | BinOp::BitOr
1419 | BinOp::BitXor,
1420 Left(0),
1421 Right(p),
1422 )
1423 | (
1424 BinOp::Add
1425 | BinOp::AddWithOverflow
1426 | BinOp::AddUnchecked
1427 | BinOp::BitOr
1428 | BinOp::BitXor
1429 | BinOp::Sub
1430 | BinOp::SubWithOverflow
1431 | BinOp::SubUnchecked
1432 | BinOp::Offset
1433 | BinOp::Shl
1434 | BinOp::Shr,
1435 Right(p),
1436 Left(0),
1437 )
1438 | (BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked, Left(1), Right(p))
1439 | (
1440 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::Div,
1441 Right(p),
1442 Left(1),
1443 ) => p,
1444 (BinOp::BitAnd, Right(p), Left(ones)) | (BinOp::BitAnd, Left(ones), Right(p))
1446 if ones == layout.size.truncate(u128::MAX)
1447 || (layout.ty.is_bool() && ones == 1) =>
1448 {
1449 p
1450 }
1451 (
1453 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::BitAnd,
1454 _,
1455 Left(0),
1456 )
1457 | (BinOp::Rem, _, Left(1))
1458 | (
1459 BinOp::Mul
1460 | BinOp::MulWithOverflow
1461 | BinOp::MulUnchecked
1462 | BinOp::Div
1463 | BinOp::Rem
1464 | BinOp::BitAnd
1465 | BinOp::Shl
1466 | BinOp::Shr,
1467 Left(0),
1468 _,
1469 ) => self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size)),
1470 (BinOp::BitOr, _, Left(ones)) | (BinOp::BitOr, Left(ones), _)
1472 if ones == layout.size.truncate(u128::MAX)
1473 || (layout.ty.is_bool() && ones == 1) =>
1474 {
1475 self.insert_scalar(lhs_ty, Scalar::from_uint(ones, layout.size))
1476 }
1477 (BinOp::Sub | BinOp::SubWithOverflow | BinOp::SubUnchecked | BinOp::BitXor, a, b)
1479 if a == b =>
1480 {
1481 self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size))
1482 }
1483 (BinOp::Eq, Left(a), Left(b)) => self.insert_bool(a == b),
1488 (BinOp::Eq, a, b) if a == b => self.insert_bool(true),
1489 (BinOp::Ne, Left(a), Left(b)) => self.insert_bool(a != b),
1490 (BinOp::Ne, a, b) if a == b => self.insert_bool(false),
1491 _ => return None,
1492 };
1493
1494 if op.is_overflowing() {
1495 let ty = Ty::new_tup(self.tcx, &[self.ty(result), self.tcx.types.bool]);
1496 let false_val = self.insert_bool(false);
1497 Some(self.insert_tuple(ty, &[result, false_val]))
1498 } else {
1499 Some(result)
1500 }
1501 }
1502
1503 fn simplify_cast(
1504 &mut self,
1505 initial_kind: &mut CastKind,
1506 initial_operand: &mut Operand<'tcx>,
1507 to: Ty<'tcx>,
1508 location: Location,
1509 ) -> Option<VnIndex> {
1510 use CastKind::*;
1511 use rustc_middle::ty::adjustment::PointerCoercion::*;
1512
1513 let mut kind = *initial_kind;
1514 let mut value = self.simplify_operand(initial_operand, location)?;
1515 let mut from = self.ty(value);
1516 if from == to {
1517 return Some(value);
1518 }
1519
1520 if let CastKind::PointerCoercion(ReifyFnPointer(_) | ClosureFnPointer(_), _) = kind {
1521 return Some(self.new_opaque(to));
1524 }
1525
1526 let mut was_ever_updated = false;
1527 loop {
1528 let mut was_updated_this_iteration = false;
1529
1530 if let Transmute = kind
1535 && from.is_raw_ptr()
1536 && to.is_raw_ptr()
1537 && self.pointers_have_same_metadata(from, to)
1538 {
1539 kind = PtrToPtr;
1540 was_updated_this_iteration = true;
1541 }
1542
1543 if let PtrToPtr = kind
1546 && let Value::RawPtr { pointer, .. } = self.get(value)
1547 && let ty::RawPtr(to_pointee, _) = to.kind()
1548 && to_pointee.is_sized(self.tcx, self.typing_env())
1549 {
1550 from = self.ty(pointer);
1551 value = pointer;
1552 was_updated_this_iteration = true;
1553 if from == to {
1554 return Some(pointer);
1555 }
1556 }
1557
1558 if let Transmute = kind
1561 && let Value::Aggregate(variant_idx, field_values) = self.get(value)
1562 && let Some((field_idx, field_ty)) =
1563 self.value_is_all_in_one_field(from, variant_idx)
1564 {
1565 from = field_ty;
1566 value = field_values[field_idx.as_usize()];
1567 was_updated_this_iteration = true;
1568 if field_ty == to {
1569 return Some(value);
1570 }
1571 }
1572
1573 if let Value::Cast { kind: inner_kind, value: inner_value } = self.get(value) {
1575 let inner_from = self.ty(inner_value);
1576 let new_kind = match (inner_kind, kind) {
1577 (PtrToPtr, PtrToPtr) => Some(PtrToPtr),
1581 (PtrToPtr, Transmute) if self.pointers_have_same_metadata(inner_from, from) => {
1585 Some(Transmute)
1586 }
1587 (Transmute, PtrToPtr) if self.pointers_have_same_metadata(from, to) => {
1590 Some(Transmute)
1591 }
1592 (Transmute, Transmute)
1595 if !self.type_may_have_niche_of_interest_to_backend(from) =>
1596 {
1597 Some(Transmute)
1598 }
1599 _ => None,
1600 };
1601 if let Some(new_kind) = new_kind {
1602 kind = new_kind;
1603 from = inner_from;
1604 value = inner_value;
1605 was_updated_this_iteration = true;
1606 if inner_from == to {
1607 return Some(inner_value);
1608 }
1609 }
1610 }
1611
1612 if was_updated_this_iteration {
1613 was_ever_updated = true;
1614 } else {
1615 break;
1616 }
1617 }
1618
1619 if was_ever_updated && let Some(op) = self.try_as_operand(value, location) {
1620 *initial_operand = op;
1621 *initial_kind = kind;
1622 }
1623
1624 Some(self.insert(to, Value::Cast { kind, value }))
1625 }
1626
1627 fn pointers_have_same_metadata(&self, left_ptr_ty: Ty<'tcx>, right_ptr_ty: Ty<'tcx>) -> bool {
1628 let left_meta_ty = left_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1629 let right_meta_ty = right_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1630 if left_meta_ty == right_meta_ty {
1631 true
1632 } else if let Ok(left) =
1633 self.tcx.try_normalize_erasing_regions(self.typing_env(), left_meta_ty)
1634 && let Ok(right) =
1635 self.tcx.try_normalize_erasing_regions(self.typing_env(), right_meta_ty)
1636 {
1637 left == right
1638 } else {
1639 false
1640 }
1641 }
1642
1643 fn type_may_have_niche_of_interest_to_backend(&self, ty: Ty<'tcx>) -> bool {
1650 let Ok(layout) = self.ecx.layout_of(ty) else {
1651 return true;
1653 };
1654
1655 if layout.uninhabited {
1656 return true;
1657 }
1658
1659 match layout.backend_repr {
1660 BackendRepr::Scalar(a) => !a.is_always_valid(&self.ecx),
1661 BackendRepr::ScalarPair(a, b) => {
1662 !a.is_always_valid(&self.ecx) || !b.is_always_valid(&self.ecx)
1663 }
1664 BackendRepr::SimdVector { .. } | BackendRepr::Memory { .. } => false,
1665 }
1666 }
1667
1668 fn value_is_all_in_one_field(
1669 &self,
1670 ty: Ty<'tcx>,
1671 variant: VariantIdx,
1672 ) -> Option<(FieldIdx, Ty<'tcx>)> {
1673 if let Ok(layout) = self.ecx.layout_of(ty)
1674 && let abi::Variants::Single { index } = layout.variants
1675 && index == variant
1676 && let Some((field_idx, field_layout)) = layout.non_1zst_field(&self.ecx)
1677 && layout.size == field_layout.size
1678 {
1679 Some((field_idx, field_layout.ty))
1683 } else if let ty::Adt(adt, args) = ty.kind()
1684 && adt.is_struct()
1685 && adt.repr().transparent()
1686 && let [single_field] = adt.non_enum_variant().fields.raw.as_slice()
1687 {
1688 Some((FieldIdx::ZERO, single_field.ty(self.tcx, args)))
1689 } else {
1690 None
1691 }
1692 }
1693}
1694
1695fn op_to_prop_const<'tcx>(
1696 ecx: &mut InterpCx<'tcx, DummyMachine>,
1697 op: &OpTy<'tcx>,
1698) -> Option<ConstValue> {
1699 if op.layout.is_unsized() {
1701 return None;
1702 }
1703
1704 if op.layout.is_zst() {
1706 return Some(ConstValue::ZeroSized);
1707 }
1708
1709 if !op.is_immediate_uninit()
1714 && !matches!(op.layout.backend_repr, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..))
1715 {
1716 return None;
1717 }
1718
1719 if let BackendRepr::Scalar(abi::Scalar::Initialized { .. }) = op.layout.backend_repr
1721 && let Some(scalar) = ecx.read_scalar(op).discard_err()
1722 {
1723 if !scalar.try_to_scalar_int().is_ok() {
1724 return None;
1728 }
1729 return Some(ConstValue::Scalar(scalar));
1730 }
1731
1732 if let Either::Left(mplace) = op.as_mplace_or_imm() {
1735 let (size, _align) = ecx.size_and_align_of_val(&mplace).discard_err()??;
1736
1737 let alloc_ref = ecx.get_ptr_alloc(mplace.ptr(), size).discard_err()??;
1741 if alloc_ref.has_provenance() {
1742 return None;
1743 }
1744
1745 let pointer = mplace.ptr().into_pointer_or_addr().ok()?;
1746 let (prov, offset) = pointer.prov_and_relative_offset();
1747 let alloc_id = prov.alloc_id();
1748 intern_const_alloc_for_constprop(ecx, alloc_id).discard_err()?;
1749
1750 if let GlobalAlloc::Memory(alloc) = ecx.tcx.global_alloc(alloc_id)
1754 && alloc.inner().align >= op.layout.align.abi
1757 {
1758 return Some(ConstValue::Indirect { alloc_id, offset });
1759 }
1760 }
1761
1762 let alloc_id =
1764 ecx.intern_with_temp_alloc(op.layout, |ecx, dest| ecx.copy_op(op, dest)).discard_err()?;
1765 let value = ConstValue::Indirect { alloc_id, offset: Size::ZERO };
1766
1767 if ecx.tcx.global_alloc(alloc_id).unwrap_memory().inner().provenance().ptrs().is_empty() {
1771 return Some(value);
1772 }
1773
1774 None
1775}
1776
1777impl<'tcx> VnState<'_, '_, 'tcx> {
1778 fn try_as_operand(&mut self, index: VnIndex, location: Location) -> Option<Operand<'tcx>> {
1781 if let Some(const_) = self.try_as_constant(index) {
1782 Some(Operand::Constant(Box::new(const_)))
1783 } else if let Some(place) = self.try_as_place(index, location, false) {
1784 self.reused_locals.insert(place.local);
1785 Some(Operand::Copy(place))
1786 } else {
1787 None
1788 }
1789 }
1790
1791 fn try_as_constant(&mut self, index: VnIndex) -> Option<ConstOperand<'tcx>> {
1793 if let Value::Constant { value, disambiguator: None } = self.get(index) {
1797 debug_assert!(value.is_deterministic());
1798 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1799 }
1800
1801 let op = self.eval_to_const(index)?;
1802 if op.layout.is_unsized() {
1803 return None;
1805 }
1806
1807 let value = op_to_prop_const(&mut self.ecx, op)?;
1808
1809 assert!(!value.may_have_provenance(self.tcx, op.layout.size));
1813
1814 let const_ = Const::Val(value, op.layout.ty);
1815 Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_ })
1816 }
1817
1818 #[instrument(level = "trace", skip(self), ret)]
1822 fn try_as_place(
1823 &mut self,
1824 mut index: VnIndex,
1825 loc: Location,
1826 allow_complex_projection: bool,
1827 ) -> Option<Place<'tcx>> {
1828 let mut projection = SmallVec::<[PlaceElem<'tcx>; 1]>::new();
1829 loop {
1830 if let Some(local) = self.try_as_local(index, loc) {
1831 projection.reverse();
1832 let place =
1833 Place { local, projection: self.tcx.mk_place_elems(projection.as_slice()) };
1834 return Some(place);
1835 } else if projection.last() == Some(&PlaceElem::Deref) {
1836 return None;
1840 } else if let Value::Projection(pointer, proj) = self.get(index)
1841 && (allow_complex_projection || proj.is_stable_offset())
1842 && let Some(proj) = self.try_as_place_elem(self.ty(index), proj, loc)
1843 {
1844 projection.push(proj);
1845 index = pointer;
1846 } else {
1847 return None;
1848 }
1849 }
1850 }
1851
1852 fn try_as_local(&mut self, index: VnIndex, loc: Location) -> Option<Local> {
1855 let other = self.rev_locals.get(index)?;
1856 other
1857 .iter()
1858 .find(|&&other| self.ssa.assignment_dominates(&self.dominators, other, loc))
1859 .copied()
1860 }
1861}
1862
1863impl<'tcx> MutVisitor<'tcx> for VnState<'_, '_, 'tcx> {
1864 fn tcx(&self) -> TyCtxt<'tcx> {
1865 self.tcx
1866 }
1867
1868 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
1869 self.simplify_place_projection(place, location);
1870 if context.is_mutating_use() && place.is_indirect() {
1871 self.invalidate_derefs();
1873 }
1874 self.super_place(place, context, location);
1875 }
1876
1877 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
1878 self.simplify_operand(operand, location);
1879 self.super_operand(operand, location);
1880 }
1881
1882 fn visit_assign(
1883 &mut self,
1884 lhs: &mut Place<'tcx>,
1885 rvalue: &mut Rvalue<'tcx>,
1886 location: Location,
1887 ) {
1888 self.simplify_place_projection(lhs, location);
1889
1890 let value = self.simplify_rvalue(lhs, rvalue, location);
1891 if let Some(value) = value {
1892 if let Some(const_) = self.try_as_constant(value) {
1893 *rvalue = Rvalue::Use(Operand::Constant(Box::new(const_)));
1894 } else if let Some(place) = self.try_as_place(value, location, false)
1895 && *rvalue != Rvalue::Use(Operand::Move(place))
1896 && *rvalue != Rvalue::Use(Operand::Copy(place))
1897 {
1898 *rvalue = Rvalue::Use(Operand::Copy(place));
1899 self.reused_locals.insert(place.local);
1900 }
1901 }
1902
1903 if lhs.is_indirect() {
1904 self.invalidate_derefs();
1906 }
1907
1908 if let Some(local) = lhs.as_local()
1909 && self.ssa.is_ssa(local)
1910 && let rvalue_ty = rvalue.ty(self.local_decls, self.tcx)
1911 && self.local_decls[local].ty == rvalue_ty
1914 {
1915 let value = value.unwrap_or_else(|| self.new_opaque(rvalue_ty));
1916 self.assign(local, value);
1917 }
1918 }
1919
1920 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
1921 if let Terminator { kind: TerminatorKind::Call { destination, .. }, .. } = terminator {
1922 if let Some(local) = destination.as_local()
1923 && self.ssa.is_ssa(local)
1924 {
1925 let ty = self.local_decls[local].ty;
1926 let opaque = self.new_opaque(ty);
1927 self.assign(local, opaque);
1928 }
1929 }
1930 if terminator.kind.can_write_to_memory() {
1932 self.invalidate_derefs();
1933 }
1934 self.super_terminator(terminator, location);
1935 }
1936}
1937
1938struct StorageRemover<'tcx> {
1939 tcx: TyCtxt<'tcx>,
1940 reused_locals: DenseBitSet<Local>,
1941}
1942
1943impl<'tcx> MutVisitor<'tcx> for StorageRemover<'tcx> {
1944 fn tcx(&self) -> TyCtxt<'tcx> {
1945 self.tcx
1946 }
1947
1948 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, _: Location) {
1949 if let Operand::Move(place) = *operand
1950 && !place.is_indirect_first_projection()
1951 && self.reused_locals.contains(place.local)
1952 {
1953 *operand = Operand::Copy(place);
1954 }
1955 }
1956
1957 fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
1958 match stmt.kind {
1959 StatementKind::StorageLive(l) | StatementKind::StorageDead(l)
1961 if self.reused_locals.contains(l) =>
1962 {
1963 stmt.make_nop(true)
1964 }
1965 _ => self.super_statement(stmt, loc),
1966 }
1967 }
1968}