Skip to main content

rustc_const_eval/const_eval/
machine.rs

1use std::borrow::{Borrow, Cow};
2use std::hash::Hash;
3use std::{fmt, mem};
4
5use rustc_abi::{Align, Size};
6use rustc_ast::Mutability;
7use rustc_attr_ir::find_attr;
8use rustc_attr_ir::lang_items::LangItem;
9use rustc_data_structures::fx::{FxHashMap, FxIndexMap, IndexEntry};
10use rustc_hir::def_id::{DefId, LocalDefId};
11use rustc_hir::{CRATE_HIR_ID, HirId};
12use rustc_lint_defs::builtin::LONG_RUNNING_CONST_EVAL;
13use rustc_middle::mir;
14use rustc_middle::mir::AssertMessage;
15use rustc_middle::mir::interpret::ReportedErrorInfo;
16use rustc_middle::query::TyCtxtAt;
17use rustc_middle::ty::layout::{HasTypingEnv, TyAndLayout};
18use rustc_middle::ty::{self, Intrinsic, Ty, TyCtxt};
19use rustc_span::{Span, Symbol, bug, span_bug};
20use rustc_target::callconv::FnAbi;
21use tracing::debug;
22
23use super::error::*;
24use crate::diagnostics::{LongRunning, LongRunningWarn};
25use crate::interpret::{
26    self, AllocId, AllocRange, ConstAllocation, CtfeProvenance, FnArg, Frame, GlobalAlloc, ImmTy,
27    InterpCx, InterpResult, OpTy, PlaceTy, Pointer, RangeSet, RetagMode, Scalar,
28    compile_time_machine, interp_ok, throw_exhaust, throw_inval, throw_ub, throw_unsup,
29    throw_unsup_format,
30};
31
32/// When hitting this many interpreted terminators we emit a deny by default lint
33/// that notfies the user that their constant takes a long time to evaluate. If that's
34/// what they intended, they can just allow the lint.
35const LINT_TERMINATOR_LIMIT: usize = 2_000_000;
36/// The limit used by `-Z tiny-const-eval-limit`. This smaller limit is useful for internal
37/// tests not needing to run 30s or more to show some behaviour.
38const TINY_LINT_TERMINATOR_LIMIT: usize = 20;
39/// After this many interpreted terminators, we start emitting progress indicators at every
40/// power of two of interpreted terminators.
41const PROGRESS_INDICATOR_START: usize = 4_000_000;
42
43/// Extra machine state for CTFE, and the Machine instance.
44//
45// Should be public because out-of-tree rustc consumers need this
46// if they want to interact with constant values.
47pub struct CompileTimeMachine<'tcx> {
48    /// The number of terminators that have been evaluated.
49    ///
50    /// This is used to produce lints informing the user that the compiler is not stuck.
51    /// Set to `usize::MAX` to never report anything.
52    pub(super) num_evaluated_steps: usize,
53
54    /// The virtual call stack.
55    pub(super) stack: Vec<Frame<'tcx>>,
56
57    /// Pattern matching on consts with references would be unsound if those references
58    /// could point to anything mutable. Therefore, when evaluating consts and when constructing valtrees,
59    /// we ensure that only immutable global memory can be accessed.
60    pub(super) can_access_mut_global: CanAccessMutGlobal,
61
62    /// Whether to check alignment during evaluation.
63    pub(super) check_alignment: CheckAlignment,
64
65    /// If `Some`, we are evaluating the initializer of the static with the given `LocalDefId`,
66    /// storing the result in the given `AllocId`.
67    /// Used to prevent accesses to a static's base allocation, as that may allow for self-initialization loops.
68    pub(crate) static_root_ids: Option<(AllocId, LocalDefId)>,
69
70    /// A cache of "data range" computations for unions (i.e., the offsets of non-padding bytes).
71    union_data_ranges: FxHashMap<Ty<'tcx>, RangeSet>,
72
73    /// The current retag mode.
74    retag_mode: RetagMode,
75}
76
77#[derive(#[automatically_derived]impl ::core::marker::Copy for CheckAlignment { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for CheckAlignment {
}
#[automatically_derived]impl ::core::clone::Clone for CheckAlignment {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone)]
78pub enum CheckAlignment {
79    /// Ignore all alignment requirements.
80    /// This is mainly used in interning.
81    No,
82    /// Hard error when dereferencing a misaligned pointer.
83    Error,
84}
85
86#[derive(#[automatically_derived]impl ::core::marker::Copy for CanAccessMutGlobal { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for CanAccessMutGlobal {
}
#[automatically_derived]impl ::core::clone::Clone for CanAccessMutGlobal {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    CanAccessMutGlobal {
}
#[automatically_derived]impl ::core::cmp::PartialEq for CanAccessMutGlobal {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
87pub(crate) enum CanAccessMutGlobal {
88    No,
89    Yes,
90}
91
92impl From<bool> for CanAccessMutGlobal {
93    fn from(value: bool) -> Self {
94        if value { Self::Yes } else { Self::No }
95    }
96}
97
98impl<'tcx> CompileTimeMachine<'tcx> {
99    pub(crate) fn new(
100        can_access_mut_global: CanAccessMutGlobal,
101        check_alignment: CheckAlignment,
102    ) -> Self {
103        CompileTimeMachine {
104            num_evaluated_steps: 0,
105            stack: Vec::new(),
106            can_access_mut_global,
107            check_alignment,
108            static_root_ids: None,
109            union_data_ranges: FxHashMap::default(),
110            retag_mode: RetagMode::Default,
111        }
112    }
113}
114
115impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxIndexMap<K, V> {
116    #[inline(always)]
117    fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
118    where
119        K: Borrow<Q>,
120    {
121        FxIndexMap::contains_key(self, k)
122    }
123
124    #[inline(always)]
125    fn contains_key_ref<Q: ?Sized + Hash + Eq>(&self, k: &Q) -> bool
126    where
127        K: Borrow<Q>,
128    {
129        FxIndexMap::contains_key(self, k)
130    }
131
132    #[inline(always)]
133    fn insert(&mut self, k: K, v: V) -> Option<V> {
134        FxIndexMap::insert(self, k, v)
135    }
136
137    #[inline(always)]
138    fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
139    where
140        K: Borrow<Q>,
141    {
142        // FIXME(#120456) - is `swap_remove` correct?
143        FxIndexMap::swap_remove(self, k)
144    }
145
146    #[inline(always)]
147    fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
148        self.iter().filter_map(move |(k, v)| f(k, v)).collect()
149    }
150
151    #[inline(always)]
152    fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
153        match self.get(&k) {
154            Some(v) => Ok(v),
155            None => {
156                vacant()?;
157                ::rustc_span::macros::bug_impl(None,
    format_args!("The CTFE machine shouldn\'t ever need to extend the alloc_map when reading"),
    Location::caller())bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
158            }
159        }
160    }
161
162    #[inline(always)]
163    fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
164        match self.entry(k) {
165            IndexEntry::Occupied(e) => Ok(e.into_mut()),
166            IndexEntry::Vacant(e) => {
167                let v = vacant()?;
168                Ok(e.insert(v))
169            }
170        }
171    }
172}
173
174pub type CompileTimeInterpCx<'tcx> = InterpCx<'tcx, CompileTimeMachine<'tcx>>;
175
176#[derive(#[automatically_derived]impl ::core::fmt::Debug for MemoryKind {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Heap { was_made_global: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Heap was_made_global", &__self_0),
        }
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    MemoryKind {
}
#[automatically_derived]impl ::core::cmp::PartialEq for MemoryKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Heap { was_made_global: __self_0 }, Self::Heap {
                was_made_global: __arg1_0 }) => __self_0 == __arg1_0,
        }
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for MemoryKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq, #[automatically_derived]impl ::core::marker::Copy for MemoryKind { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for MemoryKind {
}
#[automatically_derived]impl ::core::clone::Clone for MemoryKind {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone)]
177pub enum MemoryKind {
178    Heap {
179        /// Indicates whether `make_global` was called on this allocation.
180        /// If this is `true`, the allocation must be immutable.
181        was_made_global: bool,
182    },
183}
184
185impl fmt::Display for MemoryKind {
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        match self {
188            MemoryKind::Heap { was_made_global } => {
189                f.write_fmt(format_args!("heap allocation{0}",
        if *was_made_global { " (made global)" } else { "" }))write!(f, "heap allocation{}", if *was_made_global { " (made global)" } else { "" })
190            }
191        }
192    }
193}
194
195impl interpret::MayLeak for MemoryKind {
196    #[inline(always)]
197    fn may_leak(self) -> bool {
198        match self {
199            MemoryKind::Heap { was_made_global } => was_made_global,
200        }
201    }
202}
203
204impl interpret::MayLeak for ! {
205    #[inline(always)]
206    fn may_leak(self) -> bool {
207        // `self` is uninhabited
208        self
209    }
210}
211
212impl<'tcx> CompileTimeInterpCx<'tcx> {
213    pub(crate) fn location_triple_for_span(&self, span: Span) -> (Symbol, u32, u32) {
214        let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
215        let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
216
217        use rustc_span::RemapPathScopeComponents;
218        (
219            Symbol::intern(
220                &caller.file.name.display(RemapPathScopeComponents::DIAGNOSTICS).to_string_lossy(),
221            ),
222            u32::try_from(caller.line).unwrap(),
223            u32::try_from(caller.col_display).unwrap().checked_add(1).unwrap(),
224        )
225    }
226
227    /// "Intercept" a function call, because we have something special to do for it.
228    /// All `#[rustc_do_not_const_check]` functions MUST be hooked here.
229    /// If this returns `Some` function, which may be `instance` or a different function with
230    /// compatible arguments, then evaluation should continue with that function.
231    /// If this returns `None`, the function call has been handled and the function has returned.
232    fn hook_special_const_fn(
233        &mut self,
234        instance: ty::Instance<'tcx>,
235        args: &[FnArg<'tcx>],
236        _dest: &PlaceTy<'tcx>,
237        _ret: Option<mir::BasicBlock>,
238    ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
239        let def_id = instance.def_id();
240
241        if self.tcx.is_lang_item(def_id, LangItem::PanicDisplay)
242            || self.tcx.is_lang_item(def_id, LangItem::BeginPanic)
243        {
244            let args = Self::copy_fn_args(args);
245            // &str or &&str
246            if !(args.len() == 1) {
    ::core::panicking::panic("assertion failed: args.len() == 1")
};assert!(args.len() == 1);
247
248            let mut msg_place = self.deref_pointer(&args[0])?;
249            while msg_place.layout.ty.is_ref() {
250                msg_place = self.deref_pointer(&msg_place)?;
251            }
252
253            let msg = Symbol::intern(self.read_str(&msg_place)?);
254            let span = self.caller_location();
255            let (file, line, col) = self.location_triple_for_span(span);
256            return Err(ConstEvalErrKind::Panic { msg, file, line, col }).into();
257        } else if self.tcx.is_lang_item(def_id, LangItem::PanicFmt) {
258            // For panic_fmt, call const_panic_fmt instead.
259            let const_def_id = self.tcx.require_lang_item(LangItem::ConstPanicFmt, self.tcx.span);
260            let new_instance = ty::Instance::expect_resolve(
261                *self.tcx,
262                self.typing_env(),
263                const_def_id,
264                instance.args,
265                self.cur_span(),
266            );
267
268            return interp_ok(Some(new_instance));
269        }
270        interp_ok(Some(instance))
271    }
272
273    /// See documentation on the `ptr_guaranteed_cmp` intrinsic.
274    /// Returns `2` if the result is unknown.
275    /// Returns `1` if the pointers are guaranteed equal.
276    /// Returns `0` if the pointers are guaranteed inequal.
277    ///
278    /// Note that this intrinsic is exposed on stable for comparison with null. In other words, any
279    /// change to this function that affects comparison with null is insta-stable!
280    pub(crate) fn guaranteed_cmp(&mut self, a: Scalar, b: Scalar) -> InterpResult<'tcx, u8> {
281        interp_ok(match (a, b) {
282            // Comparisons between integers are always known.
283            (Scalar::Int(a), Scalar::Int(b)) => (a == b) as u8,
284            // Comparing a pointer `ptr` with an integer `int` is equivalent to comparing
285            // `ptr-int` with null, so we can reduce this case to a `scalar_may_be_null` test.
286            (Scalar::Int(int), Scalar::Ptr(ptr, _)) | (Scalar::Ptr(ptr, _), Scalar::Int(int)) => {
287                let int = int.to_target_usize(*self.tcx);
288                // The `wrapping_neg` here may produce a value that is not
289                // a valid target usize any more... but `wrapping_offset` handles that correctly.
290                let offset_ptr = ptr.wrapping_offset(Size::from_bytes(int.wrapping_neg()), self);
291                if !self.scalar_may_be_null(Scalar::from_pointer(offset_ptr, self))? {
292                    // `ptr.wrapping_sub(int)` is definitely not equal to `0`, so `ptr != int`
293                    0
294                } else {
295                    // `ptr.wrapping_sub(int)` could be equal to `0`, but might not be,
296                    // so we cannot know for sure if `ptr == int` or not
297                    2
298                }
299            }
300            (Scalar::Ptr(a, _), Scalar::Ptr(b, _)) => {
301                let (a_prov, a_offset) = a.prov_and_relative_offset();
302                let (b_prov, b_offset) = b.prov_and_relative_offset();
303                let a_allocid = a_prov.alloc_id();
304                let b_allocid = b_prov.alloc_id();
305                let a_info = self.get_alloc_info(a_allocid);
306                let b_info = self.get_alloc_info(b_allocid);
307
308                // Check if the pointers cannot be equal due to alignment
309                if a_info.align > Align::ONE && b_info.align > Align::ONE {
310                    let min_align = Ord::min(a_info.align.bytes(), b_info.align.bytes());
311                    let a_residue = a_offset.bytes() % min_align;
312                    let b_residue = b_offset.bytes() % min_align;
313                    if a_residue != b_residue {
314                        // If the two pointers have a different residue modulo their
315                        // common alignment, they cannot be equal.
316                        return interp_ok(0);
317                    }
318                    // The pointers have the same residue modulo their common alignment,
319                    // so they could be equal. Try the other checks.
320                }
321
322                if let (Some(GlobalAlloc::Static(a_did)), Some(GlobalAlloc::Static(b_did))) = (
323                    self.tcx.try_get_global_alloc(a_allocid),
324                    self.tcx.try_get_global_alloc(b_allocid),
325                ) {
326                    if a_allocid == b_allocid {
327                        if true {
    {
        match (&a_did, &b_did) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val,
                        ::core::option::Option::Some(format_args!("different static item DefIds had same AllocId? {0:?} == {1:?}, {2:?} != {3:?}",
                                a_allocid, b_allocid, a_did, b_did)));
                }
            }
        }
    };
};debug_assert_eq!(
328                            a_did, b_did,
329                            "different static item DefIds had same AllocId? {a_allocid:?} == {b_allocid:?}, {a_did:?} != {b_did:?}"
330                        );
331                        // Comparing two pointers into the same static. As per
332                        // https://doc.rust-lang.org/nightly/reference/items/static-items.html#r-items.static.intro
333                        // a static cannot be duplicated, so if two pointers are into the same
334                        // static, they are equal if and only if their offsets are equal.
335                        (a_offset == b_offset) as u8
336                    } else {
337                        if true {
    {
        match (&(a_did), &(b_did)) {
            (left_val, right_val) => {
                if *left_val == *right_val {
                    let kind = ::core::panicking::AssertKind::Ne;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val,
                        ::core::option::Option::Some(format_args!("same static item DefId had two different AllocIds? {0:?} != {1:?}, {2:?} == {3:?}",
                                a_allocid, b_allocid, a_did, b_did)));
                }
            }
        }
    };
};debug_assert_ne!(
338                            a_did, b_did,
339                            "same static item DefId had two different AllocIds? {a_allocid:?} != {b_allocid:?}, {a_did:?} == {b_did:?}"
340                        );
341                        // Comparing two pointers into the different statics.
342                        // We can never determine for sure that two pointers into different statics
343                        // are *equal*, but we can know that they are *inequal* if they are both
344                        // strictly in-bounds (i.e. in-bounds and not one-past-the-end) of
345                        // their respective static, as different non-zero-sized statics cannot
346                        // overlap or be deduplicated as per
347                        // https://doc.rust-lang.org/nightly/reference/items/static-items.html#r-items.static.intro
348                        // (non-deduplication), and
349                        // https://doc.rust-lang.org/nightly/reference/items/static-items.html#r-items.static.storage-disjointness
350                        // (non-overlapping).
351                        if a_offset < a_info.size && b_offset < b_info.size {
352                            0
353                        } else {
354                            // Otherwise, conservatively say we don't know.
355                            // There are some cases we could still return `0` for, e.g.
356                            // if the pointers being equal would require their statics to overlap
357                            // one or more bytes, but for simplicity we currently only check
358                            // strictly in-bounds pointers.
359                            2
360                        }
361                    }
362                } else {
363                    // All other cases we conservatively say we don't know.
364                    //
365                    // For comparing statics to non-statics, as per https://doc.rust-lang.org/nightly/reference/items/static-items.html#r-items.static.storage-disjointness
366                    // immutable statics can overlap with other kinds of allocations sometimes.
367                    //
368                    // FIXME: We could be more decisive for (non-zero-sized) mutable statics,
369                    // which cannot overlap with other kinds of allocations.
370                    //
371                    // Functions and vtables can be duplicated and deduplicated, so we
372                    // cannot be sure of runtime equality of pointers to the same one, or the
373                    // runtime inequality of pointers to different ones (see e.g. #73722),
374                    // so comparing those should return 2, whether they are the same allocation
375                    // or not.
376                    //
377                    // `GlobalAlloc::TypeId` exists mostly to prevent consteval from comparing
378                    // `TypeId`s, so comparing those should always return 2, whether they are the
379                    // same allocation or not.
380                    //
381                    // FIXME: We could revisit comparing pointers into the same
382                    // `GlobalAlloc::Memory` once https://github.com/rust-lang/rust/issues/128775
383                    // is fixed (but they can be deduplicated, so comparing pointers into different
384                    // ones should return 2).
385                    2
386                }
387            }
388        })
389    }
390}
391
392impl<'tcx> CompileTimeMachine<'tcx> {
393    #[inline(always)]
394    /// Find the first stack frame that is within the current crate, if any.
395    /// Otherwise, return the crate's HirId
396    pub fn best_lint_scope(&self, tcx: TyCtxt<'tcx>) -> HirId {
397        self.stack.iter().find_map(|frame| frame.lint_root(tcx)).unwrap_or(CRATE_HIR_ID)
398    }
399}
400
401impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
402    type Provenance = CtfeProvenance;
type ProvenanceExtra = bool;
type ExtraFnVal = !;
type MemoryKind = crate::const_eval::MemoryKind;
type MemoryMap =
    rustc_data_structures::fx::FxIndexMap<AllocId,
    (MemoryKind<Self::MemoryKind>, Allocation)>;
const GLOBAL_KIND: Option<Self::MemoryKind> = None;
type AllocExtra = ();
type FrameExtra = ();
type Bytes = Box<[u8]>;
#[inline(always)]
fn ignore_optional_overflow_checks(_ecx: &InterpCx<'tcx, Self>) -> bool {
    false
}
#[inline(always)]
fn unwind_terminate(_ecx: &mut InterpCx<'tcx, Self>,
    _reason: mir::UnwindTerminateReason) -> InterpResult<'tcx> {
    {
        ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
                format_args!("unwinding cannot happen during compile-time evaluation")));
    }
}
#[inline(always)]
fn check_fn_target_features(_ecx: &InterpCx<'tcx, Self>,
    _instance: ty::Instance<'tcx>) -> InterpResult<'tcx> {
    interp_ok(())
}
#[inline(always)]
fn call_extra_fn(_ecx: &mut InterpCx<'tcx, Self>, fn_val: !,
    _abi: &FnAbi<'tcx, Ty<'tcx>>, _args: &[FnArg<'tcx>],
    _destination: &PlaceTy<'tcx, Self::Provenance>,
    _target: Option<mir::BasicBlock>, _unwind: mir::UnwindAction)
    -> InterpResult<'tcx> {
    match fn_val {}
}
#[inline(always)]
fn float_fuse_mul_add(_ecx: &InterpCx<'tcx, Self>) -> bool { true }
#[inline(always)]
fn atomic_load(ecx: &InterpCx<'tcx, Self>,
    place: &MPlaceTy<'tcx, Self::Provenance>, _ordering: AtomicOrdering)
    -> InterpResult<'tcx, Scalar<Self::Provenance>> {
    ecx.read_scalar(place)
}
#[inline(always)]
fn atomic_store(ecx: &mut InterpCx<'tcx, Self>,
    place: &MPlaceTy<'tcx, Self::Provenance>,
    val: &ImmTy<'tcx, Self::Provenance>, _ordering: AtomicOrdering)
    -> InterpResult<'tcx> {
    ecx.write_scalar(val.to_scalar(), place)
}
fn atomic_rmw(ecx: &mut InterpCx<'tcx, Self>,
    place: &MPlaceTy<'tcx, Self::Provenance>, op: AtomicRmwOp,
    operand: &ImmTy<'tcx, Self::Provenance>, _ordering: AtomicOrdering)
    -> InterpResult<'tcx, Scalar<Self::Provenance>> {
    let old_val = ecx.read_immediate(place)?;
    let new_val = ecx.atomic_rmw_op(op, &old_val, operand)?;
    ecx.write_immediate(*new_val, place)?;
    interp_ok(old_val.to_scalar())
}
fn atomic_compare_exchange(ecx: &mut InterpCx<'tcx, Self>,
    place: &MPlaceTy<'tcx, Self::Provenance>,
    expected_old: &ImmTy<'tcx, Self::Provenance>,
    new: &ImmTy<'tcx, Self::Provenance>, _can_fail_spuriously: bool,
    _success_ordering: AtomicOrdering, _failure_ordering: AtomicOrdering)
    -> InterpResult<'tcx, (Scalar<Self::Provenance>, bool)> {
    let actual_old = ecx.read_immediate(place)?;
    let eq =
        ecx.binary_op(mir::BinOp::Eq, &actual_old,
                            expected_old)?.to_scalar().to_bool()?;
    if eq { ecx.write_immediate(**new, place)?; }
    interp_ok((actual_old.to_scalar(), eq))
}
#[inline(always)]
fn atomic_fence(_ecx: &InterpCx<'tcx, Self>, _ordering: AtomicOrdering,
    _singlethread: bool) -> InterpResult<'tcx> {
    interp_ok(())
}
#[inline(always)]
fn adjust_global_allocation<'b>(_ecx: &InterpCx<'tcx, Self>, _id: AllocId,
    alloc: &'b Allocation)
    -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance>>> {
    interp_ok(Cow::Borrowed(alloc))
}
fn init_local_allocation(_ecx: &InterpCx<'tcx, Self>, _id: AllocId,
    _kind: MemoryKind<Self::MemoryKind>, _size: Size, _align: Align)
    -> InterpResult<'tcx, Self::AllocExtra> {
    interp_ok(())
}
fn extern_static_pointer(ecx: &InterpCx<'tcx, Self>, def_id: DefId)
    -> InterpResult<'tcx, Pointer> {
    interp_ok(Pointer::new(ecx.tcx.reserve_and_set_static_alloc(def_id).into(),
            Size::ZERO))
}
#[inline(always)]
fn adjust_alloc_root_pointer(_ecx: &InterpCx<'tcx, Self>,
    ptr: Pointer<CtfeProvenance>, _kind: Option<MemoryKind<Self::MemoryKind>>)
    -> InterpResult<'tcx, Pointer<CtfeProvenance>> {
    interp_ok(ptr)
}
#[inline(always)]
fn ptr_from_addr_cast(_ecx: &InterpCx<'tcx, Self>, addr: u64)
    -> InterpResult<'tcx, Pointer<Option<CtfeProvenance>>> {
    interp_ok(Pointer::without_provenance(addr))
}
#[inline(always)]
fn ptr_get_alloc(_ecx: &InterpCx<'tcx, Self>, ptr: Pointer<CtfeProvenance>,
    _size: i64) -> Option<(AllocId, Size, Self::ProvenanceExtra)> {
    let (prov, offset) = ptr.prov_and_relative_offset();
    Some((prov.alloc_id(), offset, prov.immutable()))
}
#[inline(always)]
fn get_global_alloc_salt(_ecx: &InterpCx<'tcx, Self>,
    _instance: Option<ty::Instance<'tcx>>) -> usize {
    CTFE_ALLOC_SALT
}compile_time_machine!(<'tcx>);
403
404    const PANIC_ON_ALLOC_FAIL: bool = false; // will be raised as a proper error
405
406    #[inline(always)]
407    fn enforce_alignment(ecx: &InterpCx<'tcx, Self>) -> bool {
408        #[allow(non_exhaustive_omitted_patterns)] match ecx.machine.check_alignment {
    CheckAlignment::Error => true,
    _ => false,
}matches!(ecx.machine.check_alignment, CheckAlignment::Error)
409    }
410
411    #[inline(always)]
412    fn enforce_validity(ecx: &InterpCx<'tcx, Self>, layout: TyAndLayout<'tcx>) -> bool {
413        ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks || layout.is_uninhabited()
414    }
415
416    fn load_mir(
417        ecx: &InterpCx<'tcx, Self>,
418        instance: ty::InstanceKind<'tcx>,
419    ) -> &'tcx mir::Body<'tcx> {
420        match instance {
421            ty::InstanceKind::Item(def) => ecx.tcx.mir_for_ctfe(def),
422            _ => ecx.tcx.instance_mir(instance),
423        }
424    }
425
426    fn find_mir_or_eval_fn(
427        ecx: &mut InterpCx<'tcx, Self>,
428        orig_instance: ty::Instance<'tcx>,
429        _abi: &FnAbi<'tcx, Ty<'tcx>>,
430        args: &[FnArg<'tcx>],
431        dest: &PlaceTy<'tcx>,
432        ret: Option<mir::BasicBlock>,
433        _unwind: mir::UnwindAction, // unwinding is not supported in consts
434    ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
435        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/const_eval/machine.rs:435",
                        "rustc_const_eval::const_eval::machine",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/const_eval/machine.rs"),
                        ::tracing_core::__macro_support::Option::Some(435u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::machine"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("find_mir_or_eval_fn: {0:?}",
                                                    orig_instance) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("find_mir_or_eval_fn: {:?}", orig_instance);
436
437        // Replace some functions.
438        let Some(instance) = ecx.hook_special_const_fn(orig_instance, args, dest, ret)? else {
439            // Call has already been handled.
440            return interp_ok(None);
441        };
442
443        // Only check non-glue functions
444        if let ty::InstanceKind::Item(def) = instance.def {
445            // Execution might have wandered off into other crates, so we cannot do a stability-
446            // sensitive check here. But we can at least rule out functions that are not const at
447            // all. That said, we have to allow calling functions inside a `const trait`. These
448            // *are* const-checked!
449            if !ecx.tcx.is_const_fn(def) || {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def, &ecx.tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcDoNotConstCheck) =>
                            {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Tool { .. } |
                            ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(ecx.tcx, def, RustcDoNotConstCheck) {
450                // We certainly do *not* want to actually call this fn. const-checking should have
451                // prevented this, but this can be reached with unleashed-miri, so make testing
452                // simpler by avoiding ICEs there. (Technically this can still ICE if miri-unleash
453                // was set in a dependency rather than the current crate. That's okay, it's an
454                // internal unstable feature.)
455                if ecx.tcx.sess.opts.unstable_opts.unleash_the_miri_inside_of_you {
456                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("calling non-const function `{0}`",
                            instance))
                })))throw_unsup_format!("calling non-const function `{}`", instance)
457                } else {
458                    ::rustc_span::macros::bug_impl(Some(ecx.cur_span()),
    format_args!("calling non-const function `{0}`", instance),
    Location::caller())span_bug!(ecx.cur_span(), "calling non-const function `{}`", instance)
459                }
460            }
461        }
462
463        // This is a const fn. Call it.
464        // In case of replacement, we return the *original* instance to make backtraces work out
465        // (and we hope this does not confuse the FnAbi checks too much).
466        interp_ok(Some((ecx.load_mir(instance.def, None)?, orig_instance)))
467    }
468
469    fn panic_nounwind(ecx: &mut InterpCx<'tcx, Self>, msg: &str) -> InterpResult<'tcx> {
470        let msg = Symbol::intern(msg);
471        let span = ecx.caller_location();
472        let (file, line, col) = ecx.location_triple_for_span(span);
473        Err(ConstEvalErrKind::Panic { msg, file, line, col }).into()
474    }
475
476    fn call_intrinsic(
477        ecx: &mut InterpCx<'tcx, Self>,
478        instance: ty::Instance<'tcx>,
479        args: &[OpTy<'tcx>],
480        dest: &PlaceTy<'tcx, Self::Provenance>,
481        target: Option<mir::BasicBlock>,
482        _unwind: mir::UnwindAction,
483    ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
484        // Shared intrinsics.
485        if ecx.eval_intrinsic(instance, args, dest, target)? {
486            return interp_ok(None);
487        }
488        let intrinsic_name = ecx.tcx.intrinsic(instance.def_id()).unwrap().name;
489
490        let do_fallback = |ecx: &mut InterpCx<'tcx, Self>| {
491            // We haven't handled the intrinsic, let's see if we can use a fallback body.
492            if ecx.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden {
493                do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("intrinsic `{0}` is not supported at compile-time",
                            intrinsic_name))
                })));throw_unsup_format!(
494                    "intrinsic `{intrinsic_name}` is not supported at compile-time"
495                );
496            }
497            return interp_ok(Some(ty::Instance {
498                def: ty::InstanceKind::Item(instance.def_id()),
499                args: instance.args,
500            }));
501        };
502
503        // Backend intrinsics are not supported in const eval except with their fallback
504        // bodies.
505        let Intrinsic::Rustc(intrinsic_name) = intrinsic_name else {
506            return do_fallback(ecx);
507        };
508
509        if !ecx.call_type_info_intrinsic(intrinsic_name, instance, args, dest, target)?
510            && !ecx.call_ctfe_intrinsic(intrinsic_name, instance, args, dest, target)?
511        {
512            return do_fallback(ecx);
513        }
514
515        interp_ok(None)
516    }
517
518    fn call_llvm_intrinsic(
519        ecx: &mut InterpCx<'tcx, Self>,
520        instance: ty::Instance<'tcx>,
521        _args: &[OpTy<'tcx>],
522        _dest: &PlaceTy<'tcx, Self::Provenance>,
523        _target: Option<mir::BasicBlock>,
524    ) -> InterpResult<'tcx> {
525        let intrinsic_name = ecx.tcx.codegen_fn_attrs(instance.def_id()).symbol_name.unwrap();
526
527        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("LLVM intrinsic `{0}` is not supported at compile-time",
                            intrinsic_name))
                })));throw_unsup_format!("LLVM intrinsic `{intrinsic_name}` is not supported at compile-time");
528    }
529
530    fn assert_panic(
531        ecx: &mut InterpCx<'tcx, Self>,
532        msg: &AssertMessage<'tcx>,
533        _unwind: mir::UnwindAction,
534    ) -> InterpResult<'tcx> {
535        use rustc_middle::mir::AssertKind::*;
536        // Convert `AssertKind<Operand>` to `AssertKind<Scalar>`.
537        let eval_to_int =
538            |op| ecx.read_immediate(&ecx.eval_operand(op, None)?).map(|x| x.to_const_int());
539        let err = match msg {
540            BoundsCheck { len, index } => {
541                let len = eval_to_int(len)?;
542                let index = eval_to_int(index)?;
543                BoundsCheck { len, index }
544            }
545            Overflow(op, l, r) => Overflow(*op, eval_to_int(l)?, eval_to_int(r)?),
546            OverflowNeg(op) => OverflowNeg(eval_to_int(op)?),
547            DivisionByZero(op) => DivisionByZero(eval_to_int(op)?),
548            RemainderByZero(op) => RemainderByZero(eval_to_int(op)?),
549            ResumedAfterReturn(coroutine_kind) => ResumedAfterReturn(*coroutine_kind),
550            ResumedAfterPanic(coroutine_kind) => ResumedAfterPanic(*coroutine_kind),
551            ResumedAfterDrop(coroutine_kind) => ResumedAfterDrop(*coroutine_kind),
552            MisalignedPointerDereference { required, found } => MisalignedPointerDereference {
553                required: eval_to_int(required)?,
554                found: eval_to_int(found)?,
555            },
556            NullPointerDereference => NullPointerDereference,
557            NullReferenceConstructed => NullReferenceConstructed,
558            InvalidEnumConstruction(source) => InvalidEnumConstruction(eval_to_int(source)?),
559        };
560        Err(ConstEvalErrKind::AssertFailure(err)).into()
561    }
562
563    #[inline(always)]
564    fn runtime_checks(
565        _ecx: &InterpCx<'tcx, Self>,
566        _r: mir::RuntimeChecks,
567    ) -> InterpResult<'tcx, bool> {
568        // We can't look at `tcx.sess` here as that can differ across crates, which can lead to
569        // unsound differences in evaluating the same constant at different instantiation sites.
570        interp_ok(true)
571    }
572
573    fn binary_ptr_op(
574        _ecx: &InterpCx<'tcx, Self>,
575        _bin_op: mir::BinOp,
576        _left: &ImmTy<'tcx>,
577        _right: &ImmTy<'tcx>,
578    ) -> InterpResult<'tcx, ImmTy<'tcx>> {
579        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("pointer arithmetic or comparison is not supported at compile-time"))
                })));throw_unsup_format!("pointer arithmetic or comparison is not supported at compile-time");
580    }
581
582    fn increment_const_eval_counter(ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
583        // The step limit has already been hit in a previous call to `increment_const_eval_counter`.
584
585        if let Some(new_steps) = ecx.machine.num_evaluated_steps.checked_add(1) {
586            let (limit, start) = if ecx.tcx.sess.opts.unstable_opts.tiny_const_eval_limit {
587                (TINY_LINT_TERMINATOR_LIMIT, TINY_LINT_TERMINATOR_LIMIT)
588            } else {
589                (LINT_TERMINATOR_LIMIT, PROGRESS_INDICATOR_START)
590            };
591
592            ecx.machine.num_evaluated_steps = new_steps;
593            // By default, we have a *deny* lint kicking in after some time
594            // to ensure `loop {}` doesn't just go forever.
595            // In case that lint got reduced, in particular for `--cap-lint` situations, we also
596            // have a hard warning shown every now and then for really long executions.
597            if new_steps == limit {
598                // By default, we stop after a million steps, but the user can disable this lint
599                // to be able to run until the heat death of the universe or power loss, whichever
600                // comes first.
601                let hir_id = ecx.machine.best_lint_scope(*ecx.tcx);
602                let is_error = ecx
603                    .tcx
604                    .lint_level_spec_at_node(LONG_RUNNING_CONST_EVAL, hir_id)
605                    .level()
606                    .is_error();
607                let span = ecx.cur_span();
608                ecx.tcx.emit_node_span_lint(
609                    LONG_RUNNING_CONST_EVAL,
610                    hir_id,
611                    span,
612                    LongRunning { item_span: ecx.tcx.span },
613                );
614                // If this was a hard error, don't bother continuing evaluation.
615                if is_error {
616                    let guard = ecx
617                        .tcx
618                        .dcx()
619                        .span_delayed_bug(span, "The deny lint should have already errored");
620                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::AlreadyReported(ReportedErrorInfo::allowed_in_infallible(guard)));throw_inval!(AlreadyReported(ReportedErrorInfo::allowed_in_infallible(guard)));
621                }
622            } else if new_steps > start && new_steps.is_power_of_two() {
623                // Only report after a certain number of terminators have been evaluated and the
624                // current number of evaluated terminators is a power of 2. The latter gives us a cheap
625                // way to implement exponential backoff.
626                let span = ecx.cur_span();
627                let mut warn =
628                    ecx.tcx.dcx().create_warn(LongRunningWarn { span, item_span: ecx.tcx.span });
629                // We store a unique number in `force_duplicate` to evade `-Z deduplicate-diagnostics`.
630                // `new_steps` is guaranteed to be unique because `ecx.machine.num_evaluated_steps` is
631                // always increasing.
632                warn.arg("force_duplicate", new_steps);
633                warn.emit();
634            }
635        }
636
637        interp_ok(())
638    }
639
640    #[inline(always)]
641    fn expose_provenance(
642        _ecx: &InterpCx<'tcx, Self>,
643        _provenance: Self::Provenance,
644    ) -> InterpResult<'tcx> {
645        // This is only reachable with -Zunleash-the-miri-inside-of-you.
646        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("exposing pointers is not possible at compile-time"))
                })))throw_unsup_format!("exposing pointers is not possible at compile-time")
647    }
648
649    #[inline(always)]
650    fn init_frame(
651        ecx: &mut InterpCx<'tcx, Self>,
652        frame: Frame<'tcx>,
653    ) -> InterpResult<'tcx, Frame<'tcx>> {
654        // Enforce stack size limit. Add 1 because this is run before the new frame is pushed.
655        if !ecx.recursion_limit.value_within_limit(ecx.stack().len() + 1) {
656            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::ResourceExhaustion(::rustc_middle::mir::interpret::ResourceExhaustionInfo::StackFrameLimitReached)throw_exhaust!(StackFrameLimitReached)
657        } else {
658            interp_ok(frame)
659        }
660    }
661
662    #[inline(always)]
663    fn stack<'a>(
664        ecx: &'a InterpCx<'tcx, Self>,
665    ) -> &'a [Frame<'tcx, Self::Provenance, Self::FrameExtra>] {
666        &ecx.machine.stack
667    }
668
669    #[inline(always)]
670    fn stack_mut<'a>(
671        ecx: &'a mut InterpCx<'tcx, Self>,
672    ) -> &'a mut Vec<Frame<'tcx, Self::Provenance, Self::FrameExtra>> {
673        &mut ecx.machine.stack
674    }
675
676    fn before_access_global(
677        _tcx: TyCtxtAt<'tcx>,
678        machine: &Self,
679        alloc_id: AllocId,
680        alloc: ConstAllocation<'tcx>,
681        _static_def_id: Option<DefId>,
682        is_write: bool,
683    ) -> InterpResult<'tcx> {
684        let alloc = alloc.inner();
685        if is_write {
686            // Write access. These are never allowed, but we give a targeted error message.
687            match alloc.mutability {
688                Mutability::Not => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::WriteToReadOnly(alloc_id))throw_ub!(WriteToReadOnly(alloc_id)),
689                Mutability::Mut => Err(ConstEvalErrKind::ModifiedGlobal).into(),
690            }
691        } else {
692            // Read access. These are usually allowed, with some exceptions.
693            if machine.can_access_mut_global == CanAccessMutGlobal::Yes {
694                // Machine configuration allows us read from anything (e.g., `static` initializer).
695                interp_ok(())
696            } else if alloc.mutability == Mutability::Mut {
697                // Machine configuration does not allow us to read statics (e.g., `const`
698                // initializer).
699                Err(ConstEvalErrKind::ConstAccessesMutGlobal).into()
700            } else {
701                // Immutable global, this read is fine.
702                {
    match (&alloc.mutability, &Mutability::Not) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(alloc.mutability, Mutability::Not);
703                interp_ok(())
704            }
705        }
706    }
707
708    fn retag_ptr_value(
709        ecx: &mut InterpCx<'tcx, Self>,
710        val: &ImmTy<'tcx, CtfeProvenance>,
711        _ty: Ty<'tcx>,
712    ) -> InterpResult<'tcx, Option<ImmTy<'tcx, CtfeProvenance>>> {
713        if #[allow(non_exhaustive_omitted_patterns)] match ecx.machine.retag_mode {
    RetagMode::None | RetagMode::Raw => true,
    _ => false,
}matches!(ecx.machine.retag_mode, RetagMode::None | RetagMode::Raw) {
714            return interp_ok(None);
715        }
716        // If it's a frozen shared reference that's not already immutable, potentially make it immutable.
717        // (Do nothing on `None` provenance, that cannot be used to perform mutation anyway.)
718        // Note that const-checking relies on the UB detection we are implementing here! Specifically,
719        // the analysis for which destructors may be invoked relies on `&impl Freeze` references not
720        // being able to change what gets dropped.
721        if let ty::Ref(_, ty, mutbl) = val.layout.ty.kind()
722            && *mutbl == Mutability::Not
723            && val.to_scalar_and_meta().0.to_pointer(ecx).provenance.is_some_and(|p| !p.immutable())
724        {
725            // That next check is expensive, that's why we have all the guards above.
726            let is_immutable = ty.is_freeze(*ecx.tcx, ecx.typing_env());
727            let place = ecx.imm_ptr_to_mplace(val)?;
728            let new_place = if is_immutable {
729                place.map_provenance(CtfeProvenance::as_immutable)
730            } else {
731                // Even if it is not immutable, remember that it is a shared reference.
732                // This allows it to become part of the final value of the constant.
733                // (See <https://github.com/rust-lang/rust/pull/128543> for why we allow this
734                // even when there is interior mutability.)
735                place.map_provenance(CtfeProvenance::as_shared_ref)
736            };
737            interp_ok(Some(ImmTy::from_immediate(new_place.to_ref(ecx), val.layout)))
738        } else {
739            interp_ok(None)
740        }
741    }
742
743    fn with_retag_mode<T>(
744        ecx: &mut InterpCx<'tcx, Self>,
745        mode: RetagMode,
746        f: impl FnOnce(&mut InterpCx<'tcx, Self>) -> InterpResult<'tcx, T>,
747    ) -> InterpResult<'tcx, T> {
748        let old_mode = mem::replace(&mut ecx.machine.retag_mode, mode);
749        let ret = f(ecx);
750        ecx.machine.retag_mode = old_mode;
751        ret
752    }
753
754    fn before_memory_write(
755        _tcx: TyCtxtAt<'tcx>,
756        _machine: &mut Self,
757        _alloc_extra: &mut Self::AllocExtra,
758        _ptr: Pointer<Option<Self::Provenance>>,
759        (_alloc_id, immutable): (AllocId, bool),
760        range: AllocRange,
761    ) -> InterpResult<'tcx> {
762        if range.size == Size::ZERO {
763            // Nothing to check.
764            return interp_ok(());
765        }
766        // Reject writes through immutable pointers.
767        if immutable {
768            return Err(ConstEvalErrKind::WriteThroughImmutablePointer).into();
769        }
770        // Everything else is fine.
771        interp_ok(())
772    }
773
774    fn before_alloc_access(
775        tcx: TyCtxtAt<'tcx>,
776        machine: &Self,
777        alloc_id: AllocId,
778    ) -> InterpResult<'tcx> {
779        if machine.stack.is_empty() {
780            // Get out of the way for the final copy.
781            return interp_ok(());
782        }
783        // Check if this is the currently evaluated static.
784        if Some(alloc_id) == machine.static_root_ids.map(|(id, _)| id) {
785            return Err(ConstEvalErrKind::RecursiveStatic).into();
786        }
787        // If this is another static, make sure we fire off the query to detect cycles.
788        // But only do that when checks for static recursion are enabled.
789        if machine.static_root_ids.is_some() {
790            if let Some(GlobalAlloc::Static(def_id)) = tcx.try_get_global_alloc(alloc_id) {
791                if tcx.is_foreign_item(def_id) {
792                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::ExternStatic(def_id));throw_unsup!(ExternStatic(def_id));
793                }
794                tcx.eval_static_initializer(def_id)?;
795            }
796        }
797        interp_ok(())
798    }
799
800    fn cached_union_data_range<'e>(
801        ecx: &'e mut InterpCx<'tcx, Self>,
802        ty: Ty<'tcx>,
803        compute_range: impl FnOnce() -> RangeSet,
804    ) -> Cow<'e, RangeSet> {
805        if ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks {
806            Cow::Borrowed(ecx.machine.union_data_ranges.entry(ty).or_insert_with(compute_range))
807        } else {
808            // Don't bother caching, we're only doing one validation at the end anyway.
809            Cow::Owned(compute_range())
810        }
811    }
812
813    fn get_default_alloc_params(&self) -> <Self::Bytes as mir::interpret::AllocBytes>::AllocParams {
814    }
815}
816
817// Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups
818// so we can end up having a file with just that impl, but for now, let's keep the impl discoverable
819// at the bottom of this file.