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 if matches!(ty.backend_repr, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..))
594 {
595 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
596 let variant_dest = if let Some(variant) = variant {
597 self.ecx.project_downcast(&dest, variant).discard_err()?
598 } else {
599 dest.clone()
600 };
601 for (field_index, op) in fields.into_iter().enumerate() {
602 let field_dest = self
603 .ecx
604 .project_field(&variant_dest, FieldIdx::from_usize(field_index))
605 .discard_err()?;
606 self.ecx.copy_op(op, &field_dest).discard_err()?;
607 }
608 self.ecx
609 .write_discriminant(variant.unwrap_or(FIRST_VARIANT), &dest)
610 .discard_err()?;
611 self.ecx
612 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
613 .discard_err()?;
614 dest.into()
615 } else {
616 return None;
617 }
618 }
619 Union(active_field, field) => {
620 let field = self.eval_to_const(field)?;
621 if field.layout.layout.is_zst() {
622 ImmTy::from_immediate(Immediate::Uninit, ty).into()
623 } else if matches!(
624 ty.backend_repr,
625 BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..)
626 ) {
627 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
628 let field_dest = self.ecx.project_field(&dest, active_field).discard_err()?;
629 self.ecx.copy_op(field, &field_dest).discard_err()?;
630 self.ecx
631 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
632 .discard_err()?;
633 dest.into()
634 } else {
635 return None;
636 }
637 }
638 RawPtr { pointer, metadata } => {
639 let pointer = self.eval_to_const(pointer)?;
640 let metadata = self.eval_to_const(metadata)?;
641
642 let data = self.ecx.read_pointer(pointer).discard_err()?;
644 let meta = if metadata.layout.is_zst() {
645 MemPlaceMeta::None
646 } else {
647 MemPlaceMeta::Meta(self.ecx.read_scalar(metadata).discard_err()?)
648 };
649 let ptr_imm = Immediate::new_pointer_with_meta(data, meta, &self.ecx);
650 ImmTy::from_immediate(ptr_imm, ty).into()
651 }
652
653 Projection(base, elem) => {
654 let base = self.eval_to_const(base)?;
655 let elem = elem.try_map(|_| None, |()| ty.ty)?;
658 self.ecx.project(base, elem).discard_err()?
659 }
660 Address { base, projection, .. } => {
661 debug_assert!(!projection.contains(&ProjectionElem::Deref));
662 let pointer = match base {
663 AddressBase::Deref(pointer) => self.eval_to_const(pointer)?,
664 AddressBase::Local(_) => return None,
666 };
667 let mut mplace = self.ecx.deref_pointer(pointer).discard_err()?;
668 for elem in projection {
669 let elem = elem.try_map(|_| None, |ty| ty)?;
672 mplace = self.ecx.project(&mplace, elem).discard_err()?;
673 }
674 let pointer = mplace.to_ref(&self.ecx);
675 ImmTy::from_immediate(pointer, ty).into()
676 }
677
678 Discriminant(base) => {
679 let base = self.eval_to_const(base)?;
680 let variant = self.ecx.read_discriminant(base).discard_err()?;
681 let discr_value =
682 self.ecx.discriminant_for_variant(base.layout.ty, variant).discard_err()?;
683 discr_value.into()
684 }
685 NullaryOp(NullOp::RuntimeChecks(_)) => return None,
686 UnaryOp(un_op, operand) => {
687 let operand = self.eval_to_const(operand)?;
688 let operand = self.ecx.read_immediate(operand).discard_err()?;
689 let val = self.ecx.unary_op(un_op, &operand).discard_err()?;
690 val.into()
691 }
692 BinaryOp(bin_op, lhs, rhs) => {
693 let lhs = self.eval_to_const(lhs)?;
694 let rhs = self.eval_to_const(rhs)?;
695 let lhs = self.ecx.read_immediate(lhs).discard_err()?;
696 let rhs = self.ecx.read_immediate(rhs).discard_err()?;
697 let val = self.ecx.binary_op(bin_op, &lhs, &rhs).discard_err()?;
698 val.into()
699 }
700 Cast { kind, value } => match kind {
701 CastKind::IntToInt | CastKind::IntToFloat => {
702 let value = self.eval_to_const(value)?;
703 let value = self.ecx.read_immediate(value).discard_err()?;
704 let res = self.ecx.int_to_int_or_float(&value, ty).discard_err()?;
705 res.into()
706 }
707 CastKind::FloatToFloat | CastKind::FloatToInt => {
708 let value = self.eval_to_const(value)?;
709 let value = self.ecx.read_immediate(value).discard_err()?;
710 let res = self.ecx.float_to_float_or_int(&value, ty).discard_err()?;
711 res.into()
712 }
713 CastKind::Transmute | CastKind::Subtype => {
714 let value = self.eval_to_const(value)?;
715 if value.as_mplace_or_imm().is_right() {
720 let can_transmute = match (value.layout.backend_repr, ty.backend_repr) {
721 (BackendRepr::Scalar(s1), BackendRepr::Scalar(s2)) => {
722 s1.size(&self.ecx) == s2.size(&self.ecx)
723 && !matches!(s1.primitive(), Primitive::Pointer(..))
724 }
725 (BackendRepr::ScalarPair(a1, b1), BackendRepr::ScalarPair(a2, b2)) => {
726 a1.size(&self.ecx) == a2.size(&self.ecx)
727 && b1.size(&self.ecx) == b2.size(&self.ecx)
728 && b1.align(&self.ecx) == b2.align(&self.ecx)
730 && !matches!(a1.primitive(), Primitive::Pointer(..))
732 && !matches!(b1.primitive(), Primitive::Pointer(..))
733 }
734 _ => false,
735 };
736 if !can_transmute {
737 return None;
738 }
739 }
740 value.offset(Size::ZERO, ty, &self.ecx).discard_err()?
741 }
742 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _) => {
743 let src = self.eval_to_const(value)?;
744 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
745 self.ecx.unsize_into(src, ty, &dest).discard_err()?;
746 self.ecx
747 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
748 .discard_err()?;
749 dest.into()
750 }
751 CastKind::FnPtrToPtr | CastKind::PtrToPtr => {
752 let src = self.eval_to_const(value)?;
753 let src = self.ecx.read_immediate(src).discard_err()?;
754 let ret = self.ecx.ptr_to_ptr(&src, ty).discard_err()?;
755 ret.into()
756 }
757 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::UnsafeFnPointer, _) => {
758 let src = self.eval_to_const(value)?;
759 let src = self.ecx.read_immediate(src).discard_err()?;
760 ImmTy::from_immediate(*src, ty).into()
761 }
762 _ => return None,
763 },
764 };
765 Some(op)
766 }
767
768 fn eval_to_const(&mut self, index: VnIndex) -> Option<&'a OpTy<'tcx>> {
769 if let Some(op) = self.evaluated[index] {
770 return op;
771 }
772 let op = self.eval_to_const_inner(index);
773 self.evaluated[index] = Some(self.arena.alloc(op).as_ref());
774 self.evaluated[index].unwrap()
775 }
776
777 #[instrument(level = "trace", skip(self), ret)]
779 fn dereference_address(
780 &mut self,
781 base: AddressBase,
782 projection: &[ProjectionElem<VnIndex, Ty<'tcx>>],
783 ) -> Option<VnIndex> {
784 let (mut place_ty, mut value) = match base {
785 AddressBase::Local(local) => {
787 let local = self.locals[local]?;
788 let place_ty = PlaceTy::from_ty(self.ty(local));
789 (place_ty, local)
790 }
791 AddressBase::Deref(reborrow) => {
793 let place_ty = PlaceTy::from_ty(self.ty(reborrow));
794 self.project(place_ty, reborrow, ProjectionElem::Deref)?
795 }
796 };
797 for &proj in projection {
798 (place_ty, value) = self.project(place_ty, value, proj)?;
799 }
800 Some(value)
801 }
802
803 #[instrument(level = "trace", skip(self), ret)]
804 fn project(
805 &mut self,
806 place_ty: PlaceTy<'tcx>,
807 value: VnIndex,
808 proj: ProjectionElem<VnIndex, Ty<'tcx>>,
809 ) -> Option<(PlaceTy<'tcx>, VnIndex)> {
810 let projection_ty = place_ty.projection_ty(self.tcx, proj);
811 let proj = match proj {
812 ProjectionElem::Deref => {
813 if let Some(Mutability::Not) = place_ty.ty.ref_mutability()
814 && projection_ty.ty.is_freeze(self.tcx, self.typing_env())
815 {
816 if let Value::Address { base, projection, .. } = self.get(value)
817 && let Some(value) = self.dereference_address(base, projection)
818 {
819 return Some((projection_ty, value));
820 }
821
822 return Some((projection_ty, self.insert_deref(projection_ty.ty, value)));
825 } else {
826 return None;
827 }
828 }
829 ProjectionElem::Downcast(name, index) => ProjectionElem::Downcast(name, index),
830 ProjectionElem::Field(f, _) => match self.get(value) {
831 Value::Aggregate(_, fields) => return Some((projection_ty, fields[f.as_usize()])),
832 Value::Union(active, field) if active == f => return Some((projection_ty, field)),
833 Value::Projection(outer_value, ProjectionElem::Downcast(_, read_variant))
834 if let Value::Aggregate(written_variant, fields) = self.get(outer_value)
835 && written_variant == read_variant =>
851 {
852 return Some((projection_ty, fields[f.as_usize()]));
853 }
854 _ => ProjectionElem::Field(f, ()),
855 },
856 ProjectionElem::Index(idx) => {
857 if let Value::Repeat(inner, _) = self.get(value) {
858 return Some((projection_ty, inner));
859 }
860 ProjectionElem::Index(idx)
861 }
862 ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
863 match self.get(value) {
864 Value::Repeat(inner, _) => {
865 return Some((projection_ty, inner));
866 }
867 Value::Aggregate(_, operands) => {
868 let offset = if from_end {
869 operands.len() - offset as usize
870 } else {
871 offset as usize
872 };
873 let value = operands.get(offset).copied()?;
874 return Some((projection_ty, value));
875 }
876 _ => {}
877 };
878 ProjectionElem::ConstantIndex { offset, min_length, from_end }
879 }
880 ProjectionElem::Subslice { from, to, from_end } => {
881 ProjectionElem::Subslice { from, to, from_end }
882 }
883 ProjectionElem::OpaqueCast(_) => ProjectionElem::OpaqueCast(()),
884 ProjectionElem::UnwrapUnsafeBinder(_) => ProjectionElem::UnwrapUnsafeBinder(()),
885 };
886
887 let value = self.insert(projection_ty.ty, Value::Projection(value, proj));
888 Some((projection_ty, value))
889 }
890
891 #[instrument(level = "trace", skip(self))]
893 fn simplify_place_projection(&mut self, place: &mut Place<'tcx>, location: Location) {
894 if place.is_indirect_first_projection()
897 && let Some(base) = self.locals[place.local]
898 && let Some(new_local) = self.try_as_local(base, location)
899 && place.local != new_local
900 {
901 place.local = new_local;
902 self.reused_locals.insert(new_local);
903 }
904
905 let mut projection = Cow::Borrowed(&place.projection[..]);
906
907 for i in 0..projection.len() {
908 let elem = projection[i];
909 if let ProjectionElem::Index(idx_local) = elem
910 && let Some(idx) = self.locals[idx_local]
911 {
912 if let Some(offset) = self.eval_to_const(idx)
913 && let Some(offset) = self.ecx.read_target_usize(offset).discard_err()
914 && let Some(min_length) = offset.checked_add(1)
915 {
916 projection.to_mut()[i] =
917 ProjectionElem::ConstantIndex { offset, min_length, from_end: false };
918 } else if let Some(new_idx_local) = self.try_as_local(idx, location)
919 && idx_local != new_idx_local
920 {
921 projection.to_mut()[i] = ProjectionElem::Index(new_idx_local);
922 self.reused_locals.insert(new_idx_local);
923 }
924 }
925 }
926
927 if Cow::is_owned(&projection) {
928 place.projection = self.tcx.mk_place_elems(&projection);
929 }
930
931 trace!(?place);
932 }
933
934 #[instrument(level = "trace", skip(self), ret)]
937 fn compute_place_value(
938 &mut self,
939 place: Place<'tcx>,
940 location: Location,
941 ) -> Result<VnIndex, PlaceRef<'tcx>> {
942 let mut place_ref = place.as_ref();
945
946 let Some(mut value) = self.locals[place.local] else { return Err(place_ref) };
948 let mut place_ty = PlaceTy::from_ty(self.local_decls[place.local].ty);
950 for (index, proj) in place.projection.iter().enumerate() {
951 if let Some(local) = self.try_as_local(value, location) {
952 place_ref = PlaceRef { local, projection: &place.projection[index..] };
956 }
957
958 let Some(proj) = proj.try_map(|value| self.locals[value], |ty| ty) else {
959 return Err(place_ref);
960 };
961 let Some(ty_and_value) = self.project(place_ty, value, proj) else {
962 return Err(place_ref);
963 };
964 (place_ty, value) = ty_and_value;
965 }
966
967 Ok(value)
968 }
969
970 #[instrument(level = "trace", skip(self), ret)]
973 fn simplify_place_value(
974 &mut self,
975 place: &mut Place<'tcx>,
976 location: Location,
977 ) -> Option<VnIndex> {
978 self.simplify_place_projection(place, location);
979
980 match self.compute_place_value(*place, location) {
981 Ok(value) => {
982 if let Some(new_place) = self.try_as_place(value, location, true)
983 && (new_place.local != place.local
984 || new_place.projection.len() < place.projection.len())
985 {
986 *place = new_place;
987 self.reused_locals.insert(new_place.local);
988 }
989 Some(value)
990 }
991 Err(place_ref) => {
992 if place_ref.local != place.local
993 || place_ref.projection.len() < place.projection.len()
994 {
995 *place = place_ref.project_deeper(&[], self.tcx);
997 self.reused_locals.insert(place_ref.local);
998 }
999 None
1000 }
1001 }
1002 }
1003
1004 #[instrument(level = "trace", skip(self), ret)]
1005 fn simplify_operand(
1006 &mut self,
1007 operand: &mut Operand<'tcx>,
1008 location: Location,
1009 ) -> Option<VnIndex> {
1010 match *operand {
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 }
1017 Some(value)
1018 }
1019 }
1020 }
1021
1022 #[instrument(level = "trace", skip(self), ret)]
1023 fn simplify_rvalue(
1024 &mut self,
1025 lhs: &Place<'tcx>,
1026 rvalue: &mut Rvalue<'tcx>,
1027 location: Location,
1028 ) -> Option<VnIndex> {
1029 let value = match *rvalue {
1030 Rvalue::Use(ref mut operand) => return self.simplify_operand(operand, location),
1032
1033 Rvalue::Repeat(ref mut op, amount) => {
1035 let op = self.simplify_operand(op, location)?;
1036 Value::Repeat(op, amount)
1037 }
1038 Rvalue::NullaryOp(op) => Value::NullaryOp(op),
1039 Rvalue::Aggregate(..) => return self.simplify_aggregate(lhs, rvalue, location),
1040 Rvalue::Ref(_, borrow_kind, ref mut place) => {
1041 self.simplify_place_projection(place, location);
1042 return self.new_pointer(*place, AddressKind::Ref(borrow_kind));
1043 }
1044 Rvalue::RawPtr(mutbl, ref mut place) => {
1045 self.simplify_place_projection(place, location);
1046 return self.new_pointer(*place, AddressKind::Address(mutbl));
1047 }
1048 Rvalue::WrapUnsafeBinder(ref mut op, _) => {
1049 let value = self.simplify_operand(op, location)?;
1050 Value::Cast { kind: CastKind::Transmute, value }
1051 }
1052
1053 Rvalue::Cast(ref mut kind, ref mut value, to) => {
1055 return self.simplify_cast(kind, value, to, location);
1056 }
1057 Rvalue::BinaryOp(op, box (ref mut lhs, ref mut rhs)) => {
1058 return self.simplify_binary(op, lhs, rhs, location);
1059 }
1060 Rvalue::UnaryOp(op, ref mut arg_op) => {
1061 return self.simplify_unary(op, arg_op, location);
1062 }
1063 Rvalue::Discriminant(ref mut place) => {
1064 let place = self.simplify_place_value(place, location)?;
1065 if let Some(discr) = self.simplify_discriminant(place) {
1066 return Some(discr);
1067 }
1068 Value::Discriminant(place)
1069 }
1070
1071 Rvalue::ThreadLocalRef(..) => return None,
1073 Rvalue::CopyForDeref(_) | Rvalue::ShallowInitBox(..) => {
1074 bug!("forbidden in runtime MIR: {rvalue:?}")
1075 }
1076 };
1077 let ty = rvalue.ty(self.local_decls, self.tcx);
1078 Some(self.insert(ty, value))
1079 }
1080
1081 fn simplify_discriminant(&mut self, place: VnIndex) -> Option<VnIndex> {
1082 let enum_ty = self.ty(place);
1083 if enum_ty.is_enum()
1084 && let Value::Aggregate(variant, _) = self.get(place)
1085 {
1086 let discr = self.ecx.discriminant_for_variant(enum_ty, variant).discard_err()?;
1087 return Some(self.insert_scalar(discr.layout.ty, discr.to_scalar()));
1088 }
1089
1090 None
1091 }
1092
1093 fn try_as_place_elem(
1094 &mut self,
1095 ty: Ty<'tcx>,
1096 proj: ProjectionElem<VnIndex, ()>,
1097 loc: Location,
1098 ) -> Option<PlaceElem<'tcx>> {
1099 proj.try_map(
1100 |value| {
1101 let local = self.try_as_local(value, loc)?;
1102 self.reused_locals.insert(local);
1103 Some(local)
1104 },
1105 |()| ty,
1106 )
1107 }
1108
1109 fn simplify_aggregate_to_copy(
1110 &mut self,
1111 ty: Ty<'tcx>,
1112 variant_index: VariantIdx,
1113 fields: &[VnIndex],
1114 ) -> Option<VnIndex> {
1115 let Some(&first_field) = fields.first() else { return None };
1116 let Value::Projection(copy_from_value, _) = self.get(first_field) else { return None };
1117
1118 if fields.iter().enumerate().any(|(index, &v)| {
1120 if let Value::Projection(pointer, ProjectionElem::Field(from_index, _)) = self.get(v)
1121 && copy_from_value == pointer
1122 && from_index.index() == index
1123 {
1124 return false;
1125 }
1126 true
1127 }) {
1128 return None;
1129 }
1130
1131 let mut copy_from_local_value = copy_from_value;
1132 if let Value::Projection(pointer, proj) = self.get(copy_from_value)
1133 && let ProjectionElem::Downcast(_, read_variant) = proj
1134 {
1135 if variant_index == read_variant {
1136 copy_from_local_value = pointer;
1138 } else {
1139 return None;
1141 }
1142 }
1143
1144 if self.ty(copy_from_local_value) == ty { Some(copy_from_local_value) } else { None }
1146 }
1147
1148 fn simplify_aggregate(
1149 &mut self,
1150 lhs: &Place<'tcx>,
1151 rvalue: &mut Rvalue<'tcx>,
1152 location: Location,
1153 ) -> Option<VnIndex> {
1154 let tcx = self.tcx;
1155 let ty = rvalue.ty(self.local_decls, tcx);
1156
1157 let Rvalue::Aggregate(box ref kind, ref mut field_ops) = *rvalue else { bug!() };
1158
1159 if field_ops.is_empty() {
1160 let is_zst = match *kind {
1161 AggregateKind::Array(..)
1162 | AggregateKind::Tuple
1163 | AggregateKind::Closure(..)
1164 | AggregateKind::CoroutineClosure(..) => true,
1165 AggregateKind::Adt(did, ..) => tcx.def_kind(did) != DefKind::Enum,
1167 AggregateKind::Coroutine(..) => false,
1169 AggregateKind::RawPtr(..) => bug!("MIR for RawPtr aggregate must have 2 fields"),
1170 };
1171
1172 if is_zst {
1173 return Some(self.insert_constant(Const::zero_sized(ty)));
1174 }
1175 }
1176
1177 let fields = self.arena.alloc_from_iter(field_ops.iter_mut().map(|op| {
1178 self.simplify_operand(op, location)
1179 .unwrap_or_else(|| self.new_opaque(op.ty(self.local_decls, self.tcx)))
1180 }));
1181
1182 let variant_index = match *kind {
1183 AggregateKind::Array(..) | AggregateKind::Tuple => {
1184 assert!(!field_ops.is_empty());
1185 FIRST_VARIANT
1186 }
1187 AggregateKind::Closure(..)
1188 | AggregateKind::CoroutineClosure(..)
1189 | AggregateKind::Coroutine(..) => FIRST_VARIANT,
1190 AggregateKind::Adt(_, variant_index, _, _, None) => variant_index,
1191 AggregateKind::Adt(_, _, _, _, Some(active_field)) => {
1193 let field = *fields.first()?;
1194 return Some(self.insert(ty, Value::Union(active_field, field)));
1195 }
1196 AggregateKind::RawPtr(..) => {
1197 assert_eq!(field_ops.len(), 2);
1198 let [mut pointer, metadata] = fields.try_into().unwrap();
1199
1200 let mut was_updated = false;
1202 while let Value::Cast { kind: CastKind::PtrToPtr, value: cast_value } =
1203 self.get(pointer)
1204 && let ty::RawPtr(from_pointee_ty, from_mtbl) = self.ty(cast_value).kind()
1205 && let ty::RawPtr(_, output_mtbl) = ty.kind()
1206 && from_mtbl == output_mtbl
1207 && from_pointee_ty.is_sized(self.tcx, self.typing_env())
1208 {
1209 pointer = cast_value;
1210 was_updated = true;
1211 }
1212
1213 if was_updated && let Some(op) = self.try_as_operand(pointer, location) {
1214 field_ops[FieldIdx::ZERO] = op;
1215 }
1216
1217 return Some(self.insert(ty, Value::RawPtr { pointer, metadata }));
1218 }
1219 };
1220
1221 if ty.is_array()
1222 && fields.len() > 4
1223 && let Ok(&first) = fields.iter().all_equal_value()
1224 {
1225 let len = ty::Const::from_target_usize(self.tcx, fields.len().try_into().unwrap());
1226 if let Some(op) = self.try_as_operand(first, location) {
1227 *rvalue = Rvalue::Repeat(op, len);
1228 }
1229 return Some(self.insert(ty, Value::Repeat(first, len)));
1230 }
1231
1232 if let Some(value) = self.simplify_aggregate_to_copy(ty, variant_index, &fields) {
1233 let allow_complex_projection =
1237 lhs.projection[..].iter().all(PlaceElem::is_stable_offset);
1238 if let Some(place) = self.try_as_place(value, location, allow_complex_projection) {
1239 self.reused_locals.insert(place.local);
1240 *rvalue = Rvalue::Use(Operand::Copy(place));
1241 }
1242 return Some(value);
1243 }
1244
1245 Some(self.insert(ty, Value::Aggregate(variant_index, fields)))
1246 }
1247
1248 #[instrument(level = "trace", skip(self), ret)]
1249 fn simplify_unary(
1250 &mut self,
1251 op: UnOp,
1252 arg_op: &mut Operand<'tcx>,
1253 location: Location,
1254 ) -> Option<VnIndex> {
1255 let mut arg_index = self.simplify_operand(arg_op, location)?;
1256 let arg_ty = self.ty(arg_index);
1257 let ret_ty = op.ty(self.tcx, arg_ty);
1258
1259 if op == UnOp::PtrMetadata {
1262 let mut was_updated = false;
1263 loop {
1264 arg_index = match self.get(arg_index) {
1265 Value::Cast { kind: CastKind::PtrToPtr, value: inner }
1274 if self.pointers_have_same_metadata(self.ty(inner), arg_ty) =>
1275 {
1276 inner
1277 }
1278
1279 Value::Cast {
1281 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1282 value: from,
1283 } if let Some(from) = self.ty(from).builtin_deref(true)
1284 && let ty::Array(_, len) = from.kind()
1285 && let Some(to) = self.ty(arg_index).builtin_deref(true)
1286 && let ty::Slice(..) = to.kind() =>
1287 {
1288 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1289 }
1290
1291 Value::Address { base: AddressBase::Deref(reborrowed), projection, .. }
1293 if projection.is_empty() =>
1294 {
1295 reborrowed
1296 }
1297
1298 _ => break,
1299 };
1300 was_updated = true;
1301 }
1302
1303 if was_updated && let Some(op) = self.try_as_operand(arg_index, location) {
1304 *arg_op = op;
1305 }
1306 }
1307
1308 let value = match (op, self.get(arg_index)) {
1309 (UnOp::Not, Value::UnaryOp(UnOp::Not, inner)) => return Some(inner),
1310 (UnOp::Neg, Value::UnaryOp(UnOp::Neg, inner)) => return Some(inner),
1311 (UnOp::Not, Value::BinaryOp(BinOp::Eq, lhs, rhs)) => {
1312 Value::BinaryOp(BinOp::Ne, lhs, rhs)
1313 }
1314 (UnOp::Not, Value::BinaryOp(BinOp::Ne, lhs, rhs)) => {
1315 Value::BinaryOp(BinOp::Eq, lhs, rhs)
1316 }
1317 (UnOp::PtrMetadata, Value::RawPtr { metadata, .. }) => return Some(metadata),
1318 (
1320 UnOp::PtrMetadata,
1321 Value::Cast {
1322 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1323 value: inner,
1324 },
1325 ) if let ty::Slice(..) = arg_ty.builtin_deref(true).unwrap().kind()
1326 && let ty::Array(_, len) = self.ty(inner).builtin_deref(true).unwrap().kind() =>
1327 {
1328 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1329 }
1330 _ => Value::UnaryOp(op, arg_index),
1331 };
1332 Some(self.insert(ret_ty, value))
1333 }
1334
1335 #[instrument(level = "trace", skip(self), ret)]
1336 fn simplify_binary(
1337 &mut self,
1338 op: BinOp,
1339 lhs_operand: &mut Operand<'tcx>,
1340 rhs_operand: &mut Operand<'tcx>,
1341 location: Location,
1342 ) -> Option<VnIndex> {
1343 let lhs = self.simplify_operand(lhs_operand, location);
1344 let rhs = self.simplify_operand(rhs_operand, location);
1345
1346 let mut lhs = lhs?;
1349 let mut rhs = rhs?;
1350
1351 let lhs_ty = self.ty(lhs);
1352
1353 if let BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge = op
1356 && lhs_ty.is_any_ptr()
1357 && let Value::Cast { kind: CastKind::PtrToPtr, value: lhs_value } = self.get(lhs)
1358 && let Value::Cast { kind: CastKind::PtrToPtr, value: rhs_value } = self.get(rhs)
1359 && let lhs_from = self.ty(lhs_value)
1360 && lhs_from == self.ty(rhs_value)
1361 && self.pointers_have_same_metadata(lhs_from, lhs_ty)
1362 {
1363 lhs = lhs_value;
1364 rhs = rhs_value;
1365 if let Some(lhs_op) = self.try_as_operand(lhs, location)
1366 && let Some(rhs_op) = self.try_as_operand(rhs, location)
1367 {
1368 *lhs_operand = lhs_op;
1369 *rhs_operand = rhs_op;
1370 }
1371 }
1372
1373 if let Some(value) = self.simplify_binary_inner(op, lhs_ty, lhs, rhs) {
1374 return Some(value);
1375 }
1376 let ty = op.ty(self.tcx, lhs_ty, self.ty(rhs));
1377 let value = Value::BinaryOp(op, lhs, rhs);
1378 Some(self.insert(ty, value))
1379 }
1380
1381 fn simplify_binary_inner(
1382 &mut self,
1383 op: BinOp,
1384 lhs_ty: Ty<'tcx>,
1385 lhs: VnIndex,
1386 rhs: VnIndex,
1387 ) -> Option<VnIndex> {
1388 let reasonable_ty =
1390 lhs_ty.is_integral() || lhs_ty.is_bool() || lhs_ty.is_char() || lhs_ty.is_any_ptr();
1391 if !reasonable_ty {
1392 return None;
1393 }
1394
1395 let layout = self.ecx.layout_of(lhs_ty).ok()?;
1396
1397 let mut as_bits = |value: VnIndex| {
1398 let constant = self.eval_to_const(value)?;
1399 if layout.backend_repr.is_scalar() {
1400 let scalar = self.ecx.read_scalar(constant).discard_err()?;
1401 scalar.to_bits(constant.layout.size).discard_err()
1402 } else {
1403 None
1405 }
1406 };
1407
1408 use Either::{Left, Right};
1410 let a = as_bits(lhs).map_or(Right(lhs), Left);
1411 let b = as_bits(rhs).map_or(Right(rhs), Left);
1412
1413 let result = match (op, a, b) {
1414 (
1416 BinOp::Add
1417 | BinOp::AddWithOverflow
1418 | BinOp::AddUnchecked
1419 | BinOp::BitOr
1420 | BinOp::BitXor,
1421 Left(0),
1422 Right(p),
1423 )
1424 | (
1425 BinOp::Add
1426 | BinOp::AddWithOverflow
1427 | BinOp::AddUnchecked
1428 | BinOp::BitOr
1429 | BinOp::BitXor
1430 | BinOp::Sub
1431 | BinOp::SubWithOverflow
1432 | BinOp::SubUnchecked
1433 | BinOp::Offset
1434 | BinOp::Shl
1435 | BinOp::Shr,
1436 Right(p),
1437 Left(0),
1438 )
1439 | (BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked, Left(1), Right(p))
1440 | (
1441 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::Div,
1442 Right(p),
1443 Left(1),
1444 ) => p,
1445 (BinOp::BitAnd, Right(p), Left(ones)) | (BinOp::BitAnd, Left(ones), Right(p))
1447 if ones == layout.size.truncate(u128::MAX)
1448 || (layout.ty.is_bool() && ones == 1) =>
1449 {
1450 p
1451 }
1452 (
1454 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::BitAnd,
1455 _,
1456 Left(0),
1457 )
1458 | (BinOp::Rem, _, Left(1))
1459 | (
1460 BinOp::Mul
1461 | BinOp::MulWithOverflow
1462 | BinOp::MulUnchecked
1463 | BinOp::Div
1464 | BinOp::Rem
1465 | BinOp::BitAnd
1466 | BinOp::Shl
1467 | BinOp::Shr,
1468 Left(0),
1469 _,
1470 ) => self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size)),
1471 (BinOp::BitOr, _, Left(ones)) | (BinOp::BitOr, Left(ones), _)
1473 if ones == layout.size.truncate(u128::MAX)
1474 || (layout.ty.is_bool() && ones == 1) =>
1475 {
1476 self.insert_scalar(lhs_ty, Scalar::from_uint(ones, layout.size))
1477 }
1478 (BinOp::Sub | BinOp::SubWithOverflow | BinOp::SubUnchecked | BinOp::BitXor, a, b)
1480 if a == b =>
1481 {
1482 self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size))
1483 }
1484 (BinOp::Eq, Left(a), Left(b)) => self.insert_bool(a == b),
1489 (BinOp::Eq, a, b) if a == b => self.insert_bool(true),
1490 (BinOp::Ne, Left(a), Left(b)) => self.insert_bool(a != b),
1491 (BinOp::Ne, a, b) if a == b => self.insert_bool(false),
1492 _ => return None,
1493 };
1494
1495 if op.is_overflowing() {
1496 let ty = Ty::new_tup(self.tcx, &[self.ty(result), self.tcx.types.bool]);
1497 let false_val = self.insert_bool(false);
1498 Some(self.insert_tuple(ty, &[result, false_val]))
1499 } else {
1500 Some(result)
1501 }
1502 }
1503
1504 fn simplify_cast(
1505 &mut self,
1506 initial_kind: &mut CastKind,
1507 initial_operand: &mut Operand<'tcx>,
1508 to: Ty<'tcx>,
1509 location: Location,
1510 ) -> Option<VnIndex> {
1511 use CastKind::*;
1512 use rustc_middle::ty::adjustment::PointerCoercion::*;
1513
1514 let mut kind = *initial_kind;
1515 let mut value = self.simplify_operand(initial_operand, location)?;
1516 let mut from = self.ty(value);
1517 if from == to {
1518 return Some(value);
1519 }
1520
1521 if let CastKind::PointerCoercion(ReifyFnPointer | ClosureFnPointer(_), _) = kind {
1522 return Some(self.new_opaque(to));
1525 }
1526
1527 let mut was_ever_updated = false;
1528 loop {
1529 let mut was_updated_this_iteration = false;
1530
1531 if let Transmute = kind
1536 && from.is_raw_ptr()
1537 && to.is_raw_ptr()
1538 && self.pointers_have_same_metadata(from, to)
1539 {
1540 kind = PtrToPtr;
1541 was_updated_this_iteration = true;
1542 }
1543
1544 if let PtrToPtr = kind
1547 && let Value::RawPtr { pointer, .. } = self.get(value)
1548 && let ty::RawPtr(to_pointee, _) = to.kind()
1549 && to_pointee.is_sized(self.tcx, self.typing_env())
1550 {
1551 from = self.ty(pointer);
1552 value = pointer;
1553 was_updated_this_iteration = true;
1554 if from == to {
1555 return Some(pointer);
1556 }
1557 }
1558
1559 if let Transmute = kind
1562 && let Value::Aggregate(variant_idx, field_values) = self.get(value)
1563 && let Some((field_idx, field_ty)) =
1564 self.value_is_all_in_one_field(from, variant_idx)
1565 {
1566 from = field_ty;
1567 value = field_values[field_idx.as_usize()];
1568 was_updated_this_iteration = true;
1569 if field_ty == to {
1570 return Some(value);
1571 }
1572 }
1573
1574 if let Value::Cast { kind: inner_kind, value: inner_value } = self.get(value) {
1576 let inner_from = self.ty(inner_value);
1577 let new_kind = match (inner_kind, kind) {
1578 (PtrToPtr, PtrToPtr) => Some(PtrToPtr),
1582 (PtrToPtr, Transmute) if self.pointers_have_same_metadata(inner_from, from) => {
1586 Some(Transmute)
1587 }
1588 (Transmute, PtrToPtr) if self.pointers_have_same_metadata(from, to) => {
1591 Some(Transmute)
1592 }
1593 (Transmute, Transmute)
1596 if !self.type_may_have_niche_of_interest_to_backend(from) =>
1597 {
1598 Some(Transmute)
1599 }
1600 _ => None,
1601 };
1602 if let Some(new_kind) = new_kind {
1603 kind = new_kind;
1604 from = inner_from;
1605 value = inner_value;
1606 was_updated_this_iteration = true;
1607 if inner_from == to {
1608 return Some(inner_value);
1609 }
1610 }
1611 }
1612
1613 if was_updated_this_iteration {
1614 was_ever_updated = true;
1615 } else {
1616 break;
1617 }
1618 }
1619
1620 if was_ever_updated && let Some(op) = self.try_as_operand(value, location) {
1621 *initial_operand = op;
1622 *initial_kind = kind;
1623 }
1624
1625 Some(self.insert(to, Value::Cast { kind, value }))
1626 }
1627
1628 fn pointers_have_same_metadata(&self, left_ptr_ty: Ty<'tcx>, right_ptr_ty: Ty<'tcx>) -> bool {
1629 let left_meta_ty = left_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1630 let right_meta_ty = right_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1631 if left_meta_ty == right_meta_ty {
1632 true
1633 } else if let Ok(left) =
1634 self.tcx.try_normalize_erasing_regions(self.typing_env(), left_meta_ty)
1635 && let Ok(right) =
1636 self.tcx.try_normalize_erasing_regions(self.typing_env(), right_meta_ty)
1637 {
1638 left == right
1639 } else {
1640 false
1641 }
1642 }
1643
1644 fn type_may_have_niche_of_interest_to_backend(&self, ty: Ty<'tcx>) -> bool {
1651 let Ok(layout) = self.ecx.layout_of(ty) else {
1652 return true;
1654 };
1655
1656 if layout.uninhabited {
1657 return true;
1658 }
1659
1660 match layout.backend_repr {
1661 BackendRepr::Scalar(a) => !a.is_always_valid(&self.ecx),
1662 BackendRepr::ScalarPair(a, b) => {
1663 !a.is_always_valid(&self.ecx) || !b.is_always_valid(&self.ecx)
1664 }
1665 BackendRepr::SimdVector { .. } | BackendRepr::Memory { .. } => false,
1666 }
1667 }
1668
1669 fn value_is_all_in_one_field(
1670 &self,
1671 ty: Ty<'tcx>,
1672 variant: VariantIdx,
1673 ) -> Option<(FieldIdx, Ty<'tcx>)> {
1674 if let Ok(layout) = self.ecx.layout_of(ty)
1675 && let abi::Variants::Single { index } = layout.variants
1676 && index == variant
1677 && let Some((field_idx, field_layout)) = layout.non_1zst_field(&self.ecx)
1678 && layout.size == field_layout.size
1679 {
1680 Some((field_idx, field_layout.ty))
1684 } else if let ty::Adt(adt, args) = ty.kind()
1685 && adt.is_struct()
1686 && adt.repr().transparent()
1687 && let [single_field] = adt.non_enum_variant().fields.raw.as_slice()
1688 {
1689 Some((FieldIdx::ZERO, single_field.ty(self.tcx, args)))
1690 } else {
1691 None
1692 }
1693 }
1694}
1695
1696fn op_to_prop_const<'tcx>(
1697 ecx: &mut InterpCx<'tcx, DummyMachine>,
1698 op: &OpTy<'tcx>,
1699) -> Option<ConstValue> {
1700 if op.layout.is_unsized() {
1702 return None;
1703 }
1704
1705 if op.layout.is_zst() {
1707 return Some(ConstValue::ZeroSized);
1708 }
1709
1710 if !op.is_immediate_uninit()
1715 && !matches!(op.layout.backend_repr, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..))
1716 {
1717 return None;
1718 }
1719
1720 if let BackendRepr::Scalar(abi::Scalar::Initialized { .. }) = op.layout.backend_repr
1722 && let Some(scalar) = ecx.read_scalar(op).discard_err()
1723 {
1724 if !scalar.try_to_scalar_int().is_ok() {
1725 return None;
1729 }
1730 return Some(ConstValue::Scalar(scalar));
1731 }
1732
1733 if let Either::Left(mplace) = op.as_mplace_or_imm() {
1736 let (size, _align) = ecx.size_and_align_of_val(&mplace).discard_err()??;
1737
1738 let alloc_ref = ecx.get_ptr_alloc(mplace.ptr(), size).discard_err()??;
1742 if alloc_ref.has_provenance() {
1743 return None;
1744 }
1745
1746 let pointer = mplace.ptr().into_pointer_or_addr().ok()?;
1747 let (prov, offset) = pointer.prov_and_relative_offset();
1748 let alloc_id = prov.alloc_id();
1749 intern_const_alloc_for_constprop(ecx, alloc_id).discard_err()?;
1750
1751 if let GlobalAlloc::Memory(alloc) = ecx.tcx.global_alloc(alloc_id)
1755 && alloc.inner().align >= op.layout.align.abi
1758 {
1759 return Some(ConstValue::Indirect { alloc_id, offset });
1760 }
1761 }
1762
1763 let alloc_id =
1765 ecx.intern_with_temp_alloc(op.layout, |ecx, dest| ecx.copy_op(op, dest)).discard_err()?;
1766 let value = ConstValue::Indirect { alloc_id, offset: Size::ZERO };
1767
1768 if ecx.tcx.global_alloc(alloc_id).unwrap_memory().inner().provenance().ptrs().is_empty() {
1772 return Some(value);
1773 }
1774
1775 None
1776}
1777
1778impl<'tcx> VnState<'_, '_, 'tcx> {
1779 fn try_as_operand(&mut self, index: VnIndex, location: Location) -> Option<Operand<'tcx>> {
1782 if let Some(const_) = self.try_as_constant(index) {
1783 Some(Operand::Constant(Box::new(const_)))
1784 } else if let Some(place) = self.try_as_place(index, location, false) {
1785 self.reused_locals.insert(place.local);
1786 Some(Operand::Copy(place))
1787 } else {
1788 None
1789 }
1790 }
1791
1792 fn try_as_constant(&mut self, index: VnIndex) -> Option<ConstOperand<'tcx>> {
1794 if let Value::Constant { value, disambiguator: None } = self.get(index) {
1798 debug_assert!(value.is_deterministic());
1799 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1800 }
1801
1802 let op = self.eval_to_const(index)?;
1803 if op.layout.is_unsized() {
1804 return None;
1806 }
1807
1808 let value = op_to_prop_const(&mut self.ecx, op)?;
1809
1810 assert!(!value.may_have_provenance(self.tcx, op.layout.size));
1814
1815 let const_ = Const::Val(value, op.layout.ty);
1816 Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_ })
1817 }
1818
1819 #[instrument(level = "trace", skip(self), ret)]
1823 fn try_as_place(
1824 &mut self,
1825 mut index: VnIndex,
1826 loc: Location,
1827 allow_complex_projection: bool,
1828 ) -> Option<Place<'tcx>> {
1829 let mut projection = SmallVec::<[PlaceElem<'tcx>; 1]>::new();
1830 loop {
1831 if let Some(local) = self.try_as_local(index, loc) {
1832 projection.reverse();
1833 let place =
1834 Place { local, projection: self.tcx.mk_place_elems(projection.as_slice()) };
1835 return Some(place);
1836 } else if projection.last() == Some(&PlaceElem::Deref) {
1837 return None;
1841 } else if let Value::Projection(pointer, proj) = self.get(index)
1842 && (allow_complex_projection || proj.is_stable_offset())
1843 && let Some(proj) = self.try_as_place_elem(self.ty(index), proj, loc)
1844 {
1845 projection.push(proj);
1846 index = pointer;
1847 } else {
1848 return None;
1849 }
1850 }
1851 }
1852
1853 fn try_as_local(&mut self, index: VnIndex, loc: Location) -> Option<Local> {
1856 let other = self.rev_locals.get(index)?;
1857 other
1858 .iter()
1859 .find(|&&other| self.ssa.assignment_dominates(&self.dominators, other, loc))
1860 .copied()
1861 }
1862}
1863
1864impl<'tcx> MutVisitor<'tcx> for VnState<'_, '_, 'tcx> {
1865 fn tcx(&self) -> TyCtxt<'tcx> {
1866 self.tcx
1867 }
1868
1869 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
1870 self.simplify_place_projection(place, location);
1871 if context.is_mutating_use() && place.is_indirect() {
1872 self.invalidate_derefs();
1874 }
1875 self.super_place(place, context, location);
1876 }
1877
1878 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
1879 self.simplify_operand(operand, location);
1880 self.super_operand(operand, location);
1881 }
1882
1883 fn visit_assign(
1884 &mut self,
1885 lhs: &mut Place<'tcx>,
1886 rvalue: &mut Rvalue<'tcx>,
1887 location: Location,
1888 ) {
1889 self.simplify_place_projection(lhs, location);
1890
1891 let value = self.simplify_rvalue(lhs, rvalue, location);
1892 if let Some(value) = value {
1893 if let Some(const_) = self.try_as_constant(value) {
1894 *rvalue = Rvalue::Use(Operand::Constant(Box::new(const_)));
1895 } else if let Some(place) = self.try_as_place(value, location, false)
1896 && *rvalue != Rvalue::Use(Operand::Move(place))
1897 && *rvalue != Rvalue::Use(Operand::Copy(place))
1898 {
1899 *rvalue = Rvalue::Use(Operand::Copy(place));
1900 self.reused_locals.insert(place.local);
1901 }
1902 }
1903
1904 if lhs.is_indirect() {
1905 self.invalidate_derefs();
1907 }
1908
1909 if let Some(local) = lhs.as_local()
1910 && self.ssa.is_ssa(local)
1911 && let rvalue_ty = rvalue.ty(self.local_decls, self.tcx)
1912 && self.local_decls[local].ty == rvalue_ty
1915 {
1916 let value = value.unwrap_or_else(|| self.new_opaque(rvalue_ty));
1917 self.assign(local, value);
1918 }
1919 }
1920
1921 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
1922 if let Terminator { kind: TerminatorKind::Call { destination, .. }, .. } = terminator {
1923 if let Some(local) = destination.as_local()
1924 && self.ssa.is_ssa(local)
1925 {
1926 let ty = self.local_decls[local].ty;
1927 let opaque = self.new_opaque(ty);
1928 self.assign(local, opaque);
1929 }
1930 }
1931 if terminator.kind.can_write_to_memory() {
1933 self.invalidate_derefs();
1934 }
1935 self.super_terminator(terminator, location);
1936 }
1937}
1938
1939struct StorageRemover<'tcx> {
1940 tcx: TyCtxt<'tcx>,
1941 reused_locals: DenseBitSet<Local>,
1942}
1943
1944impl<'tcx> MutVisitor<'tcx> for StorageRemover<'tcx> {
1945 fn tcx(&self) -> TyCtxt<'tcx> {
1946 self.tcx
1947 }
1948
1949 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, _: Location) {
1950 if let Operand::Move(place) = *operand
1951 && !place.is_indirect_first_projection()
1952 && self.reused_locals.contains(place.local)
1953 {
1954 *operand = Operand::Copy(place);
1955 }
1956 }
1957
1958 fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
1959 match stmt.kind {
1960 StatementKind::StorageLive(l) | StatementKind::StorageDead(l)
1962 if self.reused_locals.contains(l) =>
1963 {
1964 stmt.make_nop(true)
1965 }
1966 _ => self.super_statement(stmt, loc),
1967 }
1968 }
1969}