rustc_const_eval/const_eval/
machine.rs

1use std::borrow::{Borrow, Cow};
2use std::fmt;
3use std::hash::Hash;
4
5use rustc_abi::{Align, Size};
6use rustc_ast::Mutability;
7use rustc_data_structures::fx::{FxHashMap, FxIndexMap, IndexEntry};
8use rustc_hir::def_id::{DefId, LocalDefId};
9use rustc_hir::{self as hir, CRATE_HIR_ID, LangItem};
10use rustc_middle::mir::AssertMessage;
11use rustc_middle::mir::interpret::ReportedErrorInfo;
12use rustc_middle::query::TyCtxtAt;
13use rustc_middle::ty::layout::{HasTypingEnv, TyAndLayout, ValidityRequirement};
14use rustc_middle::ty::{self, Ty, TyCtxt};
15use rustc_middle::{bug, mir};
16use rustc_span::{Span, Symbol, sym};
17use rustc_target::callconv::FnAbi;
18use tracing::debug;
19
20use super::error::*;
21use crate::errors::{LongRunning, LongRunningWarn};
22use crate::fluent_generated as fluent;
23use crate::interpret::{
24    self, AllocId, AllocInit, AllocRange, ConstAllocation, CtfeProvenance, FnArg, Frame,
25    GlobalAlloc, ImmTy, InterpCx, InterpResult, OpTy, PlaceTy, Pointer, RangeSet, Scalar,
26    compile_time_machine, err_inval, interp_ok, throw_exhaust, throw_inval, throw_ub,
27    throw_ub_custom, throw_unsup, throw_unsup_format,
28};
29
30/// When hitting this many interpreted terminators we emit a deny by default lint
31/// that notfies the user that their constant takes a long time to evaluate. If that's
32/// what they intended, they can just allow the lint.
33const LINT_TERMINATOR_LIMIT: usize = 2_000_000;
34/// The limit used by `-Z tiny-const-eval-limit`. This smaller limit is useful for internal
35/// tests not needing to run 30s or more to show some behaviour.
36const TINY_LINT_TERMINATOR_LIMIT: usize = 20;
37/// After this many interpreted terminators, we start emitting progress indicators at every
38/// power of two of interpreted terminators.
39const PROGRESS_INDICATOR_START: usize = 4_000_000;
40
41/// Extra machine state for CTFE, and the Machine instance.
42//
43// Should be public because out-of-tree rustc consumers need this
44// if they want to interact with constant values.
45pub struct CompileTimeMachine<'tcx> {
46    /// The number of terminators that have been evaluated.
47    ///
48    /// This is used to produce lints informing the user that the compiler is not stuck.
49    /// Set to `usize::MAX` to never report anything.
50    pub(super) num_evaluated_steps: usize,
51
52    /// The virtual call stack.
53    pub(super) stack: Vec<Frame<'tcx>>,
54
55    /// Pattern matching on consts with references would be unsound if those references
56    /// could point to anything mutable. Therefore, when evaluating consts and when constructing valtrees,
57    /// we ensure that only immutable global memory can be accessed.
58    pub(super) can_access_mut_global: CanAccessMutGlobal,
59
60    /// Whether to check alignment during evaluation.
61    pub(super) check_alignment: CheckAlignment,
62
63    /// If `Some`, we are evaluating the initializer of the static with the given `LocalDefId`,
64    /// storing the result in the given `AllocId`.
65    /// Used to prevent accesses to a static's base allocation, as that may allow for self-initialization loops.
66    pub(crate) static_root_ids: Option<(AllocId, LocalDefId)>,
67
68    /// A cache of "data range" computations for unions (i.e., the offsets of non-padding bytes).
69    union_data_ranges: FxHashMap<Ty<'tcx>, RangeSet>,
70}
71
72#[derive(Copy, Clone)]
73pub enum CheckAlignment {
74    /// Ignore all alignment requirements.
75    /// This is mainly used in interning.
76    No,
77    /// Hard error when dereferencing a misaligned pointer.
78    Error,
79}
80
81#[derive(Copy, Clone, PartialEq)]
82pub(crate) enum CanAccessMutGlobal {
83    No,
84    Yes,
85}
86
87impl From<bool> for CanAccessMutGlobal {
88    fn from(value: bool) -> Self {
89        if value { Self::Yes } else { Self::No }
90    }
91}
92
93impl<'tcx> CompileTimeMachine<'tcx> {
94    pub(crate) fn new(
95        can_access_mut_global: CanAccessMutGlobal,
96        check_alignment: CheckAlignment,
97    ) -> Self {
98        CompileTimeMachine {
99            num_evaluated_steps: 0,
100            stack: Vec::new(),
101            can_access_mut_global,
102            check_alignment,
103            static_root_ids: None,
104            union_data_ranges: FxHashMap::default(),
105        }
106    }
107}
108
109impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxIndexMap<K, V> {
110    #[inline(always)]
111    fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
112    where
113        K: Borrow<Q>,
114    {
115        FxIndexMap::contains_key(self, k)
116    }
117
118    #[inline(always)]
119    fn contains_key_ref<Q: ?Sized + Hash + Eq>(&self, k: &Q) -> bool
120    where
121        K: Borrow<Q>,
122    {
123        FxIndexMap::contains_key(self, k)
124    }
125
126    #[inline(always)]
127    fn insert(&mut self, k: K, v: V) -> Option<V> {
128        FxIndexMap::insert(self, k, v)
129    }
130
131    #[inline(always)]
132    fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
133    where
134        K: Borrow<Q>,
135    {
136        // FIXME(#120456) - is `swap_remove` correct?
137        FxIndexMap::swap_remove(self, k)
138    }
139
140    #[inline(always)]
141    fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
142        self.iter().filter_map(move |(k, v)| f(k, v)).collect()
143    }
144
145    #[inline(always)]
146    fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
147        match self.get(&k) {
148            Some(v) => Ok(v),
149            None => {
150                vacant()?;
151                bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
152            }
153        }
154    }
155
156    #[inline(always)]
157    fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
158        match self.entry(k) {
159            IndexEntry::Occupied(e) => Ok(e.into_mut()),
160            IndexEntry::Vacant(e) => {
161                let v = vacant()?;
162                Ok(e.insert(v))
163            }
164        }
165    }
166}
167
168pub type CompileTimeInterpCx<'tcx> = InterpCx<'tcx, CompileTimeMachine<'tcx>>;
169
170#[derive(Debug, PartialEq, Eq, Copy, Clone)]
171pub enum MemoryKind {
172    Heap {
173        /// Indicates whether `make_global` was called on this allocation.
174        /// If this is `true`, the allocation must be immutable.
175        was_made_global: bool,
176    },
177}
178
179impl fmt::Display for MemoryKind {
180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181        match self {
182            MemoryKind::Heap { was_made_global } => {
183                write!(f, "heap allocation{}", if *was_made_global { " (made global)" } else { "" })
184            }
185        }
186    }
187}
188
189impl interpret::MayLeak for MemoryKind {
190    #[inline(always)]
191    fn may_leak(self) -> bool {
192        match self {
193            MemoryKind::Heap { was_made_global } => was_made_global,
194        }
195    }
196}
197
198impl interpret::MayLeak for ! {
199    #[inline(always)]
200    fn may_leak(self) -> bool {
201        // `self` is uninhabited
202        self
203    }
204}
205
206impl<'tcx> CompileTimeInterpCx<'tcx> {
207    fn location_triple_for_span(&self, span: Span) -> (Symbol, u32, u32) {
208        let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
209        let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
210
211        use rustc_session::RemapFileNameExt;
212        use rustc_session::config::RemapPathScopeComponents;
213        (
214            Symbol::intern(
215                &caller
216                    .file
217                    .name
218                    .for_scope(self.tcx.sess, RemapPathScopeComponents::DIAGNOSTICS)
219                    .to_string_lossy(),
220            ),
221            u32::try_from(caller.line).unwrap(),
222            u32::try_from(caller.col_display).unwrap().checked_add(1).unwrap(),
223        )
224    }
225
226    /// "Intercept" a function call, because we have something special to do for it.
227    /// All `#[rustc_do_not_const_check]` functions MUST be hooked here.
228    /// If this returns `Some` function, which may be `instance` or a different function with
229    /// compatible arguments, then evaluation should continue with that function.
230    /// If this returns `None`, the function call has been handled and the function has returned.
231    fn hook_special_const_fn(
232        &mut self,
233        instance: ty::Instance<'tcx>,
234        args: &[FnArg<'tcx>],
235        _dest: &PlaceTy<'tcx>,
236        _ret: Option<mir::BasicBlock>,
237    ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
238        let def_id = instance.def_id();
239
240        if self.tcx.has_attr(def_id, sym::rustc_const_panic_str)
241            || self.tcx.is_lang_item(def_id, LangItem::BeginPanic)
242        {
243            let args = self.copy_fn_args(args);
244            // &str or &&str
245            assert!(args.len() == 1);
246
247            let mut msg_place = self.deref_pointer(&args[0])?;
248            while msg_place.layout.ty.is_ref() {
249                msg_place = self.deref_pointer(&msg_place)?;
250            }
251
252            let msg = Symbol::intern(self.read_str(&msg_place)?);
253            let span = self.find_closest_untracked_caller_location();
254            let (file, line, col) = self.location_triple_for_span(span);
255            return Err(ConstEvalErrKind::Panic { msg, file, line, col }).into();
256        } else if self.tcx.is_lang_item(def_id, LangItem::PanicFmt) {
257            // For panic_fmt, call const_panic_fmt instead.
258            let const_def_id = self.tcx.require_lang_item(LangItem::ConstPanicFmt, self.tcx.span);
259            let new_instance = ty::Instance::expect_resolve(
260                *self.tcx,
261                self.typing_env(),
262                const_def_id,
263                instance.args,
264                self.cur_span(),
265            );
266
267            return interp_ok(Some(new_instance));
268        }
269        interp_ok(Some(instance))
270    }
271
272    /// See documentation on the `ptr_guaranteed_cmp` intrinsic.
273    /// Returns `2` if the result is unknown.
274    /// Returns `1` if the pointers are guaranteed equal.
275    /// Returns `0` if the pointers are guaranteed inequal.
276    ///
277    /// Note that this intrinsic is exposed on stable for comparison with null. In other words, any
278    /// change to this function that affects comparison with null is insta-stable!
279    fn guaranteed_cmp(&mut self, a: Scalar, b: Scalar) -> InterpResult<'tcx, u8> {
280        interp_ok(match (a, b) {
281            // Comparisons between integers are always known.
282            (Scalar::Int(a), Scalar::Int(b)) => (a == b) as u8,
283            // Comparisons of null with an arbitrary scalar can be known if `scalar_may_be_null`
284            // indicates that the scalar can definitely *not* be null.
285            (Scalar::Int(int), ptr) | (ptr, Scalar::Int(int))
286                if int.is_null() && !self.scalar_may_be_null(ptr)? =>
287            {
288                0
289            }
290            // Other ways of comparing integers and pointers can never be known for sure.
291            (Scalar::Int { .. }, Scalar::Ptr(..)) | (Scalar::Ptr(..), Scalar::Int { .. }) => 2,
292            // FIXME: return a `1` for when both sides are the same pointer, *except* that
293            // some things (like functions and vtables) do not have stable addresses
294            // so we need to be careful around them (see e.g. #73722).
295            // FIXME: return `0` for at least some comparisons where we can reliably
296            // determine the result of runtime inequality tests at compile-time.
297            // Examples include comparison of addresses in different static items.
298            (Scalar::Ptr(..), Scalar::Ptr(..)) => 2,
299        })
300    }
301}
302
303impl<'tcx> CompileTimeMachine<'tcx> {
304    #[inline(always)]
305    /// Find the first stack frame that is within the current crate, if any.
306    /// Otherwise, return the crate's HirId
307    pub fn best_lint_scope(&self, tcx: TyCtxt<'tcx>) -> hir::HirId {
308        self.stack.iter().find_map(|frame| frame.lint_root(tcx)).unwrap_or(CRATE_HIR_ID)
309    }
310}
311
312impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
313    compile_time_machine!(<'tcx>);
314
315    const PANIC_ON_ALLOC_FAIL: bool = false; // will be raised as a proper error
316
317    #[inline(always)]
318    fn enforce_alignment(ecx: &InterpCx<'tcx, Self>) -> bool {
319        matches!(ecx.machine.check_alignment, CheckAlignment::Error)
320    }
321
322    #[inline(always)]
323    fn enforce_validity(ecx: &InterpCx<'tcx, Self>, layout: TyAndLayout<'tcx>) -> bool {
324        ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks || layout.is_uninhabited()
325    }
326
327    fn load_mir(
328        ecx: &InterpCx<'tcx, Self>,
329        instance: ty::InstanceKind<'tcx>,
330    ) -> &'tcx mir::Body<'tcx> {
331        match instance {
332            ty::InstanceKind::Item(def) => ecx.tcx.mir_for_ctfe(def),
333            _ => ecx.tcx.instance_mir(instance),
334        }
335    }
336
337    fn find_mir_or_eval_fn(
338        ecx: &mut InterpCx<'tcx, Self>,
339        orig_instance: ty::Instance<'tcx>,
340        _abi: &FnAbi<'tcx, Ty<'tcx>>,
341        args: &[FnArg<'tcx>],
342        dest: &PlaceTy<'tcx>,
343        ret: Option<mir::BasicBlock>,
344        _unwind: mir::UnwindAction, // unwinding is not supported in consts
345    ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
346        debug!("find_mir_or_eval_fn: {:?}", orig_instance);
347
348        // Replace some functions.
349        let Some(instance) = ecx.hook_special_const_fn(orig_instance, args, dest, ret)? else {
350            // Call has already been handled.
351            return interp_ok(None);
352        };
353
354        // Only check non-glue functions
355        if let ty::InstanceKind::Item(def) = instance.def {
356            // Execution might have wandered off into other crates, so we cannot do a stability-
357            // sensitive check here. But we can at least rule out functions that are not const at
358            // all. That said, we have to allow calling functions inside a `const trait`. These
359            // *are* const-checked!
360            if !ecx.tcx.is_const_fn(def) || ecx.tcx.has_attr(def, sym::rustc_do_not_const_check) {
361                // We certainly do *not* want to actually call the fn
362                // though, so be sure we return here.
363                throw_unsup_format!("calling non-const function `{}`", instance)
364            }
365        }
366
367        // This is a const fn. Call it.
368        // In case of replacement, we return the *original* instance to make backtraces work out
369        // (and we hope this does not confuse the FnAbi checks too much).
370        interp_ok(Some((ecx.load_mir(instance.def, None)?, orig_instance)))
371    }
372
373    fn panic_nounwind(ecx: &mut InterpCx<'tcx, Self>, msg: &str) -> InterpResult<'tcx> {
374        let msg = Symbol::intern(msg);
375        let span = ecx.find_closest_untracked_caller_location();
376        let (file, line, col) = ecx.location_triple_for_span(span);
377        Err(ConstEvalErrKind::Panic { msg, file, line, col }).into()
378    }
379
380    fn call_intrinsic(
381        ecx: &mut InterpCx<'tcx, Self>,
382        instance: ty::Instance<'tcx>,
383        args: &[OpTy<'tcx>],
384        dest: &PlaceTy<'tcx, Self::Provenance>,
385        target: Option<mir::BasicBlock>,
386        _unwind: mir::UnwindAction,
387    ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
388        // Shared intrinsics.
389        if ecx.eval_intrinsic(instance, args, dest, target)? {
390            return interp_ok(None);
391        }
392        let intrinsic_name = ecx.tcx.item_name(instance.def_id());
393
394        // CTFE-specific intrinsics.
395        match intrinsic_name {
396            sym::ptr_guaranteed_cmp => {
397                let a = ecx.read_scalar(&args[0])?;
398                let b = ecx.read_scalar(&args[1])?;
399                let cmp = ecx.guaranteed_cmp(a, b)?;
400                ecx.write_scalar(Scalar::from_u8(cmp), dest)?;
401            }
402            sym::const_allocate => {
403                let size = ecx.read_scalar(&args[0])?.to_target_usize(ecx)?;
404                let align = ecx.read_scalar(&args[1])?.to_target_usize(ecx)?;
405
406                let align = match Align::from_bytes(align) {
407                    Ok(a) => a,
408                    Err(err) => throw_ub_custom!(
409                        fluent::const_eval_invalid_align_details,
410                        name = "const_allocate",
411                        err_kind = err.diag_ident(),
412                        align = err.align()
413                    ),
414                };
415
416                let ptr = ecx.allocate_ptr(
417                    Size::from_bytes(size),
418                    align,
419                    interpret::MemoryKind::Machine(MemoryKind::Heap { was_made_global: false }),
420                    AllocInit::Uninit,
421                )?;
422                ecx.write_pointer(ptr, dest)?;
423            }
424            sym::const_deallocate => {
425                let ptr = ecx.read_pointer(&args[0])?;
426                let size = ecx.read_scalar(&args[1])?.to_target_usize(ecx)?;
427                let align = ecx.read_scalar(&args[2])?.to_target_usize(ecx)?;
428
429                let size = Size::from_bytes(size);
430                let align = match Align::from_bytes(align) {
431                    Ok(a) => a,
432                    Err(err) => throw_ub_custom!(
433                        fluent::const_eval_invalid_align_details,
434                        name = "const_deallocate",
435                        err_kind = err.diag_ident(),
436                        align = err.align()
437                    ),
438                };
439
440                // If an allocation is created in an another const,
441                // we don't deallocate it.
442                let (alloc_id, _, _) = ecx.ptr_get_alloc_id(ptr, 0)?;
443                let is_allocated_in_another_const = matches!(
444                    ecx.tcx.try_get_global_alloc(alloc_id),
445                    Some(interpret::GlobalAlloc::Memory(_))
446                );
447
448                if !is_allocated_in_another_const {
449                    ecx.deallocate_ptr(
450                        ptr,
451                        Some((size, align)),
452                        interpret::MemoryKind::Machine(MemoryKind::Heap { was_made_global: false }),
453                    )?;
454                }
455            }
456
457            sym::const_make_global => {
458                let ptr = ecx.read_pointer(&args[0])?;
459                ecx.make_const_heap_ptr_global(ptr)?;
460                ecx.write_pointer(ptr, dest)?;
461            }
462
463            // The intrinsic represents whether the value is known to the optimizer (LLVM).
464            // We're not doing any optimizations here, so there is no optimizer that could know the value.
465            // (We know the value here in the machine of course, but this is the runtime of that code,
466            // not the optimization stage.)
467            sym::is_val_statically_known => ecx.write_scalar(Scalar::from_bool(false), dest)?,
468
469            // We handle these here since Miri does not want to have them.
470            sym::assert_inhabited
471            | sym::assert_zero_valid
472            | sym::assert_mem_uninitialized_valid => {
473                let ty = instance.args.type_at(0);
474                let requirement = ValidityRequirement::from_intrinsic(intrinsic_name).unwrap();
475
476                let should_panic = !ecx
477                    .tcx
478                    .check_validity_requirement((requirement, ecx.typing_env().as_query_input(ty)))
479                    .map_err(|_| err_inval!(TooGeneric))?;
480
481                if should_panic {
482                    let layout = ecx.layout_of(ty)?;
483
484                    let msg = match requirement {
485                        // For *all* intrinsics we first check `is_uninhabited` to give a more specific
486                        // error message.
487                        _ if layout.is_uninhabited() => format!(
488                            "aborted execution: attempted to instantiate uninhabited type `{ty}`"
489                        ),
490                        ValidityRequirement::Inhabited => bug!("handled earlier"),
491                        ValidityRequirement::Zero => format!(
492                            "aborted execution: attempted to zero-initialize type `{ty}`, which is invalid"
493                        ),
494                        ValidityRequirement::UninitMitigated0x01Fill => format!(
495                            "aborted execution: attempted to leave type `{ty}` uninitialized, which is invalid"
496                        ),
497                        ValidityRequirement::Uninit => bug!("assert_uninit_valid doesn't exist"),
498                    };
499
500                    Self::panic_nounwind(ecx, &msg)?;
501                    // Skip the `return_to_block` at the end (we panicked, we do not return).
502                    return interp_ok(None);
503                }
504            }
505
506            _ => {
507                // We haven't handled the intrinsic, let's see if we can use a fallback body.
508                if ecx.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden {
509                    throw_unsup_format!(
510                        "intrinsic `{intrinsic_name}` is not supported at compile-time"
511                    );
512                }
513                return interp_ok(Some(ty::Instance {
514                    def: ty::InstanceKind::Item(instance.def_id()),
515                    args: instance.args,
516                }));
517            }
518        }
519
520        // Intrinsic is done, jump to next block.
521        ecx.return_to_block(target)?;
522        interp_ok(None)
523    }
524
525    fn assert_panic(
526        ecx: &mut InterpCx<'tcx, Self>,
527        msg: &AssertMessage<'tcx>,
528        _unwind: mir::UnwindAction,
529    ) -> InterpResult<'tcx> {
530        use rustc_middle::mir::AssertKind::*;
531        // Convert `AssertKind<Operand>` to `AssertKind<Scalar>`.
532        let eval_to_int =
533            |op| ecx.read_immediate(&ecx.eval_operand(op, None)?).map(|x| x.to_const_int());
534        let err = match msg {
535            BoundsCheck { len, index } => {
536                let len = eval_to_int(len)?;
537                let index = eval_to_int(index)?;
538                BoundsCheck { len, index }
539            }
540            Overflow(op, l, r) => Overflow(*op, eval_to_int(l)?, eval_to_int(r)?),
541            OverflowNeg(op) => OverflowNeg(eval_to_int(op)?),
542            DivisionByZero(op) => DivisionByZero(eval_to_int(op)?),
543            RemainderByZero(op) => RemainderByZero(eval_to_int(op)?),
544            ResumedAfterReturn(coroutine_kind) => ResumedAfterReturn(*coroutine_kind),
545            ResumedAfterPanic(coroutine_kind) => ResumedAfterPanic(*coroutine_kind),
546            ResumedAfterDrop(coroutine_kind) => ResumedAfterDrop(*coroutine_kind),
547            MisalignedPointerDereference { required, found } => MisalignedPointerDereference {
548                required: eval_to_int(required)?,
549                found: eval_to_int(found)?,
550            },
551            NullPointerDereference => NullPointerDereference,
552            InvalidEnumConstruction(source) => InvalidEnumConstruction(eval_to_int(source)?),
553        };
554        Err(ConstEvalErrKind::AssertFailure(err)).into()
555    }
556
557    fn binary_ptr_op(
558        _ecx: &InterpCx<'tcx, Self>,
559        _bin_op: mir::BinOp,
560        _left: &ImmTy<'tcx>,
561        _right: &ImmTy<'tcx>,
562    ) -> InterpResult<'tcx, ImmTy<'tcx>> {
563        throw_unsup_format!("pointer arithmetic or comparison is not supported at compile-time");
564    }
565
566    fn increment_const_eval_counter(ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
567        // The step limit has already been hit in a previous call to `increment_const_eval_counter`.
568
569        if let Some(new_steps) = ecx.machine.num_evaluated_steps.checked_add(1) {
570            let (limit, start) = if ecx.tcx.sess.opts.unstable_opts.tiny_const_eval_limit {
571                (TINY_LINT_TERMINATOR_LIMIT, TINY_LINT_TERMINATOR_LIMIT)
572            } else {
573                (LINT_TERMINATOR_LIMIT, PROGRESS_INDICATOR_START)
574            };
575
576            ecx.machine.num_evaluated_steps = new_steps;
577            // By default, we have a *deny* lint kicking in after some time
578            // to ensure `loop {}` doesn't just go forever.
579            // In case that lint got reduced, in particular for `--cap-lint` situations, we also
580            // have a hard warning shown every now and then for really long executions.
581            if new_steps == limit {
582                // By default, we stop after a million steps, but the user can disable this lint
583                // to be able to run until the heat death of the universe or power loss, whichever
584                // comes first.
585                let hir_id = ecx.machine.best_lint_scope(*ecx.tcx);
586                let is_error = ecx
587                    .tcx
588                    .lint_level_at_node(
589                        rustc_session::lint::builtin::LONG_RUNNING_CONST_EVAL,
590                        hir_id,
591                    )
592                    .level
593                    .is_error();
594                let span = ecx.cur_span();
595                ecx.tcx.emit_node_span_lint(
596                    rustc_session::lint::builtin::LONG_RUNNING_CONST_EVAL,
597                    hir_id,
598                    span,
599                    LongRunning { item_span: ecx.tcx.span },
600                );
601                // If this was a hard error, don't bother continuing evaluation.
602                if is_error {
603                    let guard = ecx
604                        .tcx
605                        .dcx()
606                        .span_delayed_bug(span, "The deny lint should have already errored");
607                    throw_inval!(AlreadyReported(ReportedErrorInfo::allowed_in_infallible(guard)));
608                }
609            } else if new_steps > start && new_steps.is_power_of_two() {
610                // Only report after a certain number of terminators have been evaluated and the
611                // current number of evaluated terminators is a power of 2. The latter gives us a cheap
612                // way to implement exponential backoff.
613                let span = ecx.cur_span();
614                // We store a unique number in `force_duplicate` to evade `-Z deduplicate-diagnostics`.
615                // `new_steps` is guaranteed to be unique because `ecx.machine.num_evaluated_steps` is
616                // always increasing.
617                ecx.tcx.dcx().emit_warn(LongRunningWarn {
618                    span,
619                    item_span: ecx.tcx.span,
620                    force_duplicate: new_steps,
621                });
622            }
623        }
624
625        interp_ok(())
626    }
627
628    #[inline(always)]
629    fn expose_provenance(
630        _ecx: &InterpCx<'tcx, Self>,
631        _provenance: Self::Provenance,
632    ) -> InterpResult<'tcx> {
633        // This is only reachable with -Zunleash-the-miri-inside-of-you.
634        throw_unsup_format!("exposing pointers is not possible at compile-time")
635    }
636
637    #[inline(always)]
638    fn init_frame(
639        ecx: &mut InterpCx<'tcx, Self>,
640        frame: Frame<'tcx>,
641    ) -> InterpResult<'tcx, Frame<'tcx>> {
642        // Enforce stack size limit. Add 1 because this is run before the new frame is pushed.
643        if !ecx.recursion_limit.value_within_limit(ecx.stack().len() + 1) {
644            throw_exhaust!(StackFrameLimitReached)
645        } else {
646            interp_ok(frame)
647        }
648    }
649
650    #[inline(always)]
651    fn stack<'a>(
652        ecx: &'a InterpCx<'tcx, Self>,
653    ) -> &'a [Frame<'tcx, Self::Provenance, Self::FrameExtra>] {
654        &ecx.machine.stack
655    }
656
657    #[inline(always)]
658    fn stack_mut<'a>(
659        ecx: &'a mut InterpCx<'tcx, Self>,
660    ) -> &'a mut Vec<Frame<'tcx, Self::Provenance, Self::FrameExtra>> {
661        &mut ecx.machine.stack
662    }
663
664    fn before_access_global(
665        _tcx: TyCtxtAt<'tcx>,
666        machine: &Self,
667        alloc_id: AllocId,
668        alloc: ConstAllocation<'tcx>,
669        _static_def_id: Option<DefId>,
670        is_write: bool,
671    ) -> InterpResult<'tcx> {
672        let alloc = alloc.inner();
673        if is_write {
674            // Write access. These are never allowed, but we give a targeted error message.
675            match alloc.mutability {
676                Mutability::Not => throw_ub!(WriteToReadOnly(alloc_id)),
677                Mutability::Mut => Err(ConstEvalErrKind::ModifiedGlobal).into(),
678            }
679        } else {
680            // Read access. These are usually allowed, with some exceptions.
681            if machine.can_access_mut_global == CanAccessMutGlobal::Yes {
682                // Machine configuration allows us read from anything (e.g., `static` initializer).
683                interp_ok(())
684            } else if alloc.mutability == Mutability::Mut {
685                // Machine configuration does not allow us to read statics (e.g., `const`
686                // initializer).
687                Err(ConstEvalErrKind::ConstAccessesMutGlobal).into()
688            } else {
689                // Immutable global, this read is fine.
690                assert_eq!(alloc.mutability, Mutability::Not);
691                interp_ok(())
692            }
693        }
694    }
695
696    fn retag_ptr_value(
697        ecx: &mut InterpCx<'tcx, Self>,
698        _kind: mir::RetagKind,
699        val: &ImmTy<'tcx, CtfeProvenance>,
700    ) -> InterpResult<'tcx, ImmTy<'tcx, CtfeProvenance>> {
701        // If it's a frozen shared reference that's not already immutable, potentially make it immutable.
702        // (Do nothing on `None` provenance, that cannot store immutability anyway.)
703        if let ty::Ref(_, ty, mutbl) = val.layout.ty.kind()
704            && *mutbl == Mutability::Not
705            && val
706                .to_scalar_and_meta()
707                .0
708                .to_pointer(ecx)?
709                .provenance
710                .is_some_and(|p| !p.immutable())
711        {
712            // That next check is expensive, that's why we have all the guards above.
713            let is_immutable = ty.is_freeze(*ecx.tcx, ecx.typing_env());
714            let place = ecx.ref_to_mplace(val)?;
715            let new_place = if is_immutable {
716                place.map_provenance(CtfeProvenance::as_immutable)
717            } else {
718                // Even if it is not immutable, remember that it is a shared reference.
719                // This allows it to become part of the final value of the constant.
720                // (See <https://github.com/rust-lang/rust/pull/128543> for why we allow this
721                // even when there is interior mutability.)
722                place.map_provenance(CtfeProvenance::as_shared_ref)
723            };
724            interp_ok(ImmTy::from_immediate(new_place.to_ref(ecx), val.layout))
725        } else {
726            interp_ok(val.clone())
727        }
728    }
729
730    fn before_memory_write(
731        _tcx: TyCtxtAt<'tcx>,
732        _machine: &mut Self,
733        _alloc_extra: &mut Self::AllocExtra,
734        _ptr: Pointer<Option<Self::Provenance>>,
735        (_alloc_id, immutable): (AllocId, bool),
736        range: AllocRange,
737    ) -> InterpResult<'tcx> {
738        if range.size == Size::ZERO {
739            // Nothing to check.
740            return interp_ok(());
741        }
742        // Reject writes through immutable pointers.
743        if immutable {
744            return Err(ConstEvalErrKind::WriteThroughImmutablePointer).into();
745        }
746        // Everything else is fine.
747        interp_ok(())
748    }
749
750    fn before_alloc_access(
751        tcx: TyCtxtAt<'tcx>,
752        machine: &Self,
753        alloc_id: AllocId,
754    ) -> InterpResult<'tcx> {
755        if machine.stack.is_empty() {
756            // Get out of the way for the final copy.
757            return interp_ok(());
758        }
759        // Check if this is the currently evaluated static.
760        if Some(alloc_id) == machine.static_root_ids.map(|(id, _)| id) {
761            return Err(ConstEvalErrKind::RecursiveStatic).into();
762        }
763        // If this is another static, make sure we fire off the query to detect cycles.
764        // But only do that when checks for static recursion are enabled.
765        if machine.static_root_ids.is_some() {
766            if let Some(GlobalAlloc::Static(def_id)) = tcx.try_get_global_alloc(alloc_id) {
767                if tcx.is_foreign_item(def_id) {
768                    throw_unsup!(ExternStatic(def_id));
769                }
770                tcx.eval_static_initializer(def_id)?;
771            }
772        }
773        interp_ok(())
774    }
775
776    fn cached_union_data_range<'e>(
777        ecx: &'e mut InterpCx<'tcx, Self>,
778        ty: Ty<'tcx>,
779        compute_range: impl FnOnce() -> RangeSet,
780    ) -> Cow<'e, RangeSet> {
781        if ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks {
782            Cow::Borrowed(ecx.machine.union_data_ranges.entry(ty).or_insert_with(compute_range))
783        } else {
784            // Don't bother caching, we're only doing one validation at the end anyway.
785            Cow::Owned(compute_range())
786        }
787    }
788
789    fn get_default_alloc_params(&self) -> <Self::Bytes as mir::interpret::AllocBytes>::AllocParams {
790    }
791}
792
793// Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups
794// so we can end up having a file with just that impl, but for now, let's keep the impl discoverable
795// at the bottom of this file.