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