Skip to main content

rustc_mir_transform/
gvn.rs

1//! Global value numbering.
2//!
3//! MIR may contain repeated and/or redundant computations. The objective of this pass is to detect
4//! such redundancies and re-use the already-computed result when possible.
5//!
6//! From those assignments, we construct a mapping `VnIndex -> Vec<(Local, Location)>` of available
7//! values, the locals in which they are stored, and the assignment location.
8//!
9//! We traverse all assignments `x = rvalue` and operands.
10//!
11//! For each SSA one, we compute a symbolic representation of values that are assigned to SSA
12//! locals. This symbolic representation is defined by the `Value` enum. Each produced instance of
13//! `Value` is interned as a `VnIndex`, which allows us to cheaply compute identical values.
14//!
15//! For each non-SSA
16//! one, we compute the `VnIndex` of the rvalue. If this `VnIndex` is associated to a constant, we
17//! replace the rvalue/operand by that constant. Otherwise, if there is an SSA local `y`
18//! associated to this `VnIndex`, and if its definition location strictly dominates the assignment
19//! to `x`, we replace the assignment by `x = y`.
20//!
21//! By opportunity, this pass simplifies some `Rvalue`s based on the accumulated knowledge.
22//!
23//! # Operational semantic
24//!
25//! Operationally, this pass attempts to prove bitwise equality between locals. Given this MIR:
26//! ```ignore (MIR)
27//! _a = some value // has VnIndex i
28//! // some MIR
29//! _b = some other value // also has VnIndex i
30//! ```
31//!
32//! We consider it to be replaceable by:
33//! ```ignore (MIR)
34//! _a = some value // has VnIndex i
35//! // some MIR
36//! _c = some other value // also has VnIndex i
37//! assume(_a bitwise equal to _c) // follows from having the same VnIndex
38//! _b = _a // follows from the `assume`
39//! ```
40//!
41//! Which is simplifiable to:
42//! ```ignore (MIR)
43//! _a = some value // has VnIndex i
44//! // some MIR
45//! _b = _a
46//! ```
47//!
48//! # Handling of references
49//!
50//! We handle references by assigning a different "provenance" index to each Ref/RawPtr rvalue.
51//! This ensure that we do not spuriously merge borrows that should not be merged. For instance:
52//! ```ignore (MIR)
53//! _x = &_a;
54//! _a = 0;
55//! _y = &_a; // cannot be turned into `_y = _x`!
56//! ```
57//!
58//! On top of that, we consider all the derefs of an immutable reference to a freeze type to give
59//! the same value:
60//! ```ignore (MIR)
61//! _a = *_b // _b is &Freeze
62//! _c = *_b // replaced by _c = _a
63//! ```
64//!
65//! # Determinism of constant propagation
66//!
67//! When registering a new `Value`, we attempt to opportunistically evaluate it as a constant.
68//! The evaluated form is inserted in `evaluated` as an `OpTy` or `None` if evaluation failed.
69//!
70//! The difficulty is non-deterministic evaluation of MIR constants. Some `Const` can have
71//! different runtime values each time they are evaluated. This happens with valtrees that
72//! generate a new allocation each time they are used. This is checked by `is_deterministic`.
73//!
74//! Meanwhile, we want to be able to read indirect constants. For instance:
75//! ```
76//! static A: &'static &'static u8 = &&63;
77//! fn foo() -> u8 {
78//!     **A // We want to replace by 63.
79//! }
80//! fn bar() -> u8 {
81//!     b"abc"[1] // We want to replace by 'b'.
82//! }
83//! ```
84//!
85//! The `Value::Constant` variant stores a possibly unevaluated constant. Evaluating that constant
86//! may be non-deterministic. When that happens, we assign a disambiguator to ensure that we do not
87//! merge the constants. See `duplicate_slice` test in `gvn.rs`.
88//!
89//! Conversely, some constants cannot cross function boundaries, which could happen because of
90//! inlining. For instance, constants that contain a fn pointer (`AllocId` pointing to a
91//! `GlobalAlloc::Function`) point to a different symbol in each codegen unit. To avoid this,
92//! when writing constants in MIR, we do not write `Const`s that contain `AllocId`s. This is
93//! checked by `may_have_provenance`. See <https://github.com/rust-lang/rust/issues/128775> for
94//! more information.
95
96use std::borrow::Cow;
97use std::hash::{Hash, Hasher};
98
99use either::Either;
100use itertools::Itertools as _;
101use rustc_abi::{self as abi, BackendRepr, FIRST_VARIANT, FieldIdx, Primitive, Size, VariantIdx};
102use rustc_arena::DroplessArena;
103use rustc_const_eval::const_eval::DummyMachine;
104use rustc_const_eval::interpret::{
105    ImmTy, Immediate, InterpCx, MemPlaceMeta, MemoryKind, OpTy, Projectable, Scalar,
106    intern_const_alloc_for_constprop,
107};
108use rustc_data_structures::fx::FxHasher;
109use rustc_data_structures::graph::dominators::Dominators;
110use rustc_data_structures::hash_table::{Entry, HashTable};
111use rustc_hir::def::DefKind;
112use rustc_index::bit_set::DenseBitSet;
113use rustc_index::{IndexVec, newtype_index};
114use rustc_middle::mir::interpret::{AllocRange, GlobalAlloc};
115use rustc_middle::mir::visit::*;
116use rustc_middle::mir::*;
117use rustc_middle::ty::layout::HasTypingEnv;
118use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
119use rustc_mir_dataflow::{Analysis, ResultsCursor};
120use rustc_span::{DUMMY_SP, bug};
121use smallvec::SmallVec;
122use tracing::{debug, instrument, trace};
123
124use crate::ssa::{MaybeUninitializedLocals, SsaLocals};
125use crate::{PassPolicy, canonicalization};
126
127pub(super) struct GVN;
128
129impl<'tcx> crate::MirPass<'tcx> for GVN {
130    fn policy(&self, ctx: &crate::PassCtx<'_>) -> PassPolicy {
131        PassPolicy::optional(ctx.mir_opt_level() >= 2)
132    }
133
134    #[instrument(level = "trace", skip(self, tcx, body))]
135    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
136        debug!(def_id = ?body.source.def_id());
137
138        let typing_env = body.typing_env(tcx);
139        let ssa = SsaLocals::new(tcx, body, typing_env);
140        let cfg_cache = body.basic_blocks.cfg_cache();
141        let dominators = cfg_cache.dominators(&body.basic_blocks);
142
143        let arena = DroplessArena::default();
144        let mut state =
145            VnState::new(tcx, body, typing_env, &ssa, dominators, &body.local_decls, &arena);
146
147        for local in body.args_iter().filter(|&local| ssa.is_ssa(local)) {
148            let opaque = state.new_argument(body.local_decls[local].ty);
149            state.assign(local, opaque);
150        }
151
152        for &bb in cfg_cache.reverse_postorder(&body.basic_blocks) {
153            let data = &mut body.basic_blocks.as_mut_preserves_cfg()[bb];
154            state.visit_basic_block_data(bb, data);
155        }
156
157        // When emitting storage statements, we want to retain the reused locals' storage statements,
158        // as this enables better optimizations. For each local use location, we mark it for storage removal
159        // only if it might be uninitialized at that point.
160        let storage_to_remove = if tcx.sess.emit_lifetime_markers() {
161            let maybe_uninit = MaybeUninitializedLocals
162                .iterate_to_fixpoint(tcx, body, Some("mir_opt::gvn"))
163                .into_results_cursor(body);
164
165            let mut storage_checker = StorageChecker {
166                reused_locals: &state.reused_locals,
167                storage_to_remove: DenseBitSet::new_empty(body.local_decls.len()),
168                maybe_uninit,
169            };
170
171            for (bb, data) in traversal::reachable(body) {
172                storage_checker.visit_basic_block_data(bb, data);
173            }
174
175            Some(storage_checker.storage_to_remove)
176        } else {
177            None
178        };
179
180        // If None, remove the storage statements of all the reused locals.
181        let storage_to_remove = storage_to_remove.as_ref().unwrap_or(&state.reused_locals);
182        debug!(?storage_to_remove);
183
184        StorageRemover { tcx, reused_locals: &state.reused_locals, storage_to_remove }
185            .visit_body_preserves_cfg(body);
186    }
187}
188
189newtype_index! {
190    /// This represents a `Value` in the symbolic execution.
191    #[debug_format = "_v{}"]
192    struct VnIndex {}
193}
194
195/// Marker type to forbid hashing and comparing opaque values.
196/// This struct should only be constructed by `ValueSet::insert_unique` to ensure we use that
197/// method to create non-unifiable values. It will ICE if used in `ValueSet::insert`.
198#[derive(Copy, Clone, Debug, Eq)]
199struct VnOpaque;
200impl PartialEq for VnOpaque {
201    fn eq(&self, _: &VnOpaque) -> bool {
202        // ICE if we try to compare unique values
203        unreachable!()
204    }
205}
206impl Hash for VnOpaque {
207    fn hash<T: Hasher>(&self, _: &mut T) {
208        // ICE if we try to hash unique values
209        unreachable!()
210    }
211}
212
213#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
214enum AddressKind {
215    Ref(BorrowKind),
216    Address(RawPtrKind),
217}
218
219#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
220enum AddressBase {
221    /// This address is based on this local.
222    Local(Local),
223    /// This address is based on the deref of this pointer.
224    Deref(VnIndex),
225}
226
227#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
228enum Value<'a, 'tcx> {
229    // Root values.
230    /// Used to represent values we know nothing about.
231    Opaque(VnOpaque),
232    /// The value is a argument.
233    Argument(VnOpaque),
234    /// Evaluated or unevaluated constant value.
235    Constant {
236        value: Const<'tcx>,
237        /// Some constants do not have a deterministic value. To avoid merging two instances of the
238        /// same `Const`, we assign them an additional integer index.
239        // `disambiguator` is `None` iff the constant is deterministic.
240        disambiguator: Option<VnOpaque>,
241    },
242
243    // Aggregates.
244    /// An aggregate value, either tuple/closure/struct/enum.
245    /// This does not contain unions, as we cannot reason with the value.
246    Aggregate(VariantIdx, &'a [VnIndex]),
247    /// A union aggregate value.
248    Union(FieldIdx, VnIndex),
249    /// A raw pointer aggregate built from a thin pointer and metadata.
250    RawPtr {
251        /// Thin pointer component. This is field 0 in MIR.
252        pointer: VnIndex,
253        /// Metadata component. This is field 1 in MIR.
254        metadata: VnIndex,
255    },
256    /// This corresponds to a `[value; count]` expression.
257    Repeat(VnIndex, ty::Const<'tcx>),
258    /// The address of a place.
259    Address {
260        base: AddressBase,
261        // We do not use a plain `Place` as we want to be able to reason about indices.
262        // This does not contain any `Deref` projection.
263        projection: &'a [ProjectionElem<VnIndex, Ty<'tcx>>],
264        kind: AddressKind,
265        /// Give each borrow and pointer a different provenance, so we don't merge them.
266        provenance: VnOpaque,
267    },
268
269    // Extractions.
270    /// This is the *value* obtained by projecting another value.
271    Projection(VnIndex, ProjectionElem<VnIndex, ()>),
272    /// Discriminant of the given value.
273    Discriminant(VnIndex),
274
275    // Operations.
276    RuntimeChecks(RuntimeChecks),
277    UnaryOp(UnOp, VnIndex),
278    BinaryOp(BinOp, VnIndex, VnIndex),
279    Cast {
280        kind: CastKind,
281        value: VnIndex,
282    },
283}
284
285/// Stores and deduplicates pairs of `(Value, Ty)` into in `VnIndex` numbered values.
286///
287/// This data structure is mostly a partial reimplementation of `FxIndexMap<VnIndex, (Value, Ty)>`.
288/// We do not use a regular `FxIndexMap` to skip hashing values that are unique by construction,
289/// like opaque values, address with provenance and non-deterministic constants.
290struct ValueSet<'a, 'tcx> {
291    indices: HashTable<VnIndex>,
292    hashes: IndexVec<VnIndex, u64>,
293    values: IndexVec<VnIndex, Value<'a, 'tcx>>,
294    types: IndexVec<VnIndex, Ty<'tcx>>,
295}
296
297impl<'a, 'tcx> ValueSet<'a, 'tcx> {
298    fn new(num_values: usize) -> ValueSet<'a, 'tcx> {
299        ValueSet {
300            indices: HashTable::with_capacity(num_values),
301            hashes: IndexVec::with_capacity(num_values),
302            values: IndexVec::with_capacity(num_values),
303            types: IndexVec::with_capacity(num_values),
304        }
305    }
306
307    /// Insert a `(Value, Ty)` pair without hashing or deduplication.
308    /// This always creates a new `VnIndex`.
309    #[inline]
310    fn insert_unique(
311        &mut self,
312        ty: Ty<'tcx>,
313        value: impl FnOnce(VnOpaque) -> Value<'a, 'tcx>,
314    ) -> VnIndex {
315        let value = value(VnOpaque);
316
317        debug_assert!(match value {
318            Value::Opaque(_) | Value::Argument(_) | Value::Address { .. } => true,
319            Value::Constant { disambiguator, .. } => disambiguator.is_some(),
320            _ => false,
321        });
322
323        let index = self.hashes.push(0);
324        let _index = self.types.push(ty);
325        debug_assert_eq!(index, _index);
326        let _index = self.values.push(value);
327        debug_assert_eq!(index, _index);
328        index
329    }
330
331    /// Insert a `(Value, Ty)` pair to be deduplicated.
332    /// Returns `true` as second tuple field if this value did not exist previously.
333    #[allow(rustc::disallowed_pass_by_ref)] // closures take `&VnIndex`
334    fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> (VnIndex, bool) {
335        debug_assert!(match value {
336            Value::Opaque(_) | Value::Address { .. } => false,
337            Value::Constant { disambiguator, .. } => disambiguator.is_none(),
338            _ => true,
339        });
340
341        let hash: u64 = {
342            let mut h = FxHasher::default();
343            value.hash(&mut h);
344            ty.hash(&mut h);
345            h.finish()
346        };
347
348        let eq = |index: &VnIndex| self.values[*index] == value && self.types[*index] == ty;
349        let hasher = |index: &VnIndex| self.hashes[*index];
350        match self.indices.entry(hash, eq, hasher) {
351            Entry::Occupied(entry) => {
352                let index = *entry.get();
353                (index, false)
354            }
355            Entry::Vacant(entry) => {
356                let index = self.hashes.push(hash);
357                entry.insert(index);
358                let _index = self.values.push(value);
359                debug_assert_eq!(index, _index);
360                let _index = self.types.push(ty);
361                debug_assert_eq!(index, _index);
362                (index, true)
363            }
364        }
365    }
366
367    /// Return the `Value` associated with the given `VnIndex`.
368    #[inline]
369    fn value(&self, index: VnIndex) -> Value<'a, 'tcx> {
370        self.values[index]
371    }
372
373    /// Return the type associated with the given `VnIndex`.
374    #[inline]
375    fn ty(&self, index: VnIndex) -> Ty<'tcx> {
376        self.types[index]
377    }
378}
379
380struct VnState<'body, 'a, 'tcx> {
381    tcx: TyCtxt<'tcx>,
382    ecx: InterpCx<'tcx, DummyMachine>,
383    local_decls: &'body LocalDecls<'tcx>,
384    is_coroutine: bool,
385    /// Value stored in each local.
386    locals: IndexVec<Local, Option<VnIndex>>,
387    /// Locals that are assigned that value.
388    // This vector does not hold all the values of `VnIndex` that we create.
389    rev_locals: IndexVec<VnIndex, SmallVec<[Local; 1]>>,
390    values: ValueSet<'a, 'tcx>,
391    /// Values evaluated as constants if possible.
392    /// - `None` are values not computed yet;
393    /// - `Some(None)` are values for which computation has failed;
394    /// - `Some(Some(op))` are successful computations.
395    evaluated: IndexVec<VnIndex, Option<Option<&'a OpTy<'tcx>>>>,
396    ssa: &'body SsaLocals,
397    dominators: &'a Dominators<BasicBlock>,
398    reused_locals: DenseBitSet<Local>,
399    arena: &'a DroplessArena,
400}
401
402impl<'body, 'a, 'tcx> VnState<'body, 'a, 'tcx> {
403    fn new(
404        tcx: TyCtxt<'tcx>,
405        body: &Body<'tcx>,
406        typing_env: ty::TypingEnv<'tcx>,
407        ssa: &'body SsaLocals,
408        dominators: &'a Dominators<BasicBlock>,
409        local_decls: &'body LocalDecls<'tcx>,
410        arena: &'a DroplessArena,
411    ) -> Self {
412        // Compute a rough estimate of the number of values in the body from the number of
413        // statements. This is meant to reduce the number of allocations, but it's all right if
414        // we miss the exact amount. We estimate based on 2 values per statement (one in LHS and
415        // one in RHS) and 4 values per terminator (for call operands).
416        let num_values =
417            2 * body.basic_blocks.iter().map(|bbdata| bbdata.statements.len()).sum::<usize>()
418                + 4 * body.basic_blocks.len();
419        VnState {
420            tcx,
421            ecx: InterpCx::new(tcx, DUMMY_SP, typing_env, DummyMachine),
422            local_decls,
423            is_coroutine: body.coroutine.is_some(),
424            locals: IndexVec::from_elem(None, local_decls),
425            rev_locals: IndexVec::with_capacity(num_values),
426            values: ValueSet::new(num_values),
427            evaluated: IndexVec::with_capacity(num_values),
428            ssa,
429            dominators,
430            reused_locals: DenseBitSet::new_empty(local_decls.len()),
431            arena,
432        }
433    }
434
435    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
436        self.ecx.typing_env()
437    }
438
439    fn insert_unique(
440        &mut self,
441        ty: Ty<'tcx>,
442        value: impl FnOnce(VnOpaque) -> Value<'a, 'tcx>,
443    ) -> VnIndex {
444        let index = self.values.insert_unique(ty, value);
445        let _index = self.evaluated.push(None);
446        debug_assert_eq!(index, _index);
447        let _index = self.rev_locals.push(SmallVec::new());
448        debug_assert_eq!(index, _index);
449        index
450    }
451
452    #[instrument(level = "trace", skip(self), ret)]
453    fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> VnIndex {
454        let (index, new) = self.values.insert(ty, value);
455        if new {
456            // Grow `evaluated` and `rev_locals` here to amortize the allocations.
457            let _index = self.evaluated.push(None);
458            debug_assert_eq!(index, _index);
459            let _index = self.rev_locals.push(SmallVec::new());
460            debug_assert_eq!(index, _index);
461        }
462        index
463    }
464
465    /// Create a new `Value` for which we have no information at all, except that it is distinct
466    /// from all the others.
467    #[instrument(level = "trace", skip(self), ret)]
468    fn new_opaque(&mut self, ty: Ty<'tcx>) -> VnIndex {
469        let index = self.insert_unique(ty, Value::Opaque);
470        self.evaluated[index] = Some(None);
471        index
472    }
473
474    #[instrument(level = "trace", skip(self), ret)]
475    fn new_argument(&mut self, ty: Ty<'tcx>) -> VnIndex {
476        let index = self.insert_unique(ty, Value::Argument);
477        self.evaluated[index] = Some(None);
478        index
479    }
480
481    /// Create a new `Value::Address` distinct from all the others.
482    #[instrument(level = "trace", skip(self), ret)]
483    fn new_pointer(&mut self, place: Place<'tcx>, kind: AddressKind) -> Option<VnIndex> {
484        let pty = place.ty(self.local_decls, self.tcx).ty;
485        let ty = match kind {
486            AddressKind::Ref(bk) => {
487                Ty::new_ref(self.tcx, self.tcx.lifetimes.re_erased, pty, bk.to_mutbl_lossy())
488            }
489            AddressKind::Address(mutbl) => Ty::new_ptr(self.tcx, pty, mutbl.to_mutbl_lossy()),
490        };
491
492        let mut projection = place.projection.iter();
493        let base = if place.is_indirect_first_projection() {
494            let base = self.locals[place.local]?;
495            // Skip the initial `Deref`.
496            projection.next();
497            AddressBase::Deref(base)
498        } else if self.ssa.is_ssa(place.local) {
499            // Only propagate the pointer of the SSA local.
500            AddressBase::Local(place.local)
501        } else {
502            return None;
503        };
504        // Do not try evaluating inside `Index`, this has been done by `simplify_place_projection`.
505        let projection =
506            projection.map(|proj| proj.try_map(|index| self.locals[index], |ty| ty).ok_or(()));
507        let projection = self.arena.try_alloc_from_iter(projection).ok()?;
508
509        let index = self.insert_unique(ty, |provenance| Value::Address {
510            base,
511            projection,
512            kind,
513            provenance,
514        });
515        Some(index)
516    }
517
518    #[instrument(level = "trace", skip(self), ret)]
519    fn insert_constant(&mut self, value: Const<'tcx>) -> VnIndex {
520        if is_deterministic(value) {
521            // The constant is deterministic, no need to disambiguate.
522            let constant = Value::Constant { value, disambiguator: None };
523            self.insert(value.ty(), constant)
524        } else {
525            // Multiple mentions of this constant will yield different values,
526            // so assign a different `disambiguator` to ensure they do not get the same `VnIndex`.
527            self.insert_unique(value.ty(), |disambiguator| Value::Constant {
528                value,
529                disambiguator: Some(disambiguator),
530            })
531        }
532    }
533
534    #[inline]
535    fn get(&self, index: VnIndex) -> Value<'a, 'tcx> {
536        self.values.value(index)
537    }
538
539    #[inline]
540    fn ty(&self, index: VnIndex) -> Ty<'tcx> {
541        self.values.ty(index)
542    }
543
544    /// Record that `local` is assigned `value`. `local` must be SSA.
545    #[instrument(level = "trace", skip(self))]
546    fn assign(&mut self, local: Local, value: VnIndex) {
547        debug_assert!(self.ssa.is_ssa(local));
548        self.locals[local] = Some(value);
549        self.rev_locals[value].push(local);
550    }
551
552    fn insert_bool(&mut self, flag: bool) -> VnIndex {
553        // Booleans are deterministic.
554        let value = Const::from_bool(self.tcx, flag);
555        debug_assert!(is_deterministic(value));
556        self.insert(self.tcx.types.bool, Value::Constant { value, disambiguator: None })
557    }
558
559    fn insert_scalar(&mut self, ty: Ty<'tcx>, scalar: Scalar) -> VnIndex {
560        // Scalars are deterministic.
561        let value = Const::from_scalar(self.tcx, scalar, ty);
562        debug_assert!(is_deterministic(value));
563        self.insert(ty, Value::Constant { value, disambiguator: None })
564    }
565
566    fn insert_tuple(&mut self, ty: Ty<'tcx>, values: &[VnIndex]) -> VnIndex {
567        self.insert(ty, Value::Aggregate(VariantIdx::ZERO, self.arena.alloc_slice(values)))
568    }
569
570    #[instrument(level = "trace", skip(self), ret)]
571    fn eval_to_const_inner(&mut self, value: VnIndex) -> Option<OpTy<'tcx>> {
572        use Value::*;
573        let ty = self.ty(value);
574        // Avoid computing layouts inside a coroutine, as that can cause cycles.
575        let ty = if !self.is_coroutine || ty.is_scalar() {
576            self.ecx.layout_of(ty).ok()?
577        } else {
578            return None;
579        };
580        let op = match self.get(value) {
581            _ if ty.is_zst() => ImmTy::uninit(ty).into(),
582
583            Opaque(_) | Argument(_) => return None,
584            // Keep runtime check constants as symbolic.
585            RuntimeChecks(..) => return None,
586
587            // In general, evaluating repeat expressions just consumes a lot of memory.
588            // But in the special case that the element is just Immediate::Uninit, we can evaluate
589            // it without extra memory! If we don't propagate uninit values like this, LLVM can get
590            // very confused: https://github.com/rust-lang/rust/issues/139355
591            Repeat(value, _count) => {
592                let value = self.eval_to_const(value)?;
593                if value.is_immediate_uninit() {
594                    ImmTy::uninit(ty).into()
595                } else {
596                    return None;
597                }
598            }
599            Constant { ref value, disambiguator: _ } => {
600                self.ecx.eval_mir_constant(value, DUMMY_SP, None).discard_err()?
601            }
602            Aggregate(variant, ref fields) => {
603                let fields =
604                    fields.iter().map(|&f| self.eval_to_const(f)).collect::<Option<Vec<_>>>()?;
605                let variant = if ty.ty.is_enum() { Some(variant) } else { None };
606                let (BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }) = ty.backend_repr
607                else {
608                    return None;
609                };
610                let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
611                let variant_dest = if let Some(variant) = variant {
612                    self.ecx.project_downcast(&dest, variant).discard_err()?
613                } else {
614                    dest.clone()
615                };
616                for (field_index, op) in fields.into_iter().enumerate() {
617                    let field_dest = self
618                        .ecx
619                        .project_field(&variant_dest, FieldIdx::from_usize(field_index))
620                        .discard_err()?;
621                    self.ecx.copy_op(op, &field_dest).discard_err()?;
622                }
623                self.ecx
624                    .write_discriminant(variant.unwrap_or(FIRST_VARIANT), &dest)
625                    .discard_err()?;
626                self.ecx
627                    .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
628                    .discard_err()?;
629                dest.into()
630            }
631            Union(active_field, field) => {
632                let field = self.eval_to_const(field)?;
633                if field.layout.layout.is_zst() {
634                    ImmTy::from_immediate(Immediate::Uninit, ty).into()
635                } else if matches!(
636                    ty.backend_repr,
637                    BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }
638                ) {
639                    let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
640                    let field_dest = self.ecx.project_field(&dest, active_field).discard_err()?;
641                    self.ecx.copy_op(field, &field_dest).discard_err()?;
642                    self.ecx
643                        .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
644                        .discard_err()?;
645                    dest.into()
646                } else {
647                    return None;
648                }
649            }
650            RawPtr { pointer, metadata } => {
651                let pointer = self.eval_to_const(pointer)?;
652                let metadata = self.eval_to_const(metadata)?;
653
654                // Pointers don't have fields, so don't `project_field` them.
655                let data = self.ecx.read_pointer(pointer).discard_err()?;
656                let meta = if metadata.layout.is_zst() {
657                    MemPlaceMeta::None
658                } else {
659                    MemPlaceMeta::Meta(self.ecx.read_scalar(metadata).discard_err()?)
660                };
661                let ptr_imm = Immediate::new_pointer_with_meta(data, meta, &self.ecx);
662                ImmTy::from_immediate(ptr_imm, ty).into()
663            }
664
665            Projection(base, elem) => {
666                let base = self.eval_to_const(base)?;
667                // `Index` by constants should have been replaced by `ConstantIndex` by
668                // `simplify_place_projection`.
669                let elem = elem.try_map(|_| None, |()| ty.ty)?;
670                self.ecx.project(base, elem).discard_err()?
671            }
672            Address { base, projection, .. } => {
673                debug_assert!(!projection.contains(&ProjectionElem::Deref));
674                let pointer = match base {
675                    AddressBase::Deref(pointer) => self.eval_to_const(pointer)?,
676                    // We have no stack to point to.
677                    AddressBase::Local(_) => return None,
678                };
679                let mut mplace = self.ecx.deref_pointer(pointer).discard_err()?;
680                for elem in projection {
681                    // `Index` by constants should have been replaced by `ConstantIndex` by
682                    // `simplify_place_projection`.
683                    let elem = elem.try_map(|_| None, |ty| ty)?;
684                    mplace = self.ecx.project(&mplace, elem).discard_err()?;
685                }
686                let pointer = mplace.to_ref(&self.ecx);
687                ImmTy::from_immediate(pointer, ty).into()
688            }
689
690            Discriminant(base) => {
691                let base = self.eval_to_const(base)?;
692                let variant = self.ecx.read_discriminant(base).discard_err()?;
693                let discr_value =
694                    self.ecx.discriminant_for_variant(base.layout.ty, variant).discard_err()?;
695                discr_value.into()
696            }
697            UnaryOp(un_op, operand) => {
698                let operand = self.eval_to_const(operand)?;
699                let operand = self.ecx.read_immediate(operand).discard_err()?;
700                let val = self.ecx.unary_op(un_op, &operand).discard_err()?;
701                val.into()
702            }
703            BinaryOp(bin_op, lhs, rhs) => {
704                let lhs = self.eval_to_const(lhs)?;
705                let rhs = self.eval_to_const(rhs)?;
706                let lhs = self.ecx.read_immediate(lhs).discard_err()?;
707                let rhs = self.ecx.read_immediate(rhs).discard_err()?;
708                let val = self.ecx.binary_op(bin_op, &lhs, &rhs).discard_err()?;
709                val.into()
710            }
711            Cast { kind, value } => match kind {
712                CastKind::IntToInt | CastKind::IntToFloat => {
713                    let value = self.eval_to_const(value)?;
714                    let value = self.ecx.read_immediate(value).discard_err()?;
715                    let res = self.ecx.int_to_int_or_float(&value, ty).discard_err()?;
716                    res.into()
717                }
718                CastKind::FloatToFloat | CastKind::FloatToInt => {
719                    let value = self.eval_to_const(value)?;
720                    let value = self.ecx.read_immediate(value).discard_err()?;
721                    let res = self.ecx.float_to_float_or_int(&value, ty).discard_err()?;
722                    res.into()
723                }
724                CastKind::Transmute | CastKind::Subtype => {
725                    let value = self.eval_to_const(value)?;
726                    if value.is_immediate_uninit() {
727                        return Some(ImmTy::uninit(ty).into());
728                    }
729                    // `offset` for immediates generally only supports projections that match the
730                    // type of the immediate. However, as a HACK, we exploit that it can also do
731                    // limited transmutes: it only works between types with the same layout, and
732                    // cannot transmute pointers to integers.
733                    if value.as_mplace_or_imm().is_right() {
734                        let can_transmute = match (value.layout.backend_repr, ty.backend_repr) {
735                            (BackendRepr::Scalar(s1), BackendRepr::Scalar(s2)) => {
736                                s1.size(&self.ecx) == s2.size(&self.ecx)
737                                    && !matches!(s1.primitive(), Primitive::Pointer(..))
738                            }
739                            (
740                                BackendRepr::ScalarPair { a: a1, b: b1, b_offset: b1_offset },
741                                BackendRepr::ScalarPair { a: a2, b: b2, b_offset: b2_offset },
742                            ) => {
743                                a1.size(&self.ecx) == a2.size(&self.ecx)
744                                    && b1.size(&self.ecx) == b2.size(&self.ecx)
745                                    // The first component is always at offset zero, but the offset to the second
746                                    // component needs to match as well for us to be able to transmute.
747                                    && b1_offset == b2_offset
748                                    // None of the inputs may be a pointer.
749                                    && !matches!(a1.primitive(), Primitive::Pointer(..))
750                                    && !matches!(b1.primitive(), Primitive::Pointer(..))
751                            }
752                            _ => false,
753                        };
754                        if !can_transmute {
755                            return None;
756                        }
757                    }
758                    value.offset(Size::ZERO, ty, &self.ecx).discard_err()?
759                }
760                CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _) => {
761                    let src = self.eval_to_const(value)?;
762                    let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
763                    self.ecx.unsize_into(src, ty, &dest).discard_err()?;
764                    self.ecx
765                        .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
766                        .discard_err()?;
767                    dest.into()
768                }
769                CastKind::FnPtrToPtr | CastKind::PtrToPtr => {
770                    let src = self.eval_to_const(value)?;
771                    let src = self.ecx.read_immediate(src).discard_err()?;
772                    let ret = self.ecx.ptr_to_ptr(&src, ty).discard_err()?;
773                    ret.into()
774                }
775                CastKind::PointerCoercion(ty::adjustment::PointerCoercion::UnsafeFnPointer, _) => {
776                    let src = self.eval_to_const(value)?;
777                    let src = self.ecx.read_immediate(src).discard_err()?;
778                    ImmTy::from_immediate(*src, ty).into()
779                }
780                _ => return None,
781            },
782        };
783        Some(op)
784    }
785
786    fn eval_to_const(&mut self, index: VnIndex) -> Option<&'a OpTy<'tcx>> {
787        if let Some(op) = self.evaluated[index] {
788            return op;
789        }
790        let op = self.eval_to_const_inner(index);
791        self.evaluated[index] = Some(self.arena.alloc(op).as_ref());
792        self.evaluated[index].unwrap()
793    }
794
795    /// Represent the *value* we obtain by dereferencing an `Address` value.
796    #[instrument(level = "trace", skip(self), ret)]
797    fn dereference_address(
798        &mut self,
799        base: AddressBase,
800        projection: &[ProjectionElem<VnIndex, Ty<'tcx>>],
801    ) -> Option<VnIndex> {
802        let (mut place_ty, mut value) = match base {
803            // The base is a local, so we take the local's value and project from it.
804            AddressBase::Local(local) => {
805                let local = self.locals[local]?;
806                let place_ty = PlaceTy::from_ty(self.ty(local));
807                (place_ty, local)
808            }
809            // The base is a pointer's deref, so we introduce the implicit deref.
810            AddressBase::Deref(reborrow) => {
811                let place_ty = PlaceTy::from_ty(self.ty(reborrow));
812                self.project(place_ty, reborrow, ProjectionElem::Deref)?
813            }
814        };
815        for &proj in projection {
816            (place_ty, value) = self.project(place_ty, value, proj)?;
817        }
818        Some(value)
819    }
820
821    #[instrument(level = "trace", skip(self), ret)]
822    fn project(
823        &mut self,
824        place_ty: PlaceTy<'tcx>,
825        value: VnIndex,
826        proj: ProjectionElem<VnIndex, Ty<'tcx>>,
827    ) -> Option<(PlaceTy<'tcx>, VnIndex)> {
828        let projection_ty = place_ty.projection_ty(self.tcx, proj);
829        let proj = match proj {
830            ProjectionElem::Deref => {
831                if let Some(Mutability::Not) = place_ty.ty.ref_mutability()
832                    && projection_ty.ty.is_freeze(self.tcx, self.typing_env())
833                {
834                    if let Value::Address { base, projection, .. } = self.get(value)
835                        && let Some(value) = self.dereference_address(base, projection)
836                    {
837                        return Some((projection_ty, value));
838                    }
839                    // We cannot unify two references produced by dereferencing the same nested reference,
840                    // because they may have different lifetimes.
841                    // ```
842                    // let b: &T = *a;
843                    // ... `a` is allowed to be modified. `c` and `b` have different borrowing lifetime.
844                    // Unifying them will extend the lifetime of `b`.
845                    // let c: &T = *a;
846                    // ```
847                    // Furthermore, unifying them can also violate Stacked Borrows or Tree Borrows.
848                    // We can only unify all `*b` and `*c` separately
849                    // because nested shared references are not read-only.
850                    // For more, see <https://github.com/rust-lang/rust/issues/155884> and
851                    // <https://github.com/rust-lang/rust/issues/130853>.
852                    if self.ty_may_have_ref(projection_ty.ty) {
853                        return None;
854                    }
855
856                    // An immutable borrow `_x` always points to the same value for the
857                    // lifetime of the borrow, so we can merge all instances of `*_x`.
858                    let deref = self
859                        .insert(projection_ty.ty, Value::Projection(value, ProjectionElem::Deref));
860                    return Some((projection_ty, deref));
861                } else {
862                    return None;
863                }
864            }
865            ProjectionElem::PhantomDeref => bug!("PhantomDeref in GVN"),
866            ProjectionElem::Downcast(name, index) => ProjectionElem::Downcast(name, index),
867            ProjectionElem::Field(f, _) => match self.get(value) {
868                Value::Aggregate(_, fields) => return Some((projection_ty, fields[f.as_usize()])),
869                Value::Union(active, field) if active == f => return Some((projection_ty, field)),
870                Value::Projection(outer_value, ProjectionElem::Downcast(_, read_variant))
871                    if let Value::Aggregate(written_variant, fields) = self.get(outer_value)
872                    // This pass is not aware of control-flow, so we do not know whether the
873                    // replacement we are doing is actually reachable. We could be in any arm of
874                    // ```
875                    // match Some(x) {
876                    //     Some(y) => /* stuff */,
877                    //     None => /* other */,
878                    // }
879                    // ```
880                    //
881                    // In surface rust, the current statement would be unreachable.
882                    //
883                    // However, from the reference chapter on enums and RFC 2195,
884                    // accessing the wrong variant is not UB if the enum has repr.
885                    // So it's not impossible for a series of MIR opts to generate
886                    // a downcast to an inactive variant.
887                    && written_variant == read_variant =>
888                {
889                    return Some((projection_ty, fields[f.as_usize()]));
890                }
891                _ => ProjectionElem::Field(f, ()),
892            },
893            ProjectionElem::Index(idx) => {
894                if let Value::Repeat(inner, _) = self.get(value) {
895                    return Some((projection_ty, inner));
896                }
897                ProjectionElem::Index(idx)
898            }
899            ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
900                match self.get(value) {
901                    Value::Repeat(inner, _) => {
902                        return Some((projection_ty, inner));
903                    }
904                    Value::Aggregate(_, operands) => {
905                        let offset = if from_end {
906                            operands.len() - offset as usize
907                        } else {
908                            offset as usize
909                        };
910                        let value = operands.get(offset).copied()?;
911                        return Some((projection_ty, value));
912                    }
913                    _ => {}
914                };
915                ProjectionElem::ConstantIndex { offset, min_length, from_end }
916            }
917            ProjectionElem::Subslice { from, to, from_end } => {
918                ProjectionElem::Subslice { from, to, from_end }
919            }
920            ProjectionElem::OpaqueCast(_) => ProjectionElem::OpaqueCast(()),
921            ProjectionElem::UnwrapUnsafeBinder(_) => ProjectionElem::UnwrapUnsafeBinder(()),
922        };
923
924        let value = self.insert(projection_ty.ty, Value::Projection(value, proj));
925        Some((projection_ty, value))
926    }
927
928    /// Simplify the projection chain if we know better.
929    #[instrument(level = "trace", skip(self))]
930    fn simplify_place_projection(&mut self, place: &mut Place<'tcx>, location: Location) {
931        // If the projection is indirect, we treat the local as a value, so can replace it with
932        // another local.
933        if place.is_indirect_first_projection()
934            && let Some(base) = self.locals[place.local]
935            && let Some(new_local) = self.try_as_local(base, location)
936            && place.local != new_local
937        {
938            place.local = new_local;
939            self.reused_locals.insert(new_local);
940        }
941
942        let mut projection = Cow::Borrowed(&place.projection[..]);
943
944        for i in 0..projection.len() {
945            let elem = projection[i];
946            if let ProjectionElem::Index(idx_local) = elem
947                && let Some(idx) = self.locals[idx_local]
948            {
949                if let Some(offset) = self.eval_to_const(idx)
950                    && let Some(offset) = self.ecx.read_target_usize(offset).discard_err()
951                    && let Some(min_length) = offset.checked_add(1)
952                {
953                    projection.to_mut()[i] =
954                        ProjectionElem::ConstantIndex { offset, min_length, from_end: false };
955                } else if let Some(new_idx_local) = self.try_as_local(idx, location)
956                    && idx_local != new_idx_local
957                {
958                    projection.to_mut()[i] = ProjectionElem::Index(new_idx_local);
959                    self.reused_locals.insert(new_idx_local);
960                }
961            }
962        }
963
964        if Cow::is_owned(&projection) {
965            place.projection = self.tcx.mk_place_elems(&projection);
966        }
967
968        trace!(?place);
969    }
970
971    /// Represent the *value* which would be read from `place`. If we succeed, return it.
972    /// If we fail, return a `PlaceRef` that contains the same value.
973    #[instrument(level = "trace", skip(self), ret)]
974    fn compute_place_value(
975        &mut self,
976        place: Place<'tcx>,
977        location: Location,
978    ) -> Result<VnIndex, PlaceRef<'tcx>> {
979        // Invariant: `place` and `place_ref` point to the same value, even if they point to
980        // different memory locations.
981        let mut place_ref = place.as_ref();
982
983        // Invariant: `value` holds the value up-to the `index`th projection excluded.
984        let Some(mut value) = self.locals[place.local] else { return Err(place_ref) };
985        // Invariant: `value` has type `place_ty`, with optional downcast variant if needed.
986        let mut place_ty = PlaceTy::from_ty(self.local_decls[place.local].ty);
987        for (index, proj) in place.projection.iter().enumerate() {
988            if let Some(local) = self.try_as_local(value, location) {
989                // Both `local` and `Place { local: place.local, projection: projection[..index] }`
990                // hold the same value. Therefore, following place holds the value in the original
991                // `place`.
992                place_ref = PlaceRef { local, projection: &place.projection[index..] };
993            }
994
995            let Some(proj) = proj.try_map(|value| self.locals[value], |ty| ty) else {
996                return Err(place_ref);
997            };
998            let Some(ty_and_value) = self.project(place_ty, value, proj) else {
999                return Err(place_ref);
1000            };
1001            (place_ty, value) = ty_and_value;
1002        }
1003
1004        Ok(value)
1005    }
1006
1007    /// Represent the *value* which would be read from `place`, and point `place` to a preexisting
1008    /// place with the same value (if that already exists).
1009    #[instrument(level = "trace", skip(self), ret)]
1010    fn simplify_place_value(
1011        &mut self,
1012        place: &mut Place<'tcx>,
1013        location: Location,
1014    ) -> Option<VnIndex> {
1015        self.simplify_place_projection(place, location);
1016
1017        match self.compute_place_value(*place, location) {
1018            Ok(value) => {
1019                if let Some(new_place) = self.try_as_place(value, location, true)
1020                    && (new_place.local != place.local
1021                        || new_place.projection.len() < place.projection.len())
1022                {
1023                    *place = new_place;
1024                    self.reused_locals.insert(new_place.local);
1025                }
1026                Some(value)
1027            }
1028            Err(place_ref) => {
1029                if place_ref.local != place.local
1030                    || place_ref.projection.len() < place.projection.len()
1031                {
1032                    // By the invariant on `place_ref`.
1033                    *place = place_ref.project_deeper(&[], self.tcx);
1034                    self.reused_locals.insert(place_ref.local);
1035                }
1036                None
1037            }
1038        }
1039    }
1040
1041    #[instrument(level = "trace", skip(self), ret)]
1042    fn simplify_operand(
1043        &mut self,
1044        operand: &mut Operand<'tcx>,
1045        location: Location,
1046    ) -> Option<VnIndex> {
1047        let value = match *operand {
1048            Operand::RuntimeChecks(c) => self.insert(self.tcx.types.bool, Value::RuntimeChecks(c)),
1049            Operand::Constant(ref constant) => self.insert_constant(constant.const_),
1050            Operand::Copy(ref mut place) | Operand::Move(ref mut place) => {
1051                self.simplify_place_value(place, location)?
1052            }
1053        };
1054        if let Some(const_) = self.try_as_constant(value) {
1055            *operand = Operand::Constant(Box::new(const_));
1056        } else if let Value::RuntimeChecks(c) = self.get(value) {
1057            *operand = Operand::RuntimeChecks(c);
1058        }
1059        Some(value)
1060    }
1061
1062    #[instrument(level = "trace", skip(self), ret)]
1063    fn simplify_rvalue(
1064        &mut self,
1065        rvalue: &mut Rvalue<'tcx>,
1066        location: Location,
1067    ) -> Option<VnIndex> {
1068        let value = match *rvalue {
1069            // Forward values.
1070            Rvalue::Use(ref mut operand, _) => return self.simplify_operand(operand, location),
1071
1072            // Roots.
1073            Rvalue::Repeat(ref mut op, amount) => {
1074                let op = self.simplify_operand(op, location)?;
1075                Value::Repeat(op, amount)
1076            }
1077            Rvalue::Aggregate(..) => return self.simplify_aggregate(rvalue, location),
1078            Rvalue::Ref(_, borrow_kind, ref mut place) => {
1079                self.simplify_place_projection(place, location);
1080                return self.new_pointer(*place, AddressKind::Ref(borrow_kind));
1081            }
1082            Rvalue::Reborrow(_, mutbl, place) => {
1083                if mutbl == Mutability::Mut {
1084                    // Note: this is adapted from simplify_aggregate.
1085                    let mut operand = Operand::Copy(place);
1086                    let val = self.simplify_operand(&mut operand, location);
1087                    // FIXME(reborrow): Is it correct to make these retagging assignments?
1088                    *rvalue = Rvalue::Use(Operand::Copy(place), WithRetag::Yes);
1089                    return val;
1090                } else {
1091                    // FIXME(reborrow): CoerceShared should perform effectively a copy followed by a
1092                    // transmute, or possibly something more complicated in the future. For now we
1093                    // leave this unoptimised.
1094                    return None;
1095                }
1096            }
1097            Rvalue::RawPtr(mutbl, ref mut place) => {
1098                self.simplify_place_projection(place, location);
1099                return self.new_pointer(*place, AddressKind::Address(mutbl));
1100            }
1101            Rvalue::WrapUnsafeBinder(ref mut op, _) => {
1102                let value = self.simplify_operand(op, location)?;
1103                Value::Cast { kind: CastKind::Transmute, value }
1104            }
1105
1106            // Operations.
1107            Rvalue::Cast(ref mut kind, ref mut value, to) => {
1108                return self.simplify_cast(kind, value, to, location);
1109            }
1110            Rvalue::BinaryOp(op, (ref mut lhs, ref mut rhs)) => {
1111                return self.simplify_binary(op, lhs, rhs, location);
1112            }
1113            Rvalue::UnaryOp(op, ref mut arg_op) => {
1114                return self.simplify_unary(op, arg_op, location);
1115            }
1116            Rvalue::Discriminant(ref mut place) => {
1117                let place = self.simplify_place_value(place, location)?;
1118                if let Some(discr) = self.simplify_discriminant(place) {
1119                    return Some(discr);
1120                }
1121                Value::Discriminant(place)
1122            }
1123
1124            // Unsupported values.
1125            Rvalue::ThreadLocalRef(..) => return None,
1126            Rvalue::CopyForDeref(_) => {
1127                bug!("forbidden in runtime MIR: {rvalue:?}")
1128            }
1129        };
1130        let ty = rvalue.ty(self.local_decls, self.tcx);
1131        Some(self.insert(ty, value))
1132    }
1133
1134    fn simplify_discriminant(&mut self, place: VnIndex) -> Option<VnIndex> {
1135        let enum_ty = self.ty(place);
1136        if enum_ty.is_enum()
1137            && let Value::Aggregate(variant, _) = self.get(place)
1138        {
1139            let discr = self.ecx.discriminant_for_variant(enum_ty, variant).discard_err()?;
1140            return Some(self.insert_scalar(discr.layout.ty, discr.to_scalar()));
1141        }
1142
1143        None
1144    }
1145
1146    fn try_as_place_elem(
1147        &mut self,
1148        ty: Ty<'tcx>,
1149        proj: ProjectionElem<VnIndex, ()>,
1150        loc: Location,
1151    ) -> Option<PlaceElem<'tcx>> {
1152        proj.try_map(
1153            |value| {
1154                let local = self.try_as_local(value, loc)?;
1155                self.reused_locals.insert(local);
1156                Some(local)
1157            },
1158            |()| ty,
1159        )
1160    }
1161
1162    fn simplify_aggregate_to_copy(
1163        &mut self,
1164        ty: Ty<'tcx>,
1165        variant_index: VariantIdx,
1166        fields: &[VnIndex],
1167    ) -> Option<VnIndex> {
1168        let Some(&first_field) = fields.first() else { return None };
1169        let Value::Projection(copy_from_value, _) = self.get(first_field) else { return None };
1170
1171        // All fields must correspond one-to-one and come from the same aggregate value.
1172        if fields.iter().enumerate().any(|(index, &v)| {
1173            if let Value::Projection(pointer, ProjectionElem::Field(from_index, _)) = self.get(v)
1174                && copy_from_value == pointer
1175                && from_index.index() == index
1176            {
1177                return false;
1178            }
1179            true
1180        }) {
1181            return None;
1182        }
1183
1184        let mut copy_from_local_value = copy_from_value;
1185        if let Value::Projection(pointer, proj) = self.get(copy_from_value)
1186            && let ProjectionElem::Downcast(_, read_variant) = proj
1187        {
1188            if variant_index == read_variant {
1189                // When copying a variant, there is no need to downcast.
1190                copy_from_local_value = pointer;
1191            } else {
1192                // The copied variant must be identical.
1193                return None;
1194            }
1195        }
1196
1197        // Both must be variants of the same type.
1198        if self.ty(copy_from_local_value) == ty { Some(copy_from_local_value) } else { None }
1199    }
1200
1201    fn simplify_aggregate(
1202        &mut self,
1203        rvalue: &mut Rvalue<'tcx>,
1204        location: Location,
1205    ) -> Option<VnIndex> {
1206        let tcx = self.tcx;
1207        let ty = rvalue.ty(self.local_decls, tcx);
1208
1209        let Rvalue::Aggregate(ref kind, ref mut field_ops) = *rvalue else { bug!() };
1210
1211        if field_ops.is_empty() {
1212            let is_zst = match *kind {
1213                AggregateKind::Array(..)
1214                | AggregateKind::Tuple
1215                | AggregateKind::Closure(..)
1216                | AggregateKind::CoroutineClosure(..) => true,
1217                // Only enums can be non-ZST.
1218                AggregateKind::Adt(did, ..) => tcx.def_kind(did) != DefKind::Enum,
1219                // Coroutines are never ZST, as they at least contain the implicit states.
1220                AggregateKind::Coroutine(..) => false,
1221                AggregateKind::RawPtr(..) => bug!("MIR for RawPtr aggregate must have 2 fields"),
1222            };
1223
1224            if is_zst {
1225                return Some(self.insert_constant(Const::zero_sized(ty)));
1226            }
1227        }
1228
1229        let fields = self.arena.alloc_from_iter(field_ops.iter_mut().map(|op| {
1230            self.simplify_operand(op, location)
1231                .unwrap_or_else(|| self.new_opaque(op.ty(self.local_decls, self.tcx)))
1232        }));
1233
1234        let variant_index = match *kind {
1235            AggregateKind::Array(..) | AggregateKind::Tuple => {
1236                assert!(!field_ops.is_empty());
1237                FIRST_VARIANT
1238            }
1239            AggregateKind::Closure(..)
1240            | AggregateKind::CoroutineClosure(..)
1241            | AggregateKind::Coroutine(..) => FIRST_VARIANT,
1242            AggregateKind::Adt(_, variant_index, _, _, None) => variant_index,
1243            // Do not track unions.
1244            AggregateKind::Adt(_, _, _, _, Some(active_field)) => {
1245                let field = *fields.first()?;
1246                return Some(self.insert(ty, Value::Union(active_field, field)));
1247            }
1248            AggregateKind::RawPtr(..) => {
1249                assert_eq!(field_ops.len(), 2);
1250                let [mut pointer, metadata] = fields.try_into().unwrap();
1251
1252                // Any thin pointer of matching mutability is fine as the data pointer.
1253                let mut was_updated = false;
1254                while let Value::Cast { kind: CastKind::PtrToPtr, value: cast_value } =
1255                    self.get(pointer)
1256                    && let ty::RawPtr(from_pointee_ty, from_mtbl) = self.ty(cast_value).kind()
1257                    && let ty::RawPtr(_, output_mtbl) = ty.kind()
1258                    && from_mtbl == output_mtbl
1259                    && from_pointee_ty.is_sized(self.tcx, self.typing_env())
1260                {
1261                    pointer = cast_value;
1262                    was_updated = true;
1263                }
1264
1265                if was_updated && let Some(op) = self.try_as_operand(pointer, location) {
1266                    field_ops[FieldIdx::ZERO] = op;
1267                }
1268
1269                return Some(self.insert(ty, Value::RawPtr { pointer, metadata }));
1270            }
1271        };
1272
1273        if ty.is_array()
1274            && fields.len() > 4
1275            && let Ok(&first) = fields.iter().all_equal_value()
1276        {
1277            let len = ty::Const::from_target_usize(self.tcx, fields.len().try_into().unwrap());
1278            if let Some(op) = self.try_as_operand(first, location) {
1279                *rvalue = Rvalue::Repeat(op, len);
1280            }
1281            return Some(self.insert(ty, Value::Repeat(first, len)));
1282        }
1283
1284        if let Some(value) = self.simplify_aggregate_to_copy(ty, variant_index, &fields) {
1285            if let Some(place) = self.try_as_place(value, location, true) {
1286                self.reused_locals.insert(place.local);
1287                // FIXME: Is it correct to make these retagging assignments?
1288                *rvalue = Rvalue::Use(Operand::Copy(place), WithRetag::Yes);
1289            }
1290            return Some(value);
1291        }
1292
1293        Some(self.insert(ty, Value::Aggregate(variant_index, fields)))
1294    }
1295
1296    #[instrument(level = "trace", skip(self), ret)]
1297    fn simplify_unary(
1298        &mut self,
1299        op: UnOp,
1300        arg_op: &mut Operand<'tcx>,
1301        location: Location,
1302    ) -> Option<VnIndex> {
1303        let mut arg_index = self.simplify_operand(arg_op, location)?;
1304        let arg_ty = self.ty(arg_index);
1305        let ret_ty = op.ty(self.tcx, arg_ty);
1306
1307        // PtrMetadata doesn't care about *const vs *mut vs & vs &mut,
1308        // so start by removing those distinctions so we can update the `Operand`
1309        if op == UnOp::PtrMetadata {
1310            let mut was_updated = false;
1311            loop {
1312                arg_index = match self.get(arg_index) {
1313                    // Pointer casts that preserve metadata, such as
1314                    // `*const [i32]` <-> `*mut [i32]` <-> `*mut [f32]`.
1315                    // It's critical that this not eliminate cases like
1316                    // `*const [T]` -> `*const T` which remove metadata.
1317                    // We run on potentially-generic MIR, though, so unlike codegen
1318                    // we can't always know exactly what the metadata are.
1319                    // To allow things like `*mut (?A, ?T)` <-> `*mut (?B, ?T)`,
1320                    // it's fine to get a projection as the type.
1321                    Value::Cast { kind: CastKind::PtrToPtr, value: inner }
1322                        if self.pointers_have_same_metadata(self.ty(inner), arg_ty) =>
1323                    {
1324                        inner
1325                    }
1326
1327                    // We have an unsizing cast, which assigns the length to wide pointer metadata.
1328                    Value::Cast {
1329                        kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1330                        value: from,
1331                    } if let Some(from) = self.ty(from).builtin_deref(true)
1332                        && let ty::Array(_, len) = from.kind()
1333                        && let Some(to) = self.ty(arg_index).builtin_deref(true)
1334                        && let ty::Slice(..) = to.kind() =>
1335                    {
1336                        return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1337                    }
1338
1339                    // `&mut *p`, `&raw *p`, etc don't change metadata.
1340                    Value::Address { base: AddressBase::Deref(reborrowed), projection, .. }
1341                        if projection.is_empty() =>
1342                    {
1343                        reborrowed
1344                    }
1345
1346                    _ => break,
1347                };
1348                was_updated = true;
1349            }
1350
1351            if was_updated && let Some(op) = self.try_as_operand(arg_index, location) {
1352                *arg_op = op;
1353            }
1354        }
1355
1356        let value = match (op, self.get(arg_index)) {
1357            (UnOp::Not, Value::UnaryOp(UnOp::Not, inner)) => return Some(inner),
1358            (UnOp::Neg, Value::UnaryOp(UnOp::Neg, inner)) => return Some(inner),
1359            (UnOp::Not, Value::BinaryOp(BinOp::Eq, lhs, rhs)) => {
1360                Value::BinaryOp(BinOp::Ne, lhs, rhs)
1361            }
1362            (UnOp::Not, Value::BinaryOp(BinOp::Ne, lhs, rhs)) => {
1363                Value::BinaryOp(BinOp::Eq, lhs, rhs)
1364            }
1365            (UnOp::PtrMetadata, Value::RawPtr { metadata, .. }) => return Some(metadata),
1366            // We have an unsizing cast, which assigns the length to wide pointer metadata.
1367            (
1368                UnOp::PtrMetadata,
1369                Value::Cast {
1370                    kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1371                    value: inner,
1372                },
1373            ) if let ty::Slice(..) = arg_ty.builtin_deref(true).unwrap().kind()
1374                && let ty::Array(_, len) = self.ty(inner).builtin_deref(true).unwrap().kind() =>
1375            {
1376                return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1377            }
1378            _ => Value::UnaryOp(op, arg_index),
1379        };
1380        Some(self.insert(ret_ty, value))
1381    }
1382
1383    #[instrument(level = "trace", skip(self), ret)]
1384    fn simplify_binary(
1385        &mut self,
1386        op: BinOp,
1387        lhs_operand: &mut Operand<'tcx>,
1388        rhs_operand: &mut Operand<'tcx>,
1389        location: Location,
1390    ) -> Option<VnIndex> {
1391        let lhs = self.simplify_operand(lhs_operand, location);
1392        let rhs = self.simplify_operand(rhs_operand, location);
1393
1394        let (lhs, rhs) = if canonicalization::canonicalize_binary_operands(
1395            self.tcx,
1396            self.local_decls,
1397            op,
1398            lhs_operand,
1399            rhs_operand,
1400        ) {
1401            (rhs, lhs)
1402        } else {
1403            (lhs, rhs)
1404        };
1405
1406        // Only short-circuit options after we called `simplify_operand`
1407        // on both operands for side effect.
1408        let mut lhs = lhs?;
1409        let mut rhs = rhs?;
1410
1411        let lhs_ty = self.ty(lhs);
1412
1413        // If we're comparing pointers, remove `PtrToPtr` casts if the from
1414        // types of both casts and the metadata all match.
1415        if let BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge = op
1416            && lhs_ty.is_any_ptr()
1417            && let Value::Cast { kind: CastKind::PtrToPtr, value: lhs_value } = self.get(lhs)
1418            && let Value::Cast { kind: CastKind::PtrToPtr, value: rhs_value } = self.get(rhs)
1419            && let lhs_from = self.ty(lhs_value)
1420            && lhs_from == self.ty(rhs_value)
1421            && self.pointers_have_same_metadata(lhs_from, lhs_ty)
1422        {
1423            lhs = lhs_value;
1424            rhs = rhs_value;
1425            if let Some(lhs_op) = self.try_as_operand(lhs, location)
1426                && let Some(rhs_op) = self.try_as_operand(rhs, location)
1427            {
1428                *lhs_operand = lhs_op;
1429                *rhs_operand = rhs_op;
1430            }
1431        }
1432
1433        if let Some(value) = self.simplify_binary_inner(op, lhs_ty, lhs, rhs) {
1434            return Some(value);
1435        }
1436        let ty = op.ty(self.tcx, lhs_ty, self.ty(rhs));
1437        let value = Value::BinaryOp(op, lhs, rhs);
1438        Some(self.insert(ty, value))
1439    }
1440
1441    fn simplify_binary_inner(
1442        &mut self,
1443        op: BinOp,
1444        lhs_ty: Ty<'tcx>,
1445        lhs: VnIndex,
1446        rhs: VnIndex,
1447    ) -> Option<VnIndex> {
1448        // Floats are weird enough that none of the logic below applies.
1449        let reasonable_ty =
1450            lhs_ty.is_integral() || lhs_ty.is_bool() || lhs_ty.is_char() || lhs_ty.is_any_ptr();
1451        if !reasonable_ty {
1452            return None;
1453        }
1454
1455        let layout = self.ecx.layout_of(lhs_ty).ok()?;
1456
1457        let mut as_bits = |value: VnIndex| {
1458            let constant = self.eval_to_const(value)?;
1459            if layout.backend_repr.is_scalar() {
1460                let scalar = self.ecx.read_scalar(constant).discard_err()?;
1461                scalar.to_bits(constant.layout.size).discard_err()
1462            } else {
1463                // `constant` is a wide pointer. Do not evaluate to bits.
1464                None
1465            }
1466        };
1467
1468        // Represent the values as `Left(bits)` or `Right(VnIndex)`.
1469        use Either::{Left, Right};
1470        let a = as_bits(lhs).map_or(Right(lhs), Left);
1471        let b = as_bits(rhs).map_or(Right(rhs), Left);
1472
1473        let result = match (op, a, b) {
1474            // Neutral elements.
1475            (
1476                BinOp::Add
1477                | BinOp::AddWithOverflow
1478                | BinOp::AddUnchecked
1479                | BinOp::BitOr
1480                | BinOp::BitXor,
1481                Left(0),
1482                Right(p),
1483            )
1484            | (
1485                BinOp::Add
1486                | BinOp::AddWithOverflow
1487                | BinOp::AddUnchecked
1488                | BinOp::BitOr
1489                | BinOp::BitXor
1490                | BinOp::Sub
1491                | BinOp::SubWithOverflow
1492                | BinOp::SubUnchecked
1493                | BinOp::Offset
1494                | BinOp::Shl
1495                | BinOp::Shr,
1496                Right(p),
1497                Left(0),
1498            )
1499            | (BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked, Left(1), Right(p))
1500            | (
1501                BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::Div,
1502                Right(p),
1503                Left(1),
1504            ) => p,
1505            // Attempt to simplify `x & ALL_ONES` to `x`, with `ALL_ONES` depending on type size.
1506            (BinOp::BitAnd, Right(p), Left(ones)) | (BinOp::BitAnd, Left(ones), Right(p))
1507                if ones == layout.size.truncate(u128::MAX)
1508                    || (layout.ty.is_bool() && ones == 1) =>
1509            {
1510                p
1511            }
1512            // Absorbing elements.
1513            (
1514                BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::BitAnd,
1515                _,
1516                Left(0),
1517            )
1518            | (BinOp::Rem, _, Left(1))
1519            | (
1520                BinOp::Mul
1521                | BinOp::MulWithOverflow
1522                | BinOp::MulUnchecked
1523                | BinOp::Div
1524                | BinOp::Rem
1525                | BinOp::BitAnd
1526                | BinOp::Shl
1527                | BinOp::Shr,
1528                Left(0),
1529                _,
1530            ) => self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size)),
1531            // Attempt to simplify `x | ALL_ONES` to `ALL_ONES`.
1532            (BinOp::BitOr, _, Left(ones)) | (BinOp::BitOr, Left(ones), _)
1533                if ones == layout.size.truncate(u128::MAX)
1534                    || (layout.ty.is_bool() && ones == 1) =>
1535            {
1536                self.insert_scalar(lhs_ty, Scalar::from_uint(ones, layout.size))
1537            }
1538            // Sub/Xor with itself.
1539            (BinOp::Sub | BinOp::SubWithOverflow | BinOp::SubUnchecked | BinOp::BitXor, a, b)
1540                if a == b =>
1541            {
1542                self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size))
1543            }
1544            // Comparison:
1545            // - if both operands can be computed as bits, just compare the bits;
1546            // - if we proved that both operands have the same value, we can insert true/false;
1547            // - otherwise, do nothing, as we do not try to prove inequality.
1548            (BinOp::Eq, Left(a), Left(b)) => self.insert_bool(a == b),
1549            (BinOp::Eq, a, b) if a == b => self.insert_bool(true),
1550            (BinOp::Ne, Left(a), Left(b)) => self.insert_bool(a != b),
1551            (BinOp::Ne, a, b) if a == b => self.insert_bool(false),
1552            _ => return None,
1553        };
1554
1555        if op.is_overflowing() {
1556            let ty = Ty::new_tup(self.tcx, &[self.ty(result), self.tcx.types.bool]);
1557            let false_val = self.insert_bool(false);
1558            Some(self.insert_tuple(ty, &[result, false_val]))
1559        } else {
1560            Some(result)
1561        }
1562    }
1563
1564    fn simplify_cast(
1565        &mut self,
1566        initial_kind: &mut CastKind,
1567        initial_operand: &mut Operand<'tcx>,
1568        to: Ty<'tcx>,
1569        location: Location,
1570    ) -> Option<VnIndex> {
1571        use CastKind::*;
1572        use rustc_middle::ty::adjustment::PointerCoercion::*;
1573
1574        let mut kind = *initial_kind;
1575        let mut value = self.simplify_operand(initial_operand, location)?;
1576        let mut from = self.ty(value);
1577        if from == to {
1578            return Some(value);
1579        }
1580
1581        if let CastKind::PointerCoercion(ReifyFnPointer(_) | ClosureFnPointer(_), _) = kind {
1582            // Each reification of a generic fn may get a different pointer.
1583            // Do not try to merge them.
1584            return Some(self.new_opaque(to));
1585        }
1586
1587        let mut was_ever_updated = false;
1588        loop {
1589            let mut was_updated_this_iteration = false;
1590
1591            // Transmuting between raw pointers is just a pointer cast so long as
1592            // they have the same metadata type (like `*const i32` <=> `*mut u64`
1593            // or `*mut [i32]` <=> `*const [u64]`), including the common special
1594            // case of `*const T` <=> `*mut T`.
1595            if let Transmute = kind
1596                && from.is_raw_ptr()
1597                && to.is_raw_ptr()
1598                && self.pointers_have_same_metadata(from, to)
1599            {
1600                kind = PtrToPtr;
1601                was_updated_this_iteration = true;
1602            }
1603
1604            // If a cast just casts away the metadata again, then we can get it by
1605            // casting the original thin pointer passed to `from_raw_parts`
1606            if let PtrToPtr = kind
1607                && let Value::RawPtr { pointer, .. } = self.get(value)
1608                && let ty::RawPtr(to_pointee, _) = to.kind()
1609                && to_pointee.is_sized(self.tcx, self.typing_env())
1610            {
1611                from = self.ty(pointer);
1612                value = pointer;
1613                was_updated_this_iteration = true;
1614                if from == to {
1615                    return Some(pointer);
1616                }
1617            }
1618
1619            // Aggregate-then-Transmute can just transmute the original field value,
1620            // so long as the bytes of a value from only from a single field.
1621            if let Transmute = kind
1622                && let Value::Aggregate(variant_idx, field_values) = self.get(value)
1623                && let Some((field_idx, field_ty)) =
1624                    self.value_is_all_in_one_field(from, variant_idx)
1625            {
1626                from = field_ty;
1627                value = field_values[field_idx.as_usize()];
1628                was_updated_this_iteration = true;
1629                if field_ty == to {
1630                    return Some(value);
1631                }
1632            }
1633
1634            // Various cast-then-cast cases can be simplified.
1635            if let Value::Cast { kind: inner_kind, value: inner_value } = self.get(value) {
1636                let inner_from = self.ty(inner_value);
1637                let new_kind = match (inner_kind, kind) {
1638                    // Even if there's a narrowing cast in here that's fine, because
1639                    // things like `*mut [i32] -> *mut i32 -> *const i32` and
1640                    // `*mut [i32] -> *const [i32] -> *const i32` can skip the middle in MIR.
1641                    (PtrToPtr, PtrToPtr) => Some(PtrToPtr),
1642                    // PtrToPtr-then-Transmute is fine so long as the pointer cast is identity:
1643                    // `*const T -> *mut T -> NonNull<T>` is fine, but we need to check for narrowing
1644                    // to skip things like `*const [i32] -> *const i32 -> NonNull<T>`.
1645                    (PtrToPtr, Transmute) if self.pointers_have_same_metadata(inner_from, from) => {
1646                        Some(Transmute)
1647                    }
1648                    // Similarly, for Transmute-then-PtrToPtr. Note that we need to check different
1649                    // variables for their metadata, and thus this can't merge with the previous arm.
1650                    (Transmute, PtrToPtr) if self.pointers_have_same_metadata(from, to) => {
1651                        Some(Transmute)
1652                    }
1653                    // It would be legal to always do this, but we don't want to hide information
1654                    // from the backend that it'd otherwise be able to use for optimizations.
1655                    (Transmute, Transmute)
1656                        if !self.transmute_may_have_niche_of_interest_to_backend(
1657                            inner_from, from, to,
1658                        ) =>
1659                    {
1660                        Some(Transmute)
1661                    }
1662                    _ => None,
1663                };
1664                if let Some(new_kind) = new_kind {
1665                    kind = new_kind;
1666                    from = inner_from;
1667                    value = inner_value;
1668                    was_updated_this_iteration = true;
1669                    if inner_from == to {
1670                        return Some(inner_value);
1671                    }
1672                }
1673            }
1674
1675            if was_updated_this_iteration {
1676                was_ever_updated = true;
1677            } else {
1678                break;
1679            }
1680        }
1681
1682        if was_ever_updated && let Some(op) = self.try_as_operand(value, location) {
1683            *initial_operand = op;
1684            *initial_kind = kind;
1685        }
1686
1687        Some(self.insert(to, Value::Cast { kind, value }))
1688    }
1689
1690    fn pointers_have_same_metadata(&self, left_ptr_ty: Ty<'tcx>, right_ptr_ty: Ty<'tcx>) -> bool {
1691        let left_meta_ty = left_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1692        let right_meta_ty = right_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1693        if left_meta_ty == right_meta_ty {
1694            true
1695        } else if let Ok(left) = self
1696            .tcx
1697            .try_normalize_erasing_regions(self.typing_env(), Unnormalized::new_wip(left_meta_ty))
1698            && let Ok(right) = self.tcx.try_normalize_erasing_regions(
1699                self.typing_env(),
1700                Unnormalized::new_wip(right_meta_ty),
1701            )
1702        {
1703            left == right
1704        } else {
1705            false
1706        }
1707    }
1708
1709    fn ty_may_have_ref(&self, ty: Ty<'tcx>) -> bool {
1710        fn ty_may_have_ref_inner<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, depth: usize) -> bool {
1711            if !tcx.recursion_limit().value_within_limit(depth) {
1712                return true;
1713            }
1714            let depth = depth + 1;
1715            match ty.kind() {
1716                ty::Int(_)
1717                | ty::Uint(_)
1718                | ty::Float(_)
1719                | ty::Bool
1720                | ty::Char
1721                | ty::Str
1722                | ty::Never
1723                | ty::FnDef(..)
1724                | ty::Error(_)
1725                | ty::FnPtr(..) => false,
1726                ty::Tuple(fields) => {
1727                    fields.iter().any(|field| ty_may_have_ref_inner(tcx, field, depth))
1728                }
1729                ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => {
1730                    ty_may_have_ref_inner(tcx, *ty, depth)
1731                }
1732                ty::Adt(adt_def, args) => {
1733                    adt_def.has_param()
1734                        || adt_def.has_aliases()
1735                        || adt_def.all_fields().any(|field| {
1736                            ty_may_have_ref_inner(
1737                                tcx,
1738                                field.ty(tcx, *args).skip_normalization(),
1739                                depth,
1740                            )
1741                        })
1742                }
1743                ty::Ref(..)
1744                | ty::RawPtr(_, _)
1745                | ty::Bound(..)
1746                | ty::Closure(..)
1747                | ty::CoroutineClosure(..)
1748                | ty::Dynamic(..)
1749                | ty::Foreign(_)
1750                | ty::Coroutine(..)
1751                | ty::CoroutineWitness(..)
1752                | ty::UnsafeBinder(_)
1753                | ty::Infer(_)
1754                | ty::Alias(..)
1755                | ty::Param(_)
1756                | ty::Placeholder(_) => true,
1757            }
1758        }
1759        ty_may_have_ref_inner(self.tcx, ty, 0)
1760    }
1761
1762    /// Returns `false` if we're confident that the middle type doesn't have an
1763    /// interesting niche so we can skip that step when transmuting.
1764    ///
1765    /// The backend will emit `assume`s when transmuting between types with niches,
1766    /// so we want to preserve `i32 -> char -> u32` so that that data is around,
1767    /// but it's fine to skip whole-range-is-value steps like `A -> u32 -> B`.
1768    fn transmute_may_have_niche_of_interest_to_backend(
1769        &self,
1770        from_ty: Ty<'tcx>,
1771        middle_ty: Ty<'tcx>,
1772        to_ty: Ty<'tcx>,
1773    ) -> bool {
1774        let Ok(middle_layout) = self.ecx.layout_of(middle_ty) else {
1775            // If it's too generic or something, then assume it might be interesting later.
1776            return true;
1777        };
1778
1779        if middle_layout.uninhabited {
1780            return true;
1781        }
1782
1783        match middle_layout.backend_repr {
1784            BackendRepr::Scalar(mid) => {
1785                if mid.is_always_valid(&self.ecx) {
1786                    // With no niche it's never interesting, so don't bother
1787                    // looking at the layout of the other two types.
1788                    false
1789                } else if let Ok(from_layout) = self.ecx.layout_of(from_ty)
1790                    && !from_layout.uninhabited
1791                    && from_layout.size == middle_layout.size
1792                    && let BackendRepr::Scalar(from_a) = from_layout.backend_repr
1793                    && let mid_range = mid.valid_range(&self.ecx)
1794                    && let from_range = from_a.valid_range(&self.ecx)
1795                    && mid_range.contains_range(from_range, middle_layout.size)
1796                {
1797                    // The `from_range` is a (non-strict) subset of `mid_range`
1798                    // such as if we're doing `bool` -> `ascii::Char` -> `_`,
1799                    // where `from_range: 0..=1` and `mid_range: 0..=127`,
1800                    // and thus the middle doesn't tell us anything we don't
1801                    // already know from the initial type.
1802                    false
1803                } else if let Ok(to_layout) = self.ecx.layout_of(to_ty)
1804                    && !to_layout.uninhabited
1805                    && to_layout.size == middle_layout.size
1806                    && let BackendRepr::Scalar(to_a) = to_layout.backend_repr
1807                    && let mid_range = mid.valid_range(&self.ecx)
1808                    && let to_range = to_a.valid_range(&self.ecx)
1809                    && mid_range.contains_range(to_range, middle_layout.size)
1810                {
1811                    // The `to_range` is a (non-strict) subset of `mid_range`
1812                    // such as if we're doing `_` -> `ascii::Char` -> `bool`,
1813                    // where `mid_range: 0..=127` and `to_range: 0..=1`,
1814                    // and thus the middle doesn't tell us anything we don't
1815                    // already know from the final type.
1816                    false
1817                } else {
1818                    true
1819                }
1820            }
1821            BackendRepr::ScalarPair { a, b, b_offset: _ } => {
1822                // The offset is irrelevant to niches since it can only cause padding,
1823                // which can never have a niche since it's uninitialized.
1824                !a.is_always_valid(&self.ecx) || !b.is_always_valid(&self.ecx)
1825            }
1826            BackendRepr::SimdVector { .. }
1827            | BackendRepr::SimdScalableVector { .. }
1828            | BackendRepr::Memory { .. } => false,
1829        }
1830    }
1831
1832    fn value_is_all_in_one_field(
1833        &self,
1834        ty: Ty<'tcx>,
1835        variant: VariantIdx,
1836    ) -> Option<(FieldIdx, Ty<'tcx>)> {
1837        if let Ok(layout) = self.ecx.layout_of(ty)
1838            && let abi::Variants::Single { index } = layout.variants
1839            && index == variant
1840            && let Some((field_idx, field_layout)) = layout.non_1zst_field(&self.ecx)
1841            && layout.size == field_layout.size
1842        {
1843            // We needed to check the variant to avoid trying to read the tag
1844            // field from an enum where no fields have variants, since that tag
1845            // field isn't in the `Aggregate` from which we're getting values.
1846            Some((field_idx, field_layout.ty))
1847        } else if let ty::Adt(adt, args) = ty.kind()
1848            && adt.is_struct()
1849            && adt.repr().transparent()
1850            && let [single_field] = adt.non_enum_variant().fields.raw.as_slice()
1851        {
1852            Some((FieldIdx::ZERO, single_field.ty(self.tcx, *args).skip_norm_wip()))
1853        } else {
1854            None
1855        }
1856    }
1857}
1858
1859/// Return true if any evaluation of this constant in the same MIR body
1860/// always returns the same value, taking into account even pointer identity tests.
1861///
1862/// In other words, this answers: is "cloning" the `Const` ok?
1863///
1864/// This returns `false` for constants that synthesize new `AllocId` when they are instantiated.
1865/// It is `true` for anything else, since a given `AllocId` *does* have a unique runtime value
1866/// within the scope of a single MIR body.
1867fn is_deterministic(c: Const<'_>) -> bool {
1868    // Primitive types cannot contain provenance and always have the same value.
1869    if c.ty().is_primitive() {
1870        return true;
1871    }
1872
1873    match c {
1874        // Some constants may generate fresh allocations for pointers they contain,
1875        // so using the same constant twice can yield two different results.
1876        // Notably, valtrees purposefully generate new allocations.
1877        Const::Ty(..) => false,
1878        // We do not know the contents, so don't attempt to do anything clever.
1879        Const::Unevaluated(..) => false,
1880        // When an evaluated constant contains provenance, it is encoded as an `AllocId`.
1881        // Cloning the constant will reuse the same `AllocId`. If this is in the same MIR
1882        // body, this same `AllocId` will result in the same pointer in codegen.
1883        Const::Val(..) => true,
1884    }
1885}
1886
1887/// Check if a constant may contain provenance information.
1888/// Can return `true` even if there is no provenance.
1889fn may_have_provenance(tcx: TyCtxt<'_>, value: ConstValue, size: Size) -> bool {
1890    match value {
1891        ConstValue::ZeroSized | ConstValue::Scalar(Scalar::Int(_)) => return false,
1892        ConstValue::Scalar(Scalar::Ptr(..)) | ConstValue::Slice { .. } => return true,
1893        ConstValue::Indirect { alloc_id, offset } => !tcx
1894            .global_alloc(alloc_id)
1895            .unwrap_memory()
1896            .inner()
1897            .provenance()
1898            .range_empty(AllocRange::from(offset..offset + size), &tcx),
1899    }
1900}
1901
1902fn op_to_prop_const<'tcx>(
1903    ecx: &mut InterpCx<'tcx, DummyMachine>,
1904    op: &OpTy<'tcx>,
1905) -> Option<ConstValue> {
1906    // Do not attempt to propagate unsized locals.
1907    if op.layout.is_unsized() {
1908        return None;
1909    }
1910
1911    // This constant is a ZST, just return an empty value.
1912    if op.layout.is_zst() {
1913        return Some(ConstValue::ZeroSized);
1914    }
1915
1916    // Do not synthetize too large constants. Codegen will just memcpy them, which we'd like to
1917    // avoid.
1918    // But we *do* want to synthesize any size constant if it is entirely uninit because that
1919    // benefits codegen, which has special handling for them.
1920    if !op.is_immediate_uninit()
1921        && !matches!(
1922            op.layout.backend_repr,
1923            BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }
1924        )
1925    {
1926        return None;
1927    }
1928
1929    // If this constant has scalar ABI, return it as a `ConstValue::Scalar`.
1930    if let BackendRepr::Scalar(abi::Scalar::Initialized { .. }) = op.layout.backend_repr
1931        && let Some(scalar) = ecx.read_scalar(op).discard_err()
1932    {
1933        if !scalar.try_to_scalar_int().is_ok() {
1934            // Check that we do not leak a pointer.
1935            // Those pointers may lose part of their identity in codegen.
1936            // FIXME: remove this hack once https://github.com/rust-lang/rust/issues/128775 is fixed.
1937            return None;
1938        }
1939        return Some(ConstValue::Scalar(scalar));
1940    }
1941
1942    // If this constant is already represented as an `Allocation`,
1943    // try putting it into global memory to return it.
1944    if let Either::Left(mplace) = op.as_mplace_or_imm() {
1945        let (alloc_id, offset, _) = ecx.ptr_try_get_alloc_id(mplace.ptr(), 0).ok()?;
1946
1947        // Do not try interning a value that contains provenance.
1948        // Due to https://github.com/rust-lang/rust/issues/128775, doing so could lead to bugs.
1949        // FIXME: remove this hack once that issue is fixed.
1950        if ecx.has_provenance_in_alloc(alloc_id).discard_err()? {
1951            return None;
1952        }
1953
1954        intern_const_alloc_for_constprop(ecx, alloc_id).discard_err()?;
1955
1956        // `alloc_id` may point to a static. Codegen will choke on an `Indirect` with anything
1957        // by `GlobalAlloc::Memory`, so do fall through to copying if needed.
1958        // FIXME: find a way to treat this more uniformly (probably by fixing codegen)
1959        if let GlobalAlloc::Memory(alloc) = ecx.tcx.global_alloc(alloc_id)
1960            // Transmuting a constant is just an offset in the allocation. If the alignment of the
1961            // allocation is not enough, fallback to copying into a properly aligned value.
1962            && alloc.inner().align >= op.layout.align
1963            // If this is a packed field the offset must also be sufficiently aligned.
1964            && offset.bytes().is_multiple_of(op.layout.align.bytes())
1965        {
1966            return Some(ConstValue::Indirect { alloc_id, offset });
1967        }
1968    }
1969
1970    // Everything failed: create a new allocation to hold the data.
1971    let alloc_id =
1972        ecx.intern_with_temp_alloc(op.layout, |ecx, dest| ecx.copy_op(op, dest)).discard_err()?;
1973    Some(ConstValue::Indirect { alloc_id, offset: Size::ZERO })
1974}
1975
1976impl<'tcx> VnState<'_, '_, 'tcx> {
1977    /// If either [`Self::try_as_constant`] as [`Self::try_as_place`] succeeds,
1978    /// returns that result as an [`Operand`].
1979    fn try_as_operand(&mut self, index: VnIndex, location: Location) -> Option<Operand<'tcx>> {
1980        if let Some(const_) = self.try_as_constant(index) {
1981            Some(Operand::Constant(Box::new(const_)))
1982        } else if let Value::RuntimeChecks(c) = self.get(index) {
1983            Some(Operand::RuntimeChecks(c))
1984        } else if let Some(place) = self.try_as_place(index, location, false) {
1985            self.reused_locals.insert(place.local);
1986            Some(Operand::Copy(place))
1987        } else {
1988            None
1989        }
1990    }
1991
1992    /// If `index` is a `Value::Constant`, return the `Constant` to be put in the MIR.
1993    fn try_as_constant(&mut self, index: VnIndex) -> Option<ConstOperand<'tcx>> {
1994        let value = self.get(index);
1995
1996        // This was already an *evaluated* constant in MIR, do not change it.
1997        if let Value::Constant { value, disambiguator: None } = value
1998            && let Const::Val(..) = value
1999        {
2000            return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
2001        }
2002
2003        if let Some(value) = self.try_as_evaluated_constant(index) {
2004            return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
2005        }
2006
2007        // We failed to provide an evaluated form, fallback to using the unevaluated constant.
2008        if let Value::Constant { value, disambiguator: None } = value {
2009            return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
2010        }
2011
2012        None
2013    }
2014
2015    fn try_as_evaluated_constant(&mut self, index: VnIndex) -> Option<Const<'tcx>> {
2016        let op = self.eval_to_const(index)?;
2017        let value = op_to_prop_const(&mut self.ecx, op)?;
2018
2019        // Check that we do not leak a pointer.
2020        // Those pointers may lose part of their identity in codegen.
2021        // FIXME: remove this hack once https://github.com/rust-lang/rust/issues/128775 is fixed.
2022        if may_have_provenance(self.tcx, value, op.layout.size) {
2023            return None;
2024        }
2025
2026        Some(Const::Val(value, op.layout.ty))
2027    }
2028
2029    /// Construct a place which holds the same value as `index` and for which all locals strictly
2030    /// dominate `loc`. If you used this place, add its base local to `reused_locals` to remove
2031    /// storage statements.
2032    #[instrument(level = "trace", skip(self), ret)]
2033    fn try_as_place(
2034        &mut self,
2035        mut index: VnIndex,
2036        loc: Location,
2037        allow_complex_projection: bool,
2038    ) -> Option<Place<'tcx>> {
2039        let mut projection = SmallVec::<[PlaceElem<'tcx>; 1]>::new();
2040        loop {
2041            if let Some(local) = self.try_as_local(index, loc) {
2042                projection.reverse();
2043                let place =
2044                    Place { local, projection: self.tcx.mk_place_elems(projection.as_slice()) };
2045                return Some(place);
2046            } else if projection.last() == Some(&PlaceElem::Deref) {
2047                // `Deref` can only be the first projection in a place.
2048                // If we are here, we failed to find a local, and we already have a `Deref`.
2049                // Trying to add projections will only result in an ill-formed place.
2050                return None;
2051            } else if let Value::Projection(pointer, proj) = self.get(index)
2052                && (allow_complex_projection || proj.is_stable_offset())
2053                && let Some(proj) = self.try_as_place_elem(self.ty(index), proj, loc)
2054            {
2055                if proj == PlaceElem::Deref {
2056                    // We can introduce a new dereference if the source value cannot be changed in the body.
2057                    // Dereferencing an immutable argument always gives the same value in the body.
2058                    match self.get(pointer) {
2059                        Value::Argument(_)
2060                            if let Some(Mutability::Not) = self.ty(pointer).ref_mutability() => {}
2061                        _ => {
2062                            return None;
2063                        }
2064                    }
2065                }
2066                projection.push(proj);
2067                index = pointer;
2068            } else {
2069                return None;
2070            }
2071        }
2072    }
2073
2074    /// If there is a local which is assigned `index`, and its assignment strictly dominates `loc`,
2075    /// return it. If you used this local, add it to `reused_locals` to remove storage statements.
2076    fn try_as_local(&mut self, index: VnIndex, loc: Location) -> Option<Local> {
2077        let other = self.rev_locals.get(index)?;
2078        other
2079            .iter()
2080            .find(|&&other| self.ssa.assignment_dominates(&self.dominators, other, loc))
2081            .copied()
2082    }
2083}
2084
2085impl<'tcx> MutVisitor<'tcx> for VnState<'_, '_, 'tcx> {
2086    fn tcx(&self) -> TyCtxt<'tcx> {
2087        self.tcx
2088    }
2089
2090    fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
2091        self.simplify_place_projection(place, location);
2092        self.super_place(place, context, location);
2093    }
2094
2095    fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
2096        self.simplify_operand(operand, location);
2097        self.super_operand(operand, location);
2098    }
2099
2100    fn visit_assign(
2101        &mut self,
2102        lhs: &mut Place<'tcx>,
2103        rvalue: &mut Rvalue<'tcx>,
2104        location: Location,
2105    ) {
2106        self.simplify_place_projection(lhs, location);
2107
2108        let value = self.simplify_rvalue(rvalue, location);
2109        if let Some(value) = value {
2110            // FIXME: Is it correct to make these retagging assignments?
2111            if let Some(const_) = self.try_as_constant(value) {
2112                *rvalue = Rvalue::Use(Operand::Constant(Box::new(const_)), WithRetag::Yes);
2113            } else if let Some(place) = self.try_as_place(value, location, false)
2114                && !matches!(rvalue, Rvalue::Use(Operand::Move(p) | Operand::Copy(p), _) if p == &place)
2115            {
2116                *rvalue = Rvalue::Use(Operand::Copy(place), WithRetag::Yes);
2117                self.reused_locals.insert(place.local);
2118            }
2119        }
2120
2121        if let Some(local) = lhs.as_local()
2122            && self.ssa.is_ssa(local)
2123            && let rvalue_ty = rvalue.ty(self.local_decls, self.tcx)
2124            // FIXME(#112651) `rvalue` may have a subtype to `local`. We can only mark
2125            // `local` as reusable if we have an exact type match.
2126            && self.local_decls[local].ty == rvalue_ty
2127        {
2128            let value = value.unwrap_or_else(|| self.new_opaque(rvalue_ty));
2129            self.assign(local, value);
2130        }
2131    }
2132
2133    fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
2134        if let Terminator { kind: TerminatorKind::Call { destination, .. }, .. } = terminator {
2135            if let Some(local) = destination.as_local()
2136                && self.ssa.is_ssa(local)
2137            {
2138                let ty = self.local_decls[local].ty;
2139                let opaque = self.new_opaque(ty);
2140                self.assign(local, opaque);
2141            }
2142        }
2143        self.super_terminator(terminator, location);
2144    }
2145}
2146
2147struct StorageRemover<'a, 'tcx> {
2148    tcx: TyCtxt<'tcx>,
2149    reused_locals: &'a DenseBitSet<Local>,
2150    storage_to_remove: &'a DenseBitSet<Local>,
2151}
2152
2153impl<'a, 'tcx> MutVisitor<'tcx> for StorageRemover<'a, 'tcx> {
2154    fn tcx(&self) -> TyCtxt<'tcx> {
2155        self.tcx
2156    }
2157
2158    fn visit_operand(&mut self, operand: &mut Operand<'tcx>, _: Location) {
2159        if let Operand::Move(place) = *operand
2160            && !place.is_indirect_first_projection()
2161            && self.reused_locals.contains(place.local)
2162        {
2163            *operand = Operand::Copy(place);
2164        }
2165    }
2166
2167    fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
2168        match stmt.kind {
2169            // When removing storage statements, we need to remove both (#107511).
2170            StatementKind::StorageLive(l) | StatementKind::StorageDead(l)
2171                if self.storage_to_remove.contains(l) =>
2172            {
2173                stmt.make_nop(true)
2174            }
2175            _ => self.super_statement(stmt, loc),
2176        }
2177    }
2178}
2179
2180struct StorageChecker<'a, 'tcx> {
2181    reused_locals: &'a DenseBitSet<Local>,
2182    storage_to_remove: DenseBitSet<Local>,
2183    maybe_uninit: ResultsCursor<'a, 'tcx, MaybeUninitializedLocals>,
2184}
2185
2186impl<'a, 'tcx> Visitor<'tcx> for StorageChecker<'a, 'tcx> {
2187    fn visit_local(&mut self, local: Local, context: PlaceContext, location: Location) {
2188        match context {
2189            // These mutating uses do not require the local to be initialized,
2190            // so we cannot use our maybe-uninit check on them.
2191            // However, GVN doesn't introduce or move mutations,
2192            // so this local must already have valid storage at this location.
2193            PlaceContext::MutatingUse(MutatingUseContext::AsmOutput)
2194            | PlaceContext::MutatingUse(MutatingUseContext::Call)
2195            | PlaceContext::MutatingUse(MutatingUseContext::Store)
2196            | PlaceContext::MutatingUse(MutatingUseContext::Yield)
2197            | PlaceContext::NonUse(_) => {
2198                return;
2199            }
2200            // Must check validity for other mutating usages and all non-mutating uses.
2201            PlaceContext::MutatingUse(_) | PlaceContext::NonMutatingUse(_) => {}
2202        }
2203
2204        // We only need to check reused locals which we haven't already removed storage for.
2205        if !self.reused_locals.contains(local) || self.storage_to_remove.contains(local) {
2206            return;
2207        }
2208
2209        self.maybe_uninit.seek_before_primary_effect(location);
2210
2211        if self.maybe_uninit.get().contains(local) {
2212            debug!(
2213                ?location,
2214                ?local,
2215                "local is reused and is maybe uninit at this location, marking it for storage statement removal"
2216            );
2217            self.storage_to_remove.insert(local);
2218        }
2219    }
2220}