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 RuntimeChecks(RuntimeChecks),
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 fn insert_unique(
424 &mut self,
425 ty: Ty<'tcx>,
426 value: impl FnOnce(VnOpaque) -> Value<'a, 'tcx>,
427 ) -> VnIndex {
428 let index = self.values.insert_unique(ty, value);
429 let _index = self.evaluated.push(None);
430 debug_assert_eq!(index, _index);
431 let _index = self.rev_locals.push(SmallVec::new());
432 debug_assert_eq!(index, _index);
433 index
434 }
435
436 #[instrument(level = "trace", skip(self), ret)]
437 fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> VnIndex {
438 let (index, new) = self.values.insert(ty, value);
439 if new {
440 let _index = self.evaluated.push(None);
442 debug_assert_eq!(index, _index);
443 let _index = self.rev_locals.push(SmallVec::new());
444 debug_assert_eq!(index, _index);
445 }
446 index
447 }
448
449 #[instrument(level = "trace", skip(self), ret)]
452 fn new_opaque(&mut self, ty: Ty<'tcx>) -> VnIndex {
453 let index = self.insert_unique(ty, Value::Opaque);
454 self.evaluated[index] = Some(None);
455 index
456 }
457
458 #[instrument(level = "trace", skip(self), ret)]
460 fn new_pointer(&mut self, place: Place<'tcx>, kind: AddressKind) -> Option<VnIndex> {
461 let pty = place.ty(self.local_decls, self.tcx).ty;
462 let ty = match kind {
463 AddressKind::Ref(bk) => {
464 Ty::new_ref(self.tcx, self.tcx.lifetimes.re_erased, pty, bk.to_mutbl_lossy())
465 }
466 AddressKind::Address(mutbl) => Ty::new_ptr(self.tcx, pty, mutbl.to_mutbl_lossy()),
467 };
468
469 let mut projection = place.projection.iter();
470 let base = if place.is_indirect_first_projection() {
471 let base = self.locals[place.local]?;
472 projection.next();
474 AddressBase::Deref(base)
475 } else {
476 AddressBase::Local(place.local)
477 };
478 let projection =
480 projection.map(|proj| proj.try_map(|index| self.locals[index], |ty| ty).ok_or(()));
481 let projection = self.arena.try_alloc_from_iter(projection).ok()?;
482
483 let index = self.insert_unique(ty, |provenance| Value::Address {
484 base,
485 projection,
486 kind,
487 provenance,
488 });
489 Some(index)
490 }
491
492 #[instrument(level = "trace", skip(self), ret)]
493 fn insert_constant(&mut self, value: Const<'tcx>) -> VnIndex {
494 if value.is_deterministic() {
495 let constant = Value::Constant { value, disambiguator: None };
497 self.insert(value.ty(), constant)
498 } else {
499 self.insert_unique(value.ty(), |disambiguator| Value::Constant {
502 value,
503 disambiguator: Some(disambiguator),
504 })
505 }
506 }
507
508 #[inline]
509 fn get(&self, index: VnIndex) -> Value<'a, 'tcx> {
510 self.values.value(index)
511 }
512
513 #[inline]
514 fn ty(&self, index: VnIndex) -> Ty<'tcx> {
515 self.values.ty(index)
516 }
517
518 #[instrument(level = "trace", skip(self))]
520 fn assign(&mut self, local: Local, value: VnIndex) {
521 debug_assert!(self.ssa.is_ssa(local));
522 self.locals[local] = Some(value);
523 self.rev_locals[value].push(local);
524 }
525
526 fn insert_bool(&mut self, flag: bool) -> VnIndex {
527 let value = Const::from_bool(self.tcx, flag);
529 debug_assert!(value.is_deterministic());
530 self.insert(self.tcx.types.bool, Value::Constant { value, disambiguator: None })
531 }
532
533 fn insert_scalar(&mut self, ty: Ty<'tcx>, scalar: Scalar) -> VnIndex {
534 let value = Const::from_scalar(self.tcx, scalar, ty);
536 debug_assert!(value.is_deterministic());
537 self.insert(ty, Value::Constant { value, disambiguator: None })
538 }
539
540 fn insert_tuple(&mut self, ty: Ty<'tcx>, values: &[VnIndex]) -> VnIndex {
541 self.insert(ty, Value::Aggregate(VariantIdx::ZERO, self.arena.alloc_slice(values)))
542 }
543
544 fn insert_deref(&mut self, ty: Ty<'tcx>, value: VnIndex) -> VnIndex {
545 let value = self.insert(ty, Value::Projection(value, ProjectionElem::Deref));
546 self.derefs.push(value);
547 value
548 }
549
550 fn invalidate_derefs(&mut self) {
551 for deref in std::mem::take(&mut self.derefs) {
552 self.values.forget(deref);
553 }
554 }
555
556 #[instrument(level = "trace", skip(self), ret)]
557 fn eval_to_const_inner(&mut self, value: VnIndex) -> Option<OpTy<'tcx>> {
558 use Value::*;
559 let ty = self.ty(value);
560 let ty = if !self.is_coroutine || ty.is_scalar() {
562 self.ecx.layout_of(ty).ok()?
563 } else {
564 return None;
565 };
566 let op = match self.get(value) {
567 _ if ty.is_zst() => ImmTy::uninit(ty).into(),
568
569 Opaque(_) => return None,
570 RuntimeChecks(..) => return None,
572
573 Repeat(value, _count) => {
578 let value = self.eval_to_const(value)?;
579 if value.is_immediate_uninit() {
580 ImmTy::uninit(ty).into()
581 } else {
582 return None;
583 }
584 }
585 Constant { ref value, disambiguator: _ } => {
586 self.ecx.eval_mir_constant(value, DUMMY_SP, None).discard_err()?
587 }
588 Aggregate(variant, ref fields) => {
589 let fields =
590 fields.iter().map(|&f| self.eval_to_const(f)).collect::<Option<Vec<_>>>()?;
591 let variant = if ty.ty.is_enum() { Some(variant) } else { None };
592 let (BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..)) = ty.backend_repr
593 else {
594 return None;
595 };
596 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
597 let variant_dest = if let Some(variant) = variant {
598 self.ecx.project_downcast(&dest, variant).discard_err()?
599 } else {
600 dest.clone()
601 };
602 for (field_index, op) in fields.into_iter().enumerate() {
603 let field_dest = self
604 .ecx
605 .project_field(&variant_dest, FieldIdx::from_usize(field_index))
606 .discard_err()?;
607 self.ecx.copy_op(op, &field_dest).discard_err()?;
608 }
609 self.ecx
610 .write_discriminant(variant.unwrap_or(FIRST_VARIANT), &dest)
611 .discard_err()?;
612 self.ecx
613 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
614 .discard_err()?;
615 dest.into()
616 }
617 Union(active_field, field) => {
618 let field = self.eval_to_const(field)?;
619 if field.layout.layout.is_zst() {
620 ImmTy::from_immediate(Immediate::Uninit, ty).into()
621 } else if matches!(
622 ty.backend_repr,
623 BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..)
624 ) {
625 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
626 let field_dest = self.ecx.project_field(&dest, active_field).discard_err()?;
627 self.ecx.copy_op(field, &field_dest).discard_err()?;
628 self.ecx
629 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
630 .discard_err()?;
631 dest.into()
632 } else {
633 return None;
634 }
635 }
636 RawPtr { pointer, metadata } => {
637 let pointer = self.eval_to_const(pointer)?;
638 let metadata = self.eval_to_const(metadata)?;
639
640 let data = self.ecx.read_pointer(pointer).discard_err()?;
642 let meta = if metadata.layout.is_zst() {
643 MemPlaceMeta::None
644 } else {
645 MemPlaceMeta::Meta(self.ecx.read_scalar(metadata).discard_err()?)
646 };
647 let ptr_imm = Immediate::new_pointer_with_meta(data, meta, &self.ecx);
648 ImmTy::from_immediate(ptr_imm, ty).into()
649 }
650
651 Projection(base, elem) => {
652 let base = self.eval_to_const(base)?;
653 let elem = elem.try_map(|_| None, |()| ty.ty)?;
656 self.ecx.project(base, elem).discard_err()?
657 }
658 Address { base, projection, .. } => {
659 debug_assert!(!projection.contains(&ProjectionElem::Deref));
660 let pointer = match base {
661 AddressBase::Deref(pointer) => self.eval_to_const(pointer)?,
662 AddressBase::Local(_) => return None,
664 };
665 let mut mplace = self.ecx.deref_pointer(pointer).discard_err()?;
666 for elem in projection {
667 let elem = elem.try_map(|_| None, |ty| ty)?;
670 mplace = self.ecx.project(&mplace, elem).discard_err()?;
671 }
672 let pointer = mplace.to_ref(&self.ecx);
673 ImmTy::from_immediate(pointer, ty).into()
674 }
675
676 Discriminant(base) => {
677 let base = self.eval_to_const(base)?;
678 let variant = self.ecx.read_discriminant(base).discard_err()?;
679 let discr_value =
680 self.ecx.discriminant_for_variant(base.layout.ty, variant).discard_err()?;
681 discr_value.into()
682 }
683 UnaryOp(un_op, operand) => {
684 let operand = self.eval_to_const(operand)?;
685 let operand = self.ecx.read_immediate(operand).discard_err()?;
686 let val = self.ecx.unary_op(un_op, &operand).discard_err()?;
687 val.into()
688 }
689 BinaryOp(bin_op, lhs, rhs) => {
690 let lhs = self.eval_to_const(lhs)?;
691 let rhs = self.eval_to_const(rhs)?;
692 let lhs = self.ecx.read_immediate(lhs).discard_err()?;
693 let rhs = self.ecx.read_immediate(rhs).discard_err()?;
694 let val = self.ecx.binary_op(bin_op, &lhs, &rhs).discard_err()?;
695 val.into()
696 }
697 Cast { kind, value } => match kind {
698 CastKind::IntToInt | CastKind::IntToFloat => {
699 let value = self.eval_to_const(value)?;
700 let value = self.ecx.read_immediate(value).discard_err()?;
701 let res = self.ecx.int_to_int_or_float(&value, ty).discard_err()?;
702 res.into()
703 }
704 CastKind::FloatToFloat | CastKind::FloatToInt => {
705 let value = self.eval_to_const(value)?;
706 let value = self.ecx.read_immediate(value).discard_err()?;
707 let res = self.ecx.float_to_float_or_int(&value, ty).discard_err()?;
708 res.into()
709 }
710 CastKind::Transmute | CastKind::Subtype => {
711 let value = self.eval_to_const(value)?;
712 if value.as_mplace_or_imm().is_right() {
717 let can_transmute = match (value.layout.backend_repr, ty.backend_repr) {
718 (BackendRepr::Scalar(s1), BackendRepr::Scalar(s2)) => {
719 s1.size(&self.ecx) == s2.size(&self.ecx)
720 && !matches!(s1.primitive(), Primitive::Pointer(..))
721 }
722 (BackendRepr::ScalarPair(a1, b1), BackendRepr::ScalarPair(a2, b2)) => {
723 a1.size(&self.ecx) == a2.size(&self.ecx)
724 && b1.size(&self.ecx) == b2.size(&self.ecx)
725 && b1.align(&self.ecx) == b2.align(&self.ecx)
727 && !matches!(a1.primitive(), Primitive::Pointer(..))
729 && !matches!(b1.primitive(), Primitive::Pointer(..))
730 }
731 _ => false,
732 };
733 if !can_transmute {
734 return None;
735 }
736 }
737 value.offset(Size::ZERO, ty, &self.ecx).discard_err()?
738 }
739 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _) => {
740 let src = self.eval_to_const(value)?;
741 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
742 self.ecx.unsize_into(src, ty, &dest).discard_err()?;
743 self.ecx
744 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
745 .discard_err()?;
746 dest.into()
747 }
748 CastKind::FnPtrToPtr | CastKind::PtrToPtr => {
749 let src = self.eval_to_const(value)?;
750 let src = self.ecx.read_immediate(src).discard_err()?;
751 let ret = self.ecx.ptr_to_ptr(&src, ty).discard_err()?;
752 ret.into()
753 }
754 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::UnsafeFnPointer, _) => {
755 let src = self.eval_to_const(value)?;
756 let src = self.ecx.read_immediate(src).discard_err()?;
757 ImmTy::from_immediate(*src, ty).into()
758 }
759 _ => return None,
760 },
761 };
762 Some(op)
763 }
764
765 fn eval_to_const(&mut self, index: VnIndex) -> Option<&'a OpTy<'tcx>> {
766 if let Some(op) = self.evaluated[index] {
767 return op;
768 }
769 let op = self.eval_to_const_inner(index);
770 self.evaluated[index] = Some(self.arena.alloc(op).as_ref());
771 self.evaluated[index].unwrap()
772 }
773
774 #[instrument(level = "trace", skip(self), ret)]
776 fn dereference_address(
777 &mut self,
778 base: AddressBase,
779 projection: &[ProjectionElem<VnIndex, Ty<'tcx>>],
780 ) -> Option<VnIndex> {
781 let (mut place_ty, mut value) = match base {
782 AddressBase::Local(local) => {
784 let local = self.locals[local]?;
785 let place_ty = PlaceTy::from_ty(self.ty(local));
786 (place_ty, local)
787 }
788 AddressBase::Deref(reborrow) => {
790 let place_ty = PlaceTy::from_ty(self.ty(reborrow));
791 self.project(place_ty, reborrow, ProjectionElem::Deref)?
792 }
793 };
794 for &proj in projection {
795 (place_ty, value) = self.project(place_ty, value, proj)?;
796 }
797 Some(value)
798 }
799
800 #[instrument(level = "trace", skip(self), ret)]
801 fn project(
802 &mut self,
803 place_ty: PlaceTy<'tcx>,
804 value: VnIndex,
805 proj: ProjectionElem<VnIndex, Ty<'tcx>>,
806 ) -> Option<(PlaceTy<'tcx>, VnIndex)> {
807 let projection_ty = place_ty.projection_ty(self.tcx, proj);
808 let proj = match proj {
809 ProjectionElem::Deref => {
810 if let Some(Mutability::Not) = place_ty.ty.ref_mutability()
811 && projection_ty.ty.is_freeze(self.tcx, self.typing_env())
812 {
813 if let Value::Address { base, projection, .. } = self.get(value)
814 && let Some(value) = self.dereference_address(base, projection)
815 {
816 return Some((projection_ty, value));
817 }
818
819 return Some((projection_ty, self.insert_deref(projection_ty.ty, value)));
822 } else {
823 return None;
824 }
825 }
826 ProjectionElem::Downcast(name, index) => ProjectionElem::Downcast(name, index),
827 ProjectionElem::Field(f, _) => match self.get(value) {
828 Value::Aggregate(_, fields) => return Some((projection_ty, fields[f.as_usize()])),
829 Value::Union(active, field) if active == f => return Some((projection_ty, field)),
830 Value::Projection(outer_value, ProjectionElem::Downcast(_, read_variant))
831 if let Value::Aggregate(written_variant, fields) = self.get(outer_value)
832 && written_variant == read_variant =>
848 {
849 return Some((projection_ty, fields[f.as_usize()]));
850 }
851 _ => ProjectionElem::Field(f, ()),
852 },
853 ProjectionElem::Index(idx) => {
854 if let Value::Repeat(inner, _) = self.get(value) {
855 return Some((projection_ty, inner));
856 }
857 ProjectionElem::Index(idx)
858 }
859 ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
860 match self.get(value) {
861 Value::Repeat(inner, _) => {
862 return Some((projection_ty, inner));
863 }
864 Value::Aggregate(_, operands) => {
865 let offset = if from_end {
866 operands.len() - offset as usize
867 } else {
868 offset as usize
869 };
870 let value = operands.get(offset).copied()?;
871 return Some((projection_ty, value));
872 }
873 _ => {}
874 };
875 ProjectionElem::ConstantIndex { offset, min_length, from_end }
876 }
877 ProjectionElem::Subslice { from, to, from_end } => {
878 ProjectionElem::Subslice { from, to, from_end }
879 }
880 ProjectionElem::OpaqueCast(_) => ProjectionElem::OpaqueCast(()),
881 ProjectionElem::UnwrapUnsafeBinder(_) => ProjectionElem::UnwrapUnsafeBinder(()),
882 };
883
884 let value = self.insert(projection_ty.ty, Value::Projection(value, proj));
885 Some((projection_ty, value))
886 }
887
888 #[instrument(level = "trace", skip(self))]
890 fn simplify_place_projection(&mut self, place: &mut Place<'tcx>, location: Location) {
891 if place.is_indirect_first_projection()
894 && let Some(base) = self.locals[place.local]
895 && let Some(new_local) = self.try_as_local(base, location)
896 && place.local != new_local
897 {
898 place.local = new_local;
899 self.reused_locals.insert(new_local);
900 }
901
902 let mut projection = Cow::Borrowed(&place.projection[..]);
903
904 for i in 0..projection.len() {
905 let elem = projection[i];
906 if let ProjectionElem::Index(idx_local) = elem
907 && let Some(idx) = self.locals[idx_local]
908 {
909 if let Some(offset) = self.eval_to_const(idx)
910 && let Some(offset) = self.ecx.read_target_usize(offset).discard_err()
911 && let Some(min_length) = offset.checked_add(1)
912 {
913 projection.to_mut()[i] =
914 ProjectionElem::ConstantIndex { offset, min_length, from_end: false };
915 } else if let Some(new_idx_local) = self.try_as_local(idx, location)
916 && idx_local != new_idx_local
917 {
918 projection.to_mut()[i] = ProjectionElem::Index(new_idx_local);
919 self.reused_locals.insert(new_idx_local);
920 }
921 }
922 }
923
924 if Cow::is_owned(&projection) {
925 place.projection = self.tcx.mk_place_elems(&projection);
926 }
927
928 trace!(?place);
929 }
930
931 #[instrument(level = "trace", skip(self), ret)]
934 fn compute_place_value(
935 &mut self,
936 place: Place<'tcx>,
937 location: Location,
938 ) -> Result<VnIndex, PlaceRef<'tcx>> {
939 let mut place_ref = place.as_ref();
942
943 let Some(mut value) = self.locals[place.local] else { return Err(place_ref) };
945 let mut place_ty = PlaceTy::from_ty(self.local_decls[place.local].ty);
947 for (index, proj) in place.projection.iter().enumerate() {
948 if let Some(local) = self.try_as_local(value, location) {
949 place_ref = PlaceRef { local, projection: &place.projection[index..] };
953 }
954
955 let Some(proj) = proj.try_map(|value| self.locals[value], |ty| ty) else {
956 return Err(place_ref);
957 };
958 let Some(ty_and_value) = self.project(place_ty, value, proj) else {
959 return Err(place_ref);
960 };
961 (place_ty, value) = ty_and_value;
962 }
963
964 Ok(value)
965 }
966
967 #[instrument(level = "trace", skip(self), ret)]
970 fn simplify_place_value(
971 &mut self,
972 place: &mut Place<'tcx>,
973 location: Location,
974 ) -> Option<VnIndex> {
975 self.simplify_place_projection(place, location);
976
977 match self.compute_place_value(*place, location) {
978 Ok(value) => {
979 if let Some(new_place) = self.try_as_place(value, location, true)
980 && (new_place.local != place.local
981 || new_place.projection.len() < place.projection.len())
982 {
983 *place = new_place;
984 self.reused_locals.insert(new_place.local);
985 }
986 Some(value)
987 }
988 Err(place_ref) => {
989 if place_ref.local != place.local
990 || place_ref.projection.len() < place.projection.len()
991 {
992 *place = place_ref.project_deeper(&[], self.tcx);
994 self.reused_locals.insert(place_ref.local);
995 }
996 None
997 }
998 }
999 }
1000
1001 #[instrument(level = "trace", skip(self), ret)]
1002 fn simplify_operand(
1003 &mut self,
1004 operand: &mut Operand<'tcx>,
1005 location: Location,
1006 ) -> Option<VnIndex> {
1007 match *operand {
1008 Operand::RuntimeChecks(c) => {
1009 Some(self.insert(self.tcx.types.bool, Value::RuntimeChecks(c)))
1010 }
1011 Operand::Constant(ref constant) => Some(self.insert_constant(constant.const_)),
1012 Operand::Copy(ref mut place) | Operand::Move(ref mut place) => {
1013 let value = self.simplify_place_value(place, location)?;
1014 if let Some(const_) = self.try_as_constant(value) {
1015 *operand = Operand::Constant(Box::new(const_));
1016 } else if let Value::RuntimeChecks(c) = self.get(value) {
1017 *operand = Operand::RuntimeChecks(c);
1018 }
1019 Some(value)
1020 }
1021 }
1022 }
1023
1024 #[instrument(level = "trace", skip(self), ret)]
1025 fn simplify_rvalue(
1026 &mut self,
1027 lhs: &Place<'tcx>,
1028 rvalue: &mut Rvalue<'tcx>,
1029 location: Location,
1030 ) -> Option<VnIndex> {
1031 let value = match *rvalue {
1032 Rvalue::Use(ref mut operand) => return self.simplify_operand(operand, location),
1034
1035 Rvalue::Repeat(ref mut op, amount) => {
1037 let op = self.simplify_operand(op, location)?;
1038 Value::Repeat(op, amount)
1039 }
1040 Rvalue::Aggregate(..) => return self.simplify_aggregate(lhs, rvalue, location),
1041 Rvalue::Ref(_, borrow_kind, ref mut place) => {
1042 self.simplify_place_projection(place, location);
1043 return self.new_pointer(*place, AddressKind::Ref(borrow_kind));
1044 }
1045 Rvalue::RawPtr(mutbl, ref mut place) => {
1046 self.simplify_place_projection(place, location);
1047 return self.new_pointer(*place, AddressKind::Address(mutbl));
1048 }
1049 Rvalue::WrapUnsafeBinder(ref mut op, _) => {
1050 let value = self.simplify_operand(op, location)?;
1051 Value::Cast { kind: CastKind::Transmute, value }
1052 }
1053
1054 Rvalue::Cast(ref mut kind, ref mut value, to) => {
1056 return self.simplify_cast(kind, value, to, location);
1057 }
1058 Rvalue::BinaryOp(op, box (ref mut lhs, ref mut rhs)) => {
1059 return self.simplify_binary(op, lhs, rhs, location);
1060 }
1061 Rvalue::UnaryOp(op, ref mut arg_op) => {
1062 return self.simplify_unary(op, arg_op, location);
1063 }
1064 Rvalue::Discriminant(ref mut place) => {
1065 let place = self.simplify_place_value(place, location)?;
1066 if let Some(discr) = self.simplify_discriminant(place) {
1067 return Some(discr);
1068 }
1069 Value::Discriminant(place)
1070 }
1071
1072 Rvalue::ThreadLocalRef(..) => return None,
1074 Rvalue::CopyForDeref(_) | Rvalue::ShallowInitBox(..) => {
1075 bug!("forbidden in runtime MIR: {rvalue:?}")
1076 }
1077 };
1078 let ty = rvalue.ty(self.local_decls, self.tcx);
1079 Some(self.insert(ty, value))
1080 }
1081
1082 fn simplify_discriminant(&mut self, place: VnIndex) -> Option<VnIndex> {
1083 let enum_ty = self.ty(place);
1084 if enum_ty.is_enum()
1085 && let Value::Aggregate(variant, _) = self.get(place)
1086 {
1087 let discr = self.ecx.discriminant_for_variant(enum_ty, variant).discard_err()?;
1088 return Some(self.insert_scalar(discr.layout.ty, discr.to_scalar()));
1089 }
1090
1091 None
1092 }
1093
1094 fn try_as_place_elem(
1095 &mut self,
1096 ty: Ty<'tcx>,
1097 proj: ProjectionElem<VnIndex, ()>,
1098 loc: Location,
1099 ) -> Option<PlaceElem<'tcx>> {
1100 proj.try_map(
1101 |value| {
1102 let local = self.try_as_local(value, loc)?;
1103 self.reused_locals.insert(local);
1104 Some(local)
1105 },
1106 |()| ty,
1107 )
1108 }
1109
1110 fn simplify_aggregate_to_copy(
1111 &mut self,
1112 ty: Ty<'tcx>,
1113 variant_index: VariantIdx,
1114 fields: &[VnIndex],
1115 ) -> Option<VnIndex> {
1116 let Some(&first_field) = fields.first() else { return None };
1117 let Value::Projection(copy_from_value, _) = self.get(first_field) else { return None };
1118
1119 if fields.iter().enumerate().any(|(index, &v)| {
1121 if let Value::Projection(pointer, ProjectionElem::Field(from_index, _)) = self.get(v)
1122 && copy_from_value == pointer
1123 && from_index.index() == index
1124 {
1125 return false;
1126 }
1127 true
1128 }) {
1129 return None;
1130 }
1131
1132 let mut copy_from_local_value = copy_from_value;
1133 if let Value::Projection(pointer, proj) = self.get(copy_from_value)
1134 && let ProjectionElem::Downcast(_, read_variant) = proj
1135 {
1136 if variant_index == read_variant {
1137 copy_from_local_value = pointer;
1139 } else {
1140 return None;
1142 }
1143 }
1144
1145 if self.ty(copy_from_local_value) == ty { Some(copy_from_local_value) } else { None }
1147 }
1148
1149 fn simplify_aggregate(
1150 &mut self,
1151 lhs: &Place<'tcx>,
1152 rvalue: &mut Rvalue<'tcx>,
1153 location: Location,
1154 ) -> Option<VnIndex> {
1155 let tcx = self.tcx;
1156 let ty = rvalue.ty(self.local_decls, tcx);
1157
1158 let Rvalue::Aggregate(box ref kind, ref mut field_ops) = *rvalue else { bug!() };
1159
1160 if field_ops.is_empty() {
1161 let is_zst = match *kind {
1162 AggregateKind::Array(..)
1163 | AggregateKind::Tuple
1164 | AggregateKind::Closure(..)
1165 | AggregateKind::CoroutineClosure(..) => true,
1166 AggregateKind::Adt(did, ..) => tcx.def_kind(did) != DefKind::Enum,
1168 AggregateKind::Coroutine(..) => false,
1170 AggregateKind::RawPtr(..) => bug!("MIR for RawPtr aggregate must have 2 fields"),
1171 };
1172
1173 if is_zst {
1174 return Some(self.insert_constant(Const::zero_sized(ty)));
1175 }
1176 }
1177
1178 let fields = self.arena.alloc_from_iter(field_ops.iter_mut().map(|op| {
1179 self.simplify_operand(op, location)
1180 .unwrap_or_else(|| self.new_opaque(op.ty(self.local_decls, self.tcx)))
1181 }));
1182
1183 let variant_index = match *kind {
1184 AggregateKind::Array(..) | AggregateKind::Tuple => {
1185 assert!(!field_ops.is_empty());
1186 FIRST_VARIANT
1187 }
1188 AggregateKind::Closure(..)
1189 | AggregateKind::CoroutineClosure(..)
1190 | AggregateKind::Coroutine(..) => FIRST_VARIANT,
1191 AggregateKind::Adt(_, variant_index, _, _, None) => variant_index,
1192 AggregateKind::Adt(_, _, _, _, Some(active_field)) => {
1194 let field = *fields.first()?;
1195 return Some(self.insert(ty, Value::Union(active_field, field)));
1196 }
1197 AggregateKind::RawPtr(..) => {
1198 assert_eq!(field_ops.len(), 2);
1199 let [mut pointer, metadata] = fields.try_into().unwrap();
1200
1201 let mut was_updated = false;
1203 while let Value::Cast { kind: CastKind::PtrToPtr, value: cast_value } =
1204 self.get(pointer)
1205 && let ty::RawPtr(from_pointee_ty, from_mtbl) = self.ty(cast_value).kind()
1206 && let ty::RawPtr(_, output_mtbl) = ty.kind()
1207 && from_mtbl == output_mtbl
1208 && from_pointee_ty.is_sized(self.tcx, self.typing_env())
1209 {
1210 pointer = cast_value;
1211 was_updated = true;
1212 }
1213
1214 if was_updated && let Some(op) = self.try_as_operand(pointer, location) {
1215 field_ops[FieldIdx::ZERO] = op;
1216 }
1217
1218 return Some(self.insert(ty, Value::RawPtr { pointer, metadata }));
1219 }
1220 };
1221
1222 if ty.is_array()
1223 && fields.len() > 4
1224 && let Ok(&first) = fields.iter().all_equal_value()
1225 {
1226 let len = ty::Const::from_target_usize(self.tcx, fields.len().try_into().unwrap());
1227 if let Some(op) = self.try_as_operand(first, location) {
1228 *rvalue = Rvalue::Repeat(op, len);
1229 }
1230 return Some(self.insert(ty, Value::Repeat(first, len)));
1231 }
1232
1233 if let Some(value) = self.simplify_aggregate_to_copy(ty, variant_index, &fields) {
1234 let allow_complex_projection =
1238 lhs.projection[..].iter().all(PlaceElem::is_stable_offset);
1239 if let Some(place) = self.try_as_place(value, location, allow_complex_projection) {
1240 self.reused_locals.insert(place.local);
1241 *rvalue = Rvalue::Use(Operand::Copy(place));
1242 }
1243 return Some(value);
1244 }
1245
1246 Some(self.insert(ty, Value::Aggregate(variant_index, fields)))
1247 }
1248
1249 #[instrument(level = "trace", skip(self), ret)]
1250 fn simplify_unary(
1251 &mut self,
1252 op: UnOp,
1253 arg_op: &mut Operand<'tcx>,
1254 location: Location,
1255 ) -> Option<VnIndex> {
1256 let mut arg_index = self.simplify_operand(arg_op, location)?;
1257 let arg_ty = self.ty(arg_index);
1258 let ret_ty = op.ty(self.tcx, arg_ty);
1259
1260 if op == UnOp::PtrMetadata {
1263 let mut was_updated = false;
1264 loop {
1265 arg_index = match self.get(arg_index) {
1266 Value::Cast { kind: CastKind::PtrToPtr, value: inner }
1275 if self.pointers_have_same_metadata(self.ty(inner), arg_ty) =>
1276 {
1277 inner
1278 }
1279
1280 Value::Cast {
1282 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1283 value: from,
1284 } if let Some(from) = self.ty(from).builtin_deref(true)
1285 && let ty::Array(_, len) = from.kind()
1286 && let Some(to) = self.ty(arg_index).builtin_deref(true)
1287 && let ty::Slice(..) = to.kind() =>
1288 {
1289 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1290 }
1291
1292 Value::Address { base: AddressBase::Deref(reborrowed), projection, .. }
1294 if projection.is_empty() =>
1295 {
1296 reborrowed
1297 }
1298
1299 _ => break,
1300 };
1301 was_updated = true;
1302 }
1303
1304 if was_updated && let Some(op) = self.try_as_operand(arg_index, location) {
1305 *arg_op = op;
1306 }
1307 }
1308
1309 let value = match (op, self.get(arg_index)) {
1310 (UnOp::Not, Value::UnaryOp(UnOp::Not, inner)) => return Some(inner),
1311 (UnOp::Neg, Value::UnaryOp(UnOp::Neg, inner)) => return Some(inner),
1312 (UnOp::Not, Value::BinaryOp(BinOp::Eq, lhs, rhs)) => {
1313 Value::BinaryOp(BinOp::Ne, lhs, rhs)
1314 }
1315 (UnOp::Not, Value::BinaryOp(BinOp::Ne, lhs, rhs)) => {
1316 Value::BinaryOp(BinOp::Eq, lhs, rhs)
1317 }
1318 (UnOp::PtrMetadata, Value::RawPtr { metadata, .. }) => return Some(metadata),
1319 (
1321 UnOp::PtrMetadata,
1322 Value::Cast {
1323 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1324 value: inner,
1325 },
1326 ) if let ty::Slice(..) = arg_ty.builtin_deref(true).unwrap().kind()
1327 && let ty::Array(_, len) = self.ty(inner).builtin_deref(true).unwrap().kind() =>
1328 {
1329 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1330 }
1331 _ => Value::UnaryOp(op, arg_index),
1332 };
1333 Some(self.insert(ret_ty, value))
1334 }
1335
1336 #[instrument(level = "trace", skip(self), ret)]
1337 fn simplify_binary(
1338 &mut self,
1339 op: BinOp,
1340 lhs_operand: &mut Operand<'tcx>,
1341 rhs_operand: &mut Operand<'tcx>,
1342 location: Location,
1343 ) -> Option<VnIndex> {
1344 let lhs = self.simplify_operand(lhs_operand, location);
1345 let rhs = self.simplify_operand(rhs_operand, location);
1346
1347 let mut lhs = lhs?;
1350 let mut rhs = rhs?;
1351
1352 let lhs_ty = self.ty(lhs);
1353
1354 if let BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge = op
1357 && lhs_ty.is_any_ptr()
1358 && let Value::Cast { kind: CastKind::PtrToPtr, value: lhs_value } = self.get(lhs)
1359 && let Value::Cast { kind: CastKind::PtrToPtr, value: rhs_value } = self.get(rhs)
1360 && let lhs_from = self.ty(lhs_value)
1361 && lhs_from == self.ty(rhs_value)
1362 && self.pointers_have_same_metadata(lhs_from, lhs_ty)
1363 {
1364 lhs = lhs_value;
1365 rhs = rhs_value;
1366 if let Some(lhs_op) = self.try_as_operand(lhs, location)
1367 && let Some(rhs_op) = self.try_as_operand(rhs, location)
1368 {
1369 *lhs_operand = lhs_op;
1370 *rhs_operand = rhs_op;
1371 }
1372 }
1373
1374 if let Some(value) = self.simplify_binary_inner(op, lhs_ty, lhs, rhs) {
1375 return Some(value);
1376 }
1377 let ty = op.ty(self.tcx, lhs_ty, self.ty(rhs));
1378 let value = Value::BinaryOp(op, lhs, rhs);
1379 Some(self.insert(ty, value))
1380 }
1381
1382 fn simplify_binary_inner(
1383 &mut self,
1384 op: BinOp,
1385 lhs_ty: Ty<'tcx>,
1386 lhs: VnIndex,
1387 rhs: VnIndex,
1388 ) -> Option<VnIndex> {
1389 let reasonable_ty =
1391 lhs_ty.is_integral() || lhs_ty.is_bool() || lhs_ty.is_char() || lhs_ty.is_any_ptr();
1392 if !reasonable_ty {
1393 return None;
1394 }
1395
1396 let layout = self.ecx.layout_of(lhs_ty).ok()?;
1397
1398 let mut as_bits = |value: VnIndex| {
1399 let constant = self.eval_to_const(value)?;
1400 if layout.backend_repr.is_scalar() {
1401 let scalar = self.ecx.read_scalar(constant).discard_err()?;
1402 scalar.to_bits(constant.layout.size).discard_err()
1403 } else {
1404 None
1406 }
1407 };
1408
1409 use Either::{Left, Right};
1411 let a = as_bits(lhs).map_or(Right(lhs), Left);
1412 let b = as_bits(rhs).map_or(Right(rhs), Left);
1413
1414 let result = match (op, a, b) {
1415 (
1417 BinOp::Add
1418 | BinOp::AddWithOverflow
1419 | BinOp::AddUnchecked
1420 | BinOp::BitOr
1421 | BinOp::BitXor,
1422 Left(0),
1423 Right(p),
1424 )
1425 | (
1426 BinOp::Add
1427 | BinOp::AddWithOverflow
1428 | BinOp::AddUnchecked
1429 | BinOp::BitOr
1430 | BinOp::BitXor
1431 | BinOp::Sub
1432 | BinOp::SubWithOverflow
1433 | BinOp::SubUnchecked
1434 | BinOp::Offset
1435 | BinOp::Shl
1436 | BinOp::Shr,
1437 Right(p),
1438 Left(0),
1439 )
1440 | (BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked, Left(1), Right(p))
1441 | (
1442 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::Div,
1443 Right(p),
1444 Left(1),
1445 ) => p,
1446 (BinOp::BitAnd, Right(p), Left(ones)) | (BinOp::BitAnd, Left(ones), Right(p))
1448 if ones == layout.size.truncate(u128::MAX)
1449 || (layout.ty.is_bool() && ones == 1) =>
1450 {
1451 p
1452 }
1453 (
1455 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::BitAnd,
1456 _,
1457 Left(0),
1458 )
1459 | (BinOp::Rem, _, Left(1))
1460 | (
1461 BinOp::Mul
1462 | BinOp::MulWithOverflow
1463 | BinOp::MulUnchecked
1464 | BinOp::Div
1465 | BinOp::Rem
1466 | BinOp::BitAnd
1467 | BinOp::Shl
1468 | BinOp::Shr,
1469 Left(0),
1470 _,
1471 ) => self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size)),
1472 (BinOp::BitOr, _, Left(ones)) | (BinOp::BitOr, Left(ones), _)
1474 if ones == layout.size.truncate(u128::MAX)
1475 || (layout.ty.is_bool() && ones == 1) =>
1476 {
1477 self.insert_scalar(lhs_ty, Scalar::from_uint(ones, layout.size))
1478 }
1479 (BinOp::Sub | BinOp::SubWithOverflow | BinOp::SubUnchecked | BinOp::BitXor, a, b)
1481 if a == b =>
1482 {
1483 self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size))
1484 }
1485 (BinOp::Eq, Left(a), Left(b)) => self.insert_bool(a == b),
1490 (BinOp::Eq, a, b) if a == b => self.insert_bool(true),
1491 (BinOp::Ne, Left(a), Left(b)) => self.insert_bool(a != b),
1492 (BinOp::Ne, a, b) if a == b => self.insert_bool(false),
1493 _ => return None,
1494 };
1495
1496 if op.is_overflowing() {
1497 let ty = Ty::new_tup(self.tcx, &[self.ty(result), self.tcx.types.bool]);
1498 let false_val = self.insert_bool(false);
1499 Some(self.insert_tuple(ty, &[result, false_val]))
1500 } else {
1501 Some(result)
1502 }
1503 }
1504
1505 fn simplify_cast(
1506 &mut self,
1507 initial_kind: &mut CastKind,
1508 initial_operand: &mut Operand<'tcx>,
1509 to: Ty<'tcx>,
1510 location: Location,
1511 ) -> Option<VnIndex> {
1512 use CastKind::*;
1513 use rustc_middle::ty::adjustment::PointerCoercion::*;
1514
1515 let mut kind = *initial_kind;
1516 let mut value = self.simplify_operand(initial_operand, location)?;
1517 let mut from = self.ty(value);
1518 if from == to {
1519 return Some(value);
1520 }
1521
1522 if let CastKind::PointerCoercion(ReifyFnPointer(_) | ClosureFnPointer(_), _) = kind {
1523 return Some(self.new_opaque(to));
1526 }
1527
1528 let mut was_ever_updated = false;
1529 loop {
1530 let mut was_updated_this_iteration = false;
1531
1532 if let Transmute = kind
1537 && from.is_raw_ptr()
1538 && to.is_raw_ptr()
1539 && self.pointers_have_same_metadata(from, to)
1540 {
1541 kind = PtrToPtr;
1542 was_updated_this_iteration = true;
1543 }
1544
1545 if let PtrToPtr = kind
1548 && let Value::RawPtr { pointer, .. } = self.get(value)
1549 && let ty::RawPtr(to_pointee, _) = to.kind()
1550 && to_pointee.is_sized(self.tcx, self.typing_env())
1551 {
1552 from = self.ty(pointer);
1553 value = pointer;
1554 was_updated_this_iteration = true;
1555 if from == to {
1556 return Some(pointer);
1557 }
1558 }
1559
1560 if let Transmute = kind
1563 && let Value::Aggregate(variant_idx, field_values) = self.get(value)
1564 && let Some((field_idx, field_ty)) =
1565 self.value_is_all_in_one_field(from, variant_idx)
1566 {
1567 from = field_ty;
1568 value = field_values[field_idx.as_usize()];
1569 was_updated_this_iteration = true;
1570 if field_ty == to {
1571 return Some(value);
1572 }
1573 }
1574
1575 if let Value::Cast { kind: inner_kind, value: inner_value } = self.get(value) {
1577 let inner_from = self.ty(inner_value);
1578 let new_kind = match (inner_kind, kind) {
1579 (PtrToPtr, PtrToPtr) => Some(PtrToPtr),
1583 (PtrToPtr, Transmute) if self.pointers_have_same_metadata(inner_from, from) => {
1587 Some(Transmute)
1588 }
1589 (Transmute, PtrToPtr) if self.pointers_have_same_metadata(from, to) => {
1592 Some(Transmute)
1593 }
1594 (Transmute, Transmute)
1597 if !self.type_may_have_niche_of_interest_to_backend(from) =>
1598 {
1599 Some(Transmute)
1600 }
1601 _ => None,
1602 };
1603 if let Some(new_kind) = new_kind {
1604 kind = new_kind;
1605 from = inner_from;
1606 value = inner_value;
1607 was_updated_this_iteration = true;
1608 if inner_from == to {
1609 return Some(inner_value);
1610 }
1611 }
1612 }
1613
1614 if was_updated_this_iteration {
1615 was_ever_updated = true;
1616 } else {
1617 break;
1618 }
1619 }
1620
1621 if was_ever_updated && let Some(op) = self.try_as_operand(value, location) {
1622 *initial_operand = op;
1623 *initial_kind = kind;
1624 }
1625
1626 Some(self.insert(to, Value::Cast { kind, value }))
1627 }
1628
1629 fn pointers_have_same_metadata(&self, left_ptr_ty: Ty<'tcx>, right_ptr_ty: Ty<'tcx>) -> bool {
1630 let left_meta_ty = left_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1631 let right_meta_ty = right_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1632 if left_meta_ty == right_meta_ty {
1633 true
1634 } else if let Ok(left) =
1635 self.tcx.try_normalize_erasing_regions(self.typing_env(), left_meta_ty)
1636 && let Ok(right) =
1637 self.tcx.try_normalize_erasing_regions(self.typing_env(), right_meta_ty)
1638 {
1639 left == right
1640 } else {
1641 false
1642 }
1643 }
1644
1645 fn type_may_have_niche_of_interest_to_backend(&self, ty: Ty<'tcx>) -> bool {
1652 let Ok(layout) = self.ecx.layout_of(ty) else {
1653 return true;
1655 };
1656
1657 if layout.uninhabited {
1658 return true;
1659 }
1660
1661 match layout.backend_repr {
1662 BackendRepr::Scalar(a) => !a.is_always_valid(&self.ecx),
1663 BackendRepr::ScalarPair(a, b) => {
1664 !a.is_always_valid(&self.ecx) || !b.is_always_valid(&self.ecx)
1665 }
1666 BackendRepr::SimdVector { .. }
1667 | BackendRepr::ScalableVector { .. }
1668 | BackendRepr::Memory { .. } => false,
1669 }
1670 }
1671
1672 fn value_is_all_in_one_field(
1673 &self,
1674 ty: Ty<'tcx>,
1675 variant: VariantIdx,
1676 ) -> Option<(FieldIdx, Ty<'tcx>)> {
1677 if let Ok(layout) = self.ecx.layout_of(ty)
1678 && let abi::Variants::Single { index } = layout.variants
1679 && index == variant
1680 && let Some((field_idx, field_layout)) = layout.non_1zst_field(&self.ecx)
1681 && layout.size == field_layout.size
1682 {
1683 Some((field_idx, field_layout.ty))
1687 } else if let ty::Adt(adt, args) = ty.kind()
1688 && adt.is_struct()
1689 && adt.repr().transparent()
1690 && let [single_field] = adt.non_enum_variant().fields.raw.as_slice()
1691 {
1692 Some((FieldIdx::ZERO, single_field.ty(self.tcx, args)))
1693 } else {
1694 None
1695 }
1696 }
1697}
1698
1699fn op_to_prop_const<'tcx>(
1700 ecx: &mut InterpCx<'tcx, DummyMachine>,
1701 op: &OpTy<'tcx>,
1702) -> Option<ConstValue> {
1703 if op.layout.is_unsized() {
1705 return None;
1706 }
1707
1708 if op.layout.is_zst() {
1710 return Some(ConstValue::ZeroSized);
1711 }
1712
1713 if !op.is_immediate_uninit()
1718 && !matches!(op.layout.backend_repr, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..))
1719 {
1720 return None;
1721 }
1722
1723 if let BackendRepr::Scalar(abi::Scalar::Initialized { .. }) = op.layout.backend_repr
1725 && let Some(scalar) = ecx.read_scalar(op).discard_err()
1726 {
1727 if !scalar.try_to_scalar_int().is_ok() {
1728 return None;
1732 }
1733 return Some(ConstValue::Scalar(scalar));
1734 }
1735
1736 if let Either::Left(mplace) = op.as_mplace_or_imm() {
1739 let (size, _align) = ecx.size_and_align_of_val(&mplace).discard_err()??;
1740
1741 let alloc_ref = ecx.get_ptr_alloc(mplace.ptr(), size).discard_err()??;
1745 if alloc_ref.has_provenance() {
1746 return None;
1747 }
1748
1749 let pointer = mplace.ptr().into_pointer_or_addr().ok()?;
1750 let (prov, offset) = pointer.prov_and_relative_offset();
1751 let alloc_id = prov.alloc_id();
1752 intern_const_alloc_for_constprop(ecx, alloc_id).discard_err()?;
1753
1754 if let GlobalAlloc::Memory(alloc) = ecx.tcx.global_alloc(alloc_id)
1758 && alloc.inner().align >= op.layout.align.abi
1761 {
1762 return Some(ConstValue::Indirect { alloc_id, offset });
1763 }
1764 }
1765
1766 let alloc_id =
1768 ecx.intern_with_temp_alloc(op.layout, |ecx, dest| ecx.copy_op(op, dest)).discard_err()?;
1769 let value = ConstValue::Indirect { alloc_id, offset: Size::ZERO };
1770
1771 if ecx.tcx.global_alloc(alloc_id).unwrap_memory().inner().provenance().ptrs().is_empty() {
1775 return Some(value);
1776 }
1777
1778 None
1779}
1780
1781impl<'tcx> VnState<'_, '_, 'tcx> {
1782 fn try_as_operand(&mut self, index: VnIndex, location: Location) -> Option<Operand<'tcx>> {
1785 if let Some(const_) = self.try_as_constant(index) {
1786 Some(Operand::Constant(Box::new(const_)))
1787 } else if let Value::RuntimeChecks(c) = self.get(index) {
1788 Some(Operand::RuntimeChecks(c))
1789 } else if let Some(place) = self.try_as_place(index, location, false) {
1790 self.reused_locals.insert(place.local);
1791 Some(Operand::Copy(place))
1792 } else {
1793 None
1794 }
1795 }
1796
1797 fn try_as_constant(&mut self, index: VnIndex) -> Option<ConstOperand<'tcx>> {
1799 if let Value::Constant { value, disambiguator: None } = self.get(index) {
1803 debug_assert!(value.is_deterministic());
1804 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1805 }
1806
1807 let op = self.eval_to_const(index)?;
1808 if op.layout.is_unsized() {
1809 return None;
1811 }
1812
1813 let value = op_to_prop_const(&mut self.ecx, op)?;
1814
1815 assert!(!value.may_have_provenance(self.tcx, op.layout.size));
1819
1820 let const_ = Const::Val(value, op.layout.ty);
1821 Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_ })
1822 }
1823
1824 #[instrument(level = "trace", skip(self), ret)]
1828 fn try_as_place(
1829 &mut self,
1830 mut index: VnIndex,
1831 loc: Location,
1832 allow_complex_projection: bool,
1833 ) -> Option<Place<'tcx>> {
1834 let mut projection = SmallVec::<[PlaceElem<'tcx>; 1]>::new();
1835 loop {
1836 if let Some(local) = self.try_as_local(index, loc) {
1837 projection.reverse();
1838 let place =
1839 Place { local, projection: self.tcx.mk_place_elems(projection.as_slice()) };
1840 return Some(place);
1841 } else if projection.last() == Some(&PlaceElem::Deref) {
1842 return None;
1846 } else if let Value::Projection(pointer, proj) = self.get(index)
1847 && (allow_complex_projection || proj.is_stable_offset())
1848 && let Some(proj) = self.try_as_place_elem(self.ty(index), proj, loc)
1849 {
1850 projection.push(proj);
1851 index = pointer;
1852 } else {
1853 return None;
1854 }
1855 }
1856 }
1857
1858 fn try_as_local(&mut self, index: VnIndex, loc: Location) -> Option<Local> {
1861 let other = self.rev_locals.get(index)?;
1862 other
1863 .iter()
1864 .find(|&&other| self.ssa.assignment_dominates(&self.dominators, other, loc))
1865 .copied()
1866 }
1867}
1868
1869impl<'tcx> MutVisitor<'tcx> for VnState<'_, '_, 'tcx> {
1870 fn tcx(&self) -> TyCtxt<'tcx> {
1871 self.tcx
1872 }
1873
1874 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
1875 self.simplify_place_projection(place, location);
1876 if context.is_mutating_use() && place.is_indirect() {
1877 self.invalidate_derefs();
1879 }
1880 self.super_place(place, context, location);
1881 }
1882
1883 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
1884 self.simplify_operand(operand, location);
1885 self.super_operand(operand, location);
1886 }
1887
1888 fn visit_assign(
1889 &mut self,
1890 lhs: &mut Place<'tcx>,
1891 rvalue: &mut Rvalue<'tcx>,
1892 location: Location,
1893 ) {
1894 self.simplify_place_projection(lhs, location);
1895
1896 let value = self.simplify_rvalue(lhs, rvalue, location);
1897 if let Some(value) = value {
1898 if let Some(const_) = self.try_as_constant(value) {
1899 *rvalue = Rvalue::Use(Operand::Constant(Box::new(const_)));
1900 } else if let Some(place) = self.try_as_place(value, location, false)
1901 && *rvalue != Rvalue::Use(Operand::Move(place))
1902 && *rvalue != Rvalue::Use(Operand::Copy(place))
1903 {
1904 *rvalue = Rvalue::Use(Operand::Copy(place));
1905 self.reused_locals.insert(place.local);
1906 }
1907 }
1908
1909 if lhs.is_indirect() {
1910 self.invalidate_derefs();
1912 }
1913
1914 if let Some(local) = lhs.as_local()
1915 && self.ssa.is_ssa(local)
1916 && let rvalue_ty = rvalue.ty(self.local_decls, self.tcx)
1917 && self.local_decls[local].ty == rvalue_ty
1920 {
1921 let value = value.unwrap_or_else(|| self.new_opaque(rvalue_ty));
1922 self.assign(local, value);
1923 }
1924 }
1925
1926 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
1927 if let Terminator { kind: TerminatorKind::Call { destination, .. }, .. } = terminator {
1928 if let Some(local) = destination.as_local()
1929 && self.ssa.is_ssa(local)
1930 {
1931 let ty = self.local_decls[local].ty;
1932 let opaque = self.new_opaque(ty);
1933 self.assign(local, opaque);
1934 }
1935 }
1936 if terminator.kind.can_write_to_memory() {
1938 self.invalidate_derefs();
1939 }
1940 self.super_terminator(terminator, location);
1941 }
1942}
1943
1944struct StorageRemover<'tcx> {
1945 tcx: TyCtxt<'tcx>,
1946 reused_locals: DenseBitSet<Local>,
1947}
1948
1949impl<'tcx> MutVisitor<'tcx> for StorageRemover<'tcx> {
1950 fn tcx(&self) -> TyCtxt<'tcx> {
1951 self.tcx
1952 }
1953
1954 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, _: Location) {
1955 if let Operand::Move(place) = *operand
1956 && !place.is_indirect_first_projection()
1957 && self.reused_locals.contains(place.local)
1958 {
1959 *operand = Operand::Copy(place);
1960 }
1961 }
1962
1963 fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
1964 match stmt.kind {
1965 StatementKind::StorageLive(l) | StatementKind::StorageDead(l)
1967 if self.reused_locals.contains(l) =>
1968 {
1969 stmt.make_nop(true)
1970 }
1971 _ => self.super_statement(stmt, loc),
1972 }
1973 }
1974}