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