1use std::borrow::Cow;
97use std::hash::{Hash, Hasher};
98
99use either::Either;
100use itertools::Itertools as _;
101use rustc_abi::{self as abi, BackendRepr, FIRST_VARIANT, FieldIdx, Primitive, Size, VariantIdx};
102use rustc_arena::DroplessArena;
103use rustc_const_eval::const_eval::DummyMachine;
104use rustc_const_eval::interpret::{
105 ImmTy, Immediate, InterpCx, MemPlaceMeta, MemoryKind, OpTy, Projectable, Scalar,
106 intern_const_alloc_for_constprop,
107};
108use rustc_data_structures::fx::FxHasher;
109use rustc_data_structures::graph::dominators::Dominators;
110use rustc_data_structures::hash_table::{Entry, HashTable};
111use rustc_hir::def::DefKind;
112use rustc_index::bit_set::DenseBitSet;
113use rustc_index::{IndexVec, newtype_index};
114use rustc_middle::mir::interpret::{AllocRange, GlobalAlloc};
115use rustc_middle::mir::visit::*;
116use rustc_middle::mir::*;
117use rustc_middle::ty::layout::HasTypingEnv;
118use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
119use rustc_mir_dataflow::{Analysis, ResultsCursor};
120use rustc_span::{DUMMY_SP, bug};
121use smallvec::SmallVec;
122use tracing::{debug, instrument, trace};
123
124use crate::PassPolicy;
125use crate::ssa::{MaybeUninitializedLocals, SsaLocals};
126
127pub(super) struct GVN;
128
129impl<'tcx> crate::MirPass<'tcx> for GVN {
130 fn policy(&self, ctx: &crate::PassCtx<'_>) -> PassPolicy {
131 PassPolicy::optional(ctx.mir_opt_level() >= 2)
132 }
133
134 #[instrument(level = "trace", skip(self, tcx, body))]
135 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
136 debug!(def_id = ?body.source.def_id());
137
138 let typing_env = body.typing_env(tcx);
139 let ssa = SsaLocals::new(tcx, body, typing_env);
140 let dominators = body.basic_blocks.dominators().clone();
142
143 let arena = DroplessArena::default();
144 let mut state =
145 VnState::new(tcx, body, typing_env, &ssa, dominators, &body.local_decls, &arena);
146
147 for local in body.args_iter().filter(|&local| ssa.is_ssa(local)) {
148 let opaque = state.new_argument(body.local_decls[local].ty);
149 state.assign(local, opaque);
150 }
151
152 let reverse_postorder = body.basic_blocks.reverse_postorder().to_vec();
153 for bb in reverse_postorder {
154 let data = &mut body.basic_blocks.as_mut_preserves_cfg()[bb];
155 state.visit_basic_block_data(bb, data);
156 }
157
158 let storage_to_remove = if tcx.sess.emit_lifetime_markers() {
162 let maybe_uninit = MaybeUninitializedLocals
163 .iterate_to_fixpoint(tcx, body, Some("mir_opt::gvn"))
164 .into_results_cursor(body);
165
166 let mut storage_checker = StorageChecker {
167 reused_locals: &state.reused_locals,
168 storage_to_remove: DenseBitSet::new_empty(body.local_decls.len()),
169 maybe_uninit,
170 };
171
172 for (bb, data) in traversal::reachable(body) {
173 storage_checker.visit_basic_block_data(bb, data);
174 }
175
176 Some(storage_checker.storage_to_remove)
177 } else {
178 None
179 };
180
181 let storage_to_remove = storage_to_remove.as_ref().unwrap_or(&state.reused_locals);
183 debug!(?storage_to_remove);
184
185 StorageRemover { tcx, reused_locals: &state.reused_locals, storage_to_remove }
186 .visit_body_preserves_cfg(body);
187 }
188}
189
190newtype_index! {
191 #[debug_format = "_v{}"]
193 struct VnIndex {}
194}
195
196#[derive(Copy, Clone, Debug, Eq)]
200struct VnOpaque;
201impl PartialEq for VnOpaque {
202 fn eq(&self, _: &VnOpaque) -> bool {
203 unreachable!()
205 }
206}
207impl Hash for VnOpaque {
208 fn hash<T: Hasher>(&self, _: &mut T) {
209 unreachable!()
211 }
212}
213
214#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
215enum AddressKind {
216 Ref(BorrowKind),
217 Address(RawPtrKind),
218}
219
220#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
221enum AddressBase {
222 Local(Local),
224 Deref(VnIndex),
226}
227
228#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
229enum Value<'a, 'tcx> {
230 Opaque(VnOpaque),
233 Argument(VnOpaque),
235 Constant {
237 value: Const<'tcx>,
238 disambiguator: Option<VnOpaque>,
242 },
243
244 Aggregate(VariantIdx, &'a [VnIndex]),
248 Union(FieldIdx, VnIndex),
250 RawPtr {
252 pointer: VnIndex,
254 metadata: VnIndex,
256 },
257 Repeat(VnIndex, ty::Const<'tcx>),
259 Address {
261 base: AddressBase,
262 projection: &'a [ProjectionElem<VnIndex, Ty<'tcx>>],
265 kind: AddressKind,
266 provenance: VnOpaque,
268 },
269
270 Projection(VnIndex, ProjectionElem<VnIndex, ()>),
273 Discriminant(VnIndex),
275
276 RuntimeChecks(RuntimeChecks),
278 UnaryOp(UnOp, VnIndex),
279 BinaryOp(BinOp, VnIndex, VnIndex),
280 Cast {
281 kind: CastKind,
282 value: VnIndex,
283 },
284}
285
286struct ValueSet<'a, 'tcx> {
292 indices: HashTable<VnIndex>,
293 hashes: IndexVec<VnIndex, u64>,
294 values: IndexVec<VnIndex, Value<'a, 'tcx>>,
295 types: IndexVec<VnIndex, Ty<'tcx>>,
296}
297
298impl<'a, 'tcx> ValueSet<'a, 'tcx> {
299 fn new(num_values: usize) -> ValueSet<'a, 'tcx> {
300 ValueSet {
301 indices: HashTable::with_capacity(num_values),
302 hashes: IndexVec::with_capacity(num_values),
303 values: IndexVec::with_capacity(num_values),
304 types: IndexVec::with_capacity(num_values),
305 }
306 }
307
308 #[inline]
311 fn insert_unique(
312 &mut self,
313 ty: Ty<'tcx>,
314 value: impl FnOnce(VnOpaque) -> Value<'a, 'tcx>,
315 ) -> VnIndex {
316 let value = value(VnOpaque);
317
318 debug_assert!(match value {
319 Value::Opaque(_) | Value::Argument(_) | Value::Address { .. } => true,
320 Value::Constant { disambiguator, .. } => disambiguator.is_some(),
321 _ => false,
322 });
323
324 let index = self.hashes.push(0);
325 let _index = self.types.push(ty);
326 debug_assert_eq!(index, _index);
327 let _index = self.values.push(value);
328 debug_assert_eq!(index, _index);
329 index
330 }
331
332 #[allow(rustc::disallowed_pass_by_ref)] fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> (VnIndex, bool) {
336 debug_assert!(match value {
337 Value::Opaque(_) | Value::Address { .. } => false,
338 Value::Constant { disambiguator, .. } => disambiguator.is_none(),
339 _ => true,
340 });
341
342 let hash: u64 = {
343 let mut h = FxHasher::default();
344 value.hash(&mut h);
345 ty.hash(&mut h);
346 h.finish()
347 };
348
349 let eq = |index: &VnIndex| self.values[*index] == value && self.types[*index] == ty;
350 let hasher = |index: &VnIndex| self.hashes[*index];
351 match self.indices.entry(hash, eq, hasher) {
352 Entry::Occupied(entry) => {
353 let index = *entry.get();
354 (index, false)
355 }
356 Entry::Vacant(entry) => {
357 let index = self.hashes.push(hash);
358 entry.insert(index);
359 let _index = self.values.push(value);
360 debug_assert_eq!(index, _index);
361 let _index = self.types.push(ty);
362 debug_assert_eq!(index, _index);
363 (index, true)
364 }
365 }
366 }
367
368 #[inline]
370 fn value(&self, index: VnIndex) -> Value<'a, 'tcx> {
371 self.values[index]
372 }
373
374 #[inline]
376 fn ty(&self, index: VnIndex) -> Ty<'tcx> {
377 self.types[index]
378 }
379}
380
381struct VnState<'body, 'a, 'tcx> {
382 tcx: TyCtxt<'tcx>,
383 ecx: InterpCx<'tcx, DummyMachine>,
384 local_decls: &'body LocalDecls<'tcx>,
385 is_coroutine: bool,
386 locals: IndexVec<Local, Option<VnIndex>>,
388 rev_locals: IndexVec<VnIndex, SmallVec<[Local; 1]>>,
391 values: ValueSet<'a, 'tcx>,
392 evaluated: IndexVec<VnIndex, Option<Option<&'a OpTy<'tcx>>>>,
397 ssa: &'body SsaLocals,
398 dominators: Dominators<BasicBlock>,
399 reused_locals: DenseBitSet<Local>,
400 arena: &'a DroplessArena,
401}
402
403impl<'body, 'a, 'tcx> VnState<'body, 'a, 'tcx> {
404 fn new(
405 tcx: TyCtxt<'tcx>,
406 body: &Body<'tcx>,
407 typing_env: ty::TypingEnv<'tcx>,
408 ssa: &'body SsaLocals,
409 dominators: Dominators<BasicBlock>,
410 local_decls: &'body LocalDecls<'tcx>,
411 arena: &'a DroplessArena,
412 ) -> Self {
413 let num_values =
418 2 * body.basic_blocks.iter().map(|bbdata| bbdata.statements.len()).sum::<usize>()
419 + 4 * body.basic_blocks.len();
420 VnState {
421 tcx,
422 ecx: InterpCx::new(tcx, DUMMY_SP, typing_env, DummyMachine),
423 local_decls,
424 is_coroutine: body.coroutine.is_some(),
425 locals: IndexVec::from_elem(None, local_decls),
426 rev_locals: IndexVec::with_capacity(num_values),
427 values: ValueSet::new(num_values),
428 evaluated: IndexVec::with_capacity(num_values),
429 ssa,
430 dominators,
431 reused_locals: DenseBitSet::new_empty(local_decls.len()),
432 arena,
433 }
434 }
435
436 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
437 self.ecx.typing_env()
438 }
439
440 fn insert_unique(
441 &mut self,
442 ty: Ty<'tcx>,
443 value: impl FnOnce(VnOpaque) -> Value<'a, 'tcx>,
444 ) -> VnIndex {
445 let index = self.values.insert_unique(ty, value);
446 let _index = self.evaluated.push(None);
447 debug_assert_eq!(index, _index);
448 let _index = self.rev_locals.push(SmallVec::new());
449 debug_assert_eq!(index, _index);
450 index
451 }
452
453 #[instrument(level = "trace", skip(self), ret)]
454 fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> VnIndex {
455 let (index, new) = self.values.insert(ty, value);
456 if new {
457 let _index = self.evaluated.push(None);
459 debug_assert_eq!(index, _index);
460 let _index = self.rev_locals.push(SmallVec::new());
461 debug_assert_eq!(index, _index);
462 }
463 index
464 }
465
466 #[instrument(level = "trace", skip(self), ret)]
469 fn new_opaque(&mut self, ty: Ty<'tcx>) -> VnIndex {
470 let index = self.insert_unique(ty, Value::Opaque);
471 self.evaluated[index] = Some(None);
472 index
473 }
474
475 #[instrument(level = "trace", skip(self), ret)]
476 fn new_argument(&mut self, ty: Ty<'tcx>) -> VnIndex {
477 let index = self.insert_unique(ty, Value::Argument);
478 self.evaluated[index] = Some(None);
479 index
480 }
481
482 #[instrument(level = "trace", skip(self), ret)]
484 fn new_pointer(&mut self, place: Place<'tcx>, kind: AddressKind) -> Option<VnIndex> {
485 let pty = place.ty(self.local_decls, self.tcx).ty;
486 let ty = match kind {
487 AddressKind::Ref(bk) => {
488 Ty::new_ref(self.tcx, self.tcx.lifetimes.re_erased, pty, bk.to_mutbl_lossy())
489 }
490 AddressKind::Address(mutbl) => Ty::new_ptr(self.tcx, pty, mutbl.to_mutbl_lossy()),
491 };
492
493 let mut projection = place.projection.iter();
494 let base = if place.is_indirect_first_projection() {
495 let base = self.locals[place.local]?;
496 projection.next();
498 AddressBase::Deref(base)
499 } else if self.ssa.is_ssa(place.local) {
500 AddressBase::Local(place.local)
502 } else {
503 return None;
504 };
505 let projection =
507 projection.map(|proj| proj.try_map(|index| self.locals[index], |ty| ty).ok_or(()));
508 let projection = self.arena.try_alloc_from_iter(projection).ok()?;
509
510 let index = self.insert_unique(ty, |provenance| Value::Address {
511 base,
512 projection,
513 kind,
514 provenance,
515 });
516 Some(index)
517 }
518
519 #[instrument(level = "trace", skip(self), ret)]
520 fn insert_constant(&mut self, value: Const<'tcx>) -> VnIndex {
521 if is_deterministic(value) {
522 let constant = Value::Constant { value, disambiguator: None };
524 self.insert(value.ty(), constant)
525 } else {
526 self.insert_unique(value.ty(), |disambiguator| Value::Constant {
529 value,
530 disambiguator: Some(disambiguator),
531 })
532 }
533 }
534
535 #[inline]
536 fn get(&self, index: VnIndex) -> Value<'a, 'tcx> {
537 self.values.value(index)
538 }
539
540 #[inline]
541 fn ty(&self, index: VnIndex) -> Ty<'tcx> {
542 self.values.ty(index)
543 }
544
545 #[instrument(level = "trace", skip(self))]
547 fn assign(&mut self, local: Local, value: VnIndex) {
548 debug_assert!(self.ssa.is_ssa(local));
549 self.locals[local] = Some(value);
550 self.rev_locals[value].push(local);
551 }
552
553 fn insert_bool(&mut self, flag: bool) -> VnIndex {
554 let value = Const::from_bool(self.tcx, flag);
556 debug_assert!(is_deterministic(value));
557 self.insert(self.tcx.types.bool, Value::Constant { value, disambiguator: None })
558 }
559
560 fn insert_scalar(&mut self, ty: Ty<'tcx>, scalar: Scalar) -> VnIndex {
561 let value = Const::from_scalar(self.tcx, scalar, ty);
563 debug_assert!(is_deterministic(value));
564 self.insert(ty, Value::Constant { value, disambiguator: None })
565 }
566
567 fn insert_tuple(&mut self, ty: Ty<'tcx>, values: &[VnIndex]) -> VnIndex {
568 self.insert(ty, Value::Aggregate(VariantIdx::ZERO, self.arena.alloc_slice(values)))
569 }
570
571 #[instrument(level = "trace", skip(self), ret)]
572 fn eval_to_const_inner(&mut self, value: VnIndex) -> Option<OpTy<'tcx>> {
573 use Value::*;
574 let ty = self.ty(value);
575 let ty = if !self.is_coroutine || ty.is_scalar() {
577 self.ecx.layout_of(ty).ok()?
578 } else {
579 return None;
580 };
581 let op = match self.get(value) {
582 _ if ty.is_zst() => ImmTy::uninit(ty).into(),
583
584 Opaque(_) | Argument(_) => return None,
585 RuntimeChecks(..) => return None,
587
588 Repeat(value, _count) => {
593 let value = self.eval_to_const(value)?;
594 if value.is_immediate_uninit() {
595 ImmTy::uninit(ty).into()
596 } else {
597 return None;
598 }
599 }
600 Constant { ref value, disambiguator: _ } => {
601 self.ecx.eval_mir_constant(value, DUMMY_SP, None).discard_err()?
602 }
603 Aggregate(variant, ref fields) => {
604 let fields =
605 fields.iter().map(|&f| self.eval_to_const(f)).collect::<Option<Vec<_>>>()?;
606 let variant = if ty.ty.is_enum() { Some(variant) } else { None };
607 let (BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }) = ty.backend_repr
608 else {
609 return None;
610 };
611 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
612 let variant_dest = if let Some(variant) = variant {
613 self.ecx.project_downcast(&dest, variant).discard_err()?
614 } else {
615 dest.clone()
616 };
617 for (field_index, op) in fields.into_iter().enumerate() {
618 let field_dest = self
619 .ecx
620 .project_field(&variant_dest, FieldIdx::from_usize(field_index))
621 .discard_err()?;
622 self.ecx.copy_op(op, &field_dest).discard_err()?;
623 }
624 self.ecx
625 .write_discriminant(variant.unwrap_or(FIRST_VARIANT), &dest)
626 .discard_err()?;
627 self.ecx
628 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
629 .discard_err()?;
630 dest.into()
631 }
632 Union(active_field, field) => {
633 let field = self.eval_to_const(field)?;
634 if field.layout.layout.is_zst() {
635 ImmTy::from_immediate(Immediate::Uninit, ty).into()
636 } else if matches!(
637 ty.backend_repr,
638 BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }
639 ) {
640 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
641 let field_dest = self.ecx.project_field(&dest, active_field).discard_err()?;
642 self.ecx.copy_op(field, &field_dest).discard_err()?;
643 self.ecx
644 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
645 .discard_err()?;
646 dest.into()
647 } else {
648 return None;
649 }
650 }
651 RawPtr { pointer, metadata } => {
652 let pointer = self.eval_to_const(pointer)?;
653 let metadata = self.eval_to_const(metadata)?;
654
655 let data = self.ecx.read_pointer(pointer).discard_err()?;
657 let meta = if metadata.layout.is_zst() {
658 MemPlaceMeta::None
659 } else {
660 MemPlaceMeta::Meta(self.ecx.read_scalar(metadata).discard_err()?)
661 };
662 let ptr_imm = Immediate::new_pointer_with_meta(data, meta, &self.ecx);
663 ImmTy::from_immediate(ptr_imm, ty).into()
664 }
665
666 Projection(base, elem) => {
667 let base = self.eval_to_const(base)?;
668 let elem = elem.try_map(|_| None, |()| ty.ty)?;
671 self.ecx.project(base, elem).discard_err()?
672 }
673 Address { base, projection, .. } => {
674 debug_assert!(!projection.contains(&ProjectionElem::Deref));
675 let pointer = match base {
676 AddressBase::Deref(pointer) => self.eval_to_const(pointer)?,
677 AddressBase::Local(_) => return None,
679 };
680 let mut mplace = self.ecx.deref_pointer(pointer).discard_err()?;
681 for elem in projection {
682 let elem = elem.try_map(|_| None, |ty| ty)?;
685 mplace = self.ecx.project(&mplace, elem).discard_err()?;
686 }
687 let pointer = mplace.to_ref(&self.ecx);
688 ImmTy::from_immediate(pointer, ty).into()
689 }
690
691 Discriminant(base) => {
692 let base = self.eval_to_const(base)?;
693 let variant = self.ecx.read_discriminant(base).discard_err()?;
694 let discr_value =
695 self.ecx.discriminant_for_variant(base.layout.ty, variant).discard_err()?;
696 discr_value.into()
697 }
698 UnaryOp(un_op, operand) => {
699 let operand = self.eval_to_const(operand)?;
700 let operand = self.ecx.read_immediate(operand).discard_err()?;
701 let val = self.ecx.unary_op(un_op, &operand).discard_err()?;
702 val.into()
703 }
704 BinaryOp(bin_op, lhs, rhs) => {
705 let lhs = self.eval_to_const(lhs)?;
706 let rhs = self.eval_to_const(rhs)?;
707 let lhs = self.ecx.read_immediate(lhs).discard_err()?;
708 let rhs = self.ecx.read_immediate(rhs).discard_err()?;
709 let val = self.ecx.binary_op(bin_op, &lhs, &rhs).discard_err()?;
710 val.into()
711 }
712 Cast { kind, value } => match kind {
713 CastKind::IntToInt | CastKind::IntToFloat => {
714 let value = self.eval_to_const(value)?;
715 let value = self.ecx.read_immediate(value).discard_err()?;
716 let res = self.ecx.int_to_int_or_float(&value, ty).discard_err()?;
717 res.into()
718 }
719 CastKind::FloatToFloat | CastKind::FloatToInt => {
720 let value = self.eval_to_const(value)?;
721 let value = self.ecx.read_immediate(value).discard_err()?;
722 let res = self.ecx.float_to_float_or_int(&value, ty).discard_err()?;
723 res.into()
724 }
725 CastKind::Transmute | CastKind::Subtype => {
726 let value = self.eval_to_const(value)?;
727 if value.as_mplace_or_imm().is_right() {
732 let can_transmute = match (value.layout.backend_repr, ty.backend_repr) {
733 (BackendRepr::Scalar(s1), BackendRepr::Scalar(s2)) => {
734 s1.size(&self.ecx) == s2.size(&self.ecx)
735 && !matches!(s1.primitive(), Primitive::Pointer(..))
736 }
737 (
738 BackendRepr::ScalarPair { a: a1, b: b1, b_offset: b1_offset },
739 BackendRepr::ScalarPair { a: a2, b: b2, b_offset: b2_offset },
740 ) => {
741 a1.size(&self.ecx) == a2.size(&self.ecx)
742 && b1.size(&self.ecx) == b2.size(&self.ecx)
743 && b1_offset == b2_offset
746 && !matches!(a1.primitive(), Primitive::Pointer(..))
748 && !matches!(b1.primitive(), Primitive::Pointer(..))
749 }
750 _ => false,
751 };
752 if !can_transmute {
753 return None;
754 }
755 }
756 value.offset(Size::ZERO, ty, &self.ecx).discard_err()?
757 }
758 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _) => {
759 let src = self.eval_to_const(value)?;
760 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
761 self.ecx.unsize_into(src, ty, &dest).discard_err()?;
762 self.ecx
763 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
764 .discard_err()?;
765 dest.into()
766 }
767 CastKind::FnPtrToPtr | CastKind::PtrToPtr => {
768 let src = self.eval_to_const(value)?;
769 let src = self.ecx.read_immediate(src).discard_err()?;
770 let ret = self.ecx.ptr_to_ptr(&src, ty).discard_err()?;
771 ret.into()
772 }
773 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::UnsafeFnPointer, _) => {
774 let src = self.eval_to_const(value)?;
775 let src = self.ecx.read_immediate(src).discard_err()?;
776 ImmTy::from_immediate(*src, ty).into()
777 }
778 _ => return None,
779 },
780 };
781 Some(op)
782 }
783
784 fn eval_to_const(&mut self, index: VnIndex) -> Option<&'a OpTy<'tcx>> {
785 if let Some(op) = self.evaluated[index] {
786 return op;
787 }
788 let op = self.eval_to_const_inner(index);
789 self.evaluated[index] = Some(self.arena.alloc(op).as_ref());
790 self.evaluated[index].unwrap()
791 }
792
793 #[instrument(level = "trace", skip(self), ret)]
795 fn dereference_address(
796 &mut self,
797 base: AddressBase,
798 projection: &[ProjectionElem<VnIndex, Ty<'tcx>>],
799 ) -> Option<VnIndex> {
800 let (mut place_ty, mut value) = match base {
801 AddressBase::Local(local) => {
803 let local = self.locals[local]?;
804 let place_ty = PlaceTy::from_ty(self.ty(local));
805 (place_ty, local)
806 }
807 AddressBase::Deref(reborrow) => {
809 let place_ty = PlaceTy::from_ty(self.ty(reborrow));
810 self.project(place_ty, reborrow, ProjectionElem::Deref)?
811 }
812 };
813 for &proj in projection {
814 (place_ty, value) = self.project(place_ty, value, proj)?;
815 }
816 Some(value)
817 }
818
819 #[instrument(level = "trace", skip(self), ret)]
820 fn project(
821 &mut self,
822 place_ty: PlaceTy<'tcx>,
823 value: VnIndex,
824 proj: ProjectionElem<VnIndex, Ty<'tcx>>,
825 ) -> Option<(PlaceTy<'tcx>, VnIndex)> {
826 let projection_ty = place_ty.projection_ty(self.tcx, proj);
827 let proj = match proj {
828 ProjectionElem::Deref => {
829 if let Some(Mutability::Not) = place_ty.ty.ref_mutability()
830 && projection_ty.ty.is_freeze(self.tcx, self.typing_env())
831 {
832 if let Value::Address { base, projection, .. } = self.get(value)
833 && let Some(value) = self.dereference_address(base, projection)
834 {
835 return Some((projection_ty, value));
836 }
837 if self.ty_may_have_ref(projection_ty.ty) {
851 return None;
852 }
853
854 let deref = self
857 .insert(projection_ty.ty, Value::Projection(value, ProjectionElem::Deref));
858 return Some((projection_ty, deref));
859 } else {
860 return None;
861 }
862 }
863 ProjectionElem::PhantomDeref => bug!("PhantomDeref in GVN"),
864 ProjectionElem::Downcast(name, index) => ProjectionElem::Downcast(name, index),
865 ProjectionElem::Field(f, _) => match self.get(value) {
866 Value::Aggregate(_, fields) => return Some((projection_ty, fields[f.as_usize()])),
867 Value::Union(active, field) if active == f => return Some((projection_ty, field)),
868 Value::Projection(outer_value, ProjectionElem::Downcast(_, read_variant))
869 if let Value::Aggregate(written_variant, fields) = self.get(outer_value)
870 && written_variant == read_variant =>
886 {
887 return Some((projection_ty, fields[f.as_usize()]));
888 }
889 _ => ProjectionElem::Field(f, ()),
890 },
891 ProjectionElem::Index(idx) => {
892 if let Value::Repeat(inner, _) = self.get(value) {
893 return Some((projection_ty, inner));
894 }
895 ProjectionElem::Index(idx)
896 }
897 ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
898 match self.get(value) {
899 Value::Repeat(inner, _) => {
900 return Some((projection_ty, inner));
901 }
902 Value::Aggregate(_, operands) => {
903 let offset = if from_end {
904 operands.len() - offset as usize
905 } else {
906 offset as usize
907 };
908 let value = operands.get(offset).copied()?;
909 return Some((projection_ty, value));
910 }
911 _ => {}
912 };
913 ProjectionElem::ConstantIndex { offset, min_length, from_end }
914 }
915 ProjectionElem::Subslice { from, to, from_end } => {
916 ProjectionElem::Subslice { from, to, from_end }
917 }
918 ProjectionElem::OpaqueCast(_) => ProjectionElem::OpaqueCast(()),
919 ProjectionElem::UnwrapUnsafeBinder(_) => ProjectionElem::UnwrapUnsafeBinder(()),
920 };
921
922 let value = self.insert(projection_ty.ty, Value::Projection(value, proj));
923 Some((projection_ty, value))
924 }
925
926 #[instrument(level = "trace", skip(self))]
928 fn simplify_place_projection(&mut self, place: &mut Place<'tcx>, location: Location) {
929 if place.is_indirect_first_projection()
932 && let Some(base) = self.locals[place.local]
933 && let Some(new_local) = self.try_as_local(base, location)
934 && place.local != new_local
935 {
936 place.local = new_local;
937 self.reused_locals.insert(new_local);
938 }
939
940 let mut projection = Cow::Borrowed(&place.projection[..]);
941
942 for i in 0..projection.len() {
943 let elem = projection[i];
944 if let ProjectionElem::Index(idx_local) = elem
945 && let Some(idx) = self.locals[idx_local]
946 {
947 if let Some(offset) = self.eval_to_const(idx)
948 && let Some(offset) = self.ecx.read_target_usize(offset).discard_err()
949 && let Some(min_length) = offset.checked_add(1)
950 {
951 projection.to_mut()[i] =
952 ProjectionElem::ConstantIndex { offset, min_length, from_end: false };
953 } else if let Some(new_idx_local) = self.try_as_local(idx, location)
954 && idx_local != new_idx_local
955 {
956 projection.to_mut()[i] = ProjectionElem::Index(new_idx_local);
957 self.reused_locals.insert(new_idx_local);
958 }
959 }
960 }
961
962 if Cow::is_owned(&projection) {
963 place.projection = self.tcx.mk_place_elems(&projection);
964 }
965
966 trace!(?place);
967 }
968
969 #[instrument(level = "trace", skip(self), ret)]
972 fn compute_place_value(
973 &mut self,
974 place: Place<'tcx>,
975 location: Location,
976 ) -> Result<VnIndex, PlaceRef<'tcx>> {
977 let mut place_ref = place.as_ref();
980
981 let Some(mut value) = self.locals[place.local] else { return Err(place_ref) };
983 let mut place_ty = PlaceTy::from_ty(self.local_decls[place.local].ty);
985 for (index, proj) in place.projection.iter().enumerate() {
986 if let Some(local) = self.try_as_local(value, location) {
987 place_ref = PlaceRef { local, projection: &place.projection[index..] };
991 }
992
993 let Some(proj) = proj.try_map(|value| self.locals[value], |ty| ty) else {
994 return Err(place_ref);
995 };
996 let Some(ty_and_value) = self.project(place_ty, value, proj) else {
997 return Err(place_ref);
998 };
999 (place_ty, value) = ty_and_value;
1000 }
1001
1002 Ok(value)
1003 }
1004
1005 #[instrument(level = "trace", skip(self), ret)]
1008 fn simplify_place_value(
1009 &mut self,
1010 place: &mut Place<'tcx>,
1011 location: Location,
1012 ) -> Option<VnIndex> {
1013 self.simplify_place_projection(place, location);
1014
1015 match self.compute_place_value(*place, location) {
1016 Ok(value) => {
1017 if let Some(new_place) = self.try_as_place(value, location, true)
1018 && (new_place.local != place.local
1019 || new_place.projection.len() < place.projection.len())
1020 {
1021 *place = new_place;
1022 self.reused_locals.insert(new_place.local);
1023 }
1024 Some(value)
1025 }
1026 Err(place_ref) => {
1027 if place_ref.local != place.local
1028 || place_ref.projection.len() < place.projection.len()
1029 {
1030 *place = place_ref.project_deeper(&[], self.tcx);
1032 self.reused_locals.insert(place_ref.local);
1033 }
1034 None
1035 }
1036 }
1037 }
1038
1039 #[instrument(level = "trace", skip(self), ret)]
1040 fn simplify_operand(
1041 &mut self,
1042 operand: &mut Operand<'tcx>,
1043 location: Location,
1044 ) -> Option<VnIndex> {
1045 let value = match *operand {
1046 Operand::RuntimeChecks(c) => self.insert(self.tcx.types.bool, Value::RuntimeChecks(c)),
1047 Operand::Constant(ref constant) => self.insert_constant(constant.const_),
1048 Operand::Copy(ref mut place) | Operand::Move(ref mut place) => {
1049 self.simplify_place_value(place, location)?
1050 }
1051 };
1052 if let Some(const_) = self.try_as_constant(value) {
1053 *operand = Operand::Constant(Box::new(const_));
1054 } else if let Value::RuntimeChecks(c) = self.get(value) {
1055 *operand = Operand::RuntimeChecks(c);
1056 }
1057 Some(value)
1058 }
1059
1060 #[instrument(level = "trace", skip(self), ret)]
1061 fn simplify_rvalue(
1062 &mut self,
1063 rvalue: &mut Rvalue<'tcx>,
1064 location: Location,
1065 ) -> Option<VnIndex> {
1066 let value = match *rvalue {
1067 Rvalue::Use(ref mut operand, _) => return self.simplify_operand(operand, location),
1069
1070 Rvalue::Repeat(ref mut op, amount) => {
1072 let op = self.simplify_operand(op, location)?;
1073 Value::Repeat(op, amount)
1074 }
1075 Rvalue::Aggregate(..) => return self.simplify_aggregate(rvalue, location),
1076 Rvalue::Ref(_, borrow_kind, ref mut place) => {
1077 self.simplify_place_projection(place, location);
1078 return self.new_pointer(*place, AddressKind::Ref(borrow_kind));
1079 }
1080 Rvalue::Reborrow(_, mutbl, place) => {
1081 if mutbl == Mutability::Mut {
1082 let mut operand = Operand::Copy(place);
1084 let val = self.simplify_operand(&mut operand, location);
1085 *rvalue = Rvalue::Use(Operand::Copy(place), WithRetag::Yes);
1087 return val;
1088 } else {
1089 return None;
1093 }
1094 }
1095 Rvalue::RawPtr(mutbl, ref mut place) => {
1096 self.simplify_place_projection(place, location);
1097 return self.new_pointer(*place, AddressKind::Address(mutbl));
1098 }
1099 Rvalue::WrapUnsafeBinder(ref mut op, _) => {
1100 let value = self.simplify_operand(op, location)?;
1101 Value::Cast { kind: CastKind::Transmute, value }
1102 }
1103
1104 Rvalue::Cast(ref mut kind, ref mut value, to) => {
1106 return self.simplify_cast(kind, value, to, location);
1107 }
1108 Rvalue::BinaryOp(op, (ref mut lhs, ref mut rhs)) => {
1109 return self.simplify_binary(op, lhs, rhs, location);
1110 }
1111 Rvalue::UnaryOp(op, ref mut arg_op) => {
1112 return self.simplify_unary(op, arg_op, location);
1113 }
1114 Rvalue::Discriminant(ref mut place) => {
1115 let place = self.simplify_place_value(place, location)?;
1116 if let Some(discr) = self.simplify_discriminant(place) {
1117 return Some(discr);
1118 }
1119 Value::Discriminant(place)
1120 }
1121
1122 Rvalue::ThreadLocalRef(..) => return None,
1124 Rvalue::CopyForDeref(_) => {
1125 bug!("forbidden in runtime MIR: {rvalue:?}")
1126 }
1127 };
1128 let ty = rvalue.ty(self.local_decls, self.tcx);
1129 Some(self.insert(ty, value))
1130 }
1131
1132 fn simplify_discriminant(&mut self, place: VnIndex) -> Option<VnIndex> {
1133 let enum_ty = self.ty(place);
1134 if enum_ty.is_enum()
1135 && let Value::Aggregate(variant, _) = self.get(place)
1136 {
1137 let discr = self.ecx.discriminant_for_variant(enum_ty, variant).discard_err()?;
1138 return Some(self.insert_scalar(discr.layout.ty, discr.to_scalar()));
1139 }
1140
1141 None
1142 }
1143
1144 fn try_as_place_elem(
1145 &mut self,
1146 ty: Ty<'tcx>,
1147 proj: ProjectionElem<VnIndex, ()>,
1148 loc: Location,
1149 ) -> Option<PlaceElem<'tcx>> {
1150 proj.try_map(
1151 |value| {
1152 let local = self.try_as_local(value, loc)?;
1153 self.reused_locals.insert(local);
1154 Some(local)
1155 },
1156 |()| ty,
1157 )
1158 }
1159
1160 fn simplify_aggregate_to_copy(
1161 &mut self,
1162 ty: Ty<'tcx>,
1163 variant_index: VariantIdx,
1164 fields: &[VnIndex],
1165 ) -> Option<VnIndex> {
1166 let Some(&first_field) = fields.first() else { return None };
1167 let Value::Projection(copy_from_value, _) = self.get(first_field) else { return None };
1168
1169 if fields.iter().enumerate().any(|(index, &v)| {
1171 if let Value::Projection(pointer, ProjectionElem::Field(from_index, _)) = self.get(v)
1172 && copy_from_value == pointer
1173 && from_index.index() == index
1174 {
1175 return false;
1176 }
1177 true
1178 }) {
1179 return None;
1180 }
1181
1182 let mut copy_from_local_value = copy_from_value;
1183 if let Value::Projection(pointer, proj) = self.get(copy_from_value)
1184 && let ProjectionElem::Downcast(_, read_variant) = proj
1185 {
1186 if variant_index == read_variant {
1187 copy_from_local_value = pointer;
1189 } else {
1190 return None;
1192 }
1193 }
1194
1195 if self.ty(copy_from_local_value) == ty { Some(copy_from_local_value) } else { None }
1197 }
1198
1199 fn simplify_aggregate(
1200 &mut self,
1201 rvalue: &mut Rvalue<'tcx>,
1202 location: Location,
1203 ) -> Option<VnIndex> {
1204 let tcx = self.tcx;
1205 let ty = rvalue.ty(self.local_decls, tcx);
1206
1207 let Rvalue::Aggregate(ref kind, ref mut field_ops) = *rvalue else { bug!() };
1208
1209 if field_ops.is_empty() {
1210 let is_zst = match *kind {
1211 AggregateKind::Array(..)
1212 | AggregateKind::Tuple
1213 | AggregateKind::Closure(..)
1214 | AggregateKind::CoroutineClosure(..) => true,
1215 AggregateKind::Adt(did, ..) => tcx.def_kind(did) != DefKind::Enum,
1217 AggregateKind::Coroutine(..) => false,
1219 AggregateKind::RawPtr(..) => bug!("MIR for RawPtr aggregate must have 2 fields"),
1220 };
1221
1222 if is_zst {
1223 return Some(self.insert_constant(Const::zero_sized(ty)));
1224 }
1225 }
1226
1227 let fields = self.arena.alloc_from_iter(field_ops.iter_mut().map(|op| {
1228 self.simplify_operand(op, location)
1229 .unwrap_or_else(|| self.new_opaque(op.ty(self.local_decls, self.tcx)))
1230 }));
1231
1232 let variant_index = match *kind {
1233 AggregateKind::Array(..) | AggregateKind::Tuple => {
1234 assert!(!field_ops.is_empty());
1235 FIRST_VARIANT
1236 }
1237 AggregateKind::Closure(..)
1238 | AggregateKind::CoroutineClosure(..)
1239 | AggregateKind::Coroutine(..) => FIRST_VARIANT,
1240 AggregateKind::Adt(_, variant_index, _, _, None) => variant_index,
1241 AggregateKind::Adt(_, _, _, _, Some(active_field)) => {
1243 let field = *fields.first()?;
1244 return Some(self.insert(ty, Value::Union(active_field, field)));
1245 }
1246 AggregateKind::RawPtr(..) => {
1247 assert_eq!(field_ops.len(), 2);
1248 let [mut pointer, metadata] = fields.try_into().unwrap();
1249
1250 let mut was_updated = false;
1252 while let Value::Cast { kind: CastKind::PtrToPtr, value: cast_value } =
1253 self.get(pointer)
1254 && let ty::RawPtr(from_pointee_ty, from_mtbl) = self.ty(cast_value).kind()
1255 && let ty::RawPtr(_, output_mtbl) = ty.kind()
1256 && from_mtbl == output_mtbl
1257 && from_pointee_ty.is_sized(self.tcx, self.typing_env())
1258 {
1259 pointer = cast_value;
1260 was_updated = true;
1261 }
1262
1263 if was_updated && let Some(op) = self.try_as_operand(pointer, location) {
1264 field_ops[FieldIdx::ZERO] = op;
1265 }
1266
1267 return Some(self.insert(ty, Value::RawPtr { pointer, metadata }));
1268 }
1269 };
1270
1271 if ty.is_array()
1272 && fields.len() > 4
1273 && let Ok(&first) = fields.iter().all_equal_value()
1274 {
1275 let len = ty::Const::from_target_usize(self.tcx, fields.len().try_into().unwrap());
1276 if let Some(op) = self.try_as_operand(first, location) {
1277 *rvalue = Rvalue::Repeat(op, len);
1278 }
1279 return Some(self.insert(ty, Value::Repeat(first, len)));
1280 }
1281
1282 if let Some(value) = self.simplify_aggregate_to_copy(ty, variant_index, &fields) {
1283 if let Some(place) = self.try_as_place(value, location, true) {
1284 self.reused_locals.insert(place.local);
1285 *rvalue = Rvalue::Use(Operand::Copy(place), WithRetag::Yes);
1287 }
1288 return Some(value);
1289 }
1290
1291 Some(self.insert(ty, Value::Aggregate(variant_index, fields)))
1292 }
1293
1294 #[instrument(level = "trace", skip(self), ret)]
1295 fn simplify_unary(
1296 &mut self,
1297 op: UnOp,
1298 arg_op: &mut Operand<'tcx>,
1299 location: Location,
1300 ) -> Option<VnIndex> {
1301 let mut arg_index = self.simplify_operand(arg_op, location)?;
1302 let arg_ty = self.ty(arg_index);
1303 let ret_ty = op.ty(self.tcx, arg_ty);
1304
1305 if op == UnOp::PtrMetadata {
1308 let mut was_updated = false;
1309 loop {
1310 arg_index = match self.get(arg_index) {
1311 Value::Cast { kind: CastKind::PtrToPtr, value: inner }
1320 if self.pointers_have_same_metadata(self.ty(inner), arg_ty) =>
1321 {
1322 inner
1323 }
1324
1325 Value::Cast {
1327 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1328 value: from,
1329 } if let Some(from) = self.ty(from).builtin_deref(true)
1330 && let ty::Array(_, len) = from.kind()
1331 && let Some(to) = self.ty(arg_index).builtin_deref(true)
1332 && let ty::Slice(..) = to.kind() =>
1333 {
1334 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1335 }
1336
1337 Value::Address { base: AddressBase::Deref(reborrowed), projection, .. }
1339 if projection.is_empty() =>
1340 {
1341 reborrowed
1342 }
1343
1344 _ => break,
1345 };
1346 was_updated = true;
1347 }
1348
1349 if was_updated && let Some(op) = self.try_as_operand(arg_index, location) {
1350 *arg_op = op;
1351 }
1352 }
1353
1354 let value = match (op, self.get(arg_index)) {
1355 (UnOp::Not, Value::UnaryOp(UnOp::Not, inner)) => return Some(inner),
1356 (UnOp::Neg, Value::UnaryOp(UnOp::Neg, inner)) => return Some(inner),
1357 (UnOp::Not, Value::BinaryOp(BinOp::Eq, lhs, rhs)) => {
1358 Value::BinaryOp(BinOp::Ne, lhs, rhs)
1359 }
1360 (UnOp::Not, Value::BinaryOp(BinOp::Ne, lhs, rhs)) => {
1361 Value::BinaryOp(BinOp::Eq, lhs, rhs)
1362 }
1363 (UnOp::PtrMetadata, Value::RawPtr { metadata, .. }) => return Some(metadata),
1364 (
1366 UnOp::PtrMetadata,
1367 Value::Cast {
1368 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1369 value: inner,
1370 },
1371 ) if let ty::Slice(..) = arg_ty.builtin_deref(true).unwrap().kind()
1372 && let ty::Array(_, len) = self.ty(inner).builtin_deref(true).unwrap().kind() =>
1373 {
1374 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1375 }
1376 _ => Value::UnaryOp(op, arg_index),
1377 };
1378 Some(self.insert(ret_ty, value))
1379 }
1380
1381 #[instrument(level = "trace", skip(self), ret)]
1382 fn simplify_binary(
1383 &mut self,
1384 op: BinOp,
1385 lhs_operand: &mut Operand<'tcx>,
1386 rhs_operand: &mut Operand<'tcx>,
1387 location: Location,
1388 ) -> Option<VnIndex> {
1389 let lhs = self.simplify_operand(lhs_operand, location);
1390 let rhs = self.simplify_operand(rhs_operand, location);
1391
1392 let mut lhs = lhs?;
1395 let mut rhs = rhs?;
1396
1397 let lhs_ty = self.ty(lhs);
1398
1399 if let BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge = op
1402 && lhs_ty.is_any_ptr()
1403 && let Value::Cast { kind: CastKind::PtrToPtr, value: lhs_value } = self.get(lhs)
1404 && let Value::Cast { kind: CastKind::PtrToPtr, value: rhs_value } = self.get(rhs)
1405 && let lhs_from = self.ty(lhs_value)
1406 && lhs_from == self.ty(rhs_value)
1407 && self.pointers_have_same_metadata(lhs_from, lhs_ty)
1408 {
1409 lhs = lhs_value;
1410 rhs = rhs_value;
1411 if let Some(lhs_op) = self.try_as_operand(lhs, location)
1412 && let Some(rhs_op) = self.try_as_operand(rhs, location)
1413 {
1414 *lhs_operand = lhs_op;
1415 *rhs_operand = rhs_op;
1416 }
1417 }
1418
1419 if let Some(value) = self.simplify_binary_inner(op, lhs_ty, lhs, rhs) {
1420 return Some(value);
1421 }
1422 let ty = op.ty(self.tcx, lhs_ty, self.ty(rhs));
1423 let value = Value::BinaryOp(op, lhs, rhs);
1424 Some(self.insert(ty, value))
1425 }
1426
1427 fn simplify_binary_inner(
1428 &mut self,
1429 op: BinOp,
1430 lhs_ty: Ty<'tcx>,
1431 lhs: VnIndex,
1432 rhs: VnIndex,
1433 ) -> Option<VnIndex> {
1434 let reasonable_ty =
1436 lhs_ty.is_integral() || lhs_ty.is_bool() || lhs_ty.is_char() || lhs_ty.is_any_ptr();
1437 if !reasonable_ty {
1438 return None;
1439 }
1440
1441 let layout = self.ecx.layout_of(lhs_ty).ok()?;
1442
1443 let mut as_bits = |value: VnIndex| {
1444 let constant = self.eval_to_const(value)?;
1445 if layout.backend_repr.is_scalar() {
1446 let scalar = self.ecx.read_scalar(constant).discard_err()?;
1447 scalar.to_bits(constant.layout.size).discard_err()
1448 } else {
1449 None
1451 }
1452 };
1453
1454 use Either::{Left, Right};
1456 let a = as_bits(lhs).map_or(Right(lhs), Left);
1457 let b = as_bits(rhs).map_or(Right(rhs), Left);
1458
1459 let result = match (op, a, b) {
1460 (
1462 BinOp::Add
1463 | BinOp::AddWithOverflow
1464 | BinOp::AddUnchecked
1465 | BinOp::BitOr
1466 | BinOp::BitXor,
1467 Left(0),
1468 Right(p),
1469 )
1470 | (
1471 BinOp::Add
1472 | BinOp::AddWithOverflow
1473 | BinOp::AddUnchecked
1474 | BinOp::BitOr
1475 | BinOp::BitXor
1476 | BinOp::Sub
1477 | BinOp::SubWithOverflow
1478 | BinOp::SubUnchecked
1479 | BinOp::Offset
1480 | BinOp::Shl
1481 | BinOp::Shr,
1482 Right(p),
1483 Left(0),
1484 )
1485 | (BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked, Left(1), Right(p))
1486 | (
1487 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::Div,
1488 Right(p),
1489 Left(1),
1490 ) => p,
1491 (BinOp::BitAnd, Right(p), Left(ones)) | (BinOp::BitAnd, Left(ones), Right(p))
1493 if ones == layout.size.truncate(u128::MAX)
1494 || (layout.ty.is_bool() && ones == 1) =>
1495 {
1496 p
1497 }
1498 (
1500 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::BitAnd,
1501 _,
1502 Left(0),
1503 )
1504 | (BinOp::Rem, _, Left(1))
1505 | (
1506 BinOp::Mul
1507 | BinOp::MulWithOverflow
1508 | BinOp::MulUnchecked
1509 | BinOp::Div
1510 | BinOp::Rem
1511 | BinOp::BitAnd
1512 | BinOp::Shl
1513 | BinOp::Shr,
1514 Left(0),
1515 _,
1516 ) => self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size)),
1517 (BinOp::BitOr, _, Left(ones)) | (BinOp::BitOr, Left(ones), _)
1519 if ones == layout.size.truncate(u128::MAX)
1520 || (layout.ty.is_bool() && ones == 1) =>
1521 {
1522 self.insert_scalar(lhs_ty, Scalar::from_uint(ones, layout.size))
1523 }
1524 (BinOp::Sub | BinOp::SubWithOverflow | BinOp::SubUnchecked | BinOp::BitXor, a, b)
1526 if a == b =>
1527 {
1528 self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size))
1529 }
1530 (BinOp::Eq, Left(a), Left(b)) => self.insert_bool(a == b),
1535 (BinOp::Eq, a, b) if a == b => self.insert_bool(true),
1536 (BinOp::Ne, Left(a), Left(b)) => self.insert_bool(a != b),
1537 (BinOp::Ne, a, b) if a == b => self.insert_bool(false),
1538 _ => return None,
1539 };
1540
1541 if op.is_overflowing() {
1542 let ty = Ty::new_tup(self.tcx, &[self.ty(result), self.tcx.types.bool]);
1543 let false_val = self.insert_bool(false);
1544 Some(self.insert_tuple(ty, &[result, false_val]))
1545 } else {
1546 Some(result)
1547 }
1548 }
1549
1550 fn simplify_cast(
1551 &mut self,
1552 initial_kind: &mut CastKind,
1553 initial_operand: &mut Operand<'tcx>,
1554 to: Ty<'tcx>,
1555 location: Location,
1556 ) -> Option<VnIndex> {
1557 use CastKind::*;
1558 use rustc_middle::ty::adjustment::PointerCoercion::*;
1559
1560 let mut kind = *initial_kind;
1561 let mut value = self.simplify_operand(initial_operand, location)?;
1562 let mut from = self.ty(value);
1563 if from == to {
1564 return Some(value);
1565 }
1566
1567 if let CastKind::PointerCoercion(ReifyFnPointer(_) | ClosureFnPointer(_), _) = kind {
1568 return Some(self.new_opaque(to));
1571 }
1572
1573 let mut was_ever_updated = false;
1574 loop {
1575 let mut was_updated_this_iteration = false;
1576
1577 if let Transmute = kind
1582 && from.is_raw_ptr()
1583 && to.is_raw_ptr()
1584 && self.pointers_have_same_metadata(from, to)
1585 {
1586 kind = PtrToPtr;
1587 was_updated_this_iteration = true;
1588 }
1589
1590 if let PtrToPtr = kind
1593 && let Value::RawPtr { pointer, .. } = self.get(value)
1594 && let ty::RawPtr(to_pointee, _) = to.kind()
1595 && to_pointee.is_sized(self.tcx, self.typing_env())
1596 {
1597 from = self.ty(pointer);
1598 value = pointer;
1599 was_updated_this_iteration = true;
1600 if from == to {
1601 return Some(pointer);
1602 }
1603 }
1604
1605 if let Transmute = kind
1608 && let Value::Aggregate(variant_idx, field_values) = self.get(value)
1609 && let Some((field_idx, field_ty)) =
1610 self.value_is_all_in_one_field(from, variant_idx)
1611 {
1612 from = field_ty;
1613 value = field_values[field_idx.as_usize()];
1614 was_updated_this_iteration = true;
1615 if field_ty == to {
1616 return Some(value);
1617 }
1618 }
1619
1620 if let Value::Cast { kind: inner_kind, value: inner_value } = self.get(value) {
1622 let inner_from = self.ty(inner_value);
1623 let new_kind = match (inner_kind, kind) {
1624 (PtrToPtr, PtrToPtr) => Some(PtrToPtr),
1628 (PtrToPtr, Transmute) if self.pointers_have_same_metadata(inner_from, from) => {
1632 Some(Transmute)
1633 }
1634 (Transmute, PtrToPtr) if self.pointers_have_same_metadata(from, to) => {
1637 Some(Transmute)
1638 }
1639 (Transmute, Transmute)
1642 if !self.transmute_may_have_niche_of_interest_to_backend(
1643 inner_from, from, to,
1644 ) =>
1645 {
1646 Some(Transmute)
1647 }
1648 _ => None,
1649 };
1650 if let Some(new_kind) = new_kind {
1651 kind = new_kind;
1652 from = inner_from;
1653 value = inner_value;
1654 was_updated_this_iteration = true;
1655 if inner_from == to {
1656 return Some(inner_value);
1657 }
1658 }
1659 }
1660
1661 if was_updated_this_iteration {
1662 was_ever_updated = true;
1663 } else {
1664 break;
1665 }
1666 }
1667
1668 if was_ever_updated && let Some(op) = self.try_as_operand(value, location) {
1669 *initial_operand = op;
1670 *initial_kind = kind;
1671 }
1672
1673 Some(self.insert(to, Value::Cast { kind, value }))
1674 }
1675
1676 fn pointers_have_same_metadata(&self, left_ptr_ty: Ty<'tcx>, right_ptr_ty: Ty<'tcx>) -> bool {
1677 let left_meta_ty = left_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1678 let right_meta_ty = right_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1679 if left_meta_ty == right_meta_ty {
1680 true
1681 } else if let Ok(left) = self
1682 .tcx
1683 .try_normalize_erasing_regions(self.typing_env(), Unnormalized::new_wip(left_meta_ty))
1684 && let Ok(right) = self.tcx.try_normalize_erasing_regions(
1685 self.typing_env(),
1686 Unnormalized::new_wip(right_meta_ty),
1687 )
1688 {
1689 left == right
1690 } else {
1691 false
1692 }
1693 }
1694
1695 fn ty_may_have_ref(&self, ty: Ty<'tcx>) -> bool {
1696 fn ty_may_have_ref_inner<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, depth: usize) -> bool {
1697 if !tcx.recursion_limit().value_within_limit(depth) {
1698 return true;
1699 }
1700 let depth = depth + 1;
1701 match ty.kind() {
1702 ty::Int(_)
1703 | ty::Uint(_)
1704 | ty::Float(_)
1705 | ty::Bool
1706 | ty::Char
1707 | ty::Str
1708 | ty::Never
1709 | ty::FnDef(..)
1710 | ty::Error(_)
1711 | ty::FnPtr(..) => false,
1712 ty::Tuple(fields) => {
1713 fields.iter().any(|field| ty_may_have_ref_inner(tcx, field, depth))
1714 }
1715 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => {
1716 ty_may_have_ref_inner(tcx, *ty, depth)
1717 }
1718 ty::Adt(adt_def, args) => {
1719 adt_def.has_param()
1720 || adt_def.has_aliases()
1721 || adt_def.all_fields().any(|field| {
1722 ty_may_have_ref_inner(
1723 tcx,
1724 field.ty(tcx, args).skip_normalization(),
1725 depth,
1726 )
1727 })
1728 }
1729 ty::Ref(..)
1730 | ty::RawPtr(_, _)
1731 | ty::Bound(..)
1732 | ty::Closure(..)
1733 | ty::CoroutineClosure(..)
1734 | ty::Dynamic(..)
1735 | ty::Foreign(_)
1736 | ty::Coroutine(..)
1737 | ty::CoroutineWitness(..)
1738 | ty::UnsafeBinder(_)
1739 | ty::Infer(_)
1740 | ty::Alias(..)
1741 | ty::Param(_)
1742 | ty::Placeholder(_) => true,
1743 }
1744 }
1745 ty_may_have_ref_inner(self.tcx, ty, 0)
1746 }
1747
1748 fn transmute_may_have_niche_of_interest_to_backend(
1755 &self,
1756 from_ty: Ty<'tcx>,
1757 middle_ty: Ty<'tcx>,
1758 to_ty: Ty<'tcx>,
1759 ) -> bool {
1760 let Ok(middle_layout) = self.ecx.layout_of(middle_ty) else {
1761 return true;
1763 };
1764
1765 if middle_layout.uninhabited {
1766 return true;
1767 }
1768
1769 match middle_layout.backend_repr {
1770 BackendRepr::Scalar(mid) => {
1771 if mid.is_always_valid(&self.ecx) {
1772 false
1775 } else if let Ok(from_layout) = self.ecx.layout_of(from_ty)
1776 && !from_layout.uninhabited
1777 && from_layout.size == middle_layout.size
1778 && let BackendRepr::Scalar(from_a) = from_layout.backend_repr
1779 && let mid_range = mid.valid_range(&self.ecx)
1780 && let from_range = from_a.valid_range(&self.ecx)
1781 && mid_range.contains_range(from_range, middle_layout.size)
1782 {
1783 false
1789 } else if let Ok(to_layout) = self.ecx.layout_of(to_ty)
1790 && !to_layout.uninhabited
1791 && to_layout.size == middle_layout.size
1792 && let BackendRepr::Scalar(to_a) = to_layout.backend_repr
1793 && let mid_range = mid.valid_range(&self.ecx)
1794 && let to_range = to_a.valid_range(&self.ecx)
1795 && mid_range.contains_range(to_range, middle_layout.size)
1796 {
1797 false
1803 } else {
1804 true
1805 }
1806 }
1807 BackendRepr::ScalarPair { a, b, b_offset: _ } => {
1808 !a.is_always_valid(&self.ecx) || !b.is_always_valid(&self.ecx)
1811 }
1812 BackendRepr::SimdVector { .. }
1813 | BackendRepr::SimdScalableVector { .. }
1814 | BackendRepr::Memory { .. } => false,
1815 }
1816 }
1817
1818 fn value_is_all_in_one_field(
1819 &self,
1820 ty: Ty<'tcx>,
1821 variant: VariantIdx,
1822 ) -> Option<(FieldIdx, Ty<'tcx>)> {
1823 if let Ok(layout) = self.ecx.layout_of(ty)
1824 && let abi::Variants::Single { index } = layout.variants
1825 && index == variant
1826 && let Some((field_idx, field_layout)) = layout.non_1zst_field(&self.ecx)
1827 && layout.size == field_layout.size
1828 {
1829 Some((field_idx, field_layout.ty))
1833 } else if let ty::Adt(adt, args) = ty.kind()
1834 && adt.is_struct()
1835 && adt.repr().transparent()
1836 && let [single_field] = adt.non_enum_variant().fields.raw.as_slice()
1837 {
1838 Some((FieldIdx::ZERO, single_field.ty(self.tcx, args).skip_norm_wip()))
1839 } else {
1840 None
1841 }
1842 }
1843}
1844
1845fn is_deterministic(c: Const<'_>) -> bool {
1854 if c.ty().is_primitive() {
1856 return true;
1857 }
1858
1859 match c {
1860 Const::Ty(..) => false,
1864 Const::Unevaluated(..) => false,
1866 Const::Val(..) => true,
1870 }
1871}
1872
1873fn may_have_provenance(tcx: TyCtxt<'_>, value: ConstValue, size: Size) -> bool {
1876 match value {
1877 ConstValue::ZeroSized | ConstValue::Scalar(Scalar::Int(_)) => return false,
1878 ConstValue::Scalar(Scalar::Ptr(..)) | ConstValue::Slice { .. } => return true,
1879 ConstValue::Indirect { alloc_id, offset } => !tcx
1880 .global_alloc(alloc_id)
1881 .unwrap_memory()
1882 .inner()
1883 .provenance()
1884 .range_empty(AllocRange::from(offset..offset + size), &tcx),
1885 }
1886}
1887
1888fn op_to_prop_const<'tcx>(
1889 ecx: &mut InterpCx<'tcx, DummyMachine>,
1890 op: &OpTy<'tcx>,
1891) -> Option<ConstValue> {
1892 if op.layout.is_unsized() {
1894 return None;
1895 }
1896
1897 if op.layout.is_zst() {
1899 return Some(ConstValue::ZeroSized);
1900 }
1901
1902 if !op.is_immediate_uninit()
1907 && !matches!(
1908 op.layout.backend_repr,
1909 BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }
1910 )
1911 {
1912 return None;
1913 }
1914
1915 if let BackendRepr::Scalar(abi::Scalar::Initialized { .. }) = op.layout.backend_repr
1917 && let Some(scalar) = ecx.read_scalar(op).discard_err()
1918 {
1919 if !scalar.try_to_scalar_int().is_ok() {
1920 return None;
1924 }
1925 return Some(ConstValue::Scalar(scalar));
1926 }
1927
1928 if let Either::Left(mplace) = op.as_mplace_or_imm() {
1931 let (alloc_id, offset, _) = ecx.ptr_try_get_alloc_id(mplace.ptr(), 0).ok()?;
1932
1933 if ecx.has_provenance_in_alloc(alloc_id).discard_err()? {
1937 return None;
1938 }
1939
1940 intern_const_alloc_for_constprop(ecx, alloc_id).discard_err()?;
1941
1942 if let GlobalAlloc::Memory(alloc) = ecx.tcx.global_alloc(alloc_id)
1946 && alloc.inner().align >= op.layout.align.abi
1949 {
1950 return Some(ConstValue::Indirect { alloc_id, offset });
1951 }
1952 }
1953
1954 let alloc_id =
1956 ecx.intern_with_temp_alloc(op.layout, |ecx, dest| ecx.copy_op(op, dest)).discard_err()?;
1957 Some(ConstValue::Indirect { alloc_id, offset: Size::ZERO })
1958}
1959
1960impl<'tcx> VnState<'_, '_, 'tcx> {
1961 fn try_as_operand(&mut self, index: VnIndex, location: Location) -> Option<Operand<'tcx>> {
1964 if let Some(const_) = self.try_as_constant(index) {
1965 Some(Operand::Constant(Box::new(const_)))
1966 } else if let Value::RuntimeChecks(c) = self.get(index) {
1967 Some(Operand::RuntimeChecks(c))
1968 } else if let Some(place) = self.try_as_place(index, location, false) {
1969 self.reused_locals.insert(place.local);
1970 Some(Operand::Copy(place))
1971 } else {
1972 None
1973 }
1974 }
1975
1976 fn try_as_constant(&mut self, index: VnIndex) -> Option<ConstOperand<'tcx>> {
1978 let value = self.get(index);
1979
1980 if let Value::Constant { value, disambiguator: None } = value
1982 && let Const::Val(..) = value
1983 {
1984 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1985 }
1986
1987 if let Some(value) = self.try_as_evaluated_constant(index) {
1988 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1989 }
1990
1991 if let Value::Constant { value, disambiguator: None } = value {
1993 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1994 }
1995
1996 None
1997 }
1998
1999 fn try_as_evaluated_constant(&mut self, index: VnIndex) -> Option<Const<'tcx>> {
2000 let op = self.eval_to_const(index)?;
2001 let value = op_to_prop_const(&mut self.ecx, op)?;
2002
2003 if may_have_provenance(self.tcx, value, op.layout.size) {
2007 return None;
2008 }
2009
2010 Some(Const::Val(value, op.layout.ty))
2011 }
2012
2013 #[instrument(level = "trace", skip(self), ret)]
2017 fn try_as_place(
2018 &mut self,
2019 mut index: VnIndex,
2020 loc: Location,
2021 allow_complex_projection: bool,
2022 ) -> Option<Place<'tcx>> {
2023 let mut projection = SmallVec::<[PlaceElem<'tcx>; 1]>::new();
2024 loop {
2025 if let Some(local) = self.try_as_local(index, loc) {
2026 projection.reverse();
2027 let place =
2028 Place { local, projection: self.tcx.mk_place_elems(projection.as_slice()) };
2029 return Some(place);
2030 } else if projection.last() == Some(&PlaceElem::Deref) {
2031 return None;
2035 } else if let Value::Projection(pointer, proj) = self.get(index)
2036 && (allow_complex_projection || proj.is_stable_offset())
2037 && let Some(proj) = self.try_as_place_elem(self.ty(index), proj, loc)
2038 {
2039 if proj == PlaceElem::Deref {
2040 match self.get(pointer) {
2043 Value::Argument(_)
2044 if let Some(Mutability::Not) = self.ty(pointer).ref_mutability() => {}
2045 _ => {
2046 return None;
2047 }
2048 }
2049 }
2050 projection.push(proj);
2051 index = pointer;
2052 } else {
2053 return None;
2054 }
2055 }
2056 }
2057
2058 fn try_as_local(&mut self, index: VnIndex, loc: Location) -> Option<Local> {
2061 let other = self.rev_locals.get(index)?;
2062 other
2063 .iter()
2064 .find(|&&other| self.ssa.assignment_dominates(&self.dominators, other, loc))
2065 .copied()
2066 }
2067}
2068
2069impl<'tcx> MutVisitor<'tcx> for VnState<'_, '_, 'tcx> {
2070 fn tcx(&self) -> TyCtxt<'tcx> {
2071 self.tcx
2072 }
2073
2074 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
2075 self.simplify_place_projection(place, location);
2076 self.super_place(place, context, location);
2077 }
2078
2079 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
2080 self.simplify_operand(operand, location);
2081 self.super_operand(operand, location);
2082 }
2083
2084 fn visit_assign(
2085 &mut self,
2086 lhs: &mut Place<'tcx>,
2087 rvalue: &mut Rvalue<'tcx>,
2088 location: Location,
2089 ) {
2090 self.simplify_place_projection(lhs, location);
2091
2092 let value = self.simplify_rvalue(rvalue, location);
2093 if let Some(value) = value {
2094 if let Some(const_) = self.try_as_constant(value) {
2096 *rvalue = Rvalue::Use(Operand::Constant(Box::new(const_)), WithRetag::Yes);
2097 } else if let Some(place) = self.try_as_place(value, location, false)
2098 && !matches!(rvalue, Rvalue::Use(Operand::Move(p) | Operand::Copy(p), _) if p == &place)
2099 {
2100 *rvalue = Rvalue::Use(Operand::Copy(place), WithRetag::Yes);
2101 self.reused_locals.insert(place.local);
2102 }
2103 }
2104
2105 if let Some(local) = lhs.as_local()
2106 && self.ssa.is_ssa(local)
2107 && let rvalue_ty = rvalue.ty(self.local_decls, self.tcx)
2108 && self.local_decls[local].ty == rvalue_ty
2111 {
2112 let value = value.unwrap_or_else(|| self.new_opaque(rvalue_ty));
2113 self.assign(local, value);
2114 }
2115 }
2116
2117 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
2118 if let Terminator { kind: TerminatorKind::Call { destination, .. }, .. } = terminator {
2119 if let Some(local) = destination.as_local()
2120 && self.ssa.is_ssa(local)
2121 {
2122 let ty = self.local_decls[local].ty;
2123 let opaque = self.new_opaque(ty);
2124 self.assign(local, opaque);
2125 }
2126 }
2127 self.super_terminator(terminator, location);
2128 }
2129}
2130
2131struct StorageRemover<'a, 'tcx> {
2132 tcx: TyCtxt<'tcx>,
2133 reused_locals: &'a DenseBitSet<Local>,
2134 storage_to_remove: &'a DenseBitSet<Local>,
2135}
2136
2137impl<'a, 'tcx> MutVisitor<'tcx> for StorageRemover<'a, 'tcx> {
2138 fn tcx(&self) -> TyCtxt<'tcx> {
2139 self.tcx
2140 }
2141
2142 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, _: Location) {
2143 if let Operand::Move(place) = *operand
2144 && !place.is_indirect_first_projection()
2145 && self.reused_locals.contains(place.local)
2146 {
2147 *operand = Operand::Copy(place);
2148 }
2149 }
2150
2151 fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
2152 match stmt.kind {
2153 StatementKind::StorageLive(l) | StatementKind::StorageDead(l)
2155 if self.storage_to_remove.contains(l) =>
2156 {
2157 stmt.make_nop(true)
2158 }
2159 _ => self.super_statement(stmt, loc),
2160 }
2161 }
2162}
2163
2164struct StorageChecker<'a, 'tcx> {
2165 reused_locals: &'a DenseBitSet<Local>,
2166 storage_to_remove: DenseBitSet<Local>,
2167 maybe_uninit: ResultsCursor<'a, 'tcx, MaybeUninitializedLocals>,
2168}
2169
2170impl<'a, 'tcx> Visitor<'tcx> for StorageChecker<'a, 'tcx> {
2171 fn visit_local(&mut self, local: Local, context: PlaceContext, location: Location) {
2172 match context {
2173 PlaceContext::MutatingUse(MutatingUseContext::AsmOutput)
2178 | PlaceContext::MutatingUse(MutatingUseContext::Call)
2179 | PlaceContext::MutatingUse(MutatingUseContext::Store)
2180 | PlaceContext::MutatingUse(MutatingUseContext::Yield)
2181 | PlaceContext::NonUse(_) => {
2182 return;
2183 }
2184 PlaceContext::MutatingUse(_) | PlaceContext::NonMutatingUse(_) => {}
2186 }
2187
2188 if !self.reused_locals.contains(local) || self.storage_to_remove.contains(local) {
2190 return;
2191 }
2192
2193 self.maybe_uninit.seek_before_primary_effect(location);
2194
2195 if self.maybe_uninit.get().contains(local) {
2196 debug!(
2197 ?location,
2198 ?local,
2199 "local is reused and is maybe uninit at this location, marking it for storage statement removal"
2200 );
2201 self.storage_to_remove.insert(local);
2202 }
2203 }
2204}