1use std::borrow::Cow;
88
89use either::Either;
90use rustc_abi::{self as abi, BackendRepr, FIRST_VARIANT, FieldIdx, Primitive, Size, VariantIdx};
91use rustc_const_eval::const_eval::DummyMachine;
92use rustc_const_eval::interpret::{
93 ImmTy, Immediate, InterpCx, MemPlaceMeta, MemoryKind, OpTy, Projectable, Scalar,
94 intern_const_alloc_for_constprop,
95};
96use rustc_data_structures::fx::{FxIndexSet, MutableValues};
97use rustc_data_structures::graph::dominators::Dominators;
98use rustc_hir::def::DefKind;
99use rustc_index::bit_set::DenseBitSet;
100use rustc_index::{IndexVec, newtype_index};
101use rustc_middle::bug;
102use rustc_middle::mir::interpret::GlobalAlloc;
103use rustc_middle::mir::visit::*;
104use rustc_middle::mir::*;
105use rustc_middle::ty::layout::HasTypingEnv;
106use rustc_middle::ty::{self, Ty, TyCtxt};
107use rustc_span::DUMMY_SP;
108use smallvec::SmallVec;
109use tracing::{debug, instrument, trace};
110
111use crate::ssa::SsaLocals;
112
113pub(super) struct GVN;
114
115impl<'tcx> crate::MirPass<'tcx> for GVN {
116 fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
117 sess.mir_opt_level() >= 2
118 }
119
120 #[instrument(level = "trace", skip(self, tcx, body))]
121 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
122 debug!(def_id = ?body.source.def_id());
123
124 let typing_env = body.typing_env(tcx);
125 let ssa = SsaLocals::new(tcx, body, typing_env);
126 let dominators = body.basic_blocks.dominators().clone();
128
129 let mut state = VnState::new(tcx, body, typing_env, &ssa, dominators, &body.local_decls);
130
131 for local in body.args_iter().filter(|&local| ssa.is_ssa(local)) {
132 let opaque = state.new_opaque(body.local_decls[local].ty);
133 state.assign(local, opaque);
134 }
135
136 let reverse_postorder = body.basic_blocks.reverse_postorder().to_vec();
137 for bb in reverse_postorder {
138 let data = &mut body.basic_blocks.as_mut_preserves_cfg()[bb];
139 state.visit_basic_block_data(bb, data);
140 }
141
142 StorageRemover { tcx, reused_locals: state.reused_locals }.visit_body_preserves_cfg(body);
146 }
147
148 fn is_required(&self) -> bool {
149 false
150 }
151}
152
153newtype_index! {
154 struct VnIndex {}
155}
156
157#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
158enum AddressKind {
159 Ref(BorrowKind),
160 Address(RawPtrKind),
161}
162
163#[derive(Debug, PartialEq, Eq, Hash)]
164enum Value<'tcx> {
165 Opaque(usize),
169 Constant {
171 value: Const<'tcx>,
172 disambiguator: usize,
176 },
177 Aggregate(VariantIdx, Vec<VnIndex>),
180 RawPtr {
182 pointer: VnIndex,
184 metadata: VnIndex,
186 },
187 Repeat(VnIndex, ty::Const<'tcx>),
189 Address {
191 place: Place<'tcx>,
192 kind: AddressKind,
193 provenance: usize,
195 },
196
197 Projection(VnIndex, ProjectionElem<VnIndex, ()>),
200 Discriminant(VnIndex),
202 Len(VnIndex),
204
205 NullaryOp(NullOp<'tcx>, Ty<'tcx>),
207 UnaryOp(UnOp, VnIndex),
208 BinaryOp(BinOp, VnIndex, VnIndex),
209 Cast {
210 kind: CastKind,
211 value: VnIndex,
212 },
213}
214
215struct VnState<'body, 'tcx> {
216 tcx: TyCtxt<'tcx>,
217 ecx: InterpCx<'tcx, DummyMachine>,
218 local_decls: &'body LocalDecls<'tcx>,
219 is_coroutine: bool,
220 locals: IndexVec<Local, Option<VnIndex>>,
222 rev_locals: IndexVec<VnIndex, SmallVec<[Local; 1]>>,
225 values: FxIndexSet<(Value<'tcx>, Ty<'tcx>)>,
226 evaluated: IndexVec<VnIndex, Option<OpTy<'tcx>>>,
228 next_opaque: usize,
230 derefs: Vec<VnIndex>,
232 ssa: &'body SsaLocals,
233 dominators: Dominators<BasicBlock>,
234 reused_locals: DenseBitSet<Local>,
235}
236
237impl<'body, 'tcx> VnState<'body, 'tcx> {
238 fn new(
239 tcx: TyCtxt<'tcx>,
240 body: &Body<'tcx>,
241 typing_env: ty::TypingEnv<'tcx>,
242 ssa: &'body SsaLocals,
243 dominators: Dominators<BasicBlock>,
244 local_decls: &'body LocalDecls<'tcx>,
245 ) -> Self {
246 let num_values =
251 2 * body.basic_blocks.iter().map(|bbdata| bbdata.statements.len()).sum::<usize>()
252 + 4 * body.basic_blocks.len();
253 VnState {
254 tcx,
255 ecx: InterpCx::new(tcx, DUMMY_SP, typing_env, DummyMachine),
256 local_decls,
257 is_coroutine: body.coroutine.is_some(),
258 locals: IndexVec::from_elem(None, local_decls),
259 rev_locals: IndexVec::with_capacity(num_values),
260 values: FxIndexSet::with_capacity_and_hasher(num_values, Default::default()),
261 evaluated: IndexVec::with_capacity(num_values),
262 next_opaque: 1,
263 derefs: Vec::new(),
264 ssa,
265 dominators,
266 reused_locals: DenseBitSet::new_empty(local_decls.len()),
267 }
268 }
269
270 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
271 self.ecx.typing_env()
272 }
273
274 #[instrument(level = "trace", skip(self), ret)]
275 fn insert(&mut self, ty: Ty<'tcx>, value: Value<'tcx>) -> VnIndex {
276 let (index, new) = self.values.insert_full((value, ty));
277 let index = VnIndex::from_usize(index);
278 if new {
279 let evaluated = self.eval_to_const(index);
281 let _index = self.evaluated.push(evaluated);
282 debug_assert_eq!(index, _index);
283 let _index = self.rev_locals.push(SmallVec::new());
284 debug_assert_eq!(index, _index);
285 }
286 index
287 }
288
289 fn next_opaque(&mut self) -> usize {
290 let next_opaque = self.next_opaque;
291 self.next_opaque += 1;
292 next_opaque
293 }
294
295 #[instrument(level = "trace", skip(self), ret)]
298 fn new_opaque(&mut self, ty: Ty<'tcx>) -> VnIndex {
299 let value = Value::Opaque(self.next_opaque());
300 self.insert(ty, value)
301 }
302
303 #[instrument(level = "trace", skip(self), ret)]
305 fn new_pointer(&mut self, place: Place<'tcx>, kind: AddressKind) -> VnIndex {
306 let pty = place.ty(self.local_decls, self.tcx).ty;
307 let ty = match kind {
308 AddressKind::Ref(bk) => {
309 Ty::new_ref(self.tcx, self.tcx.lifetimes.re_erased, pty, bk.to_mutbl_lossy())
310 }
311 AddressKind::Address(mutbl) => Ty::new_ptr(self.tcx, pty, mutbl.to_mutbl_lossy()),
312 };
313 let value = Value::Address { place, kind, provenance: self.next_opaque() };
314 self.insert(ty, value)
315 }
316
317 #[inline]
318 fn get(&self, index: VnIndex) -> &Value<'tcx> {
319 &self.values.get_index(index.as_usize()).unwrap().0
320 }
321
322 #[inline]
323 fn ty(&self, index: VnIndex) -> Ty<'tcx> {
324 self.values.get_index(index.as_usize()).unwrap().1
325 }
326
327 #[instrument(level = "trace", skip(self))]
329 fn assign(&mut self, local: Local, value: VnIndex) {
330 debug_assert!(self.ssa.is_ssa(local));
331 self.locals[local] = Some(value);
332 self.rev_locals[value].push(local);
333 }
334
335 fn insert_constant(&mut self, value: Const<'tcx>) -> VnIndex {
336 let disambiguator = if value.is_deterministic() {
337 0
339 } else {
340 let disambiguator = self.next_opaque();
343 debug_assert_ne!(disambiguator, 0);
345 disambiguator
346 };
347 self.insert(value.ty(), Value::Constant { value, disambiguator })
348 }
349
350 fn insert_bool(&mut self, flag: bool) -> VnIndex {
351 let value = Const::from_bool(self.tcx, flag);
353 debug_assert!(value.is_deterministic());
354 self.insert(self.tcx.types.bool, Value::Constant { value, disambiguator: 0 })
355 }
356
357 fn insert_scalar(&mut self, ty: Ty<'tcx>, scalar: Scalar) -> VnIndex {
358 let value = Const::from_scalar(self.tcx, scalar, ty);
360 debug_assert!(value.is_deterministic());
361 self.insert(ty, Value::Constant { value, disambiguator: 0 })
362 }
363
364 fn insert_tuple(&mut self, ty: Ty<'tcx>, values: Vec<VnIndex>) -> VnIndex {
365 self.insert(ty, Value::Aggregate(VariantIdx::ZERO, values))
366 }
367
368 fn insert_deref(&mut self, ty: Ty<'tcx>, value: VnIndex) -> VnIndex {
369 let value = self.insert(ty, Value::Projection(value, ProjectionElem::Deref));
370 self.derefs.push(value);
371 value
372 }
373
374 fn invalidate_derefs(&mut self) {
375 for deref in std::mem::take(&mut self.derefs) {
376 let opaque = self.next_opaque();
377 self.values.get_index_mut2(deref.index()).unwrap().0 = Value::Opaque(opaque);
378 }
379 }
380
381 #[instrument(level = "trace", skip(self), ret)]
382 fn eval_to_const(&mut self, value: VnIndex) -> Option<OpTy<'tcx>> {
383 use Value::*;
384 let ty = self.ty(value);
385 let ty = if !self.is_coroutine || ty.is_scalar() {
387 self.ecx.layout_of(ty).ok()?
388 } else {
389 return None;
390 };
391 let op = match *self.get(value) {
392 _ if ty.is_zst() => ImmTy::uninit(ty).into(),
393
394 Opaque(_) => return None,
395 Repeat(..) => return None,
397
398 Constant { ref value, disambiguator: _ } => {
399 self.ecx.eval_mir_constant(value, DUMMY_SP, None).discard_err()?
400 }
401 Aggregate(variant, ref fields) => {
402 let fields = fields
403 .iter()
404 .map(|&f| self.evaluated[f].as_ref())
405 .collect::<Option<Vec<_>>>()?;
406 let variant = if ty.ty.is_enum() { Some(variant) } else { None };
407 if matches!(ty.backend_repr, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..))
408 {
409 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
410 let variant_dest = if let Some(variant) = variant {
411 self.ecx.project_downcast(&dest, variant).discard_err()?
412 } else {
413 dest.clone()
414 };
415 for (field_index, op) in fields.into_iter().enumerate() {
416 let field_dest = self
417 .ecx
418 .project_field(&variant_dest, FieldIdx::from_usize(field_index))
419 .discard_err()?;
420 self.ecx.copy_op(op, &field_dest).discard_err()?;
421 }
422 self.ecx
423 .write_discriminant(variant.unwrap_or(FIRST_VARIANT), &dest)
424 .discard_err()?;
425 self.ecx
426 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
427 .discard_err()?;
428 dest.into()
429 } else {
430 return None;
431 }
432 }
433 RawPtr { pointer, metadata } => {
434 let pointer = self.evaluated[pointer].as_ref()?;
435 let metadata = self.evaluated[metadata].as_ref()?;
436
437 let data = self.ecx.read_pointer(pointer).discard_err()?;
439 let meta = if metadata.layout.is_zst() {
440 MemPlaceMeta::None
441 } else {
442 MemPlaceMeta::Meta(self.ecx.read_scalar(metadata).discard_err()?)
443 };
444 let ptr_imm = Immediate::new_pointer_with_meta(data, meta, &self.ecx);
445 ImmTy::from_immediate(ptr_imm, ty).into()
446 }
447
448 Projection(base, elem) => {
449 let base = self.evaluated[base].as_ref()?;
450 let elem = match elem {
451 ProjectionElem::Deref => ProjectionElem::Deref,
452 ProjectionElem::Downcast(name, read_variant) => {
453 ProjectionElem::Downcast(name, read_variant)
454 }
455 ProjectionElem::Field(f, ()) => ProjectionElem::Field(f, ty.ty),
456 ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
457 ProjectionElem::ConstantIndex { offset, min_length, from_end }
458 }
459 ProjectionElem::Subslice { from, to, from_end } => {
460 ProjectionElem::Subslice { from, to, from_end }
461 }
462 ProjectionElem::OpaqueCast(()) => ProjectionElem::OpaqueCast(ty.ty),
463 ProjectionElem::Subtype(()) => ProjectionElem::Subtype(ty.ty),
464 ProjectionElem::UnwrapUnsafeBinder(()) => {
465 ProjectionElem::UnwrapUnsafeBinder(ty.ty)
466 }
467 ProjectionElem::Index(_) => return None,
469 };
470 self.ecx.project(base, elem).discard_err()?
471 }
472 Address { place, kind: _, provenance: _ } => {
473 if !place.is_indirect_first_projection() {
474 return None;
475 }
476 let local = self.locals[place.local]?;
477 let pointer = self.evaluated[local].as_ref()?;
478 let mut mplace = self.ecx.deref_pointer(pointer).discard_err()?;
479 for proj in place.projection.iter().skip(1) {
480 if matches!(proj, ProjectionElem::Index(_)) {
483 return None;
484 }
485 mplace = self.ecx.project(&mplace, proj).discard_err()?;
486 }
487 let pointer = mplace.to_ref(&self.ecx);
488 ImmTy::from_immediate(pointer, ty).into()
489 }
490
491 Discriminant(base) => {
492 let base = self.evaluated[base].as_ref()?;
493 let variant = self.ecx.read_discriminant(base).discard_err()?;
494 let discr_value =
495 self.ecx.discriminant_for_variant(base.layout.ty, variant).discard_err()?;
496 discr_value.into()
497 }
498 Len(slice) => {
499 let slice = self.evaluated[slice].as_ref()?;
500 let len = slice.len(&self.ecx).discard_err()?;
501 ImmTy::from_uint(len, ty).into()
502 }
503 NullaryOp(null_op, arg_ty) => {
504 let arg_layout = self.ecx.layout_of(arg_ty).ok()?;
505 if let NullOp::SizeOf | NullOp::AlignOf = null_op
506 && arg_layout.is_unsized()
507 {
508 return None;
509 }
510 let val = match null_op {
511 NullOp::SizeOf => arg_layout.size.bytes(),
512 NullOp::AlignOf => arg_layout.align.abi.bytes(),
513 NullOp::OffsetOf(fields) => self
514 .ecx
515 .tcx
516 .offset_of_subfield(self.typing_env(), arg_layout, fields.iter())
517 .bytes(),
518 NullOp::UbChecks => return None,
519 NullOp::ContractChecks => return None,
520 };
521 ImmTy::from_uint(val, ty).into()
522 }
523 UnaryOp(un_op, operand) => {
524 let operand = self.evaluated[operand].as_ref()?;
525 let operand = self.ecx.read_immediate(operand).discard_err()?;
526 let val = self.ecx.unary_op(un_op, &operand).discard_err()?;
527 val.into()
528 }
529 BinaryOp(bin_op, lhs, rhs) => {
530 let lhs = self.evaluated[lhs].as_ref()?;
531 let lhs = self.ecx.read_immediate(lhs).discard_err()?;
532 let rhs = self.evaluated[rhs].as_ref()?;
533 let rhs = self.ecx.read_immediate(rhs).discard_err()?;
534 let val = self.ecx.binary_op(bin_op, &lhs, &rhs).discard_err()?;
535 val.into()
536 }
537 Cast { kind, value } => match kind {
538 CastKind::IntToInt | CastKind::IntToFloat => {
539 let value = self.evaluated[value].as_ref()?;
540 let value = self.ecx.read_immediate(value).discard_err()?;
541 let res = self.ecx.int_to_int_or_float(&value, ty).discard_err()?;
542 res.into()
543 }
544 CastKind::FloatToFloat | CastKind::FloatToInt => {
545 let value = self.evaluated[value].as_ref()?;
546 let value = self.ecx.read_immediate(value).discard_err()?;
547 let res = self.ecx.float_to_float_or_int(&value, ty).discard_err()?;
548 res.into()
549 }
550 CastKind::Transmute => {
551 let value = self.evaluated[value].as_ref()?;
552 if value.as_mplace_or_imm().is_right() {
557 let can_transmute = match (value.layout.backend_repr, ty.backend_repr) {
558 (BackendRepr::Scalar(s1), BackendRepr::Scalar(s2)) => {
559 s1.size(&self.ecx) == s2.size(&self.ecx)
560 && !matches!(s1.primitive(), Primitive::Pointer(..))
561 }
562 (BackendRepr::ScalarPair(a1, b1), BackendRepr::ScalarPair(a2, b2)) => {
563 a1.size(&self.ecx) == a2.size(&self.ecx) &&
564 b1.size(&self.ecx) == b2.size(&self.ecx) &&
565 b1.align(&self.ecx) == b2.align(&self.ecx) &&
567 !matches!(a1.primitive(), Primitive::Pointer(..))
569 && !matches!(b1.primitive(), Primitive::Pointer(..))
570 }
571 _ => false,
572 };
573 if !can_transmute {
574 return None;
575 }
576 }
577 value.offset(Size::ZERO, ty, &self.ecx).discard_err()?
578 }
579 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _) => {
580 let src = self.evaluated[value].as_ref()?;
581 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
582 self.ecx.unsize_into(src, ty, &dest).discard_err()?;
583 self.ecx
584 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
585 .discard_err()?;
586 dest.into()
587 }
588 CastKind::FnPtrToPtr | CastKind::PtrToPtr => {
589 let src = self.evaluated[value].as_ref()?;
590 let src = self.ecx.read_immediate(src).discard_err()?;
591 let ret = self.ecx.ptr_to_ptr(&src, ty).discard_err()?;
592 ret.into()
593 }
594 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::UnsafeFnPointer, _) => {
595 let src = self.evaluated[value].as_ref()?;
596 let src = self.ecx.read_immediate(src).discard_err()?;
597 ImmTy::from_immediate(*src, ty).into()
598 }
599 _ => return None,
600 },
601 };
602 Some(op)
603 }
604
605 fn project(
606 &mut self,
607 place_ty: PlaceTy<'tcx>,
608 value: VnIndex,
609 proj: PlaceElem<'tcx>,
610 from_non_ssa_index: &mut bool,
611 ) -> Option<(PlaceTy<'tcx>, VnIndex)> {
612 let projection_ty = place_ty.projection_ty(self.tcx, proj);
613 let proj = match proj {
614 ProjectionElem::Deref => {
615 if let Some(Mutability::Not) = place_ty.ty.ref_mutability()
616 && projection_ty.ty.is_freeze(self.tcx, self.typing_env())
617 {
618 return Some((projection_ty, self.insert_deref(projection_ty.ty, value)));
621 } else {
622 return None;
623 }
624 }
625 ProjectionElem::Downcast(name, index) => ProjectionElem::Downcast(name, index),
626 ProjectionElem::Field(f, _) => {
627 if let Value::Aggregate(_, fields) = self.get(value) {
628 return Some((projection_ty, fields[f.as_usize()]));
629 } else if let Value::Projection(outer_value, ProjectionElem::Downcast(_, read_variant)) = self.get(value)
630 && let Value::Aggregate(written_variant, fields) = self.get(*outer_value)
631 && written_variant == read_variant
647 {
648 return Some((projection_ty, fields[f.as_usize()]));
649 }
650 ProjectionElem::Field(f, ())
651 }
652 ProjectionElem::Index(idx) => {
653 if let Value::Repeat(inner, _) = self.get(value) {
654 *from_non_ssa_index |= self.locals[idx].is_none();
655 return Some((projection_ty, *inner));
656 }
657 let idx = self.locals[idx]?;
658 ProjectionElem::Index(idx)
659 }
660 ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
661 match self.get(value) {
662 Value::Repeat(inner, _) => {
663 return Some((projection_ty, *inner));
664 }
665 Value::Aggregate(_, operands) => {
666 let offset = if from_end {
667 operands.len() - offset as usize
668 } else {
669 offset as usize
670 };
671 let value = operands.get(offset).copied()?;
672 return Some((projection_ty, value));
673 }
674 _ => {}
675 };
676 ProjectionElem::ConstantIndex { offset, min_length, from_end }
677 }
678 ProjectionElem::Subslice { from, to, from_end } => {
679 ProjectionElem::Subslice { from, to, from_end }
680 }
681 ProjectionElem::OpaqueCast(_) => ProjectionElem::OpaqueCast(()),
682 ProjectionElem::Subtype(_) => ProjectionElem::Subtype(()),
683 ProjectionElem::UnwrapUnsafeBinder(_) => ProjectionElem::UnwrapUnsafeBinder(()),
684 };
685
686 let value = self.insert(projection_ty.ty, Value::Projection(value, proj));
687 Some((projection_ty, value))
688 }
689
690 #[instrument(level = "trace", skip(self))]
692 fn simplify_place_projection(&mut self, place: &mut Place<'tcx>, location: Location) {
693 if place.is_indirect_first_projection()
696 && let Some(base) = self.locals[place.local]
697 && let Some(new_local) = self.try_as_local(base, location)
698 && place.local != new_local
699 {
700 place.local = new_local;
701 self.reused_locals.insert(new_local);
702 }
703
704 let mut projection = Cow::Borrowed(&place.projection[..]);
705
706 for i in 0..projection.len() {
707 let elem = projection[i];
708 if let ProjectionElem::Index(idx_local) = elem
709 && let Some(idx) = self.locals[idx_local]
710 {
711 if let Some(offset) = self.evaluated[idx].as_ref()
712 && let Some(offset) = self.ecx.read_target_usize(offset).discard_err()
713 && let Some(min_length) = offset.checked_add(1)
714 {
715 projection.to_mut()[i] =
716 ProjectionElem::ConstantIndex { offset, min_length, from_end: false };
717 } else if let Some(new_idx_local) = self.try_as_local(idx, location)
718 && idx_local != new_idx_local
719 {
720 projection.to_mut()[i] = ProjectionElem::Index(new_idx_local);
721 self.reused_locals.insert(new_idx_local);
722 }
723 }
724 }
725
726 if projection.is_owned() {
727 place.projection = self.tcx.mk_place_elems(&projection);
728 }
729
730 trace!(?place);
731 }
732
733 #[instrument(level = "trace", skip(self), ret)]
736 fn simplify_place_value(
737 &mut self,
738 place: &mut Place<'tcx>,
739 location: Location,
740 ) -> Option<VnIndex> {
741 self.simplify_place_projection(place, location);
742
743 let mut place_ref = place.as_ref();
746
747 let mut value = self.locals[place.local]?;
749 let mut place_ty = PlaceTy::from_ty(self.local_decls[place.local].ty);
751 let mut from_non_ssa_index = false;
752 for (index, proj) in place.projection.iter().enumerate() {
753 if let Value::Projection(pointer, ProjectionElem::Deref) = *self.get(value)
754 && let Value::Address { place: mut pointee, kind, .. } = *self.get(pointer)
755 && let AddressKind::Ref(BorrowKind::Shared) = kind
756 && let Some(v) = self.simplify_place_value(&mut pointee, location)
757 {
758 value = v;
759 place_ref = pointee.project_deeper(&place.projection[index..], self.tcx).as_ref();
760 }
761 if let Some(local) = self.try_as_local(value, location) {
762 place_ref = PlaceRef { local, projection: &place.projection[index..] };
766 }
767
768 (place_ty, value) = self.project(place_ty, value, proj, &mut from_non_ssa_index)?;
769 }
770
771 if let Value::Projection(pointer, ProjectionElem::Deref) = *self.get(value)
772 && let Value::Address { place: mut pointee, kind, .. } = *self.get(pointer)
773 && let AddressKind::Ref(BorrowKind::Shared) = kind
774 && let Some(v) = self.simplify_place_value(&mut pointee, location)
775 {
776 value = v;
777 place_ref = pointee.project_deeper(&[], self.tcx).as_ref();
778 }
779 if let Some(new_local) = self.try_as_local(value, location) {
780 place_ref = PlaceRef { local: new_local, projection: &[] };
781 } else if from_non_ssa_index {
782 return None;
784 }
785
786 if place_ref.local != place.local || place_ref.projection.len() < place.projection.len() {
787 *place = place_ref.project_deeper(&[], self.tcx);
789 self.reused_locals.insert(place_ref.local);
790 }
791
792 Some(value)
793 }
794
795 #[instrument(level = "trace", skip(self), ret)]
796 fn simplify_operand(
797 &mut self,
798 operand: &mut Operand<'tcx>,
799 location: Location,
800 ) -> Option<VnIndex> {
801 match *operand {
802 Operand::Constant(ref constant) => Some(self.insert_constant(constant.const_)),
803 Operand::Copy(ref mut place) | Operand::Move(ref mut place) => {
804 let value = self.simplify_place_value(place, location)?;
805 if let Some(const_) = self.try_as_constant(value) {
806 *operand = Operand::Constant(Box::new(const_));
807 }
808 Some(value)
809 }
810 }
811 }
812
813 #[instrument(level = "trace", skip(self), ret)]
814 fn simplify_rvalue(
815 &mut self,
816 lhs: &Place<'tcx>,
817 rvalue: &mut Rvalue<'tcx>,
818 location: Location,
819 ) -> Option<VnIndex> {
820 let value = match *rvalue {
821 Rvalue::Use(ref mut operand) => return self.simplify_operand(operand, location),
823 Rvalue::CopyForDeref(place) => {
824 let mut operand = Operand::Copy(place);
825 let val = self.simplify_operand(&mut operand, location);
826 *rvalue = Rvalue::Use(operand);
827 return val;
828 }
829
830 Rvalue::Repeat(ref mut op, amount) => {
832 let op = self.simplify_operand(op, location)?;
833 Value::Repeat(op, amount)
834 }
835 Rvalue::NullaryOp(op, ty) => Value::NullaryOp(op, ty),
836 Rvalue::Aggregate(..) => return self.simplify_aggregate(lhs, rvalue, location),
837 Rvalue::Ref(_, borrow_kind, ref mut place) => {
838 self.simplify_place_projection(place, location);
839 return Some(self.new_pointer(*place, AddressKind::Ref(borrow_kind)));
840 }
841 Rvalue::RawPtr(mutbl, ref mut place) => {
842 self.simplify_place_projection(place, location);
843 return Some(self.new_pointer(*place, AddressKind::Address(mutbl)));
844 }
845 Rvalue::WrapUnsafeBinder(ref mut op, _) => {
846 let value = self.simplify_operand(op, location)?;
847 Value::Cast { kind: CastKind::Transmute, value }
848 }
849
850 Rvalue::Len(ref mut place) => return self.simplify_len(place, location),
852 Rvalue::Cast(ref mut kind, ref mut value, to) => {
853 return self.simplify_cast(kind, value, to, location);
854 }
855 Rvalue::BinaryOp(op, box (ref mut lhs, ref mut rhs)) => {
856 return self.simplify_binary(op, lhs, rhs, location);
857 }
858 Rvalue::UnaryOp(op, ref mut arg_op) => {
859 return self.simplify_unary(op, arg_op, location);
860 }
861 Rvalue::Discriminant(ref mut place) => {
862 let place = self.simplify_place_value(place, location)?;
863 if let Some(discr) = self.simplify_discriminant(place) {
864 return Some(discr);
865 }
866 Value::Discriminant(place)
867 }
868
869 Rvalue::ThreadLocalRef(..) | Rvalue::ShallowInitBox(..) => return None,
871 };
872 let ty = rvalue.ty(self.local_decls, self.tcx);
873 Some(self.insert(ty, value))
874 }
875
876 fn simplify_discriminant(&mut self, place: VnIndex) -> Option<VnIndex> {
877 let enum_ty = self.ty(place);
878 if enum_ty.is_enum()
879 && let Value::Aggregate(variant, _) = *self.get(place)
880 {
881 let discr = self.ecx.discriminant_for_variant(enum_ty, variant).discard_err()?;
882 return Some(self.insert_scalar(discr.layout.ty, discr.to_scalar()));
883 }
884
885 None
886 }
887
888 fn try_as_place_elem(
889 &mut self,
890 ty: Ty<'tcx>,
891 proj: ProjectionElem<VnIndex, ()>,
892 loc: Location,
893 ) -> Option<PlaceElem<'tcx>> {
894 Some(match proj {
895 ProjectionElem::Deref => ProjectionElem::Deref,
896 ProjectionElem::Field(idx, ()) => ProjectionElem::Field(idx, ty),
897 ProjectionElem::Index(idx) => {
898 let Some(local) = self.try_as_local(idx, loc) else {
899 return None;
900 };
901 self.reused_locals.insert(local);
902 ProjectionElem::Index(local)
903 }
904 ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
905 ProjectionElem::ConstantIndex { offset, min_length, from_end }
906 }
907 ProjectionElem::Subslice { from, to, from_end } => {
908 ProjectionElem::Subslice { from, to, from_end }
909 }
910 ProjectionElem::Downcast(symbol, idx) => ProjectionElem::Downcast(symbol, idx),
911 ProjectionElem::OpaqueCast(()) => ProjectionElem::OpaqueCast(ty),
912 ProjectionElem::Subtype(()) => ProjectionElem::Subtype(ty),
913 ProjectionElem::UnwrapUnsafeBinder(()) => ProjectionElem::UnwrapUnsafeBinder(ty),
914 })
915 }
916
917 fn simplify_aggregate_to_copy(
918 &mut self,
919 lhs: &Place<'tcx>,
920 rvalue: &mut Rvalue<'tcx>,
921 location: Location,
922 fields: &[VnIndex],
923 variant_index: VariantIdx,
924 ) -> Option<VnIndex> {
925 let Some(&first_field) = fields.first() else {
926 return None;
927 };
928 let Value::Projection(copy_from_value, _) = *self.get(first_field) else {
929 return None;
930 };
931 if fields.iter().enumerate().any(|(index, &v)| {
933 if let Value::Projection(pointer, ProjectionElem::Field(from_index, _)) = *self.get(v)
934 && copy_from_value == pointer
935 && from_index.index() == index
936 {
937 return false;
938 }
939 true
940 }) {
941 return None;
942 }
943
944 let mut copy_from_local_value = copy_from_value;
945 if let Value::Projection(pointer, proj) = *self.get(copy_from_value)
946 && let ProjectionElem::Downcast(_, read_variant) = proj
947 {
948 if variant_index == read_variant {
949 copy_from_local_value = pointer;
951 } else {
952 return None;
954 }
955 }
956
957 if self.ty(copy_from_local_value) == rvalue.ty(self.local_decls, self.tcx)
960 && let Some(place) = self.try_as_place(copy_from_local_value, location, true)
961 {
962 if lhs.as_local().is_some() {
965 self.reused_locals.insert(place.local);
966 *rvalue = Rvalue::Use(Operand::Copy(place));
967 }
968 return Some(copy_from_local_value);
969 }
970
971 None
972 }
973
974 fn simplify_aggregate(
975 &mut self,
976 lhs: &Place<'tcx>,
977 rvalue: &mut Rvalue<'tcx>,
978 location: Location,
979 ) -> Option<VnIndex> {
980 let tcx = self.tcx;
981 let ty = rvalue.ty(self.local_decls, tcx);
982
983 let Rvalue::Aggregate(box ref kind, ref mut field_ops) = *rvalue else { bug!() };
984
985 if field_ops.is_empty() {
986 let is_zst = match *kind {
987 AggregateKind::Array(..)
988 | AggregateKind::Tuple
989 | AggregateKind::Closure(..)
990 | AggregateKind::CoroutineClosure(..) => true,
991 AggregateKind::Adt(did, ..) => tcx.def_kind(did) != DefKind::Enum,
993 AggregateKind::Coroutine(..) => false,
995 AggregateKind::RawPtr(..) => bug!("MIR for RawPtr aggregate must have 2 fields"),
996 };
997
998 if is_zst {
999 return Some(self.insert_constant(Const::zero_sized(ty)));
1000 }
1001 }
1002
1003 let fields: Vec<_> = field_ops
1004 .iter_mut()
1005 .map(|op| {
1006 self.simplify_operand(op, location)
1007 .unwrap_or_else(|| self.new_opaque(op.ty(self.local_decls, self.tcx)))
1008 })
1009 .collect();
1010
1011 let variant_index = match *kind {
1012 AggregateKind::Array(..) | AggregateKind::Tuple => {
1013 assert!(!field_ops.is_empty());
1014 FIRST_VARIANT
1015 }
1016 AggregateKind::Closure(..)
1017 | AggregateKind::CoroutineClosure(..)
1018 | AggregateKind::Coroutine(..) => FIRST_VARIANT,
1019 AggregateKind::Adt(_, variant_index, _, _, None) => variant_index,
1020 AggregateKind::Adt(_, _, _, _, Some(_)) => return None,
1022 AggregateKind::RawPtr(..) => {
1023 assert_eq!(field_ops.len(), 2);
1024 let [mut pointer, metadata] = fields.try_into().unwrap();
1025
1026 let mut was_updated = false;
1028 while let Value::Cast { kind: CastKind::PtrToPtr, value: cast_value } =
1029 self.get(pointer)
1030 && let ty::RawPtr(from_pointee_ty, from_mtbl) = self.ty(*cast_value).kind()
1031 && let ty::RawPtr(_, output_mtbl) = ty.kind()
1032 && from_mtbl == output_mtbl
1033 && from_pointee_ty.is_sized(self.tcx, self.typing_env())
1034 {
1035 pointer = *cast_value;
1036 was_updated = true;
1037 }
1038
1039 if was_updated && let Some(op) = self.try_as_operand(pointer, location) {
1040 field_ops[FieldIdx::ZERO] = op;
1041 }
1042
1043 return Some(self.insert(ty, Value::RawPtr { pointer, metadata }));
1044 }
1045 };
1046
1047 if ty.is_array() && fields.len() > 4 {
1048 let first = fields[0];
1049 if fields.iter().all(|&v| v == first) {
1050 let len = ty::Const::from_target_usize(self.tcx, fields.len().try_into().unwrap());
1051 if let Some(op) = self.try_as_operand(first, location) {
1052 *rvalue = Rvalue::Repeat(op, len);
1053 }
1054 return Some(self.insert(ty, Value::Repeat(first, len)));
1055 }
1056 }
1057
1058 if let Some(value) =
1059 self.simplify_aggregate_to_copy(lhs, rvalue, location, &fields, variant_index)
1060 {
1061 return Some(value);
1062 }
1063
1064 Some(self.insert(ty, Value::Aggregate(variant_index, fields)))
1065 }
1066
1067 #[instrument(level = "trace", skip(self), ret)]
1068 fn simplify_unary(
1069 &mut self,
1070 op: UnOp,
1071 arg_op: &mut Operand<'tcx>,
1072 location: Location,
1073 ) -> Option<VnIndex> {
1074 let mut arg_index = self.simplify_operand(arg_op, location)?;
1075 let arg_ty = self.ty(arg_index);
1076 let ret_ty = op.ty(self.tcx, arg_ty);
1077
1078 if op == UnOp::PtrMetadata {
1081 let mut was_updated = false;
1082 loop {
1083 match self.get(arg_index) {
1084 Value::Cast { kind: CastKind::PtrToPtr, value: inner }
1093 if self.pointers_have_same_metadata(self.ty(*inner), arg_ty) =>
1094 {
1095 arg_index = *inner;
1096 was_updated = true;
1097 continue;
1098 }
1099
1100 Value::Address { place, kind: _, provenance: _ }
1102 if let PlaceRef { local, projection: [PlaceElem::Deref] } =
1103 place.as_ref()
1104 && let Some(local_index) = self.locals[local] =>
1105 {
1106 arg_index = local_index;
1107 was_updated = true;
1108 continue;
1109 }
1110
1111 _ => {
1112 if was_updated && let Some(op) = self.try_as_operand(arg_index, location) {
1113 *arg_op = op;
1114 }
1115 break;
1116 }
1117 }
1118 }
1119 }
1120
1121 let value = match (op, self.get(arg_index)) {
1122 (UnOp::Not, Value::UnaryOp(UnOp::Not, inner)) => return Some(*inner),
1123 (UnOp::Neg, Value::UnaryOp(UnOp::Neg, inner)) => return Some(*inner),
1124 (UnOp::Not, Value::BinaryOp(BinOp::Eq, lhs, rhs)) => {
1125 Value::BinaryOp(BinOp::Ne, *lhs, *rhs)
1126 }
1127 (UnOp::Not, Value::BinaryOp(BinOp::Ne, lhs, rhs)) => {
1128 Value::BinaryOp(BinOp::Eq, *lhs, *rhs)
1129 }
1130 (UnOp::PtrMetadata, Value::RawPtr { metadata, .. }) => return Some(*metadata),
1131 (
1133 UnOp::PtrMetadata,
1134 Value::Cast {
1135 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1136 value: inner,
1137 },
1138 ) if let ty::Slice(..) = arg_ty.builtin_deref(true).unwrap().kind()
1139 && let ty::Array(_, len) = self.ty(*inner).builtin_deref(true).unwrap().kind() =>
1140 {
1141 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1142 }
1143 _ => Value::UnaryOp(op, arg_index),
1144 };
1145 Some(self.insert(ret_ty, value))
1146 }
1147
1148 #[instrument(level = "trace", skip(self), ret)]
1149 fn simplify_binary(
1150 &mut self,
1151 op: BinOp,
1152 lhs_operand: &mut Operand<'tcx>,
1153 rhs_operand: &mut Operand<'tcx>,
1154 location: Location,
1155 ) -> Option<VnIndex> {
1156 let lhs = self.simplify_operand(lhs_operand, location);
1157 let rhs = self.simplify_operand(rhs_operand, location);
1158
1159 let mut lhs = lhs?;
1162 let mut rhs = rhs?;
1163
1164 let lhs_ty = self.ty(lhs);
1165
1166 if let BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge = op
1169 && lhs_ty.is_any_ptr()
1170 && let Value::Cast { kind: CastKind::PtrToPtr, value: lhs_value } = self.get(lhs)
1171 && let Value::Cast { kind: CastKind::PtrToPtr, value: rhs_value } = self.get(rhs)
1172 && let lhs_from = self.ty(*lhs_value)
1173 && lhs_from == self.ty(*rhs_value)
1174 && self.pointers_have_same_metadata(lhs_from, lhs_ty)
1175 {
1176 lhs = *lhs_value;
1177 rhs = *rhs_value;
1178 if let Some(lhs_op) = self.try_as_operand(lhs, location)
1179 && let Some(rhs_op) = self.try_as_operand(rhs, location)
1180 {
1181 *lhs_operand = lhs_op;
1182 *rhs_operand = rhs_op;
1183 }
1184 }
1185
1186 if let Some(value) = self.simplify_binary_inner(op, lhs_ty, lhs, rhs) {
1187 return Some(value);
1188 }
1189 let ty = op.ty(self.tcx, lhs_ty, self.ty(rhs));
1190 let value = Value::BinaryOp(op, lhs, rhs);
1191 Some(self.insert(ty, value))
1192 }
1193
1194 fn simplify_binary_inner(
1195 &mut self,
1196 op: BinOp,
1197 lhs_ty: Ty<'tcx>,
1198 lhs: VnIndex,
1199 rhs: VnIndex,
1200 ) -> Option<VnIndex> {
1201 let reasonable_ty =
1203 lhs_ty.is_integral() || lhs_ty.is_bool() || lhs_ty.is_char() || lhs_ty.is_any_ptr();
1204 if !reasonable_ty {
1205 return None;
1206 }
1207
1208 let layout = self.ecx.layout_of(lhs_ty).ok()?;
1209
1210 let as_bits = |value: VnIndex| {
1211 let constant = self.evaluated[value].as_ref()?;
1212 if layout.backend_repr.is_scalar() {
1213 let scalar = self.ecx.read_scalar(constant).discard_err()?;
1214 scalar.to_bits(constant.layout.size).discard_err()
1215 } else {
1216 None
1218 }
1219 };
1220
1221 use Either::{Left, Right};
1223 let a = as_bits(lhs).map_or(Right(lhs), Left);
1224 let b = as_bits(rhs).map_or(Right(rhs), Left);
1225
1226 let result = match (op, a, b) {
1227 (
1229 BinOp::Add
1230 | BinOp::AddWithOverflow
1231 | BinOp::AddUnchecked
1232 | BinOp::BitOr
1233 | BinOp::BitXor,
1234 Left(0),
1235 Right(p),
1236 )
1237 | (
1238 BinOp::Add
1239 | BinOp::AddWithOverflow
1240 | BinOp::AddUnchecked
1241 | BinOp::BitOr
1242 | BinOp::BitXor
1243 | BinOp::Sub
1244 | BinOp::SubWithOverflow
1245 | BinOp::SubUnchecked
1246 | BinOp::Offset
1247 | BinOp::Shl
1248 | BinOp::Shr,
1249 Right(p),
1250 Left(0),
1251 )
1252 | (BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked, Left(1), Right(p))
1253 | (
1254 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::Div,
1255 Right(p),
1256 Left(1),
1257 ) => p,
1258 (BinOp::BitAnd, Right(p), Left(ones)) | (BinOp::BitAnd, Left(ones), Right(p))
1260 if ones == layout.size.truncate(u128::MAX)
1261 || (layout.ty.is_bool() && ones == 1) =>
1262 {
1263 p
1264 }
1265 (
1267 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::BitAnd,
1268 _,
1269 Left(0),
1270 )
1271 | (BinOp::Rem, _, Left(1))
1272 | (
1273 BinOp::Mul
1274 | BinOp::MulWithOverflow
1275 | BinOp::MulUnchecked
1276 | BinOp::Div
1277 | BinOp::Rem
1278 | BinOp::BitAnd
1279 | BinOp::Shl
1280 | BinOp::Shr,
1281 Left(0),
1282 _,
1283 ) => self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size)),
1284 (BinOp::BitOr, _, Left(ones)) | (BinOp::BitOr, Left(ones), _)
1286 if ones == layout.size.truncate(u128::MAX)
1287 || (layout.ty.is_bool() && ones == 1) =>
1288 {
1289 self.insert_scalar(lhs_ty, Scalar::from_uint(ones, layout.size))
1290 }
1291 (BinOp::Sub | BinOp::SubWithOverflow | BinOp::SubUnchecked | BinOp::BitXor, a, b)
1293 if a == b =>
1294 {
1295 self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size))
1296 }
1297 (BinOp::Eq, Left(a), Left(b)) => self.insert_bool(a == b),
1302 (BinOp::Eq, a, b) if a == b => self.insert_bool(true),
1303 (BinOp::Ne, Left(a), Left(b)) => self.insert_bool(a != b),
1304 (BinOp::Ne, a, b) if a == b => self.insert_bool(false),
1305 _ => return None,
1306 };
1307
1308 if op.is_overflowing() {
1309 let ty = Ty::new_tup(self.tcx, &[self.ty(result), self.tcx.types.bool]);
1310 let false_val = self.insert_bool(false);
1311 Some(self.insert_tuple(ty, vec![result, false_val]))
1312 } else {
1313 Some(result)
1314 }
1315 }
1316
1317 fn simplify_cast(
1318 &mut self,
1319 initial_kind: &mut CastKind,
1320 initial_operand: &mut Operand<'tcx>,
1321 to: Ty<'tcx>,
1322 location: Location,
1323 ) -> Option<VnIndex> {
1324 use CastKind::*;
1325 use rustc_middle::ty::adjustment::PointerCoercion::*;
1326
1327 let mut kind = *initial_kind;
1328 let mut value = self.simplify_operand(initial_operand, location)?;
1329 let mut from = self.ty(value);
1330 if from == to {
1331 return Some(value);
1332 }
1333
1334 if let CastKind::PointerCoercion(ReifyFnPointer | ClosureFnPointer(_), _) = kind {
1335 return Some(self.new_opaque(to));
1338 }
1339
1340 let mut was_ever_updated = false;
1341 loop {
1342 let mut was_updated_this_iteration = false;
1343
1344 if let Transmute = kind
1349 && from.is_raw_ptr()
1350 && to.is_raw_ptr()
1351 && self.pointers_have_same_metadata(from, to)
1352 {
1353 kind = PtrToPtr;
1354 was_updated_this_iteration = true;
1355 }
1356
1357 if let PtrToPtr = kind
1360 && let Value::RawPtr { pointer, .. } = self.get(value)
1361 && let ty::RawPtr(to_pointee, _) = to.kind()
1362 && to_pointee.is_sized(self.tcx, self.typing_env())
1363 {
1364 from = self.ty(*pointer);
1365 value = *pointer;
1366 was_updated_this_iteration = true;
1367 if from == to {
1368 return Some(*pointer);
1369 }
1370 }
1371
1372 if let Transmute = kind
1375 && let Value::Aggregate(variant_idx, field_values) = self.get(value)
1376 && let Some((field_idx, field_ty)) =
1377 self.value_is_all_in_one_field(from, *variant_idx)
1378 {
1379 from = field_ty;
1380 value = field_values[field_idx.as_usize()];
1381 was_updated_this_iteration = true;
1382 if field_ty == to {
1383 return Some(value);
1384 }
1385 }
1386
1387 if let Value::Cast { kind: inner_kind, value: inner_value } = *self.get(value) {
1389 let inner_from = self.ty(inner_value);
1390 let new_kind = match (inner_kind, kind) {
1391 (PtrToPtr, PtrToPtr) => Some(PtrToPtr),
1395 (PtrToPtr, Transmute) if self.pointers_have_same_metadata(inner_from, from) => {
1399 Some(Transmute)
1400 }
1401 (Transmute, PtrToPtr) if self.pointers_have_same_metadata(from, to) => {
1404 Some(Transmute)
1405 }
1406 (Transmute, Transmute)
1409 if !self.type_may_have_niche_of_interest_to_backend(from) =>
1410 {
1411 Some(Transmute)
1412 }
1413 _ => None,
1414 };
1415 if let Some(new_kind) = new_kind {
1416 kind = new_kind;
1417 from = inner_from;
1418 value = inner_value;
1419 was_updated_this_iteration = true;
1420 if inner_from == to {
1421 return Some(inner_value);
1422 }
1423 }
1424 }
1425
1426 if was_updated_this_iteration {
1427 was_ever_updated = true;
1428 } else {
1429 break;
1430 }
1431 }
1432
1433 if was_ever_updated && let Some(op) = self.try_as_operand(value, location) {
1434 *initial_operand = op;
1435 *initial_kind = kind;
1436 }
1437
1438 Some(self.insert(to, Value::Cast { kind, value }))
1439 }
1440
1441 fn simplify_len(&mut self, place: &mut Place<'tcx>, location: Location) -> Option<VnIndex> {
1442 let place_ty = place.ty(self.local_decls, self.tcx).ty;
1444 if let ty::Array(_, len) = place_ty.kind() {
1445 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1446 }
1447
1448 let mut inner = self.simplify_place_value(place, location)?;
1449
1450 while let Value::Address { place: borrowed, .. } = self.get(inner)
1453 && let [PlaceElem::Deref] = borrowed.projection[..]
1454 && let Some(borrowed) = self.locals[borrowed.local]
1455 {
1456 inner = borrowed;
1457 }
1458
1459 if let Value::Cast { kind, value: from } = self.get(inner)
1461 && let CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _) = kind
1462 && let Some(from) = self.ty(*from).builtin_deref(true)
1463 && let ty::Array(_, len) = from.kind()
1464 && let Some(to) = self.ty(inner).builtin_deref(true)
1465 && let ty::Slice(..) = to.kind()
1466 {
1467 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1468 }
1469
1470 Some(self.insert(self.tcx.types.usize, Value::Len(inner)))
1472 }
1473
1474 fn pointers_have_same_metadata(&self, left_ptr_ty: Ty<'tcx>, right_ptr_ty: Ty<'tcx>) -> bool {
1475 let left_meta_ty = left_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1476 let right_meta_ty = right_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1477 if left_meta_ty == right_meta_ty {
1478 true
1479 } else if let Ok(left) =
1480 self.tcx.try_normalize_erasing_regions(self.typing_env(), left_meta_ty)
1481 && let Ok(right) =
1482 self.tcx.try_normalize_erasing_regions(self.typing_env(), right_meta_ty)
1483 {
1484 left == right
1485 } else {
1486 false
1487 }
1488 }
1489
1490 fn type_may_have_niche_of_interest_to_backend(&self, ty: Ty<'tcx>) -> bool {
1497 let Ok(layout) = self.ecx.layout_of(ty) else {
1498 return true;
1500 };
1501
1502 if layout.uninhabited {
1503 return true;
1504 }
1505
1506 match layout.backend_repr {
1507 BackendRepr::Scalar(a) => !a.is_always_valid(&self.ecx),
1508 BackendRepr::ScalarPair(a, b) => {
1509 !a.is_always_valid(&self.ecx) || !b.is_always_valid(&self.ecx)
1510 }
1511 BackendRepr::SimdVector { .. } | BackendRepr::Memory { .. } => false,
1512 }
1513 }
1514
1515 fn value_is_all_in_one_field(
1516 &self,
1517 ty: Ty<'tcx>,
1518 variant: VariantIdx,
1519 ) -> Option<(FieldIdx, Ty<'tcx>)> {
1520 if let Ok(layout) = self.ecx.layout_of(ty)
1521 && let abi::Variants::Single { index } = layout.variants
1522 && index == variant
1523 && let Some((field_idx, field_layout)) = layout.non_1zst_field(&self.ecx)
1524 && layout.size == field_layout.size
1525 {
1526 Some((field_idx, field_layout.ty))
1530 } else if let ty::Adt(adt, args) = ty.kind()
1531 && adt.is_struct()
1532 && adt.repr().transparent()
1533 && let [single_field] = adt.non_enum_variant().fields.raw.as_slice()
1534 {
1535 Some((FieldIdx::ZERO, single_field.ty(self.tcx, args)))
1536 } else {
1537 None
1538 }
1539 }
1540}
1541
1542fn op_to_prop_const<'tcx>(
1543 ecx: &mut InterpCx<'tcx, DummyMachine>,
1544 op: &OpTy<'tcx>,
1545) -> Option<ConstValue> {
1546 if op.layout.is_unsized() {
1548 return None;
1549 }
1550
1551 if op.layout.is_zst() {
1553 return Some(ConstValue::ZeroSized);
1554 }
1555
1556 if !matches!(op.layout.backend_repr, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..)) {
1559 return None;
1560 }
1561
1562 if let BackendRepr::Scalar(abi::Scalar::Initialized { .. }) = op.layout.backend_repr
1564 && let Some(scalar) = ecx.read_scalar(op).discard_err()
1565 {
1566 if !scalar.try_to_scalar_int().is_ok() {
1567 return None;
1571 }
1572 return Some(ConstValue::Scalar(scalar));
1573 }
1574
1575 if let Either::Left(mplace) = op.as_mplace_or_imm() {
1578 let (size, _align) = ecx.size_and_align_of_val(&mplace).discard_err()??;
1579
1580 let alloc_ref = ecx.get_ptr_alloc(mplace.ptr(), size).discard_err()??;
1584 if alloc_ref.has_provenance() {
1585 return None;
1586 }
1587
1588 let pointer = mplace.ptr().into_pointer_or_addr().ok()?;
1589 let (prov, offset) = pointer.prov_and_relative_offset();
1590 let alloc_id = prov.alloc_id();
1591 intern_const_alloc_for_constprop(ecx, alloc_id).discard_err()?;
1592
1593 if let GlobalAlloc::Memory(alloc) = ecx.tcx.global_alloc(alloc_id)
1597 && alloc.inner().align >= op.layout.align.abi
1600 {
1601 return Some(ConstValue::Indirect { alloc_id, offset });
1602 }
1603 }
1604
1605 let alloc_id =
1607 ecx.intern_with_temp_alloc(op.layout, |ecx, dest| ecx.copy_op(op, dest)).discard_err()?;
1608 let value = ConstValue::Indirect { alloc_id, offset: Size::ZERO };
1609
1610 if ecx.tcx.global_alloc(alloc_id).unwrap_memory().inner().provenance().ptrs().is_empty() {
1614 return Some(value);
1615 }
1616
1617 None
1618}
1619
1620impl<'tcx> VnState<'_, 'tcx> {
1621 fn try_as_operand(&mut self, index: VnIndex, location: Location) -> Option<Operand<'tcx>> {
1624 if let Some(const_) = self.try_as_constant(index) {
1625 Some(Operand::Constant(Box::new(const_)))
1626 } else if let Some(place) = self.try_as_place(index, location, false) {
1627 self.reused_locals.insert(place.local);
1628 Some(Operand::Copy(place))
1629 } else {
1630 None
1631 }
1632 }
1633
1634 fn try_as_constant(&mut self, index: VnIndex) -> Option<ConstOperand<'tcx>> {
1636 if let Value::Constant { value, disambiguator: 0 } = *self.get(index) {
1640 debug_assert!(value.is_deterministic());
1641 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1642 }
1643
1644 let op = self.evaluated[index].as_ref()?;
1645 if op.layout.is_unsized() {
1646 return None;
1648 }
1649
1650 let value = op_to_prop_const(&mut self.ecx, op)?;
1651
1652 assert!(!value.may_have_provenance(self.tcx, op.layout.size));
1656
1657 let const_ = Const::Val(value, op.layout.ty);
1658 Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_ })
1659 }
1660
1661 #[instrument(level = "trace", skip(self), ret)]
1665 fn try_as_place(
1666 &mut self,
1667 mut index: VnIndex,
1668 loc: Location,
1669 allow_complex_projection: bool,
1670 ) -> Option<Place<'tcx>> {
1671 let mut projection = SmallVec::<[PlaceElem<'tcx>; 1]>::new();
1672 loop {
1673 if let Some(local) = self.try_as_local(index, loc) {
1674 projection.reverse();
1675 let place =
1676 Place { local, projection: self.tcx.mk_place_elems(projection.as_slice()) };
1677 return Some(place);
1678 } else if let Value::Projection(pointer, proj) = *self.get(index)
1679 && (allow_complex_projection || proj.is_stable_offset())
1680 && let Some(proj) = self.try_as_place_elem(self.ty(index), proj, loc)
1681 {
1682 projection.push(proj);
1683 index = pointer;
1684 } else {
1685 return None;
1686 }
1687 }
1688 }
1689
1690 fn try_as_local(&mut self, index: VnIndex, loc: Location) -> Option<Local> {
1693 let other = self.rev_locals.get(index)?;
1694 other
1695 .iter()
1696 .find(|&&other| self.ssa.assignment_dominates(&self.dominators, other, loc))
1697 .copied()
1698 }
1699}
1700
1701impl<'tcx> MutVisitor<'tcx> for VnState<'_, 'tcx> {
1702 fn tcx(&self) -> TyCtxt<'tcx> {
1703 self.tcx
1704 }
1705
1706 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
1707 self.simplify_place_projection(place, location);
1708 if context.is_mutating_use() && place.is_indirect() {
1709 self.invalidate_derefs();
1711 }
1712 self.super_place(place, context, location);
1713 }
1714
1715 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
1716 self.simplify_operand(operand, location);
1717 self.super_operand(operand, location);
1718 }
1719
1720 fn visit_assign(
1721 &mut self,
1722 lhs: &mut Place<'tcx>,
1723 rvalue: &mut Rvalue<'tcx>,
1724 location: Location,
1725 ) {
1726 self.simplify_place_projection(lhs, location);
1727
1728 let value = self.simplify_rvalue(lhs, rvalue, location);
1729 if let Some(value) = value {
1730 if let Some(const_) = self.try_as_constant(value) {
1731 *rvalue = Rvalue::Use(Operand::Constant(Box::new(const_)));
1732 } else if let Some(place) = self.try_as_place(value, location, false)
1733 && *rvalue != Rvalue::Use(Operand::Move(place))
1734 && *rvalue != Rvalue::Use(Operand::Copy(place))
1735 {
1736 *rvalue = Rvalue::Use(Operand::Copy(place));
1737 self.reused_locals.insert(place.local);
1738 }
1739 }
1740
1741 if lhs.is_indirect() {
1742 self.invalidate_derefs();
1744 }
1745
1746 if let Some(local) = lhs.as_local()
1747 && self.ssa.is_ssa(local)
1748 && let rvalue_ty = rvalue.ty(self.local_decls, self.tcx)
1749 && self.local_decls[local].ty == rvalue_ty
1752 {
1753 let value = value.unwrap_or_else(|| self.new_opaque(rvalue_ty));
1754 self.assign(local, value);
1755 }
1756 }
1757
1758 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
1759 if let Terminator { kind: TerminatorKind::Call { destination, .. }, .. } = terminator {
1760 if let Some(local) = destination.as_local()
1761 && self.ssa.is_ssa(local)
1762 {
1763 let ty = self.local_decls[local].ty;
1764 let opaque = self.new_opaque(ty);
1765 self.assign(local, opaque);
1766 }
1767 }
1768 let safe_to_preserve_derefs = matches!(
1771 terminator.kind,
1772 TerminatorKind::SwitchInt { .. } | TerminatorKind::Goto { .. }
1773 );
1774 if !safe_to_preserve_derefs {
1775 self.invalidate_derefs();
1776 }
1777 self.super_terminator(terminator, location);
1778 }
1779}
1780
1781struct StorageRemover<'tcx> {
1782 tcx: TyCtxt<'tcx>,
1783 reused_locals: DenseBitSet<Local>,
1784}
1785
1786impl<'tcx> MutVisitor<'tcx> for StorageRemover<'tcx> {
1787 fn tcx(&self) -> TyCtxt<'tcx> {
1788 self.tcx
1789 }
1790
1791 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, _: Location) {
1792 if let Operand::Move(place) = *operand
1793 && !place.is_indirect_first_projection()
1794 && self.reused_locals.contains(place.local)
1795 {
1796 *operand = Operand::Copy(place);
1797 }
1798 }
1799
1800 fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
1801 match stmt.kind {
1802 StatementKind::StorageLive(l) | StatementKind::StorageDead(l)
1804 if self.reused_locals.contains(l) =>
1805 {
1806 stmt.make_nop()
1807 }
1808 _ => self.super_statement(stmt, loc),
1809 }
1810 }
1811}