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::PassPolicy;
126use crate::ssa::{MaybeUninitializedLocals, SsaLocals};
127
128pub(super) struct GVN;
129
130impl<'tcx> crate::MirPass<'tcx> for GVN {
131 fn policy(&self, sess: &rustc_session::Session) -> PassPolicy {
132 PassPolicy::optimization(sess.mir_opt_level() >= 2)
133 }
134
135 #[instrument(level = "trace", skip(self, tcx, body))]
136 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
137 debug!(def_id = ?body.source.def_id());
138
139 let typing_env = body.typing_env(tcx);
140 let ssa = SsaLocals::new(tcx, body, typing_env);
141 let dominators = body.basic_blocks.dominators().clone();
143
144 let arena = DroplessArena::default();
145 let mut state =
146 VnState::new(tcx, body, typing_env, &ssa, dominators, &body.local_decls, &arena);
147
148 for local in body.args_iter().filter(|&local| ssa.is_ssa(local)) {
149 let opaque = state.new_argument(body.local_decls[local].ty);
150 state.assign(local, opaque);
151 }
152
153 let reverse_postorder = body.basic_blocks.reverse_postorder().to_vec();
154 for bb in reverse_postorder {
155 let data = &mut body.basic_blocks.as_mut_preserves_cfg()[bb];
156 state.visit_basic_block_data(bb, data);
157 }
158
159 let storage_to_remove = if tcx.sess.emit_lifetime_markers() {
163 let maybe_uninit = MaybeUninitializedLocals
164 .iterate_to_fixpoint(tcx, body, Some("mir_opt::gvn"))
165 .into_results_cursor(body);
166
167 let mut storage_checker = StorageChecker {
168 reused_locals: &state.reused_locals,
169 storage_to_remove: DenseBitSet::new_empty(body.local_decls.len()),
170 maybe_uninit,
171 };
172
173 for (bb, data) in traversal::reachable(body) {
174 storage_checker.visit_basic_block_data(bb, data);
175 }
176
177 Some(storage_checker.storage_to_remove)
178 } else {
179 None
180 };
181
182 let storage_to_remove = storage_to_remove.as_ref().unwrap_or(&state.reused_locals);
184 debug!(?storage_to_remove);
185
186 StorageRemover { tcx, reused_locals: &state.reused_locals, storage_to_remove }
187 .visit_body_preserves_cfg(body);
188 }
189}
190
191newtype_index! {
192 #[debug_format = "_v{}"]
194 struct VnIndex {}
195}
196
197#[derive(Copy, Clone, Debug, Eq)]
201struct VnOpaque;
202impl PartialEq for VnOpaque {
203 fn eq(&self, _: &VnOpaque) -> bool {
204 unreachable!()
206 }
207}
208impl Hash for VnOpaque {
209 fn hash<T: Hasher>(&self, _: &mut T) {
210 unreachable!()
212 }
213}
214
215#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
216enum AddressKind {
217 Ref(BorrowKind),
218 Address(RawPtrKind),
219}
220
221#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
222enum AddressBase {
223 Local(Local),
225 Deref(VnIndex),
227}
228
229#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
230enum Value<'a, 'tcx> {
231 Opaque(VnOpaque),
234 Argument(VnOpaque),
236 Constant {
238 value: Const<'tcx>,
239 disambiguator: Option<VnOpaque>,
243 },
244
245 Aggregate(VariantIdx, &'a [VnIndex]),
249 Union(FieldIdx, VnIndex),
251 RawPtr {
253 pointer: VnIndex,
255 metadata: VnIndex,
257 },
258 Repeat(VnIndex, ty::Const<'tcx>),
260 Address {
262 base: AddressBase,
263 projection: &'a [ProjectionElem<VnIndex, Ty<'tcx>>],
266 kind: AddressKind,
267 provenance: VnOpaque,
269 },
270
271 Projection(VnIndex, ProjectionElem<VnIndex, ()>),
274 Discriminant(VnIndex),
276
277 RuntimeChecks(RuntimeChecks),
279 UnaryOp(UnOp, VnIndex),
280 BinaryOp(BinOp, VnIndex, VnIndex),
281 Cast {
282 kind: CastKind,
283 value: VnIndex,
284 },
285}
286
287struct ValueSet<'a, 'tcx> {
293 indices: HashTable<VnIndex>,
294 hashes: IndexVec<VnIndex, u64>,
295 values: IndexVec<VnIndex, Value<'a, 'tcx>>,
296 types: IndexVec<VnIndex, Ty<'tcx>>,
297}
298
299impl<'a, 'tcx> ValueSet<'a, 'tcx> {
300 fn new(num_values: usize) -> ValueSet<'a, 'tcx> {
301 ValueSet {
302 indices: HashTable::with_capacity(num_values),
303 hashes: IndexVec::with_capacity(num_values),
304 values: IndexVec::with_capacity(num_values),
305 types: IndexVec::with_capacity(num_values),
306 }
307 }
308
309 #[inline]
312 fn insert_unique(
313 &mut self,
314 ty: Ty<'tcx>,
315 value: impl FnOnce(VnOpaque) -> Value<'a, 'tcx>,
316 ) -> VnIndex {
317 let value = value(VnOpaque);
318
319 debug_assert!(match value {
320 Value::Opaque(_) | Value::Argument(_) | Value::Address { .. } => true,
321 Value::Constant { disambiguator, .. } => disambiguator.is_some(),
322 _ => false,
323 });
324
325 let index = self.hashes.push(0);
326 let _index = self.types.push(ty);
327 debug_assert_eq!(index, _index);
328 let _index = self.values.push(value);
329 debug_assert_eq!(index, _index);
330 index
331 }
332
333 #[allow(rustc::disallowed_pass_by_ref)] fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> (VnIndex, bool) {
337 debug_assert!(match value {
338 Value::Opaque(_) | Value::Address { .. } => false,
339 Value::Constant { disambiguator, .. } => disambiguator.is_none(),
340 _ => true,
341 });
342
343 let hash: u64 = {
344 let mut h = FxHasher::default();
345 value.hash(&mut h);
346 ty.hash(&mut h);
347 h.finish()
348 };
349
350 let eq = |index: &VnIndex| self.values[*index] == value && self.types[*index] == ty;
351 let hasher = |index: &VnIndex| self.hashes[*index];
352 match self.indices.entry(hash, eq, hasher) {
353 Entry::Occupied(entry) => {
354 let index = *entry.get();
355 (index, false)
356 }
357 Entry::Vacant(entry) => {
358 let index = self.hashes.push(hash);
359 entry.insert(index);
360 let _index = self.values.push(value);
361 debug_assert_eq!(index, _index);
362 let _index = self.types.push(ty);
363 debug_assert_eq!(index, _index);
364 (index, true)
365 }
366 }
367 }
368
369 #[inline]
371 fn value(&self, index: VnIndex) -> Value<'a, 'tcx> {
372 self.values[index]
373 }
374
375 #[inline]
377 fn ty(&self, index: VnIndex) -> Ty<'tcx> {
378 self.types[index]
379 }
380}
381
382struct VnState<'body, 'a, 'tcx> {
383 tcx: TyCtxt<'tcx>,
384 ecx: InterpCx<'tcx, DummyMachine>,
385 local_decls: &'body LocalDecls<'tcx>,
386 is_coroutine: bool,
387 locals: IndexVec<Local, Option<VnIndex>>,
389 rev_locals: IndexVec<VnIndex, SmallVec<[Local; 1]>>,
392 values: ValueSet<'a, 'tcx>,
393 evaluated: IndexVec<VnIndex, Option<Option<&'a OpTy<'tcx>>>>,
398 ssa: &'body SsaLocals,
399 dominators: Dominators<BasicBlock>,
400 reused_locals: DenseBitSet<Local>,
401 arena: &'a DroplessArena,
402}
403
404impl<'body, 'a, 'tcx> VnState<'body, 'a, 'tcx> {
405 fn new(
406 tcx: TyCtxt<'tcx>,
407 body: &Body<'tcx>,
408 typing_env: ty::TypingEnv<'tcx>,
409 ssa: &'body SsaLocals,
410 dominators: Dominators<BasicBlock>,
411 local_decls: &'body LocalDecls<'tcx>,
412 arena: &'a DroplessArena,
413 ) -> Self {
414 let num_values =
419 2 * body.basic_blocks.iter().map(|bbdata| bbdata.statements.len()).sum::<usize>()
420 + 4 * body.basic_blocks.len();
421 VnState {
422 tcx,
423 ecx: InterpCx::new(tcx, DUMMY_SP, typing_env, DummyMachine),
424 local_decls,
425 is_coroutine: body.coroutine.is_some(),
426 locals: IndexVec::from_elem(None, local_decls),
427 rev_locals: IndexVec::with_capacity(num_values),
428 values: ValueSet::new(num_values),
429 evaluated: IndexVec::with_capacity(num_values),
430 ssa,
431 dominators,
432 reused_locals: DenseBitSet::new_empty(local_decls.len()),
433 arena,
434 }
435 }
436
437 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
438 self.ecx.typing_env()
439 }
440
441 fn insert_unique(
442 &mut self,
443 ty: Ty<'tcx>,
444 value: impl FnOnce(VnOpaque) -> Value<'a, 'tcx>,
445 ) -> VnIndex {
446 let index = self.values.insert_unique(ty, value);
447 let _index = self.evaluated.push(None);
448 debug_assert_eq!(index, _index);
449 let _index = self.rev_locals.push(SmallVec::new());
450 debug_assert_eq!(index, _index);
451 index
452 }
453
454 #[instrument(level = "trace", skip(self), ret)]
455 fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> VnIndex {
456 let (index, new) = self.values.insert(ty, value);
457 if new {
458 let _index = self.evaluated.push(None);
460 debug_assert_eq!(index, _index);
461 let _index = self.rev_locals.push(SmallVec::new());
462 debug_assert_eq!(index, _index);
463 }
464 index
465 }
466
467 #[instrument(level = "trace", skip(self), ret)]
470 fn new_opaque(&mut self, ty: Ty<'tcx>) -> VnIndex {
471 let index = self.insert_unique(ty, Value::Opaque);
472 self.evaluated[index] = Some(None);
473 index
474 }
475
476 #[instrument(level = "trace", skip(self), ret)]
477 fn new_argument(&mut self, ty: Ty<'tcx>) -> VnIndex {
478 let index = self.insert_unique(ty, Value::Argument);
479 self.evaluated[index] = Some(None);
480 index
481 }
482
483 #[instrument(level = "trace", skip(self), ret)]
485 fn new_pointer(&mut self, place: Place<'tcx>, kind: AddressKind) -> Option<VnIndex> {
486 let pty = place.ty(self.local_decls, self.tcx).ty;
487 let ty = match kind {
488 AddressKind::Ref(bk) => {
489 Ty::new_ref(self.tcx, self.tcx.lifetimes.re_erased, pty, bk.to_mutbl_lossy())
490 }
491 AddressKind::Address(mutbl) => Ty::new_ptr(self.tcx, pty, mutbl.to_mutbl_lossy()),
492 };
493
494 let mut projection = place.projection.iter();
495 let base = if place.is_indirect_first_projection() {
496 let base = self.locals[place.local]?;
497 projection.next();
499 AddressBase::Deref(base)
500 } else if self.ssa.is_ssa(place.local) {
501 AddressBase::Local(place.local)
503 } else {
504 return None;
505 };
506 let projection =
508 projection.map(|proj| proj.try_map(|index| self.locals[index], |ty| ty).ok_or(()));
509 let projection = self.arena.try_alloc_from_iter(projection).ok()?;
510
511 let index = self.insert_unique(ty, |provenance| Value::Address {
512 base,
513 projection,
514 kind,
515 provenance,
516 });
517 Some(index)
518 }
519
520 #[instrument(level = "trace", skip(self), ret)]
521 fn insert_constant(&mut self, value: Const<'tcx>) -> VnIndex {
522 if is_deterministic(value) {
523 let constant = Value::Constant { value, disambiguator: None };
525 self.insert(value.ty(), constant)
526 } else {
527 self.insert_unique(value.ty(), |disambiguator| Value::Constant {
530 value,
531 disambiguator: Some(disambiguator),
532 })
533 }
534 }
535
536 #[inline]
537 fn get(&self, index: VnIndex) -> Value<'a, 'tcx> {
538 self.values.value(index)
539 }
540
541 #[inline]
542 fn ty(&self, index: VnIndex) -> Ty<'tcx> {
543 self.values.ty(index)
544 }
545
546 #[instrument(level = "trace", skip(self))]
548 fn assign(&mut self, local: Local, value: VnIndex) {
549 debug_assert!(self.ssa.is_ssa(local));
550 self.locals[local] = Some(value);
551 self.rev_locals[value].push(local);
552 }
553
554 fn insert_bool(&mut self, flag: bool) -> VnIndex {
555 let value = Const::from_bool(self.tcx, flag);
557 debug_assert!(is_deterministic(value));
558 self.insert(self.tcx.types.bool, Value::Constant { value, disambiguator: None })
559 }
560
561 fn insert_scalar(&mut self, ty: Ty<'tcx>, scalar: Scalar) -> VnIndex {
562 let value = Const::from_scalar(self.tcx, scalar, ty);
564 debug_assert!(is_deterministic(value));
565 self.insert(ty, Value::Constant { value, disambiguator: None })
566 }
567
568 fn insert_tuple(&mut self, ty: Ty<'tcx>, values: &[VnIndex]) -> VnIndex {
569 self.insert(ty, Value::Aggregate(VariantIdx::ZERO, self.arena.alloc_slice(values)))
570 }
571
572 #[instrument(level = "trace", skip(self), ret)]
573 fn eval_to_const_inner(&mut self, value: VnIndex) -> Option<OpTy<'tcx>> {
574 use Value::*;
575 let ty = self.ty(value);
576 let ty = if !self.is_coroutine || ty.is_scalar() {
578 self.ecx.layout_of(ty).ok()?
579 } else {
580 return None;
581 };
582 let op = match self.get(value) {
583 _ if ty.is_zst() => ImmTy::uninit(ty).into(),
584
585 Opaque(_) | Argument(_) => return None,
586 RuntimeChecks(..) => return None,
588
589 Repeat(value, _count) => {
594 let value = self.eval_to_const(value)?;
595 if value.is_immediate_uninit() {
596 ImmTy::uninit(ty).into()
597 } else {
598 return None;
599 }
600 }
601 Constant { ref value, disambiguator: _ } => {
602 self.ecx.eval_mir_constant(value, DUMMY_SP, None).discard_err()?
603 }
604 Aggregate(variant, ref fields) => {
605 let fields =
606 fields.iter().map(|&f| self.eval_to_const(f)).collect::<Option<Vec<_>>>()?;
607 let variant = if ty.ty.is_enum() { Some(variant) } else { None };
608 let (BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }) = ty.backend_repr
609 else {
610 return None;
611 };
612 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
613 let variant_dest = if let Some(variant) = variant {
614 self.ecx.project_downcast(&dest, variant).discard_err()?
615 } else {
616 dest.clone()
617 };
618 for (field_index, op) in fields.into_iter().enumerate() {
619 let field_dest = self
620 .ecx
621 .project_field(&variant_dest, FieldIdx::from_usize(field_index))
622 .discard_err()?;
623 self.ecx.copy_op(op, &field_dest).discard_err()?;
624 }
625 self.ecx
626 .write_discriminant(variant.unwrap_or(FIRST_VARIANT), &dest)
627 .discard_err()?;
628 self.ecx
629 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
630 .discard_err()?;
631 dest.into()
632 }
633 Union(active_field, field) => {
634 let field = self.eval_to_const(field)?;
635 if field.layout.layout.is_zst() {
636 ImmTy::from_immediate(Immediate::Uninit, ty).into()
637 } else if matches!(
638 ty.backend_repr,
639 BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }
640 ) {
641 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
642 let field_dest = self.ecx.project_field(&dest, active_field).discard_err()?;
643 self.ecx.copy_op(field, &field_dest).discard_err()?;
644 self.ecx
645 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
646 .discard_err()?;
647 dest.into()
648 } else {
649 return None;
650 }
651 }
652 RawPtr { pointer, metadata } => {
653 let pointer = self.eval_to_const(pointer)?;
654 let metadata = self.eval_to_const(metadata)?;
655
656 let data = self.ecx.read_pointer(pointer).discard_err()?;
658 let meta = if metadata.layout.is_zst() {
659 MemPlaceMeta::None
660 } else {
661 MemPlaceMeta::Meta(self.ecx.read_scalar(metadata).discard_err()?)
662 };
663 let ptr_imm = Immediate::new_pointer_with_meta(data, meta, &self.ecx);
664 ImmTy::from_immediate(ptr_imm, ty).into()
665 }
666
667 Projection(base, elem) => {
668 let base = self.eval_to_const(base)?;
669 let elem = elem.try_map(|_| None, |()| ty.ty)?;
672 self.ecx.project(base, elem).discard_err()?
673 }
674 Address { base, projection, .. } => {
675 debug_assert!(!projection.contains(&ProjectionElem::Deref));
676 let pointer = match base {
677 AddressBase::Deref(pointer) => self.eval_to_const(pointer)?,
678 AddressBase::Local(_) => return None,
680 };
681 let mut mplace = self.ecx.deref_pointer(pointer).discard_err()?;
682 for elem in projection {
683 let elem = elem.try_map(|_| None, |ty| ty)?;
686 mplace = self.ecx.project(&mplace, elem).discard_err()?;
687 }
688 let pointer = mplace.to_ref(&self.ecx);
689 ImmTy::from_immediate(pointer, ty).into()
690 }
691
692 Discriminant(base) => {
693 let base = self.eval_to_const(base)?;
694 let variant = self.ecx.read_discriminant(base).discard_err()?;
695 let discr_value =
696 self.ecx.discriminant_for_variant(base.layout.ty, variant).discard_err()?;
697 discr_value.into()
698 }
699 UnaryOp(un_op, operand) => {
700 let operand = self.eval_to_const(operand)?;
701 let operand = self.ecx.read_immediate(operand).discard_err()?;
702 let val = self.ecx.unary_op(un_op, &operand).discard_err()?;
703 val.into()
704 }
705 BinaryOp(bin_op, lhs, rhs) => {
706 let lhs = self.eval_to_const(lhs)?;
707 let rhs = self.eval_to_const(rhs)?;
708 let lhs = self.ecx.read_immediate(lhs).discard_err()?;
709 let rhs = self.ecx.read_immediate(rhs).discard_err()?;
710 let val = self.ecx.binary_op(bin_op, &lhs, &rhs).discard_err()?;
711 val.into()
712 }
713 Cast { kind, value } => match kind {
714 CastKind::IntToInt | CastKind::IntToFloat => {
715 let value = self.eval_to_const(value)?;
716 let value = self.ecx.read_immediate(value).discard_err()?;
717 let res = self.ecx.int_to_int_or_float(&value, ty).discard_err()?;
718 res.into()
719 }
720 CastKind::FloatToFloat | CastKind::FloatToInt => {
721 let value = self.eval_to_const(value)?;
722 let value = self.ecx.read_immediate(value).discard_err()?;
723 let res = self.ecx.float_to_float_or_int(&value, ty).discard_err()?;
724 res.into()
725 }
726 CastKind::Transmute | CastKind::Subtype => {
727 let value = self.eval_to_const(value)?;
728 if value.as_mplace_or_imm().is_right() {
733 let can_transmute = match (value.layout.backend_repr, ty.backend_repr) {
734 (BackendRepr::Scalar(s1), BackendRepr::Scalar(s2)) => {
735 s1.size(&self.ecx) == s2.size(&self.ecx)
736 && !matches!(s1.primitive(), Primitive::Pointer(..))
737 }
738 (
739 BackendRepr::ScalarPair { a: a1, b: b1, b_offset: b1_offset },
740 BackendRepr::ScalarPair { a: a2, b: b2, b_offset: b2_offset },
741 ) => {
742 a1.size(&self.ecx) == a2.size(&self.ecx)
743 && b1.size(&self.ecx) == b2.size(&self.ecx)
744 && b1_offset == b2_offset
747 && !matches!(a1.primitive(), Primitive::Pointer(..))
749 && !matches!(b1.primitive(), Primitive::Pointer(..))
750 }
751 _ => false,
752 };
753 if !can_transmute {
754 return None;
755 }
756 }
757 value.offset(Size::ZERO, ty, &self.ecx).discard_err()?
758 }
759 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _) => {
760 let src = self.eval_to_const(value)?;
761 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
762 self.ecx.unsize_into(src, ty, &dest).discard_err()?;
763 self.ecx
764 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
765 .discard_err()?;
766 dest.into()
767 }
768 CastKind::FnPtrToPtr | CastKind::PtrToPtr => {
769 let src = self.eval_to_const(value)?;
770 let src = self.ecx.read_immediate(src).discard_err()?;
771 let ret = self.ecx.ptr_to_ptr(&src, ty).discard_err()?;
772 ret.into()
773 }
774 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::UnsafeFnPointer, _) => {
775 let src = self.eval_to_const(value)?;
776 let src = self.ecx.read_immediate(src).discard_err()?;
777 ImmTy::from_immediate(*src, ty).into()
778 }
779 _ => return None,
780 },
781 };
782 Some(op)
783 }
784
785 fn eval_to_const(&mut self, index: VnIndex) -> Option<&'a OpTy<'tcx>> {
786 if let Some(op) = self.evaluated[index] {
787 return op;
788 }
789 let op = self.eval_to_const_inner(index);
790 self.evaluated[index] = Some(self.arena.alloc(op).as_ref());
791 self.evaluated[index].unwrap()
792 }
793
794 #[instrument(level = "trace", skip(self), ret)]
796 fn dereference_address(
797 &mut self,
798 base: AddressBase,
799 projection: &[ProjectionElem<VnIndex, Ty<'tcx>>],
800 ) -> Option<VnIndex> {
801 let (mut place_ty, mut value) = match base {
802 AddressBase::Local(local) => {
804 let local = self.locals[local]?;
805 let place_ty = PlaceTy::from_ty(self.ty(local));
806 (place_ty, local)
807 }
808 AddressBase::Deref(reborrow) => {
810 let place_ty = PlaceTy::from_ty(self.ty(reborrow));
811 self.project(place_ty, reborrow, ProjectionElem::Deref)?
812 }
813 };
814 for &proj in projection {
815 (place_ty, value) = self.project(place_ty, value, proj)?;
816 }
817 Some(value)
818 }
819
820 #[instrument(level = "trace", skip(self), ret)]
821 fn project(
822 &mut self,
823 place_ty: PlaceTy<'tcx>,
824 value: VnIndex,
825 proj: ProjectionElem<VnIndex, Ty<'tcx>>,
826 ) -> Option<(PlaceTy<'tcx>, VnIndex)> {
827 let projection_ty = place_ty.projection_ty(self.tcx, proj);
828 let proj = match proj {
829 ProjectionElem::Deref => {
830 if let Some(Mutability::Not) = place_ty.ty.ref_mutability()
831 && projection_ty.ty.is_freeze(self.tcx, self.typing_env())
832 {
833 if let Value::Address { base, projection, .. } = self.get(value)
834 && let Some(value) = self.dereference_address(base, projection)
835 {
836 return Some((projection_ty, value));
837 }
838 if self.ty_may_have_ref(projection_ty.ty) {
852 return None;
853 }
854
855 let deref = self
858 .insert(projection_ty.ty, Value::Projection(value, ProjectionElem::Deref));
859 return Some((projection_ty, deref));
860 } else {
861 return None;
862 }
863 }
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 lhs: &Place<'tcx>,
1064 rvalue: &mut Rvalue<'tcx>,
1065 location: Location,
1066 ) -> Option<VnIndex> {
1067 let value = match *rvalue {
1068 Rvalue::Use(ref mut operand, _) => return self.simplify_operand(operand, location),
1070
1071 Rvalue::Repeat(ref mut op, amount) => {
1073 let op = self.simplify_operand(op, location)?;
1074 Value::Repeat(op, amount)
1075 }
1076 Rvalue::Aggregate(..) => return self.simplify_aggregate(rvalue, location),
1077 Rvalue::Ref(_, borrow_kind, ref mut place) => {
1078 self.simplify_place_projection(place, location);
1079 return self.new_pointer(*place, AddressKind::Ref(borrow_kind));
1080 }
1081 Rvalue::Reborrow(_, mutbl, place) => {
1082 if mutbl == Mutability::Mut {
1083 let mut operand = Operand::Copy(place);
1085 let val = self.simplify_operand(&mut operand, location);
1086 *rvalue = Rvalue::Use(Operand::Copy(place), WithRetag::Yes);
1088 return val;
1089 } else {
1090 return None;
1094 }
1095 }
1096 Rvalue::RawPtr(mutbl, ref mut place) => {
1097 self.simplify_place_projection(place, location);
1098 return self.new_pointer(*place, AddressKind::Address(mutbl));
1099 }
1100 Rvalue::WrapUnsafeBinder(ref mut op, _) => {
1101 let value = self.simplify_operand(op, location)?;
1102 Value::Cast { kind: CastKind::Transmute, value }
1103 }
1104
1105 Rvalue::Cast(ref mut kind, ref mut value, to) => {
1107 return self.simplify_cast(kind, value, to, location);
1108 }
1109 Rvalue::BinaryOp(op, (ref mut lhs, ref mut rhs)) => {
1110 return self.simplify_binary(op, lhs, rhs, location);
1111 }
1112 Rvalue::UnaryOp(op, ref mut arg_op) => {
1113 return self.simplify_unary(op, arg_op, location);
1114 }
1115 Rvalue::Discriminant(ref mut place) => {
1116 let place = self.simplify_place_value(place, location)?;
1117 if let Some(discr) = self.simplify_discriminant(place) {
1118 return Some(discr);
1119 }
1120 Value::Discriminant(place)
1121 }
1122
1123 Rvalue::ThreadLocalRef(..) => return None,
1125 Rvalue::CopyForDeref(_) => {
1126 bug!("forbidden in runtime MIR: {rvalue:?}")
1127 }
1128 };
1129 let ty = rvalue.ty(self.local_decls, self.tcx);
1130 Some(self.insert(ty, value))
1131 }
1132
1133 fn simplify_discriminant(&mut self, place: VnIndex) -> Option<VnIndex> {
1134 let enum_ty = self.ty(place);
1135 if enum_ty.is_enum()
1136 && let Value::Aggregate(variant, _) = self.get(place)
1137 {
1138 let discr = self.ecx.discriminant_for_variant(enum_ty, variant).discard_err()?;
1139 return Some(self.insert_scalar(discr.layout.ty, discr.to_scalar()));
1140 }
1141
1142 None
1143 }
1144
1145 fn try_as_place_elem(
1146 &mut self,
1147 ty: Ty<'tcx>,
1148 proj: ProjectionElem<VnIndex, ()>,
1149 loc: Location,
1150 ) -> Option<PlaceElem<'tcx>> {
1151 proj.try_map(
1152 |value| {
1153 let local = self.try_as_local(value, loc)?;
1154 self.reused_locals.insert(local);
1155 Some(local)
1156 },
1157 |()| ty,
1158 )
1159 }
1160
1161 fn simplify_aggregate_to_copy(
1162 &mut self,
1163 ty: Ty<'tcx>,
1164 variant_index: VariantIdx,
1165 fields: &[VnIndex],
1166 ) -> Option<VnIndex> {
1167 let Some(&first_field) = fields.first() else { return None };
1168 let Value::Projection(copy_from_value, _) = self.get(first_field) else { return None };
1169
1170 if fields.iter().enumerate().any(|(index, &v)| {
1172 if let Value::Projection(pointer, ProjectionElem::Field(from_index, _)) = self.get(v)
1173 && copy_from_value == pointer
1174 && from_index.index() == index
1175 {
1176 return false;
1177 }
1178 true
1179 }) {
1180 return None;
1181 }
1182
1183 let mut copy_from_local_value = copy_from_value;
1184 if let Value::Projection(pointer, proj) = self.get(copy_from_value)
1185 && let ProjectionElem::Downcast(_, read_variant) = proj
1186 {
1187 if variant_index == read_variant {
1188 copy_from_local_value = pointer;
1190 } else {
1191 return None;
1193 }
1194 }
1195
1196 if self.ty(copy_from_local_value) == ty { Some(copy_from_local_value) } else { None }
1198 }
1199
1200 fn simplify_aggregate(
1201 &mut self,
1202 rvalue: &mut Rvalue<'tcx>,
1203 location: Location,
1204 ) -> Option<VnIndex> {
1205 let tcx = self.tcx;
1206 let ty = rvalue.ty(self.local_decls, tcx);
1207
1208 let Rvalue::Aggregate(ref kind, ref mut field_ops) = *rvalue else { bug!() };
1209
1210 if field_ops.is_empty() {
1211 let is_zst = match *kind {
1212 AggregateKind::Array(..)
1213 | AggregateKind::Tuple
1214 | AggregateKind::Closure(..)
1215 | AggregateKind::CoroutineClosure(..) => true,
1216 AggregateKind::Adt(did, ..) => tcx.def_kind(did) != DefKind::Enum,
1218 AggregateKind::Coroutine(..) => false,
1220 AggregateKind::RawPtr(..) => bug!("MIR for RawPtr aggregate must have 2 fields"),
1221 };
1222
1223 if is_zst {
1224 return Some(self.insert_constant(Const::zero_sized(ty)));
1225 }
1226 }
1227
1228 let fields = self.arena.alloc_from_iter(field_ops.iter_mut().map(|op| {
1229 self.simplify_operand(op, location)
1230 .unwrap_or_else(|| self.new_opaque(op.ty(self.local_decls, self.tcx)))
1231 }));
1232
1233 let variant_index = match *kind {
1234 AggregateKind::Array(..) | AggregateKind::Tuple => {
1235 assert!(!field_ops.is_empty());
1236 FIRST_VARIANT
1237 }
1238 AggregateKind::Closure(..)
1239 | AggregateKind::CoroutineClosure(..)
1240 | AggregateKind::Coroutine(..) => FIRST_VARIANT,
1241 AggregateKind::Adt(_, variant_index, _, _, None) => variant_index,
1242 AggregateKind::Adt(_, _, _, _, Some(active_field)) => {
1244 let field = *fields.first()?;
1245 return Some(self.insert(ty, Value::Union(active_field, field)));
1246 }
1247 AggregateKind::RawPtr(..) => {
1248 assert_eq!(field_ops.len(), 2);
1249 let [mut pointer, metadata] = fields.try_into().unwrap();
1250
1251 let mut was_updated = false;
1253 while let Value::Cast { kind: CastKind::PtrToPtr, value: cast_value } =
1254 self.get(pointer)
1255 && let ty::RawPtr(from_pointee_ty, from_mtbl) = self.ty(cast_value).kind()
1256 && let ty::RawPtr(_, output_mtbl) = ty.kind()
1257 && from_mtbl == output_mtbl
1258 && from_pointee_ty.is_sized(self.tcx, self.typing_env())
1259 {
1260 pointer = cast_value;
1261 was_updated = true;
1262 }
1263
1264 if was_updated && let Some(op) = self.try_as_operand(pointer, location) {
1265 field_ops[FieldIdx::ZERO] = op;
1266 }
1267
1268 return Some(self.insert(ty, Value::RawPtr { pointer, metadata }));
1269 }
1270 };
1271
1272 if ty.is_array()
1273 && fields.len() > 4
1274 && let Ok(&first) = fields.iter().all_equal_value()
1275 {
1276 let len = ty::Const::from_target_usize(self.tcx, fields.len().try_into().unwrap());
1277 if let Some(op) = self.try_as_operand(first, location) {
1278 *rvalue = Rvalue::Repeat(op, len);
1279 }
1280 return Some(self.insert(ty, Value::Repeat(first, len)));
1281 }
1282
1283 if let Some(value) = self.simplify_aggregate_to_copy(ty, variant_index, &fields) {
1284 if let Some(place) = self.try_as_place(value, location, true) {
1285 self.reused_locals.insert(place.local);
1286 *rvalue = Rvalue::Use(Operand::Copy(place), WithRetag::Yes);
1288 }
1289 return Some(value);
1290 }
1291
1292 Some(self.insert(ty, Value::Aggregate(variant_index, fields)))
1293 }
1294
1295 #[instrument(level = "trace", skip(self), ret)]
1296 fn simplify_unary(
1297 &mut self,
1298 op: UnOp,
1299 arg_op: &mut Operand<'tcx>,
1300 location: Location,
1301 ) -> Option<VnIndex> {
1302 let mut arg_index = self.simplify_operand(arg_op, location)?;
1303 let arg_ty = self.ty(arg_index);
1304 let ret_ty = op.ty(self.tcx, arg_ty);
1305
1306 if op == UnOp::PtrMetadata {
1309 let mut was_updated = false;
1310 loop {
1311 arg_index = match self.get(arg_index) {
1312 Value::Cast { kind: CastKind::PtrToPtr, value: inner }
1321 if self.pointers_have_same_metadata(self.ty(inner), arg_ty) =>
1322 {
1323 inner
1324 }
1325
1326 Value::Cast {
1328 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1329 value: from,
1330 } if let Some(from) = self.ty(from).builtin_deref(true)
1331 && let ty::Array(_, len) = from.kind()
1332 && let Some(to) = self.ty(arg_index).builtin_deref(true)
1333 && let ty::Slice(..) = to.kind() =>
1334 {
1335 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1336 }
1337
1338 Value::Address { base: AddressBase::Deref(reborrowed), projection, .. }
1340 if projection.is_empty() =>
1341 {
1342 reborrowed
1343 }
1344
1345 _ => break,
1346 };
1347 was_updated = true;
1348 }
1349
1350 if was_updated && let Some(op) = self.try_as_operand(arg_index, location) {
1351 *arg_op = op;
1352 }
1353 }
1354
1355 let value = match (op, self.get(arg_index)) {
1356 (UnOp::Not, Value::UnaryOp(UnOp::Not, inner)) => return Some(inner),
1357 (UnOp::Neg, Value::UnaryOp(UnOp::Neg, inner)) => return Some(inner),
1358 (UnOp::Not, Value::BinaryOp(BinOp::Eq, lhs, rhs)) => {
1359 Value::BinaryOp(BinOp::Ne, lhs, rhs)
1360 }
1361 (UnOp::Not, Value::BinaryOp(BinOp::Ne, lhs, rhs)) => {
1362 Value::BinaryOp(BinOp::Eq, lhs, rhs)
1363 }
1364 (UnOp::PtrMetadata, Value::RawPtr { metadata, .. }) => return Some(metadata),
1365 (
1367 UnOp::PtrMetadata,
1368 Value::Cast {
1369 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1370 value: inner,
1371 },
1372 ) if let ty::Slice(..) = arg_ty.builtin_deref(true).unwrap().kind()
1373 && let ty::Array(_, len) = self.ty(inner).builtin_deref(true).unwrap().kind() =>
1374 {
1375 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1376 }
1377 _ => Value::UnaryOp(op, arg_index),
1378 };
1379 Some(self.insert(ret_ty, value))
1380 }
1381
1382 #[instrument(level = "trace", skip(self), ret)]
1383 fn simplify_binary(
1384 &mut self,
1385 op: BinOp,
1386 lhs_operand: &mut Operand<'tcx>,
1387 rhs_operand: &mut Operand<'tcx>,
1388 location: Location,
1389 ) -> Option<VnIndex> {
1390 let lhs = self.simplify_operand(lhs_operand, location);
1391 let rhs = self.simplify_operand(rhs_operand, location);
1392
1393 let mut lhs = lhs?;
1396 let mut rhs = rhs?;
1397
1398 let lhs_ty = self.ty(lhs);
1399
1400 if let BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge = op
1403 && lhs_ty.is_any_ptr()
1404 && let Value::Cast { kind: CastKind::PtrToPtr, value: lhs_value } = self.get(lhs)
1405 && let Value::Cast { kind: CastKind::PtrToPtr, value: rhs_value } = self.get(rhs)
1406 && let lhs_from = self.ty(lhs_value)
1407 && lhs_from == self.ty(rhs_value)
1408 && self.pointers_have_same_metadata(lhs_from, lhs_ty)
1409 {
1410 lhs = lhs_value;
1411 rhs = rhs_value;
1412 if let Some(lhs_op) = self.try_as_operand(lhs, location)
1413 && let Some(rhs_op) = self.try_as_operand(rhs, location)
1414 {
1415 *lhs_operand = lhs_op;
1416 *rhs_operand = rhs_op;
1417 }
1418 }
1419
1420 if let Some(value) = self.simplify_binary_inner(op, lhs_ty, lhs, rhs) {
1421 return Some(value);
1422 }
1423 let ty = op.ty(self.tcx, lhs_ty, self.ty(rhs));
1424 let value = Value::BinaryOp(op, lhs, rhs);
1425 Some(self.insert(ty, value))
1426 }
1427
1428 fn simplify_binary_inner(
1429 &mut self,
1430 op: BinOp,
1431 lhs_ty: Ty<'tcx>,
1432 lhs: VnIndex,
1433 rhs: VnIndex,
1434 ) -> Option<VnIndex> {
1435 let reasonable_ty =
1437 lhs_ty.is_integral() || lhs_ty.is_bool() || lhs_ty.is_char() || lhs_ty.is_any_ptr();
1438 if !reasonable_ty {
1439 return None;
1440 }
1441
1442 let layout = self.ecx.layout_of(lhs_ty).ok()?;
1443
1444 let mut as_bits = |value: VnIndex| {
1445 let constant = self.eval_to_const(value)?;
1446 if layout.backend_repr.is_scalar() {
1447 let scalar = self.ecx.read_scalar(constant).discard_err()?;
1448 scalar.to_bits(constant.layout.size).discard_err()
1449 } else {
1450 None
1452 }
1453 };
1454
1455 use Either::{Left, Right};
1457 let a = as_bits(lhs).map_or(Right(lhs), Left);
1458 let b = as_bits(rhs).map_or(Right(rhs), Left);
1459
1460 let result = match (op, a, b) {
1461 (
1463 BinOp::Add
1464 | BinOp::AddWithOverflow
1465 | BinOp::AddUnchecked
1466 | BinOp::BitOr
1467 | BinOp::BitXor,
1468 Left(0),
1469 Right(p),
1470 )
1471 | (
1472 BinOp::Add
1473 | BinOp::AddWithOverflow
1474 | BinOp::AddUnchecked
1475 | BinOp::BitOr
1476 | BinOp::BitXor
1477 | BinOp::Sub
1478 | BinOp::SubWithOverflow
1479 | BinOp::SubUnchecked
1480 | BinOp::Offset
1481 | BinOp::Shl
1482 | BinOp::Shr,
1483 Right(p),
1484 Left(0),
1485 )
1486 | (BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked, Left(1), Right(p))
1487 | (
1488 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::Div,
1489 Right(p),
1490 Left(1),
1491 ) => p,
1492 (BinOp::BitAnd, Right(p), Left(ones)) | (BinOp::BitAnd, Left(ones), Right(p))
1494 if ones == layout.size.truncate(u128::MAX)
1495 || (layout.ty.is_bool() && ones == 1) =>
1496 {
1497 p
1498 }
1499 (
1501 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::BitAnd,
1502 _,
1503 Left(0),
1504 )
1505 | (BinOp::Rem, _, Left(1))
1506 | (
1507 BinOp::Mul
1508 | BinOp::MulWithOverflow
1509 | BinOp::MulUnchecked
1510 | BinOp::Div
1511 | BinOp::Rem
1512 | BinOp::BitAnd
1513 | BinOp::Shl
1514 | BinOp::Shr,
1515 Left(0),
1516 _,
1517 ) => self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size)),
1518 (BinOp::BitOr, _, Left(ones)) | (BinOp::BitOr, Left(ones), _)
1520 if ones == layout.size.truncate(u128::MAX)
1521 || (layout.ty.is_bool() && ones == 1) =>
1522 {
1523 self.insert_scalar(lhs_ty, Scalar::from_uint(ones, layout.size))
1524 }
1525 (BinOp::Sub | BinOp::SubWithOverflow | BinOp::SubUnchecked | BinOp::BitXor, a, b)
1527 if a == b =>
1528 {
1529 self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size))
1530 }
1531 (BinOp::Eq, Left(a), Left(b)) => self.insert_bool(a == b),
1536 (BinOp::Eq, a, b) if a == b => self.insert_bool(true),
1537 (BinOp::Ne, Left(a), Left(b)) => self.insert_bool(a != b),
1538 (BinOp::Ne, a, b) if a == b => self.insert_bool(false),
1539 _ => return None,
1540 };
1541
1542 if op.is_overflowing() {
1543 let ty = Ty::new_tup(self.tcx, &[self.ty(result), self.tcx.types.bool]);
1544 let false_val = self.insert_bool(false);
1545 Some(self.insert_tuple(ty, &[result, false_val]))
1546 } else {
1547 Some(result)
1548 }
1549 }
1550
1551 fn simplify_cast(
1552 &mut self,
1553 initial_kind: &mut CastKind,
1554 initial_operand: &mut Operand<'tcx>,
1555 to: Ty<'tcx>,
1556 location: Location,
1557 ) -> Option<VnIndex> {
1558 use CastKind::*;
1559 use rustc_middle::ty::adjustment::PointerCoercion::*;
1560
1561 let mut kind = *initial_kind;
1562 let mut value = self.simplify_operand(initial_operand, location)?;
1563 let mut from = self.ty(value);
1564 if from == to {
1565 return Some(value);
1566 }
1567
1568 if let CastKind::PointerCoercion(ReifyFnPointer(_) | ClosureFnPointer(_), _) = kind {
1569 return Some(self.new_opaque(to));
1572 }
1573
1574 let mut was_ever_updated = false;
1575 loop {
1576 let mut was_updated_this_iteration = false;
1577
1578 if let Transmute = kind
1583 && from.is_raw_ptr()
1584 && to.is_raw_ptr()
1585 && self.pointers_have_same_metadata(from, to)
1586 {
1587 kind = PtrToPtr;
1588 was_updated_this_iteration = true;
1589 }
1590
1591 if let PtrToPtr = kind
1594 && let Value::RawPtr { pointer, .. } = self.get(value)
1595 && let ty::RawPtr(to_pointee, _) = to.kind()
1596 && to_pointee.is_sized(self.tcx, self.typing_env())
1597 {
1598 from = self.ty(pointer);
1599 value = pointer;
1600 was_updated_this_iteration = true;
1601 if from == to {
1602 return Some(pointer);
1603 }
1604 }
1605
1606 if let Transmute = kind
1609 && let Value::Aggregate(variant_idx, field_values) = self.get(value)
1610 && let Some((field_idx, field_ty)) =
1611 self.value_is_all_in_one_field(from, variant_idx)
1612 {
1613 from = field_ty;
1614 value = field_values[field_idx.as_usize()];
1615 was_updated_this_iteration = true;
1616 if field_ty == to {
1617 return Some(value);
1618 }
1619 }
1620
1621 if let Value::Cast { kind: inner_kind, value: inner_value } = self.get(value) {
1623 let inner_from = self.ty(inner_value);
1624 let new_kind = match (inner_kind, kind) {
1625 (PtrToPtr, PtrToPtr) => Some(PtrToPtr),
1629 (PtrToPtr, Transmute) if self.pointers_have_same_metadata(inner_from, from) => {
1633 Some(Transmute)
1634 }
1635 (Transmute, PtrToPtr) if self.pointers_have_same_metadata(from, to) => {
1638 Some(Transmute)
1639 }
1640 (Transmute, Transmute)
1643 if !self.transmute_may_have_niche_of_interest_to_backend(
1644 inner_from, from, to,
1645 ) =>
1646 {
1647 Some(Transmute)
1648 }
1649 _ => None,
1650 };
1651 if let Some(new_kind) = new_kind {
1652 kind = new_kind;
1653 from = inner_from;
1654 value = inner_value;
1655 was_updated_this_iteration = true;
1656 if inner_from == to {
1657 return Some(inner_value);
1658 }
1659 }
1660 }
1661
1662 if was_updated_this_iteration {
1663 was_ever_updated = true;
1664 } else {
1665 break;
1666 }
1667 }
1668
1669 if was_ever_updated && let Some(op) = self.try_as_operand(value, location) {
1670 *initial_operand = op;
1671 *initial_kind = kind;
1672 }
1673
1674 Some(self.insert(to, Value::Cast { kind, value }))
1675 }
1676
1677 fn pointers_have_same_metadata(&self, left_ptr_ty: Ty<'tcx>, right_ptr_ty: Ty<'tcx>) -> bool {
1678 let left_meta_ty = left_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1679 let right_meta_ty = right_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1680 if left_meta_ty == right_meta_ty {
1681 true
1682 } else if let Ok(left) = self
1683 .tcx
1684 .try_normalize_erasing_regions(self.typing_env(), Unnormalized::new_wip(left_meta_ty))
1685 && let Ok(right) = self.tcx.try_normalize_erasing_regions(
1686 self.typing_env(),
1687 Unnormalized::new_wip(right_meta_ty),
1688 )
1689 {
1690 left == right
1691 } else {
1692 false
1693 }
1694 }
1695
1696 fn ty_may_have_ref(&self, ty: Ty<'tcx>) -> bool {
1697 fn ty_may_have_ref_inner<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, depth: usize) -> bool {
1698 if !tcx.recursion_limit().value_within_limit(depth) {
1699 return true;
1700 }
1701 let depth = depth + 1;
1702 match ty.kind() {
1703 ty::Int(_)
1704 | ty::Uint(_)
1705 | ty::Float(_)
1706 | ty::Bool
1707 | ty::Char
1708 | ty::Str
1709 | ty::Never
1710 | ty::FnDef(..)
1711 | ty::Error(_)
1712 | ty::FnPtr(..) => false,
1713 ty::Tuple(fields) => {
1714 fields.iter().any(|field| ty_may_have_ref_inner(tcx, field, depth))
1715 }
1716 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => {
1717 ty_may_have_ref_inner(tcx, *ty, depth)
1718 }
1719 ty::Adt(adt_def, args) => {
1720 adt_def.has_param()
1721 || adt_def.has_aliases()
1722 || adt_def.all_fields().any(|field| {
1723 ty_may_have_ref_inner(
1724 tcx,
1725 field.ty(tcx, args).skip_normalization(),
1726 depth,
1727 )
1728 })
1729 }
1730 ty::Ref(..)
1731 | ty::RawPtr(_, _)
1732 | ty::Bound(..)
1733 | ty::Closure(..)
1734 | ty::CoroutineClosure(..)
1735 | ty::Dynamic(..)
1736 | ty::Foreign(_)
1737 | ty::Coroutine(..)
1738 | ty::CoroutineWitness(..)
1739 | ty::UnsafeBinder(_)
1740 | ty::Infer(_)
1741 | ty::Alias(..)
1742 | ty::Param(_)
1743 | ty::Placeholder(_) => true,
1744 }
1745 }
1746 ty_may_have_ref_inner(self.tcx, ty, 0)
1747 }
1748
1749 fn transmute_may_have_niche_of_interest_to_backend(
1756 &self,
1757 from_ty: Ty<'tcx>,
1758 middle_ty: Ty<'tcx>,
1759 to_ty: Ty<'tcx>,
1760 ) -> bool {
1761 let Ok(middle_layout) = self.ecx.layout_of(middle_ty) else {
1762 return true;
1764 };
1765
1766 if middle_layout.uninhabited {
1767 return true;
1768 }
1769
1770 match middle_layout.backend_repr {
1771 BackendRepr::Scalar(mid) => {
1772 if mid.is_always_valid(&self.ecx) {
1773 false
1776 } else if let Ok(from_layout) = self.ecx.layout_of(from_ty)
1777 && !from_layout.uninhabited
1778 && from_layout.size == middle_layout.size
1779 && let BackendRepr::Scalar(from_a) = from_layout.backend_repr
1780 && let mid_range = mid.valid_range(&self.ecx)
1781 && let from_range = from_a.valid_range(&self.ecx)
1782 && mid_range.contains_range(from_range, middle_layout.size)
1783 {
1784 false
1790 } else if let Ok(to_layout) = self.ecx.layout_of(to_ty)
1791 && !to_layout.uninhabited
1792 && to_layout.size == middle_layout.size
1793 && let BackendRepr::Scalar(to_a) = to_layout.backend_repr
1794 && let mid_range = mid.valid_range(&self.ecx)
1795 && let to_range = to_a.valid_range(&self.ecx)
1796 && mid_range.contains_range(to_range, middle_layout.size)
1797 {
1798 false
1804 } else {
1805 true
1806 }
1807 }
1808 BackendRepr::ScalarPair { a, b, b_offset: _ } => {
1809 !a.is_always_valid(&self.ecx) || !b.is_always_valid(&self.ecx)
1812 }
1813 BackendRepr::SimdVector { .. }
1814 | BackendRepr::SimdScalableVector { .. }
1815 | BackendRepr::Memory { .. } => false,
1816 }
1817 }
1818
1819 fn value_is_all_in_one_field(
1820 &self,
1821 ty: Ty<'tcx>,
1822 variant: VariantIdx,
1823 ) -> Option<(FieldIdx, Ty<'tcx>)> {
1824 if let Ok(layout) = self.ecx.layout_of(ty)
1825 && let abi::Variants::Single { index } = layout.variants
1826 && index == variant
1827 && let Some((field_idx, field_layout)) = layout.non_1zst_field(&self.ecx)
1828 && layout.size == field_layout.size
1829 {
1830 Some((field_idx, field_layout.ty))
1834 } else if let ty::Adt(adt, args) = ty.kind()
1835 && adt.is_struct()
1836 && adt.repr().transparent()
1837 && let [single_field] = adt.non_enum_variant().fields.raw.as_slice()
1838 {
1839 Some((FieldIdx::ZERO, single_field.ty(self.tcx, args).skip_norm_wip()))
1840 } else {
1841 None
1842 }
1843 }
1844}
1845
1846fn is_deterministic(c: Const<'_>) -> bool {
1855 if c.ty().is_primitive() {
1857 return true;
1858 }
1859
1860 match c {
1861 Const::Ty(..) => false,
1865 Const::Unevaluated(..) => false,
1867 Const::Val(..) => true,
1871 }
1872}
1873
1874fn may_have_provenance(tcx: TyCtxt<'_>, value: ConstValue, size: Size) -> bool {
1877 match value {
1878 ConstValue::ZeroSized | ConstValue::Scalar(Scalar::Int(_)) => return false,
1879 ConstValue::Scalar(Scalar::Ptr(..)) | ConstValue::Slice { .. } => return true,
1880 ConstValue::Indirect { alloc_id, offset } => !tcx
1881 .global_alloc(alloc_id)
1882 .unwrap_memory()
1883 .inner()
1884 .provenance()
1885 .range_empty(AllocRange::from(offset..offset + size), &tcx),
1886 }
1887}
1888
1889fn op_to_prop_const<'tcx>(
1890 ecx: &mut InterpCx<'tcx, DummyMachine>,
1891 op: &OpTy<'tcx>,
1892) -> Option<ConstValue> {
1893 if op.layout.is_unsized() {
1895 return None;
1896 }
1897
1898 if op.layout.is_zst() {
1900 return Some(ConstValue::ZeroSized);
1901 }
1902
1903 if !op.is_immediate_uninit()
1908 && !matches!(
1909 op.layout.backend_repr,
1910 BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }
1911 )
1912 {
1913 return None;
1914 }
1915
1916 if let BackendRepr::Scalar(abi::Scalar::Initialized { .. }) = op.layout.backend_repr
1918 && let Some(scalar) = ecx.read_scalar(op).discard_err()
1919 {
1920 if !scalar.try_to_scalar_int().is_ok() {
1921 return None;
1925 }
1926 return Some(ConstValue::Scalar(scalar));
1927 }
1928
1929 if let Either::Left(mplace) = op.as_mplace_or_imm() {
1932 let (size, _align) = ecx.size_and_align_of_val(&mplace).discard_err()??;
1933
1934 let alloc_ref = ecx.get_ptr_alloc(mplace.ptr(), size).discard_err()??;
1938 if alloc_ref.has_provenance() {
1939 return None;
1940 }
1941
1942 let pointer = mplace.ptr().into_pointer_or_addr().ok()?;
1943 let (prov, offset) = pointer.prov_and_relative_offset();
1944 let alloc_id = prov.alloc_id();
1945 intern_const_alloc_for_constprop(ecx, alloc_id).discard_err()?;
1946
1947 if let GlobalAlloc::Memory(alloc) = ecx.tcx.global_alloc(alloc_id)
1951 && alloc.inner().align >= op.layout.align.abi
1954 {
1955 return Some(ConstValue::Indirect { alloc_id, offset });
1956 }
1957 }
1958
1959 let alloc_id =
1961 ecx.intern_with_temp_alloc(op.layout, |ecx, dest| ecx.copy_op(op, dest)).discard_err()?;
1962 Some(ConstValue::Indirect { alloc_id, offset: Size::ZERO })
1963}
1964
1965impl<'tcx> VnState<'_, '_, 'tcx> {
1966 fn try_as_operand(&mut self, index: VnIndex, location: Location) -> Option<Operand<'tcx>> {
1969 if let Some(const_) = self.try_as_constant(index) {
1970 Some(Operand::Constant(Box::new(const_)))
1971 } else if let Value::RuntimeChecks(c) = self.get(index) {
1972 Some(Operand::RuntimeChecks(c))
1973 } else if let Some(place) = self.try_as_place(index, location, false) {
1974 self.reused_locals.insert(place.local);
1975 Some(Operand::Copy(place))
1976 } else {
1977 None
1978 }
1979 }
1980
1981 fn try_as_constant(&mut self, index: VnIndex) -> Option<ConstOperand<'tcx>> {
1983 let value = self.get(index);
1984
1985 if let Value::Constant { value, disambiguator: None } = value
1987 && let Const::Val(..) = value
1988 {
1989 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1990 }
1991
1992 if let Some(value) = self.try_as_evaluated_constant(index) {
1993 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1994 }
1995
1996 if let Value::Constant { value, disambiguator: None } = value {
1998 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1999 }
2000
2001 None
2002 }
2003
2004 fn try_as_evaluated_constant(&mut self, index: VnIndex) -> Option<Const<'tcx>> {
2005 let op = self.eval_to_const(index)?;
2006 if op.layout.is_unsized() {
2007 return None;
2009 }
2010
2011 let value = op_to_prop_const(&mut self.ecx, op)?;
2012
2013 if may_have_provenance(self.tcx, value, op.layout.size) {
2017 return None;
2018 }
2019
2020 Some(Const::Val(value, op.layout.ty))
2021 }
2022
2023 #[instrument(level = "trace", skip(self), ret)]
2027 fn try_as_place(
2028 &mut self,
2029 mut index: VnIndex,
2030 loc: Location,
2031 allow_complex_projection: bool,
2032 ) -> Option<Place<'tcx>> {
2033 let mut projection = SmallVec::<[PlaceElem<'tcx>; 1]>::new();
2034 loop {
2035 if let Some(local) = self.try_as_local(index, loc) {
2036 projection.reverse();
2037 let place =
2038 Place { local, projection: self.tcx.mk_place_elems(projection.as_slice()) };
2039 return Some(place);
2040 } else if projection.last() == Some(&PlaceElem::Deref) {
2041 return None;
2045 } else if let Value::Projection(pointer, proj) = self.get(index)
2046 && (allow_complex_projection || proj.is_stable_offset())
2047 && let Some(proj) = self.try_as_place_elem(self.ty(index), proj, loc)
2048 {
2049 if proj == PlaceElem::Deref {
2050 match self.get(pointer) {
2053 Value::Argument(_)
2054 if let Some(Mutability::Not) = self.ty(pointer).ref_mutability() => {}
2055 _ => {
2056 return None;
2057 }
2058 }
2059 }
2060 projection.push(proj);
2061 index = pointer;
2062 } else {
2063 return None;
2064 }
2065 }
2066 }
2067
2068 fn try_as_local(&mut self, index: VnIndex, loc: Location) -> Option<Local> {
2071 let other = self.rev_locals.get(index)?;
2072 other
2073 .iter()
2074 .find(|&&other| self.ssa.assignment_dominates(&self.dominators, other, loc))
2075 .copied()
2076 }
2077}
2078
2079impl<'tcx> MutVisitor<'tcx> for VnState<'_, '_, 'tcx> {
2080 fn tcx(&self) -> TyCtxt<'tcx> {
2081 self.tcx
2082 }
2083
2084 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
2085 self.simplify_place_projection(place, location);
2086 self.super_place(place, context, location);
2087 }
2088
2089 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
2090 self.simplify_operand(operand, location);
2091 self.super_operand(operand, location);
2092 }
2093
2094 fn visit_assign(
2095 &mut self,
2096 lhs: &mut Place<'tcx>,
2097 rvalue: &mut Rvalue<'tcx>,
2098 location: Location,
2099 ) {
2100 self.simplify_place_projection(lhs, location);
2101
2102 let value = self.simplify_rvalue(lhs, rvalue, location);
2103 if let Some(value) = value {
2104 if let Some(const_) = self.try_as_constant(value) {
2106 *rvalue = Rvalue::Use(Operand::Constant(Box::new(const_)), WithRetag::Yes);
2107 } else if let Some(place) = self.try_as_place(value, location, false)
2108 && !matches!(rvalue, Rvalue::Use(Operand::Move(p) | Operand::Copy(p), _) if p == &place)
2109 {
2110 *rvalue = Rvalue::Use(Operand::Copy(place), WithRetag::Yes);
2111 self.reused_locals.insert(place.local);
2112 }
2113 }
2114
2115 if let Some(local) = lhs.as_local()
2116 && self.ssa.is_ssa(local)
2117 && let rvalue_ty = rvalue.ty(self.local_decls, self.tcx)
2118 && self.local_decls[local].ty == rvalue_ty
2121 {
2122 let value = value.unwrap_or_else(|| self.new_opaque(rvalue_ty));
2123 self.assign(local, value);
2124 }
2125 }
2126
2127 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
2128 if let Terminator { kind: TerminatorKind::Call { destination, .. }, .. } = terminator {
2129 if let Some(local) = destination.as_local()
2130 && self.ssa.is_ssa(local)
2131 {
2132 let ty = self.local_decls[local].ty;
2133 let opaque = self.new_opaque(ty);
2134 self.assign(local, opaque);
2135 }
2136 }
2137 self.super_terminator(terminator, location);
2138 }
2139}
2140
2141struct StorageRemover<'a, 'tcx> {
2142 tcx: TyCtxt<'tcx>,
2143 reused_locals: &'a DenseBitSet<Local>,
2144 storage_to_remove: &'a DenseBitSet<Local>,
2145}
2146
2147impl<'a, 'tcx> MutVisitor<'tcx> for StorageRemover<'a, 'tcx> {
2148 fn tcx(&self) -> TyCtxt<'tcx> {
2149 self.tcx
2150 }
2151
2152 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, _: Location) {
2153 if let Operand::Move(place) = *operand
2154 && !place.is_indirect_first_projection()
2155 && self.reused_locals.contains(place.local)
2156 {
2157 *operand = Operand::Copy(place);
2158 }
2159 }
2160
2161 fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
2162 match stmt.kind {
2163 StatementKind::StorageLive(l) | StatementKind::StorageDead(l)
2165 if self.storage_to_remove.contains(l) =>
2166 {
2167 stmt.make_nop(true)
2168 }
2169 _ => self.super_statement(stmt, loc),
2170 }
2171 }
2172}
2173
2174struct StorageChecker<'a, 'tcx> {
2175 reused_locals: &'a DenseBitSet<Local>,
2176 storage_to_remove: DenseBitSet<Local>,
2177 maybe_uninit: ResultsCursor<'a, 'tcx, MaybeUninitializedLocals>,
2178}
2179
2180impl<'a, 'tcx> Visitor<'tcx> for StorageChecker<'a, 'tcx> {
2181 fn visit_local(&mut self, local: Local, context: PlaceContext, location: Location) {
2182 match context {
2183 PlaceContext::MutatingUse(MutatingUseContext::AsmOutput)
2188 | PlaceContext::MutatingUse(MutatingUseContext::Call)
2189 | PlaceContext::MutatingUse(MutatingUseContext::Store)
2190 | PlaceContext::MutatingUse(MutatingUseContext::Yield)
2191 | PlaceContext::NonUse(_) => {
2192 return;
2193 }
2194 PlaceContext::MutatingUse(_) | PlaceContext::NonMutatingUse(_) => {}
2196 }
2197
2198 if !self.reused_locals.contains(local) || self.storage_to_remove.contains(local) {
2200 return;
2201 }
2202
2203 self.maybe_uninit.seek_before_primary_effect(location);
2204
2205 if self.maybe_uninit.get().contains(local) {
2206 debug!(
2207 ?location,
2208 ?local,
2209 "local is reused and is maybe uninit at this location, marking it for storage statement removal"
2210 );
2211 self.storage_to_remove.insert(local);
2212 }
2213 }
2214}