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::bug;
115use rustc_middle::mir::interpret::{AllocRange, GlobalAlloc};
116use rustc_middle::mir::visit::*;
117use rustc_middle::mir::*;
118use rustc_middle::ty::layout::HasTypingEnv;
119use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
120use rustc_mir_dataflow::{Analysis, ResultsCursor};
121use rustc_span::DUMMY_SP;
122use smallvec::SmallVec;
123use tracing::{debug, instrument, trace};
124
125use crate::ssa::{MaybeUninitializedLocals, SsaLocals};
126
127pub(super) struct GVN;
128
129impl<'tcx> crate::MirPass<'tcx> for GVN {
130 fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
131 sess.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 fn is_required(&self) -> bool {
190 false
191 }
192}
193
194newtype_index! {
195 #[debug_format = "_v{}"]
197 struct VnIndex {}
198}
199
200#[derive(Copy, Clone, Debug, Eq)]
204struct VnOpaque;
205impl PartialEq for VnOpaque {
206 fn eq(&self, _: &VnOpaque) -> bool {
207 unreachable!()
209 }
210}
211impl Hash for VnOpaque {
212 fn hash<T: Hasher>(&self, _: &mut T) {
213 unreachable!()
215 }
216}
217
218#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
219enum AddressKind {
220 Ref(BorrowKind),
221 Address(RawPtrKind),
222}
223
224#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
225enum AddressBase {
226 Local(Local),
228 Deref(VnIndex),
230}
231
232#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
233enum Value<'a, 'tcx> {
234 Opaque(VnOpaque),
237 Argument(VnOpaque),
239 Constant {
241 value: Const<'tcx>,
242 disambiguator: Option<VnOpaque>,
246 },
247
248 Aggregate(VariantIdx, &'a [VnIndex]),
252 Union(FieldIdx, VnIndex),
254 RawPtr {
256 pointer: VnIndex,
258 metadata: VnIndex,
260 },
261 Repeat(VnIndex, ty::Const<'tcx>),
263 Address {
265 base: AddressBase,
266 projection: &'a [ProjectionElem<VnIndex, Ty<'tcx>>],
269 kind: AddressKind,
270 provenance: VnOpaque,
272 },
273
274 Projection(VnIndex, ProjectionElem<VnIndex, ()>),
277 Discriminant(VnIndex),
279
280 RuntimeChecks(RuntimeChecks),
282 UnaryOp(UnOp, VnIndex),
283 BinaryOp(BinOp, VnIndex, VnIndex),
284 Cast {
285 kind: CastKind,
286 value: VnIndex,
287 },
288}
289
290struct ValueSet<'a, 'tcx> {
296 indices: HashTable<VnIndex>,
297 hashes: IndexVec<VnIndex, u64>,
298 values: IndexVec<VnIndex, Value<'a, 'tcx>>,
299 types: IndexVec<VnIndex, Ty<'tcx>>,
300}
301
302impl<'a, 'tcx> ValueSet<'a, 'tcx> {
303 fn new(num_values: usize) -> ValueSet<'a, 'tcx> {
304 ValueSet {
305 indices: HashTable::with_capacity(num_values),
306 hashes: IndexVec::with_capacity(num_values),
307 values: IndexVec::with_capacity(num_values),
308 types: IndexVec::with_capacity(num_values),
309 }
310 }
311
312 #[inline]
315 fn insert_unique(
316 &mut self,
317 ty: Ty<'tcx>,
318 value: impl FnOnce(VnOpaque) -> Value<'a, 'tcx>,
319 ) -> VnIndex {
320 let value = value(VnOpaque);
321
322 debug_assert!(match value {
323 Value::Opaque(_) | Value::Argument(_) | Value::Address { .. } => true,
324 Value::Constant { disambiguator, .. } => disambiguator.is_some(),
325 _ => false,
326 });
327
328 let index = self.hashes.push(0);
329 let _index = self.types.push(ty);
330 debug_assert_eq!(index, _index);
331 let _index = self.values.push(value);
332 debug_assert_eq!(index, _index);
333 index
334 }
335
336 #[allow(rustc::disallowed_pass_by_ref)] fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> (VnIndex, bool) {
340 debug_assert!(match value {
341 Value::Opaque(_) | Value::Address { .. } => false,
342 Value::Constant { disambiguator, .. } => disambiguator.is_none(),
343 _ => true,
344 });
345
346 let hash: u64 = {
347 let mut h = FxHasher::default();
348 value.hash(&mut h);
349 ty.hash(&mut h);
350 h.finish()
351 };
352
353 let eq = |index: &VnIndex| self.values[*index] == value && self.types[*index] == ty;
354 let hasher = |index: &VnIndex| self.hashes[*index];
355 match self.indices.entry(hash, eq, hasher) {
356 Entry::Occupied(entry) => {
357 let index = *entry.get();
358 (index, false)
359 }
360 Entry::Vacant(entry) => {
361 let index = self.hashes.push(hash);
362 entry.insert(index);
363 let _index = self.values.push(value);
364 debug_assert_eq!(index, _index);
365 let _index = self.types.push(ty);
366 debug_assert_eq!(index, _index);
367 (index, true)
368 }
369 }
370 }
371
372 #[inline]
374 fn value(&self, index: VnIndex) -> Value<'a, 'tcx> {
375 self.values[index]
376 }
377
378 #[inline]
380 fn ty(&self, index: VnIndex) -> Ty<'tcx> {
381 self.types[index]
382 }
383}
384
385struct VnState<'body, 'a, 'tcx> {
386 tcx: TyCtxt<'tcx>,
387 ecx: InterpCx<'tcx, DummyMachine>,
388 local_decls: &'body LocalDecls<'tcx>,
389 is_coroutine: bool,
390 locals: IndexVec<Local, Option<VnIndex>>,
392 rev_locals: IndexVec<VnIndex, SmallVec<[Local; 1]>>,
395 values: ValueSet<'a, 'tcx>,
396 evaluated: IndexVec<VnIndex, Option<Option<&'a OpTy<'tcx>>>>,
401 ssa: &'body SsaLocals,
402 dominators: Dominators<BasicBlock>,
403 reused_locals: DenseBitSet<Local>,
404 arena: &'a DroplessArena,
405}
406
407impl<'body, 'a, 'tcx> VnState<'body, 'a, 'tcx> {
408 fn new(
409 tcx: TyCtxt<'tcx>,
410 body: &Body<'tcx>,
411 typing_env: ty::TypingEnv<'tcx>,
412 ssa: &'body SsaLocals,
413 dominators: Dominators<BasicBlock>,
414 local_decls: &'body LocalDecls<'tcx>,
415 arena: &'a DroplessArena,
416 ) -> Self {
417 let num_values =
422 2 * body.basic_blocks.iter().map(|bbdata| bbdata.statements.len()).sum::<usize>()
423 + 4 * body.basic_blocks.len();
424 VnState {
425 tcx,
426 ecx: InterpCx::new(tcx, DUMMY_SP, typing_env, DummyMachine),
427 local_decls,
428 is_coroutine: body.coroutine.is_some(),
429 locals: IndexVec::from_elem(None, local_decls),
430 rev_locals: IndexVec::with_capacity(num_values),
431 values: ValueSet::new(num_values),
432 evaluated: IndexVec::with_capacity(num_values),
433 ssa,
434 dominators,
435 reused_locals: DenseBitSet::new_empty(local_decls.len()),
436 arena,
437 }
438 }
439
440 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
441 self.ecx.typing_env()
442 }
443
444 fn insert_unique(
445 &mut self,
446 ty: Ty<'tcx>,
447 value: impl FnOnce(VnOpaque) -> Value<'a, 'tcx>,
448 ) -> VnIndex {
449 let index = self.values.insert_unique(ty, value);
450 let _index = self.evaluated.push(None);
451 debug_assert_eq!(index, _index);
452 let _index = self.rev_locals.push(SmallVec::new());
453 debug_assert_eq!(index, _index);
454 index
455 }
456
457 #[instrument(level = "trace", skip(self), ret)]
458 fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> VnIndex {
459 let (index, new) = self.values.insert(ty, value);
460 if new {
461 let _index = self.evaluated.push(None);
463 debug_assert_eq!(index, _index);
464 let _index = self.rev_locals.push(SmallVec::new());
465 debug_assert_eq!(index, _index);
466 }
467 index
468 }
469
470 #[instrument(level = "trace", skip(self), ret)]
473 fn new_opaque(&mut self, ty: Ty<'tcx>) -> VnIndex {
474 let index = self.insert_unique(ty, Value::Opaque);
475 self.evaluated[index] = Some(None);
476 index
477 }
478
479 #[instrument(level = "trace", skip(self), ret)]
480 fn new_argument(&mut self, ty: Ty<'tcx>) -> VnIndex {
481 let index = self.insert_unique(ty, Value::Argument);
482 self.evaluated[index] = Some(None);
483 index
484 }
485
486 #[instrument(level = "trace", skip(self), ret)]
488 fn new_pointer(&mut self, place: Place<'tcx>, kind: AddressKind) -> Option<VnIndex> {
489 let pty = place.ty(self.local_decls, self.tcx).ty;
490 let ty = match kind {
491 AddressKind::Ref(bk) => {
492 Ty::new_ref(self.tcx, self.tcx.lifetimes.re_erased, pty, bk.to_mutbl_lossy())
493 }
494 AddressKind::Address(mutbl) => Ty::new_ptr(self.tcx, pty, mutbl.to_mutbl_lossy()),
495 };
496
497 let mut projection = place.projection.iter();
498 let base = if place.is_indirect_first_projection() {
499 let base = self.locals[place.local]?;
500 projection.next();
502 AddressBase::Deref(base)
503 } else if self.ssa.is_ssa(place.local) {
504 AddressBase::Local(place.local)
506 } else {
507 return None;
508 };
509 let projection =
511 projection.map(|proj| proj.try_map(|index| self.locals[index], |ty| ty).ok_or(()));
512 let projection = self.arena.try_alloc_from_iter(projection).ok()?;
513
514 let index = self.insert_unique(ty, |provenance| Value::Address {
515 base,
516 projection,
517 kind,
518 provenance,
519 });
520 Some(index)
521 }
522
523 #[instrument(level = "trace", skip(self), ret)]
524 fn insert_constant(&mut self, value: Const<'tcx>) -> VnIndex {
525 if is_deterministic(value) {
526 let constant = Value::Constant { value, disambiguator: None };
528 self.insert(value.ty(), constant)
529 } else {
530 self.insert_unique(value.ty(), |disambiguator| Value::Constant {
533 value,
534 disambiguator: Some(disambiguator),
535 })
536 }
537 }
538
539 #[inline]
540 fn get(&self, index: VnIndex) -> Value<'a, 'tcx> {
541 self.values.value(index)
542 }
543
544 #[inline]
545 fn ty(&self, index: VnIndex) -> Ty<'tcx> {
546 self.values.ty(index)
547 }
548
549 #[instrument(level = "trace", skip(self))]
551 fn assign(&mut self, local: Local, value: VnIndex) {
552 debug_assert!(self.ssa.is_ssa(local));
553 self.locals[local] = Some(value);
554 self.rev_locals[value].push(local);
555 }
556
557 fn insert_bool(&mut self, flag: bool) -> VnIndex {
558 let value = Const::from_bool(self.tcx, flag);
560 debug_assert!(is_deterministic(value));
561 self.insert(self.tcx.types.bool, Value::Constant { value, disambiguator: None })
562 }
563
564 fn insert_scalar(&mut self, ty: Ty<'tcx>, scalar: Scalar) -> VnIndex {
565 let value = Const::from_scalar(self.tcx, scalar, ty);
567 debug_assert!(is_deterministic(value));
568 self.insert(ty, Value::Constant { value, disambiguator: None })
569 }
570
571 fn insert_tuple(&mut self, ty: Ty<'tcx>, values: &[VnIndex]) -> VnIndex {
572 self.insert(ty, Value::Aggregate(VariantIdx::ZERO, self.arena.alloc_slice(values)))
573 }
574
575 #[instrument(level = "trace", skip(self), ret)]
576 fn eval_to_const_inner(&mut self, value: VnIndex) -> Option<OpTy<'tcx>> {
577 use Value::*;
578 let ty = self.ty(value);
579 let ty = if !self.is_coroutine || ty.is_scalar() {
581 self.ecx.layout_of(ty).ok()?
582 } else {
583 return None;
584 };
585 let op = match self.get(value) {
586 _ if ty.is_zst() => ImmTy::uninit(ty).into(),
587
588 Opaque(_) | Argument(_) => return None,
589 RuntimeChecks(..) => return None,
591
592 Repeat(value, _count) => {
597 let value = self.eval_to_const(value)?;
598 if value.is_immediate_uninit() {
599 ImmTy::uninit(ty).into()
600 } else {
601 return None;
602 }
603 }
604 Constant { ref value, disambiguator: _ } => {
605 self.ecx.eval_mir_constant(value, DUMMY_SP, None).discard_err()?
606 }
607 Aggregate(variant, ref fields) => {
608 let fields =
609 fields.iter().map(|&f| self.eval_to_const(f)).collect::<Option<Vec<_>>>()?;
610 let variant = if ty.ty.is_enum() { Some(variant) } else { None };
611 let (BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }) = ty.backend_repr
612 else {
613 return None;
614 };
615 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
616 let variant_dest = if let Some(variant) = variant {
617 self.ecx.project_downcast(&dest, variant).discard_err()?
618 } else {
619 dest.clone()
620 };
621 for (field_index, op) in fields.into_iter().enumerate() {
622 let field_dest = self
623 .ecx
624 .project_field(&variant_dest, FieldIdx::from_usize(field_index))
625 .discard_err()?;
626 self.ecx.copy_op(op, &field_dest).discard_err()?;
627 }
628 self.ecx
629 .write_discriminant(variant.unwrap_or(FIRST_VARIANT), &dest)
630 .discard_err()?;
631 self.ecx
632 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
633 .discard_err()?;
634 dest.into()
635 }
636 Union(active_field, field) => {
637 let field = self.eval_to_const(field)?;
638 if field.layout.layout.is_zst() {
639 ImmTy::from_immediate(Immediate::Uninit, ty).into()
640 } else if matches!(
641 ty.backend_repr,
642 BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }
643 ) {
644 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
645 let field_dest = self.ecx.project_field(&dest, active_field).discard_err()?;
646 self.ecx.copy_op(field, &field_dest).discard_err()?;
647 self.ecx
648 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
649 .discard_err()?;
650 dest.into()
651 } else {
652 return None;
653 }
654 }
655 RawPtr { pointer, metadata } => {
656 let pointer = self.eval_to_const(pointer)?;
657 let metadata = self.eval_to_const(metadata)?;
658
659 let data = self.ecx.read_pointer(pointer).discard_err()?;
661 let meta = if metadata.layout.is_zst() {
662 MemPlaceMeta::None
663 } else {
664 MemPlaceMeta::Meta(self.ecx.read_scalar(metadata).discard_err()?)
665 };
666 let ptr_imm = Immediate::new_pointer_with_meta(data, meta, &self.ecx);
667 ImmTy::from_immediate(ptr_imm, ty).into()
668 }
669
670 Projection(base, elem) => {
671 let base = self.eval_to_const(base)?;
672 let elem = elem.try_map(|_| None, |()| ty.ty)?;
675 self.ecx.project(base, elem).discard_err()?
676 }
677 Address { base, projection, .. } => {
678 debug_assert!(!projection.contains(&ProjectionElem::Deref));
679 let pointer = match base {
680 AddressBase::Deref(pointer) => self.eval_to_const(pointer)?,
681 AddressBase::Local(_) => return None,
683 };
684 let mut mplace = self.ecx.deref_pointer(pointer).discard_err()?;
685 for elem in projection {
686 let elem = elem.try_map(|_| None, |ty| ty)?;
689 mplace = self.ecx.project(&mplace, elem).discard_err()?;
690 }
691 let pointer = mplace.to_ref(&self.ecx);
692 ImmTy::from_immediate(pointer, ty).into()
693 }
694
695 Discriminant(base) => {
696 let base = self.eval_to_const(base)?;
697 let variant = self.ecx.read_discriminant(base).discard_err()?;
698 let discr_value =
699 self.ecx.discriminant_for_variant(base.layout.ty, variant).discard_err()?;
700 discr_value.into()
701 }
702 UnaryOp(un_op, operand) => {
703 let operand = self.eval_to_const(operand)?;
704 let operand = self.ecx.read_immediate(operand).discard_err()?;
705 let val = self.ecx.unary_op(un_op, &operand).discard_err()?;
706 val.into()
707 }
708 BinaryOp(bin_op, lhs, rhs) => {
709 let lhs = self.eval_to_const(lhs)?;
710 let rhs = self.eval_to_const(rhs)?;
711 let lhs = self.ecx.read_immediate(lhs).discard_err()?;
712 let rhs = self.ecx.read_immediate(rhs).discard_err()?;
713 let val = self.ecx.binary_op(bin_op, &lhs, &rhs).discard_err()?;
714 val.into()
715 }
716 Cast { kind, value } => match kind {
717 CastKind::IntToInt | CastKind::IntToFloat => {
718 let value = self.eval_to_const(value)?;
719 let value = self.ecx.read_immediate(value).discard_err()?;
720 let res = self.ecx.int_to_int_or_float(&value, ty).discard_err()?;
721 res.into()
722 }
723 CastKind::FloatToFloat | CastKind::FloatToInt => {
724 let value = self.eval_to_const(value)?;
725 let value = self.ecx.read_immediate(value).discard_err()?;
726 let res = self.ecx.float_to_float_or_int(&value, ty).discard_err()?;
727 res.into()
728 }
729 CastKind::Transmute | CastKind::Subtype => {
730 let value = self.eval_to_const(value)?;
731 if value.as_mplace_or_imm().is_right() {
736 let can_transmute = match (value.layout.backend_repr, ty.backend_repr) {
737 (BackendRepr::Scalar(s1), BackendRepr::Scalar(s2)) => {
738 s1.size(&self.ecx) == s2.size(&self.ecx)
739 && !matches!(s1.primitive(), Primitive::Pointer(..))
740 }
741 (
742 BackendRepr::ScalarPair { a: a1, b: b1, b_offset: b1_offset },
743 BackendRepr::ScalarPair { a: a2, b: b2, b_offset: b2_offset },
744 ) => {
745 a1.size(&self.ecx) == a2.size(&self.ecx)
746 && b1.size(&self.ecx) == b2.size(&self.ecx)
747 && b1_offset == b2_offset
750 && !matches!(a1.primitive(), Primitive::Pointer(..))
752 && !matches!(b1.primitive(), Primitive::Pointer(..))
753 }
754 _ => false,
755 };
756 if !can_transmute {
757 return None;
758 }
759 }
760 value.offset(Size::ZERO, ty, &self.ecx).discard_err()?
761 }
762 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _) => {
763 let src = self.eval_to_const(value)?;
764 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
765 self.ecx.unsize_into(src, ty, &dest).discard_err()?;
766 self.ecx
767 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
768 .discard_err()?;
769 dest.into()
770 }
771 CastKind::FnPtrToPtr | CastKind::PtrToPtr => {
772 let src = self.eval_to_const(value)?;
773 let src = self.ecx.read_immediate(src).discard_err()?;
774 let ret = self.ecx.ptr_to_ptr(&src, ty).discard_err()?;
775 ret.into()
776 }
777 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::UnsafeFnPointer, _) => {
778 let src = self.eval_to_const(value)?;
779 let src = self.ecx.read_immediate(src).discard_err()?;
780 ImmTy::from_immediate(*src, ty).into()
781 }
782 _ => return None,
783 },
784 };
785 Some(op)
786 }
787
788 fn eval_to_const(&mut self, index: VnIndex) -> Option<&'a OpTy<'tcx>> {
789 if let Some(op) = self.evaluated[index] {
790 return op;
791 }
792 let op = self.eval_to_const_inner(index);
793 self.evaluated[index] = Some(self.arena.alloc(op).as_ref());
794 self.evaluated[index].unwrap()
795 }
796
797 #[instrument(level = "trace", skip(self), ret)]
799 fn dereference_address(
800 &mut self,
801 base: AddressBase,
802 projection: &[ProjectionElem<VnIndex, Ty<'tcx>>],
803 ) -> Option<VnIndex> {
804 let (mut place_ty, mut value) = match base {
805 AddressBase::Local(local) => {
807 let local = self.locals[local]?;
808 let place_ty = PlaceTy::from_ty(self.ty(local));
809 (place_ty, local)
810 }
811 AddressBase::Deref(reborrow) => {
813 let place_ty = PlaceTy::from_ty(self.ty(reborrow));
814 self.project(place_ty, reborrow, ProjectionElem::Deref)?
815 }
816 };
817 for &proj in projection {
818 (place_ty, value) = self.project(place_ty, value, proj)?;
819 }
820 Some(value)
821 }
822
823 #[instrument(level = "trace", skip(self), ret)]
824 fn project(
825 &mut self,
826 place_ty: PlaceTy<'tcx>,
827 value: VnIndex,
828 proj: ProjectionElem<VnIndex, Ty<'tcx>>,
829 ) -> Option<(PlaceTy<'tcx>, VnIndex)> {
830 let projection_ty = place_ty.projection_ty(self.tcx, proj);
831 let proj = match proj {
832 ProjectionElem::Deref => {
833 if let Some(Mutability::Not) = place_ty.ty.ref_mutability()
834 && projection_ty.ty.is_freeze(self.tcx, self.typing_env())
835 {
836 if let Value::Address { base, projection, .. } = self.get(value)
837 && let Some(value) = self.dereference_address(base, projection)
838 {
839 return Some((projection_ty, value));
840 }
841 if self.ty_may_have_ref(projection_ty.ty) {
855 return None;
856 }
857
858 let deref = self
861 .insert(projection_ty.ty, Value::Projection(value, ProjectionElem::Deref));
862 return Some((projection_ty, deref));
863 } else {
864 return None;
865 }
866 }
867 ProjectionElem::Downcast(name, index) => ProjectionElem::Downcast(name, index),
868 ProjectionElem::Field(f, _) => match self.get(value) {
869 Value::Aggregate(_, fields) => return Some((projection_ty, fields[f.as_usize()])),
870 Value::Union(active, field) if active == f => return Some((projection_ty, field)),
871 Value::Projection(outer_value, ProjectionElem::Downcast(_, read_variant))
872 if let Value::Aggregate(written_variant, fields) = self.get(outer_value)
873 && written_variant == read_variant =>
889 {
890 return Some((projection_ty, fields[f.as_usize()]));
891 }
892 _ => ProjectionElem::Field(f, ()),
893 },
894 ProjectionElem::Index(idx) => {
895 if let Value::Repeat(inner, _) = self.get(value) {
896 return Some((projection_ty, inner));
897 }
898 ProjectionElem::Index(idx)
899 }
900 ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
901 match self.get(value) {
902 Value::Repeat(inner, _) => {
903 return Some((projection_ty, inner));
904 }
905 Value::Aggregate(_, operands) => {
906 let offset = if from_end {
907 operands.len() - offset as usize
908 } else {
909 offset as usize
910 };
911 let value = operands.get(offset).copied()?;
912 return Some((projection_ty, value));
913 }
914 _ => {}
915 };
916 ProjectionElem::ConstantIndex { offset, min_length, from_end }
917 }
918 ProjectionElem::Subslice { from, to, from_end } => {
919 ProjectionElem::Subslice { from, to, from_end }
920 }
921 ProjectionElem::OpaqueCast(_) => ProjectionElem::OpaqueCast(()),
922 ProjectionElem::UnwrapUnsafeBinder(_) => ProjectionElem::UnwrapUnsafeBinder(()),
923 };
924
925 let value = self.insert(projection_ty.ty, Value::Projection(value, proj));
926 Some((projection_ty, value))
927 }
928
929 #[instrument(level = "trace", skip(self))]
931 fn simplify_place_projection(&mut self, place: &mut Place<'tcx>, location: Location) {
932 if place.is_indirect_first_projection()
935 && let Some(base) = self.locals[place.local]
936 && let Some(new_local) = self.try_as_local(base, location)
937 && place.local != new_local
938 {
939 place.local = new_local;
940 self.reused_locals.insert(new_local);
941 }
942
943 let mut projection = Cow::Borrowed(&place.projection[..]);
944
945 for i in 0..projection.len() {
946 let elem = projection[i];
947 if let ProjectionElem::Index(idx_local) = elem
948 && let Some(idx) = self.locals[idx_local]
949 {
950 if let Some(offset) = self.eval_to_const(idx)
951 && let Some(offset) = self.ecx.read_target_usize(offset).discard_err()
952 && let Some(min_length) = offset.checked_add(1)
953 {
954 projection.to_mut()[i] =
955 ProjectionElem::ConstantIndex { offset, min_length, from_end: false };
956 } else if let Some(new_idx_local) = self.try_as_local(idx, location)
957 && idx_local != new_idx_local
958 {
959 projection.to_mut()[i] = ProjectionElem::Index(new_idx_local);
960 self.reused_locals.insert(new_idx_local);
961 }
962 }
963 }
964
965 if Cow::is_owned(&projection) {
966 place.projection = self.tcx.mk_place_elems(&projection);
967 }
968
969 trace!(?place);
970 }
971
972 #[instrument(level = "trace", skip(self), ret)]
975 fn compute_place_value(
976 &mut self,
977 place: Place<'tcx>,
978 location: Location,
979 ) -> Result<VnIndex, PlaceRef<'tcx>> {
980 let mut place_ref = place.as_ref();
983
984 let Some(mut value) = self.locals[place.local] else { return Err(place_ref) };
986 let mut place_ty = PlaceTy::from_ty(self.local_decls[place.local].ty);
988 for (index, proj) in place.projection.iter().enumerate() {
989 if let Some(local) = self.try_as_local(value, location) {
990 place_ref = PlaceRef { local, projection: &place.projection[index..] };
994 }
995
996 let Some(proj) = proj.try_map(|value| self.locals[value], |ty| ty) else {
997 return Err(place_ref);
998 };
999 let Some(ty_and_value) = self.project(place_ty, value, proj) else {
1000 return Err(place_ref);
1001 };
1002 (place_ty, value) = ty_and_value;
1003 }
1004
1005 Ok(value)
1006 }
1007
1008 #[instrument(level = "trace", skip(self), ret)]
1011 fn simplify_place_value(
1012 &mut self,
1013 place: &mut Place<'tcx>,
1014 location: Location,
1015 ) -> Option<VnIndex> {
1016 self.simplify_place_projection(place, location);
1017
1018 match self.compute_place_value(*place, location) {
1019 Ok(value) => {
1020 if let Some(new_place) = self.try_as_place(value, location, true)
1021 && (new_place.local != place.local
1022 || new_place.projection.len() < place.projection.len())
1023 {
1024 *place = new_place;
1025 self.reused_locals.insert(new_place.local);
1026 }
1027 Some(value)
1028 }
1029 Err(place_ref) => {
1030 if place_ref.local != place.local
1031 || place_ref.projection.len() < place.projection.len()
1032 {
1033 *place = place_ref.project_deeper(&[], self.tcx);
1035 self.reused_locals.insert(place_ref.local);
1036 }
1037 None
1038 }
1039 }
1040 }
1041
1042 #[instrument(level = "trace", skip(self), ret)]
1043 fn simplify_operand(
1044 &mut self,
1045 operand: &mut Operand<'tcx>,
1046 location: Location,
1047 ) -> Option<VnIndex> {
1048 let value = match *operand {
1049 Operand::RuntimeChecks(c) => self.insert(self.tcx.types.bool, Value::RuntimeChecks(c)),
1050 Operand::Constant(ref constant) => self.insert_constant(constant.const_),
1051 Operand::Copy(ref mut place) | Operand::Move(ref mut place) => {
1052 self.simplify_place_value(place, location)?
1053 }
1054 };
1055 if let Some(const_) = self.try_as_constant(value) {
1056 *operand = Operand::Constant(Box::new(const_));
1057 } else if let Value::RuntimeChecks(c) = self.get(value) {
1058 *operand = Operand::RuntimeChecks(c);
1059 }
1060 Some(value)
1061 }
1062
1063 #[instrument(level = "trace", skip(self), ret)]
1064 fn simplify_rvalue(
1065 &mut self,
1066 lhs: &Place<'tcx>,
1067 rvalue: &mut Rvalue<'tcx>,
1068 location: Location,
1069 ) -> Option<VnIndex> {
1070 let value = match *rvalue {
1071 Rvalue::Use(ref mut operand, _) => return self.simplify_operand(operand, location),
1073
1074 Rvalue::Repeat(ref mut op, amount) => {
1076 let op = self.simplify_operand(op, location)?;
1077 Value::Repeat(op, amount)
1078 }
1079 Rvalue::Aggregate(..) => return self.simplify_aggregate(rvalue, location),
1080 Rvalue::Ref(_, borrow_kind, ref mut place) => {
1081 self.simplify_place_projection(place, location);
1082 return self.new_pointer(*place, AddressKind::Ref(borrow_kind));
1083 }
1084 Rvalue::Reborrow(_, mutbl, place) => {
1085 if mutbl == Mutability::Mut {
1086 let mut operand = Operand::Copy(place);
1088 let val = self.simplify_operand(&mut operand, location);
1089 *rvalue = Rvalue::Use(Operand::Copy(place), WithRetag::Yes);
1091 return val;
1092 } else {
1093 return None;
1097 }
1098 }
1099 Rvalue::RawPtr(mutbl, ref mut place) => {
1100 self.simplify_place_projection(place, location);
1101 return self.new_pointer(*place, AddressKind::Address(mutbl));
1102 }
1103 Rvalue::WrapUnsafeBinder(ref mut op, _) => {
1104 let value = self.simplify_operand(op, location)?;
1105 Value::Cast { kind: CastKind::Transmute, value }
1106 }
1107
1108 Rvalue::Cast(ref mut kind, ref mut value, to) => {
1110 return self.simplify_cast(kind, value, to, location);
1111 }
1112 Rvalue::BinaryOp(op, (ref mut lhs, ref mut rhs)) => {
1113 return self.simplify_binary(op, lhs, rhs, location);
1114 }
1115 Rvalue::UnaryOp(op, ref mut arg_op) => {
1116 return self.simplify_unary(op, arg_op, location);
1117 }
1118 Rvalue::Discriminant(ref mut place) => {
1119 let place = self.simplify_place_value(place, location)?;
1120 if let Some(discr) = self.simplify_discriminant(place) {
1121 return Some(discr);
1122 }
1123 Value::Discriminant(place)
1124 }
1125
1126 Rvalue::ThreadLocalRef(..) => return None,
1128 Rvalue::CopyForDeref(_) => {
1129 bug!("forbidden in runtime MIR: {rvalue:?}")
1130 }
1131 };
1132 let ty = rvalue.ty(self.local_decls, self.tcx);
1133 Some(self.insert(ty, value))
1134 }
1135
1136 fn simplify_discriminant(&mut self, place: VnIndex) -> Option<VnIndex> {
1137 let enum_ty = self.ty(place);
1138 if enum_ty.is_enum()
1139 && let Value::Aggregate(variant, _) = self.get(place)
1140 {
1141 let discr = self.ecx.discriminant_for_variant(enum_ty, variant).discard_err()?;
1142 return Some(self.insert_scalar(discr.layout.ty, discr.to_scalar()));
1143 }
1144
1145 None
1146 }
1147
1148 fn try_as_place_elem(
1149 &mut self,
1150 ty: Ty<'tcx>,
1151 proj: ProjectionElem<VnIndex, ()>,
1152 loc: Location,
1153 ) -> Option<PlaceElem<'tcx>> {
1154 proj.try_map(
1155 |value| {
1156 let local = self.try_as_local(value, loc)?;
1157 self.reused_locals.insert(local);
1158 Some(local)
1159 },
1160 |()| ty,
1161 )
1162 }
1163
1164 fn simplify_aggregate_to_copy(
1165 &mut self,
1166 ty: Ty<'tcx>,
1167 variant_index: VariantIdx,
1168 fields: &[VnIndex],
1169 ) -> Option<VnIndex> {
1170 let Some(&first_field) = fields.first() else { return None };
1171 let Value::Projection(copy_from_value, _) = self.get(first_field) else { return None };
1172
1173 if fields.iter().enumerate().any(|(index, &v)| {
1175 if let Value::Projection(pointer, ProjectionElem::Field(from_index, _)) = self.get(v)
1176 && copy_from_value == pointer
1177 && from_index.index() == index
1178 {
1179 return false;
1180 }
1181 true
1182 }) {
1183 return None;
1184 }
1185
1186 let mut copy_from_local_value = copy_from_value;
1187 if let Value::Projection(pointer, proj) = self.get(copy_from_value)
1188 && let ProjectionElem::Downcast(_, read_variant) = proj
1189 {
1190 if variant_index == read_variant {
1191 copy_from_local_value = pointer;
1193 } else {
1194 return None;
1196 }
1197 }
1198
1199 if self.ty(copy_from_local_value) == ty { Some(copy_from_local_value) } else { None }
1201 }
1202
1203 fn simplify_aggregate(
1204 &mut self,
1205 rvalue: &mut Rvalue<'tcx>,
1206 location: Location,
1207 ) -> Option<VnIndex> {
1208 let tcx = self.tcx;
1209 let ty = rvalue.ty(self.local_decls, tcx);
1210
1211 let Rvalue::Aggregate(ref kind, ref mut field_ops) = *rvalue else { bug!() };
1212
1213 if field_ops.is_empty() {
1214 let is_zst = match *kind {
1215 AggregateKind::Array(..)
1216 | AggregateKind::Tuple
1217 | AggregateKind::Closure(..)
1218 | AggregateKind::CoroutineClosure(..) => true,
1219 AggregateKind::Adt(did, ..) => tcx.def_kind(did) != DefKind::Enum,
1221 AggregateKind::Coroutine(..) => false,
1223 AggregateKind::RawPtr(..) => bug!("MIR for RawPtr aggregate must have 2 fields"),
1224 };
1225
1226 if is_zst {
1227 return Some(self.insert_constant(Const::zero_sized(ty)));
1228 }
1229 }
1230
1231 let fields = self.arena.alloc_from_iter(field_ops.iter_mut().map(|op| {
1232 self.simplify_operand(op, location)
1233 .unwrap_or_else(|| self.new_opaque(op.ty(self.local_decls, self.tcx)))
1234 }));
1235
1236 let variant_index = match *kind {
1237 AggregateKind::Array(..) | AggregateKind::Tuple => {
1238 assert!(!field_ops.is_empty());
1239 FIRST_VARIANT
1240 }
1241 AggregateKind::Closure(..)
1242 | AggregateKind::CoroutineClosure(..)
1243 | AggregateKind::Coroutine(..) => FIRST_VARIANT,
1244 AggregateKind::Adt(_, variant_index, _, _, None) => variant_index,
1245 AggregateKind::Adt(_, _, _, _, Some(active_field)) => {
1247 let field = *fields.first()?;
1248 return Some(self.insert(ty, Value::Union(active_field, field)));
1249 }
1250 AggregateKind::RawPtr(..) => {
1251 assert_eq!(field_ops.len(), 2);
1252 let [mut pointer, metadata] = fields.try_into().unwrap();
1253
1254 let mut was_updated = false;
1256 while let Value::Cast { kind: CastKind::PtrToPtr, value: cast_value } =
1257 self.get(pointer)
1258 && let ty::RawPtr(from_pointee_ty, from_mtbl) = self.ty(cast_value).kind()
1259 && let ty::RawPtr(_, output_mtbl) = ty.kind()
1260 && from_mtbl == output_mtbl
1261 && from_pointee_ty.is_sized(self.tcx, self.typing_env())
1262 {
1263 pointer = cast_value;
1264 was_updated = true;
1265 }
1266
1267 if was_updated && let Some(op) = self.try_as_operand(pointer, location) {
1268 field_ops[FieldIdx::ZERO] = op;
1269 }
1270
1271 return Some(self.insert(ty, Value::RawPtr { pointer, metadata }));
1272 }
1273 };
1274
1275 if ty.is_array()
1276 && fields.len() > 4
1277 && let Ok(&first) = fields.iter().all_equal_value()
1278 {
1279 let len = ty::Const::from_target_usize(self.tcx, fields.len().try_into().unwrap());
1280 if let Some(op) = self.try_as_operand(first, location) {
1281 *rvalue = Rvalue::Repeat(op, len);
1282 }
1283 return Some(self.insert(ty, Value::Repeat(first, len)));
1284 }
1285
1286 if let Some(value) = self.simplify_aggregate_to_copy(ty, variant_index, &fields) {
1287 if let Some(place) = self.try_as_place(value, location, true) {
1288 self.reused_locals.insert(place.local);
1289 *rvalue = Rvalue::Use(Operand::Copy(place), WithRetag::Yes);
1291 }
1292 return Some(value);
1293 }
1294
1295 Some(self.insert(ty, Value::Aggregate(variant_index, fields)))
1296 }
1297
1298 #[instrument(level = "trace", skip(self), ret)]
1299 fn simplify_unary(
1300 &mut self,
1301 op: UnOp,
1302 arg_op: &mut Operand<'tcx>,
1303 location: Location,
1304 ) -> Option<VnIndex> {
1305 let mut arg_index = self.simplify_operand(arg_op, location)?;
1306 let arg_ty = self.ty(arg_index);
1307 let ret_ty = op.ty(self.tcx, arg_ty);
1308
1309 if op == UnOp::PtrMetadata {
1312 let mut was_updated = false;
1313 loop {
1314 arg_index = match self.get(arg_index) {
1315 Value::Cast { kind: CastKind::PtrToPtr, value: inner }
1324 if self.pointers_have_same_metadata(self.ty(inner), arg_ty) =>
1325 {
1326 inner
1327 }
1328
1329 Value::Cast {
1331 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1332 value: from,
1333 } if let Some(from) = self.ty(from).builtin_deref(true)
1334 && let ty::Array(_, len) = from.kind()
1335 && let Some(to) = self.ty(arg_index).builtin_deref(true)
1336 && let ty::Slice(..) = to.kind() =>
1337 {
1338 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1339 }
1340
1341 Value::Address { base: AddressBase::Deref(reborrowed), projection, .. }
1343 if projection.is_empty() =>
1344 {
1345 reborrowed
1346 }
1347
1348 _ => break,
1349 };
1350 was_updated = true;
1351 }
1352
1353 if was_updated && let Some(op) = self.try_as_operand(arg_index, location) {
1354 *arg_op = op;
1355 }
1356 }
1357
1358 let value = match (op, self.get(arg_index)) {
1359 (UnOp::Not, Value::UnaryOp(UnOp::Not, inner)) => return Some(inner),
1360 (UnOp::Neg, Value::UnaryOp(UnOp::Neg, inner)) => return Some(inner),
1361 (UnOp::Not, Value::BinaryOp(BinOp::Eq, lhs, rhs)) => {
1362 Value::BinaryOp(BinOp::Ne, lhs, rhs)
1363 }
1364 (UnOp::Not, Value::BinaryOp(BinOp::Ne, lhs, rhs)) => {
1365 Value::BinaryOp(BinOp::Eq, lhs, rhs)
1366 }
1367 (UnOp::PtrMetadata, Value::RawPtr { metadata, .. }) => return Some(metadata),
1368 (
1370 UnOp::PtrMetadata,
1371 Value::Cast {
1372 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1373 value: inner,
1374 },
1375 ) if let ty::Slice(..) = arg_ty.builtin_deref(true).unwrap().kind()
1376 && let ty::Array(_, len) = self.ty(inner).builtin_deref(true).unwrap().kind() =>
1377 {
1378 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1379 }
1380 _ => Value::UnaryOp(op, arg_index),
1381 };
1382 Some(self.insert(ret_ty, value))
1383 }
1384
1385 #[instrument(level = "trace", skip(self), ret)]
1386 fn simplify_binary(
1387 &mut self,
1388 op: BinOp,
1389 lhs_operand: &mut Operand<'tcx>,
1390 rhs_operand: &mut Operand<'tcx>,
1391 location: Location,
1392 ) -> Option<VnIndex> {
1393 let lhs = self.simplify_operand(lhs_operand, location);
1394 let rhs = self.simplify_operand(rhs_operand, location);
1395
1396 let mut lhs = lhs?;
1399 let mut rhs = rhs?;
1400
1401 let lhs_ty = self.ty(lhs);
1402
1403 if let BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge = op
1406 && lhs_ty.is_any_ptr()
1407 && let Value::Cast { kind: CastKind::PtrToPtr, value: lhs_value } = self.get(lhs)
1408 && let Value::Cast { kind: CastKind::PtrToPtr, value: rhs_value } = self.get(rhs)
1409 && let lhs_from = self.ty(lhs_value)
1410 && lhs_from == self.ty(rhs_value)
1411 && self.pointers_have_same_metadata(lhs_from, lhs_ty)
1412 {
1413 lhs = lhs_value;
1414 rhs = rhs_value;
1415 if let Some(lhs_op) = self.try_as_operand(lhs, location)
1416 && let Some(rhs_op) = self.try_as_operand(rhs, location)
1417 {
1418 *lhs_operand = lhs_op;
1419 *rhs_operand = rhs_op;
1420 }
1421 }
1422
1423 if let Some(value) = self.simplify_binary_inner(op, lhs_ty, lhs, rhs) {
1424 return Some(value);
1425 }
1426 let ty = op.ty(self.tcx, lhs_ty, self.ty(rhs));
1427 let value = Value::BinaryOp(op, lhs, rhs);
1428 Some(self.insert(ty, value))
1429 }
1430
1431 fn simplify_binary_inner(
1432 &mut self,
1433 op: BinOp,
1434 lhs_ty: Ty<'tcx>,
1435 lhs: VnIndex,
1436 rhs: VnIndex,
1437 ) -> Option<VnIndex> {
1438 let reasonable_ty =
1440 lhs_ty.is_integral() || lhs_ty.is_bool() || lhs_ty.is_char() || lhs_ty.is_any_ptr();
1441 if !reasonable_ty {
1442 return None;
1443 }
1444
1445 let layout = self.ecx.layout_of(lhs_ty).ok()?;
1446
1447 let mut as_bits = |value: VnIndex| {
1448 let constant = self.eval_to_const(value)?;
1449 if layout.backend_repr.is_scalar() {
1450 let scalar = self.ecx.read_scalar(constant).discard_err()?;
1451 scalar.to_bits(constant.layout.size).discard_err()
1452 } else {
1453 None
1455 }
1456 };
1457
1458 use Either::{Left, Right};
1460 let a = as_bits(lhs).map_or(Right(lhs), Left);
1461 let b = as_bits(rhs).map_or(Right(rhs), Left);
1462
1463 let result = match (op, a, b) {
1464 (
1466 BinOp::Add
1467 | BinOp::AddWithOverflow
1468 | BinOp::AddUnchecked
1469 | BinOp::BitOr
1470 | BinOp::BitXor,
1471 Left(0),
1472 Right(p),
1473 )
1474 | (
1475 BinOp::Add
1476 | BinOp::AddWithOverflow
1477 | BinOp::AddUnchecked
1478 | BinOp::BitOr
1479 | BinOp::BitXor
1480 | BinOp::Sub
1481 | BinOp::SubWithOverflow
1482 | BinOp::SubUnchecked
1483 | BinOp::Offset
1484 | BinOp::Shl
1485 | BinOp::Shr,
1486 Right(p),
1487 Left(0),
1488 )
1489 | (BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked, Left(1), Right(p))
1490 | (
1491 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::Div,
1492 Right(p),
1493 Left(1),
1494 ) => p,
1495 (BinOp::BitAnd, Right(p), Left(ones)) | (BinOp::BitAnd, Left(ones), Right(p))
1497 if ones == layout.size.truncate(u128::MAX)
1498 || (layout.ty.is_bool() && ones == 1) =>
1499 {
1500 p
1501 }
1502 (
1504 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::BitAnd,
1505 _,
1506 Left(0),
1507 )
1508 | (BinOp::Rem, _, Left(1))
1509 | (
1510 BinOp::Mul
1511 | BinOp::MulWithOverflow
1512 | BinOp::MulUnchecked
1513 | BinOp::Div
1514 | BinOp::Rem
1515 | BinOp::BitAnd
1516 | BinOp::Shl
1517 | BinOp::Shr,
1518 Left(0),
1519 _,
1520 ) => self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size)),
1521 (BinOp::BitOr, _, Left(ones)) | (BinOp::BitOr, Left(ones), _)
1523 if ones == layout.size.truncate(u128::MAX)
1524 || (layout.ty.is_bool() && ones == 1) =>
1525 {
1526 self.insert_scalar(lhs_ty, Scalar::from_uint(ones, layout.size))
1527 }
1528 (BinOp::Sub | BinOp::SubWithOverflow | BinOp::SubUnchecked | BinOp::BitXor, a, b)
1530 if a == b =>
1531 {
1532 self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size))
1533 }
1534 (BinOp::Eq, Left(a), Left(b)) => self.insert_bool(a == b),
1539 (BinOp::Eq, a, b) if a == b => self.insert_bool(true),
1540 (BinOp::Ne, Left(a), Left(b)) => self.insert_bool(a != b),
1541 (BinOp::Ne, a, b) if a == b => self.insert_bool(false),
1542 _ => return None,
1543 };
1544
1545 if op.is_overflowing() {
1546 let ty = Ty::new_tup(self.tcx, &[self.ty(result), self.tcx.types.bool]);
1547 let false_val = self.insert_bool(false);
1548 Some(self.insert_tuple(ty, &[result, false_val]))
1549 } else {
1550 Some(result)
1551 }
1552 }
1553
1554 fn simplify_cast(
1555 &mut self,
1556 initial_kind: &mut CastKind,
1557 initial_operand: &mut Operand<'tcx>,
1558 to: Ty<'tcx>,
1559 location: Location,
1560 ) -> Option<VnIndex> {
1561 use CastKind::*;
1562 use rustc_middle::ty::adjustment::PointerCoercion::*;
1563
1564 let mut kind = *initial_kind;
1565 let mut value = self.simplify_operand(initial_operand, location)?;
1566 let mut from = self.ty(value);
1567 if from == to {
1568 return Some(value);
1569 }
1570
1571 if let CastKind::PointerCoercion(ReifyFnPointer(_) | ClosureFnPointer(_), _) = kind {
1572 return Some(self.new_opaque(to));
1575 }
1576
1577 let mut was_ever_updated = false;
1578 loop {
1579 let mut was_updated_this_iteration = false;
1580
1581 if let Transmute = kind
1586 && from.is_raw_ptr()
1587 && to.is_raw_ptr()
1588 && self.pointers_have_same_metadata(from, to)
1589 {
1590 kind = PtrToPtr;
1591 was_updated_this_iteration = true;
1592 }
1593
1594 if let PtrToPtr = kind
1597 && let Value::RawPtr { pointer, .. } = self.get(value)
1598 && let ty::RawPtr(to_pointee, _) = to.kind()
1599 && to_pointee.is_sized(self.tcx, self.typing_env())
1600 {
1601 from = self.ty(pointer);
1602 value = pointer;
1603 was_updated_this_iteration = true;
1604 if from == to {
1605 return Some(pointer);
1606 }
1607 }
1608
1609 if let Transmute = kind
1612 && let Value::Aggregate(variant_idx, field_values) = self.get(value)
1613 && let Some((field_idx, field_ty)) =
1614 self.value_is_all_in_one_field(from, variant_idx)
1615 {
1616 from = field_ty;
1617 value = field_values[field_idx.as_usize()];
1618 was_updated_this_iteration = true;
1619 if field_ty == to {
1620 return Some(value);
1621 }
1622 }
1623
1624 if let Value::Cast { kind: inner_kind, value: inner_value } = self.get(value) {
1626 let inner_from = self.ty(inner_value);
1627 let new_kind = match (inner_kind, kind) {
1628 (PtrToPtr, PtrToPtr) => Some(PtrToPtr),
1632 (PtrToPtr, Transmute) if self.pointers_have_same_metadata(inner_from, from) => {
1636 Some(Transmute)
1637 }
1638 (Transmute, PtrToPtr) if self.pointers_have_same_metadata(from, to) => {
1641 Some(Transmute)
1642 }
1643 (Transmute, Transmute)
1646 if !self.transmute_may_have_niche_of_interest_to_backend(
1647 inner_from, from, to,
1648 ) =>
1649 {
1650 Some(Transmute)
1651 }
1652 _ => None,
1653 };
1654 if let Some(new_kind) = new_kind {
1655 kind = new_kind;
1656 from = inner_from;
1657 value = inner_value;
1658 was_updated_this_iteration = true;
1659 if inner_from == to {
1660 return Some(inner_value);
1661 }
1662 }
1663 }
1664
1665 if was_updated_this_iteration {
1666 was_ever_updated = true;
1667 } else {
1668 break;
1669 }
1670 }
1671
1672 if was_ever_updated && let Some(op) = self.try_as_operand(value, location) {
1673 *initial_operand = op;
1674 *initial_kind = kind;
1675 }
1676
1677 Some(self.insert(to, Value::Cast { kind, value }))
1678 }
1679
1680 fn pointers_have_same_metadata(&self, left_ptr_ty: Ty<'tcx>, right_ptr_ty: Ty<'tcx>) -> bool {
1681 let left_meta_ty = left_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1682 let right_meta_ty = right_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1683 if left_meta_ty == right_meta_ty {
1684 true
1685 } else if let Ok(left) = self
1686 .tcx
1687 .try_normalize_erasing_regions(self.typing_env(), Unnormalized::new_wip(left_meta_ty))
1688 && let Ok(right) = self.tcx.try_normalize_erasing_regions(
1689 self.typing_env(),
1690 Unnormalized::new_wip(right_meta_ty),
1691 )
1692 {
1693 left == right
1694 } else {
1695 false
1696 }
1697 }
1698
1699 fn ty_may_have_ref(&self, ty: Ty<'tcx>) -> bool {
1700 fn ty_may_have_ref_inner<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, depth: usize) -> bool {
1701 if !tcx.recursion_limit().value_within_limit(depth) {
1702 return true;
1703 }
1704 let depth = depth + 1;
1705 match ty.kind() {
1706 ty::Int(_)
1707 | ty::Uint(_)
1708 | ty::Float(_)
1709 | ty::Bool
1710 | ty::Char
1711 | ty::Str
1712 | ty::Never
1713 | ty::FnDef(..)
1714 | ty::Error(_)
1715 | ty::FnPtr(..) => false,
1716 ty::Tuple(fields) => {
1717 fields.iter().any(|field| ty_may_have_ref_inner(tcx, field, depth))
1718 }
1719 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => {
1720 ty_may_have_ref_inner(tcx, *ty, depth)
1721 }
1722 ty::Adt(adt_def, args) => {
1723 adt_def.has_param()
1724 || adt_def.has_aliases()
1725 || adt_def.all_fields().any(|field| {
1726 ty_may_have_ref_inner(
1727 tcx,
1728 field.ty(tcx, args).skip_normalization(),
1729 depth,
1730 )
1731 })
1732 }
1733 ty::Ref(..)
1734 | ty::RawPtr(_, _)
1735 | ty::Bound(..)
1736 | ty::Closure(..)
1737 | ty::CoroutineClosure(..)
1738 | ty::Dynamic(..)
1739 | ty::Foreign(_)
1740 | ty::Coroutine(..)
1741 | ty::CoroutineWitness(..)
1742 | ty::UnsafeBinder(_)
1743 | ty::Infer(_)
1744 | ty::Alias(..)
1745 | ty::Param(_)
1746 | ty::Placeholder(_) => true,
1747 }
1748 }
1749 ty_may_have_ref_inner(self.tcx, ty, 0)
1750 }
1751
1752 fn transmute_may_have_niche_of_interest_to_backend(
1759 &self,
1760 from_ty: Ty<'tcx>,
1761 middle_ty: Ty<'tcx>,
1762 to_ty: Ty<'tcx>,
1763 ) -> bool {
1764 let Ok(middle_layout) = self.ecx.layout_of(middle_ty) else {
1765 return true;
1767 };
1768
1769 if middle_layout.uninhabited {
1770 return true;
1771 }
1772
1773 match middle_layout.backend_repr {
1774 BackendRepr::Scalar(mid) => {
1775 if mid.is_always_valid(&self.ecx) {
1776 false
1779 } else if let Ok(from_layout) = self.ecx.layout_of(from_ty)
1780 && !from_layout.uninhabited
1781 && from_layout.size == middle_layout.size
1782 && let BackendRepr::Scalar(from_a) = from_layout.backend_repr
1783 && let mid_range = mid.valid_range(&self.ecx)
1784 && let from_range = from_a.valid_range(&self.ecx)
1785 && mid_range.contains_range(from_range, middle_layout.size)
1786 {
1787 false
1793 } else if let Ok(to_layout) = self.ecx.layout_of(to_ty)
1794 && !to_layout.uninhabited
1795 && to_layout.size == middle_layout.size
1796 && let BackendRepr::Scalar(to_a) = to_layout.backend_repr
1797 && let mid_range = mid.valid_range(&self.ecx)
1798 && let to_range = to_a.valid_range(&self.ecx)
1799 && mid_range.contains_range(to_range, middle_layout.size)
1800 {
1801 false
1807 } else {
1808 true
1809 }
1810 }
1811 BackendRepr::ScalarPair { a, b, b_offset: _ } => {
1812 !a.is_always_valid(&self.ecx) || !b.is_always_valid(&self.ecx)
1815 }
1816 BackendRepr::SimdVector { .. }
1817 | BackendRepr::SimdScalableVector { .. }
1818 | BackendRepr::Memory { .. } => false,
1819 }
1820 }
1821
1822 fn value_is_all_in_one_field(
1823 &self,
1824 ty: Ty<'tcx>,
1825 variant: VariantIdx,
1826 ) -> Option<(FieldIdx, Ty<'tcx>)> {
1827 if let Ok(layout) = self.ecx.layout_of(ty)
1828 && let abi::Variants::Single { index } = layout.variants
1829 && index == variant
1830 && let Some((field_idx, field_layout)) = layout.non_1zst_field(&self.ecx)
1831 && layout.size == field_layout.size
1832 {
1833 Some((field_idx, field_layout.ty))
1837 } else if let ty::Adt(adt, args) = ty.kind()
1838 && adt.is_struct()
1839 && adt.repr().transparent()
1840 && let [single_field] = adt.non_enum_variant().fields.raw.as_slice()
1841 {
1842 Some((FieldIdx::ZERO, single_field.ty(self.tcx, args).skip_norm_wip()))
1843 } else {
1844 None
1845 }
1846 }
1847}
1848
1849fn is_deterministic(c: Const<'_>) -> bool {
1858 if c.ty().is_primitive() {
1860 return true;
1861 }
1862
1863 match c {
1864 Const::Ty(..) => false,
1868 Const::Unevaluated(..) => false,
1870 Const::Val(..) => true,
1874 }
1875}
1876
1877fn may_have_provenance(tcx: TyCtxt<'_>, value: ConstValue, size: Size) -> bool {
1880 match value {
1881 ConstValue::ZeroSized | ConstValue::Scalar(Scalar::Int(_)) => return false,
1882 ConstValue::Scalar(Scalar::Ptr(..)) | ConstValue::Slice { .. } => return true,
1883 ConstValue::Indirect { alloc_id, offset } => !tcx
1884 .global_alloc(alloc_id)
1885 .unwrap_memory()
1886 .inner()
1887 .provenance()
1888 .range_empty(AllocRange::from(offset..offset + size), &tcx),
1889 }
1890}
1891
1892fn op_to_prop_const<'tcx>(
1893 ecx: &mut InterpCx<'tcx, DummyMachine>,
1894 op: &OpTy<'tcx>,
1895) -> Option<ConstValue> {
1896 if op.layout.is_unsized() {
1898 return None;
1899 }
1900
1901 if op.layout.is_zst() {
1903 return Some(ConstValue::ZeroSized);
1904 }
1905
1906 if !op.is_immediate_uninit()
1911 && !matches!(
1912 op.layout.backend_repr,
1913 BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }
1914 )
1915 {
1916 return None;
1917 }
1918
1919 if let BackendRepr::Scalar(abi::Scalar::Initialized { .. }) = op.layout.backend_repr
1921 && let Some(scalar) = ecx.read_scalar(op).discard_err()
1922 {
1923 if !scalar.try_to_scalar_int().is_ok() {
1924 return None;
1928 }
1929 return Some(ConstValue::Scalar(scalar));
1930 }
1931
1932 if let Either::Left(mplace) = op.as_mplace_or_imm() {
1935 let (size, _align) = ecx.size_and_align_of_val(&mplace).discard_err()??;
1936
1937 let alloc_ref = ecx.get_ptr_alloc(mplace.ptr(), size).discard_err()??;
1941 if alloc_ref.has_provenance() {
1942 return None;
1943 }
1944
1945 let pointer = mplace.ptr().into_pointer_or_addr().ok()?;
1946 let (prov, offset) = pointer.prov_and_relative_offset();
1947 let alloc_id = prov.alloc_id();
1948 intern_const_alloc_for_constprop(ecx, alloc_id).discard_err()?;
1949
1950 if let GlobalAlloc::Memory(alloc) = ecx.tcx.global_alloc(alloc_id)
1954 && alloc.inner().align >= op.layout.align.abi
1957 {
1958 return Some(ConstValue::Indirect { alloc_id, offset });
1959 }
1960 }
1961
1962 let alloc_id =
1964 ecx.intern_with_temp_alloc(op.layout, |ecx, dest| ecx.copy_op(op, dest)).discard_err()?;
1965 Some(ConstValue::Indirect { alloc_id, offset: Size::ZERO })
1966}
1967
1968impl<'tcx> VnState<'_, '_, 'tcx> {
1969 fn try_as_operand(&mut self, index: VnIndex, location: Location) -> Option<Operand<'tcx>> {
1972 if let Some(const_) = self.try_as_constant(index) {
1973 Some(Operand::Constant(Box::new(const_)))
1974 } else if let Value::RuntimeChecks(c) = self.get(index) {
1975 Some(Operand::RuntimeChecks(c))
1976 } else if let Some(place) = self.try_as_place(index, location, false) {
1977 self.reused_locals.insert(place.local);
1978 Some(Operand::Copy(place))
1979 } else {
1980 None
1981 }
1982 }
1983
1984 fn try_as_constant(&mut self, index: VnIndex) -> Option<ConstOperand<'tcx>> {
1986 let value = self.get(index);
1987
1988 if let Value::Constant { value, disambiguator: None } = value
1990 && let Const::Val(..) = value
1991 {
1992 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1993 }
1994
1995 if let Some(value) = self.try_as_evaluated_constant(index) {
1996 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1997 }
1998
1999 if let Value::Constant { value, disambiguator: None } = value {
2001 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
2002 }
2003
2004 None
2005 }
2006
2007 fn try_as_evaluated_constant(&mut self, index: VnIndex) -> Option<Const<'tcx>> {
2008 let op = self.eval_to_const(index)?;
2009 if op.layout.is_unsized() {
2010 return None;
2012 }
2013
2014 let value = op_to_prop_const(&mut self.ecx, op)?;
2015
2016 if may_have_provenance(self.tcx, value, op.layout.size) {
2020 return None;
2021 }
2022
2023 Some(Const::Val(value, op.layout.ty))
2024 }
2025
2026 #[instrument(level = "trace", skip(self), ret)]
2030 fn try_as_place(
2031 &mut self,
2032 mut index: VnIndex,
2033 loc: Location,
2034 allow_complex_projection: bool,
2035 ) -> Option<Place<'tcx>> {
2036 let mut projection = SmallVec::<[PlaceElem<'tcx>; 1]>::new();
2037 loop {
2038 if let Some(local) = self.try_as_local(index, loc) {
2039 projection.reverse();
2040 let place =
2041 Place { local, projection: self.tcx.mk_place_elems(projection.as_slice()) };
2042 return Some(place);
2043 } else if projection.last() == Some(&PlaceElem::Deref) {
2044 return None;
2048 } else if let Value::Projection(pointer, proj) = self.get(index)
2049 && (allow_complex_projection || proj.is_stable_offset())
2050 && let Some(proj) = self.try_as_place_elem(self.ty(index), proj, loc)
2051 {
2052 if proj == PlaceElem::Deref {
2053 match self.get(pointer) {
2056 Value::Argument(_)
2057 if let Some(Mutability::Not) = self.ty(pointer).ref_mutability() => {}
2058 _ => {
2059 return None;
2060 }
2061 }
2062 }
2063 projection.push(proj);
2064 index = pointer;
2065 } else {
2066 return None;
2067 }
2068 }
2069 }
2070
2071 fn try_as_local(&mut self, index: VnIndex, loc: Location) -> Option<Local> {
2074 let other = self.rev_locals.get(index)?;
2075 other
2076 .iter()
2077 .find(|&&other| self.ssa.assignment_dominates(&self.dominators, other, loc))
2078 .copied()
2079 }
2080}
2081
2082impl<'tcx> MutVisitor<'tcx> for VnState<'_, '_, 'tcx> {
2083 fn tcx(&self) -> TyCtxt<'tcx> {
2084 self.tcx
2085 }
2086
2087 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
2088 self.simplify_place_projection(place, location);
2089 self.super_place(place, context, location);
2090 }
2091
2092 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
2093 self.simplify_operand(operand, location);
2094 self.super_operand(operand, location);
2095 }
2096
2097 fn visit_assign(
2098 &mut self,
2099 lhs: &mut Place<'tcx>,
2100 rvalue: &mut Rvalue<'tcx>,
2101 location: Location,
2102 ) {
2103 self.simplify_place_projection(lhs, location);
2104
2105 let value = self.simplify_rvalue(lhs, rvalue, location);
2106 if let Some(value) = value {
2107 if let Some(const_) = self.try_as_constant(value) {
2109 *rvalue = Rvalue::Use(Operand::Constant(Box::new(const_)), WithRetag::Yes);
2110 } else if let Some(place) = self.try_as_place(value, location, false)
2111 && !matches!(rvalue, Rvalue::Use(Operand::Move(p) | Operand::Copy(p), _) if p == &place)
2112 {
2113 *rvalue = Rvalue::Use(Operand::Copy(place), WithRetag::Yes);
2114 self.reused_locals.insert(place.local);
2115 }
2116 }
2117
2118 if let Some(local) = lhs.as_local()
2119 && self.ssa.is_ssa(local)
2120 && let rvalue_ty = rvalue.ty(self.local_decls, self.tcx)
2121 && self.local_decls[local].ty == rvalue_ty
2124 {
2125 let value = value.unwrap_or_else(|| self.new_opaque(rvalue_ty));
2126 self.assign(local, value);
2127 }
2128 }
2129
2130 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
2131 if let Terminator { kind: TerminatorKind::Call { destination, .. }, .. } = terminator {
2132 if let Some(local) = destination.as_local()
2133 && self.ssa.is_ssa(local)
2134 {
2135 let ty = self.local_decls[local].ty;
2136 let opaque = self.new_opaque(ty);
2137 self.assign(local, opaque);
2138 }
2139 }
2140 self.super_terminator(terminator, location);
2141 }
2142}
2143
2144struct StorageRemover<'a, 'tcx> {
2145 tcx: TyCtxt<'tcx>,
2146 reused_locals: &'a DenseBitSet<Local>,
2147 storage_to_remove: &'a DenseBitSet<Local>,
2148}
2149
2150impl<'a, 'tcx> MutVisitor<'tcx> for StorageRemover<'a, 'tcx> {
2151 fn tcx(&self) -> TyCtxt<'tcx> {
2152 self.tcx
2153 }
2154
2155 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, _: Location) {
2156 if let Operand::Move(place) = *operand
2157 && !place.is_indirect_first_projection()
2158 && self.reused_locals.contains(place.local)
2159 {
2160 *operand = Operand::Copy(place);
2161 }
2162 }
2163
2164 fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
2165 match stmt.kind {
2166 StatementKind::StorageLive(l) | StatementKind::StorageDead(l)
2168 if self.storage_to_remove.contains(l) =>
2169 {
2170 stmt.make_nop(true)
2171 }
2172 _ => self.super_statement(stmt, loc),
2173 }
2174 }
2175}
2176
2177struct StorageChecker<'a, 'tcx> {
2178 reused_locals: &'a DenseBitSet<Local>,
2179 storage_to_remove: DenseBitSet<Local>,
2180 maybe_uninit: ResultsCursor<'a, 'tcx, MaybeUninitializedLocals>,
2181}
2182
2183impl<'a, 'tcx> Visitor<'tcx> for StorageChecker<'a, 'tcx> {
2184 fn visit_local(&mut self, local: Local, context: PlaceContext, location: Location) {
2185 match context {
2186 PlaceContext::MutatingUse(MutatingUseContext::AsmOutput)
2191 | PlaceContext::MutatingUse(MutatingUseContext::Call)
2192 | PlaceContext::MutatingUse(MutatingUseContext::Store)
2193 | PlaceContext::MutatingUse(MutatingUseContext::Yield)
2194 | PlaceContext::NonUse(_) => {
2195 return;
2196 }
2197 PlaceContext::MutatingUse(_) | PlaceContext::NonMutatingUse(_) => {}
2199 }
2200
2201 if !self.reused_locals.contains(local) || self.storage_to_remove.contains(local) {
2203 return;
2204 }
2205
2206 self.maybe_uninit.seek_before_primary_effect(location);
2207
2208 if self.maybe_uninit.get().contains(local) {
2209 debug!(
2210 ?location,
2211 ?local,
2212 "local is reused and is maybe uninit at this location, marking it for storage statement removal"
2213 );
2214 self.storage_to_remove.insert(local);
2215 }
2216 }
2217}