rustc_const_eval/interpret/
machine.rs

1//! This module contains everything needed to instantiate an interpreter.
2//! This separation exists to ensure that no fancy miri features like
3//! interpreting common C functions leak into CTFE.
4
5use std::borrow::{Borrow, Cow};
6use std::fmt::Debug;
7use std::hash::Hash;
8
9use rustc_abi::{Align, Size};
10use rustc_apfloat::{Float, FloatConvert};
11use rustc_middle::query::TyCtxtAt;
12use rustc_middle::ty::Ty;
13use rustc_middle::ty::layout::TyAndLayout;
14use rustc_middle::{mir, ty};
15use rustc_span::Span;
16use rustc_span::def_id::DefId;
17use rustc_target::callconv::FnAbi;
18
19use super::{
20    AllocBytes, AllocId, AllocKind, AllocRange, Allocation, CTFE_ALLOC_SALT, ConstAllocation,
21    CtfeProvenance, FnArg, Frame, ImmTy, InterpCx, InterpResult, MPlaceTy, MemoryKind,
22    Misalignment, OpTy, PlaceTy, Pointer, Provenance, RangeSet, interp_ok, throw_unsup,
23};
24
25/// Data returned by [`Machine::after_stack_pop`], and consumed by
26/// [`InterpCx::return_from_current_stack_frame`] to determine what actions should be done when
27/// returning from a stack frame.
28#[derive(Eq, PartialEq, Debug, Copy, Clone)]
29pub enum ReturnAction {
30    /// Indicates that no special handling should be
31    /// done - we'll either return normally or unwind
32    /// based on the terminator for the function
33    /// we're leaving.
34    Normal,
35
36    /// Indicates that we should *not* jump to the return/unwind address, as the callback already
37    /// took care of everything.
38    NoJump,
39
40    /// Returned by [`InterpCx::pop_stack_frame_raw`] when no cleanup should be done.
41    NoCleanup,
42}
43
44/// Whether this kind of memory is allowed to leak
45pub trait MayLeak: Copy {
46    fn may_leak(self) -> bool;
47}
48
49/// The functionality needed by memory to manage its allocations
50pub trait AllocMap<K: Hash + Eq, V> {
51    /// Tests if the map contains the given key.
52    /// Deliberately takes `&mut` because that is sufficient, and some implementations
53    /// can be more efficient then (using `RefCell::get_mut`).
54    fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
55    where
56        K: Borrow<Q>;
57
58    /// Callers should prefer [`AllocMap::contains_key`] when it is possible to call because it may
59    /// be more efficient. This function exists for callers that only have a shared reference
60    /// (which might make it slightly less efficient than `contains_key`, e.g. if
61    /// the data is stored inside a `RefCell`).
62    fn contains_key_ref<Q: ?Sized + Hash + Eq>(&self, k: &Q) -> bool
63    where
64        K: Borrow<Q>;
65
66    /// Inserts a new entry into the map.
67    fn insert(&mut self, k: K, v: V) -> Option<V>;
68
69    /// Removes an entry from the map.
70    fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
71    where
72        K: Borrow<Q>;
73
74    /// Returns data based on the keys and values in the map.
75    fn filter_map_collect<T>(&self, f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T>;
76
77    /// Returns a reference to entry `k`. If no such entry exists, call
78    /// `vacant` and either forward its error, or add its result to the map
79    /// and return a reference to *that*.
80    fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E>;
81
82    /// Returns a mutable reference to entry `k`. If no such entry exists, call
83    /// `vacant` and either forward its error, or add its result to the map
84    /// and return a reference to *that*.
85    fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E>;
86
87    /// Read-only lookup.
88    fn get(&self, k: K) -> Option<&V> {
89        self.get_or(k, || Err(())).ok()
90    }
91
92    /// Mutable lookup.
93    fn get_mut(&mut self, k: K) -> Option<&mut V> {
94        self.get_mut_or(k, || Err(())).ok()
95    }
96}
97
98/// Methods of this trait signifies a point where CTFE evaluation would fail
99/// and some use case dependent behaviour can instead be applied.
100pub trait Machine<'tcx>: Sized {
101    /// Additional memory kinds a machine wishes to distinguish from the builtin ones
102    type MemoryKind: Debug + std::fmt::Display + MayLeak + Eq + 'static;
103
104    /// Pointers are "tagged" with provenance information; typically the `AllocId` they belong to.
105    type Provenance: Provenance + Eq + Hash + 'static;
106
107    /// When getting the AllocId of a pointer, some extra data is also obtained from the provenance
108    /// that is passed to memory access hooks so they can do things with it.
109    type ProvenanceExtra: Copy + 'static;
110
111    /// Machines can define extra (non-instance) things that represent values of function pointers.
112    /// For example, Miri uses this to return a function pointer from `dlsym`
113    /// that can later be called to execute the right thing.
114    type ExtraFnVal: Debug + Copy;
115
116    /// Extra data stored in every call frame.
117    type FrameExtra;
118
119    /// Extra data stored in every allocation.
120    type AllocExtra: Debug + Clone + 'tcx;
121
122    /// Type for the bytes of the allocation.
123    type Bytes: AllocBytes + 'static;
124
125    /// Memory's allocation map
126    type MemoryMap: AllocMap<
127            AllocId,
128            (
129                MemoryKind<Self::MemoryKind>,
130                Allocation<Self::Provenance, Self::AllocExtra, Self::Bytes>,
131            ),
132        > + Default
133        + Clone;
134
135    /// The memory kind to use for copied global memory (held in `tcx`) --
136    /// or None if such memory should not be mutated and thus any such attempt will cause
137    /// a `ModifiedStatic` error to be raised.
138    /// Statics are copied under two circumstances: When they are mutated, and when
139    /// `adjust_allocation` (see below) returns an owned allocation
140    /// that is added to the memory so that the work is not done twice.
141    const GLOBAL_KIND: Option<Self::MemoryKind>;
142
143    /// Should the machine panic on allocation failures?
144    const PANIC_ON_ALLOC_FAIL: bool;
145
146    /// Determines whether `eval_mir_constant` can never fail because all required consts have
147    /// already been checked before.
148    const ALL_CONSTS_ARE_PRECHECKED: bool = true;
149
150    /// Determines whether rustc_const_eval functions that make use of the [Machine] should make
151    /// tracing calls (to the `tracing` library). By default this is `false`, meaning the tracing
152    /// calls will supposedly be optimized out. This flag is set to `true` inside Miri, to allow
153    /// tracing the interpretation steps, among other things.
154    const TRACING_ENABLED: bool = false;
155
156    /// Whether memory accesses should be alignment-checked.
157    fn enforce_alignment(ecx: &InterpCx<'tcx, Self>) -> bool;
158
159    /// Gives the machine a chance to detect more misalignment than the built-in checks would catch.
160    #[inline(always)]
161    fn alignment_check(
162        _ecx: &InterpCx<'tcx, Self>,
163        _alloc_id: AllocId,
164        _alloc_align: Align,
165        _alloc_kind: AllocKind,
166        _offset: Size,
167        _align: Align,
168    ) -> Option<Misalignment> {
169        None
170    }
171
172    /// Whether to enforce the validity invariant for a specific layout.
173    fn enforce_validity(ecx: &InterpCx<'tcx, Self>, layout: TyAndLayout<'tcx>) -> bool;
174    /// Whether to enforce the validity invariant *recursively*.
175    fn enforce_validity_recursively(
176        _ecx: &InterpCx<'tcx, Self>,
177        _layout: TyAndLayout<'tcx>,
178    ) -> bool {
179        false
180    }
181
182    /// Whether Assert(OverflowNeg) and Assert(Overflow) MIR terminators should actually
183    /// check for overflow.
184    fn ignore_optional_overflow_checks(_ecx: &InterpCx<'tcx, Self>) -> bool;
185
186    /// Entry point for obtaining the MIR of anything that should get evaluated.
187    /// So not just functions and shims, but also const/static initializers, anonymous
188    /// constants, ...
189    fn load_mir(
190        ecx: &InterpCx<'tcx, Self>,
191        instance: ty::InstanceKind<'tcx>,
192    ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
193        interp_ok(ecx.tcx.instance_mir(instance))
194    }
195
196    /// Entry point to all function calls.
197    ///
198    /// Returns either the mir to use for the call, or `None` if execution should
199    /// just proceed (which usually means this hook did all the work that the
200    /// called function should usually have done). In the latter case, it is
201    /// this hook's responsibility to advance the instruction pointer!
202    /// (This is to support functions like `__rust_maybe_catch_panic` that neither find a MIR
203    /// nor just jump to `ret`, but instead push their own stack frame.)
204    /// Passing `dest`and `ret` in the same `Option` proved very annoying when only one of them
205    /// was used.
206    fn find_mir_or_eval_fn(
207        ecx: &mut InterpCx<'tcx, Self>,
208        instance: ty::Instance<'tcx>,
209        abi: &FnAbi<'tcx, Ty<'tcx>>,
210        args: &[FnArg<'tcx, Self::Provenance>],
211        destination: &PlaceTy<'tcx, Self::Provenance>,
212        target: Option<mir::BasicBlock>,
213        unwind: mir::UnwindAction,
214    ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>>;
215
216    /// Execute `fn_val`. It is the hook's responsibility to advance the instruction
217    /// pointer as appropriate.
218    fn call_extra_fn(
219        ecx: &mut InterpCx<'tcx, Self>,
220        fn_val: Self::ExtraFnVal,
221        abi: &FnAbi<'tcx, Ty<'tcx>>,
222        args: &[FnArg<'tcx, Self::Provenance>],
223        destination: &PlaceTy<'tcx, Self::Provenance>,
224        target: Option<mir::BasicBlock>,
225        unwind: mir::UnwindAction,
226    ) -> InterpResult<'tcx>;
227
228    /// Directly process an intrinsic without pushing a stack frame. It is the hook's
229    /// responsibility to advance the instruction pointer as appropriate.
230    ///
231    /// Returns `None` if the intrinsic was fully handled.
232    /// Otherwise, returns an `Instance` of the function that implements the intrinsic.
233    fn call_intrinsic(
234        ecx: &mut InterpCx<'tcx, Self>,
235        instance: ty::Instance<'tcx>,
236        args: &[OpTy<'tcx, Self::Provenance>],
237        destination: &PlaceTy<'tcx, Self::Provenance>,
238        target: Option<mir::BasicBlock>,
239        unwind: mir::UnwindAction,
240    ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>>;
241
242    /// Check whether the given function may be executed on the current machine, in terms of the
243    /// target features is requires.
244    fn check_fn_target_features(
245        _ecx: &InterpCx<'tcx, Self>,
246        _instance: ty::Instance<'tcx>,
247    ) -> InterpResult<'tcx>;
248
249    /// Called to evaluate `Assert` MIR terminators that trigger a panic.
250    fn assert_panic(
251        ecx: &mut InterpCx<'tcx, Self>,
252        msg: &mir::AssertMessage<'tcx>,
253        unwind: mir::UnwindAction,
254    ) -> InterpResult<'tcx>;
255
256    /// Called to trigger a non-unwinding panic.
257    fn panic_nounwind(_ecx: &mut InterpCx<'tcx, Self>, msg: &str) -> InterpResult<'tcx>;
258
259    /// Called when unwinding reached a state where execution should be terminated.
260    fn unwind_terminate(
261        ecx: &mut InterpCx<'tcx, Self>,
262        reason: mir::UnwindTerminateReason,
263    ) -> InterpResult<'tcx>;
264
265    /// Called for all binary operations where the LHS has pointer type.
266    ///
267    /// Returns a (value, overflowed) pair if the operation succeeded
268    fn binary_ptr_op(
269        ecx: &InterpCx<'tcx, Self>,
270        bin_op: mir::BinOp,
271        left: &ImmTy<'tcx, Self::Provenance>,
272        right: &ImmTy<'tcx, Self::Provenance>,
273    ) -> InterpResult<'tcx, ImmTy<'tcx, Self::Provenance>>;
274
275    /// Generate the NaN returned by a float operation, given the list of inputs.
276    /// (This is all inputs, not just NaN inputs!)
277    fn generate_nan<F1: Float + FloatConvert<F2>, F2: Float>(
278        _ecx: &InterpCx<'tcx, Self>,
279        _inputs: &[F1],
280    ) -> F2 {
281        // By default we always return the preferred NaN.
282        F2::NAN
283    }
284
285    /// Apply non-determinism to float operations that do not return a precise result.
286    fn apply_float_nondet(
287        _ecx: &mut InterpCx<'tcx, Self>,
288        val: ImmTy<'tcx, Self::Provenance>,
289    ) -> InterpResult<'tcx, ImmTy<'tcx, Self::Provenance>> {
290        interp_ok(val)
291    }
292
293    /// Determines the result of `min`/`max` on floats when the arguments are equal.
294    fn equal_float_min_max<F: Float>(_ecx: &InterpCx<'tcx, Self>, a: F, _b: F) -> F {
295        // By default, we pick the left argument.
296        a
297    }
298
299    /// Called before a basic block terminator is executed.
300    #[inline]
301    fn before_terminator(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
302        interp_ok(())
303    }
304
305    /// Determines the result of a `NullaryOp::UbChecks` invocation.
306    fn ub_checks(_ecx: &InterpCx<'tcx, Self>) -> InterpResult<'tcx, bool>;
307
308    /// Determines the result of a `NullaryOp::ContractChecks` invocation.
309    fn contract_checks(_ecx: &InterpCx<'tcx, Self>) -> InterpResult<'tcx, bool>;
310
311    /// Called when the interpreter encounters a `StatementKind::ConstEvalCounter` instruction.
312    /// You can use this to detect long or endlessly running programs.
313    #[inline]
314    fn increment_const_eval_counter(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
315        interp_ok(())
316    }
317
318    /// Called before a global allocation is accessed.
319    /// `def_id` is `Some` if this is the "lazy" allocation of a static.
320    #[inline]
321    fn before_access_global(
322        _tcx: TyCtxtAt<'tcx>,
323        _machine: &Self,
324        _alloc_id: AllocId,
325        _allocation: ConstAllocation<'tcx>,
326        _static_def_id: Option<DefId>,
327        _is_write: bool,
328    ) -> InterpResult<'tcx> {
329        interp_ok(())
330    }
331
332    /// Return the `AllocId` for the given thread-local static in the current thread.
333    fn thread_local_static_pointer(
334        _ecx: &mut InterpCx<'tcx, Self>,
335        def_id: DefId,
336    ) -> InterpResult<'tcx, Pointer<Self::Provenance>> {
337        throw_unsup!(ThreadLocalStatic(def_id))
338    }
339
340    /// Return the `AllocId` for the given `extern static`.
341    fn extern_static_pointer(
342        ecx: &InterpCx<'tcx, Self>,
343        def_id: DefId,
344    ) -> InterpResult<'tcx, Pointer<Self::Provenance>>;
345
346    /// "Int-to-pointer cast"
347    fn ptr_from_addr_cast(
348        ecx: &InterpCx<'tcx, Self>,
349        addr: u64,
350    ) -> InterpResult<'tcx, Pointer<Option<Self::Provenance>>>;
351
352    /// Marks a pointer as exposed, allowing its provenance
353    /// to be recovered. "Pointer-to-int cast"
354    fn expose_provenance(
355        ecx: &InterpCx<'tcx, Self>,
356        provenance: Self::Provenance,
357    ) -> InterpResult<'tcx>;
358
359    /// Convert a pointer with provenance into an allocation-offset pair and extra provenance info.
360    /// `size` says how many bytes of memory are expected at that pointer. The *sign* of `size` can
361    /// be used to disambiguate situations where a wildcard pointer sits right in between two
362    /// allocations.
363    ///
364    /// If `ptr.provenance.get_alloc_id()` is `Some(p)`, the returned `AllocId` must be `p`.
365    /// The resulting `AllocId` will just be used for that one step and the forgotten again
366    /// (i.e., we'll never turn the data returned here back into a `Pointer` that might be
367    /// stored in machine state).
368    ///
369    /// When this fails, that means the pointer does not point to a live allocation.
370    fn ptr_get_alloc(
371        ecx: &InterpCx<'tcx, Self>,
372        ptr: Pointer<Self::Provenance>,
373        size: i64,
374    ) -> Option<(AllocId, Size, Self::ProvenanceExtra)>;
375
376    /// Return a "root" pointer for the given allocation: the one that is used for direct
377    /// accesses to this static/const/fn allocation, or the one returned from the heap allocator.
378    ///
379    /// Not called on `extern` or thread-local statics (those use the methods above).
380    ///
381    /// `kind` is the kind of the allocation the pointer points to; it can be `None` when
382    /// it's a global and `GLOBAL_KIND` is `None`.
383    fn adjust_alloc_root_pointer(
384        ecx: &InterpCx<'tcx, Self>,
385        ptr: Pointer,
386        kind: Option<MemoryKind<Self::MemoryKind>>,
387    ) -> InterpResult<'tcx, Pointer<Self::Provenance>>;
388
389    /// Called to adjust global allocations to the Provenance and AllocExtra of this machine.
390    ///
391    /// If `alloc` contains pointers, then they are all pointing to globals.
392    ///
393    /// This should avoid copying if no work has to be done! If this returns an owned
394    /// allocation (because a copy had to be done to adjust things), machine memory will
395    /// cache the result. (This relies on `AllocMap::get_or` being able to add the
396    /// owned allocation to the map even when the map is shared.)
397    fn adjust_global_allocation<'b>(
398        ecx: &InterpCx<'tcx, Self>,
399        id: AllocId,
400        alloc: &'b Allocation,
401    ) -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance, Self::AllocExtra, Self::Bytes>>>;
402
403    /// Initialize the extra state of an allocation local to this machine.
404    ///
405    /// This is guaranteed to be called exactly once on all allocations local to this machine.
406    /// It will not be called automatically for global allocations; `adjust_global_allocation`
407    /// has to do that itself if that is desired.
408    fn init_local_allocation(
409        ecx: &InterpCx<'tcx, Self>,
410        id: AllocId,
411        kind: MemoryKind<Self::MemoryKind>,
412        size: Size,
413        align: Align,
414    ) -> InterpResult<'tcx, Self::AllocExtra>;
415
416    /// Hook for performing extra checks on a memory read access.
417    /// `ptr` will always be a pointer with the provenance in `prov` pointing to the beginning of
418    /// `range`.
419    ///
420    /// This will *not* be called during validation!
421    ///
422    /// Takes read-only access to the allocation so we can keep all the memory read
423    /// operations take `&self`. Use a `RefCell` in `AllocExtra` if you
424    /// need to mutate.
425    ///
426    /// This is not invoked for ZST accesses, as no read actually happens.
427    #[inline(always)]
428    fn before_memory_read(
429        _tcx: TyCtxtAt<'tcx>,
430        _machine: &Self,
431        _alloc_extra: &Self::AllocExtra,
432        _ptr: Pointer<Option<Self::Provenance>>,
433        _prov: (AllocId, Self::ProvenanceExtra),
434        _range: AllocRange,
435    ) -> InterpResult<'tcx> {
436        interp_ok(())
437    }
438
439    /// Hook for performing extra checks on any memory read access,
440    /// that involves an allocation, even ZST reads.
441    ///
442    /// This will *not* be called during validation!
443    ///
444    /// Used to prevent statics from self-initializing by reading from their own memory
445    /// as it is being initialized.
446    fn before_alloc_read(_ecx: &InterpCx<'tcx, Self>, _alloc_id: AllocId) -> InterpResult<'tcx> {
447        interp_ok(())
448    }
449
450    /// Hook for performing extra checks on a memory write access.
451    /// This is not invoked for ZST accesses, as no write actually happens.
452    /// `ptr` will always be a pointer with the provenance in `prov` pointing to the beginning of
453    /// `range`.
454    #[inline(always)]
455    fn before_memory_write(
456        _tcx: TyCtxtAt<'tcx>,
457        _machine: &mut Self,
458        _alloc_extra: &mut Self::AllocExtra,
459        _ptr: Pointer<Option<Self::Provenance>>,
460        _prov: (AllocId, Self::ProvenanceExtra),
461        _range: AllocRange,
462    ) -> InterpResult<'tcx> {
463        interp_ok(())
464    }
465
466    /// Hook for performing extra operations on a memory deallocation.
467    /// `ptr` will always be a pointer with the provenance in `prov` pointing to the beginning of
468    /// the allocation.
469    #[inline(always)]
470    fn before_memory_deallocation(
471        _tcx: TyCtxtAt<'tcx>,
472        _machine: &mut Self,
473        _alloc_extra: &mut Self::AllocExtra,
474        _ptr: Pointer<Option<Self::Provenance>>,
475        _prov: (AllocId, Self::ProvenanceExtra),
476        _size: Size,
477        _align: Align,
478        _kind: MemoryKind<Self::MemoryKind>,
479    ) -> InterpResult<'tcx> {
480        interp_ok(())
481    }
482
483    /// Executes a retagging operation for a single pointer.
484    /// Returns the possibly adjusted pointer.
485    #[inline]
486    fn retag_ptr_value(
487        _ecx: &mut InterpCx<'tcx, Self>,
488        _kind: mir::RetagKind,
489        val: &ImmTy<'tcx, Self::Provenance>,
490    ) -> InterpResult<'tcx, ImmTy<'tcx, Self::Provenance>> {
491        interp_ok(val.clone())
492    }
493
494    /// Executes a retagging operation on a compound value.
495    /// Replaces all pointers stored in the given place.
496    #[inline]
497    fn retag_place_contents(
498        _ecx: &mut InterpCx<'tcx, Self>,
499        _kind: mir::RetagKind,
500        _place: &PlaceTy<'tcx, Self::Provenance>,
501    ) -> InterpResult<'tcx> {
502        interp_ok(())
503    }
504
505    /// Called on places used for in-place function argument and return value handling.
506    ///
507    /// These places need to be protected to make sure the program cannot tell whether the
508    /// argument/return value was actually copied or passed in-place..
509    fn protect_in_place_function_argument(
510        ecx: &mut InterpCx<'tcx, Self>,
511        mplace: &MPlaceTy<'tcx, Self::Provenance>,
512    ) -> InterpResult<'tcx> {
513        // Without an aliasing model, all we can do is put `Uninit` into the place.
514        // Conveniently this also ensures that the place actually points to suitable memory.
515        ecx.write_uninit(mplace)
516    }
517
518    /// Called immediately before a new stack frame gets pushed.
519    fn init_frame(
520        ecx: &mut InterpCx<'tcx, Self>,
521        frame: Frame<'tcx, Self::Provenance>,
522    ) -> InterpResult<'tcx, Frame<'tcx, Self::Provenance, Self::FrameExtra>>;
523
524    /// Borrow the current thread's stack.
525    fn stack<'a>(
526        ecx: &'a InterpCx<'tcx, Self>,
527    ) -> &'a [Frame<'tcx, Self::Provenance, Self::FrameExtra>];
528
529    /// Mutably borrow the current thread's stack.
530    fn stack_mut<'a>(
531        ecx: &'a mut InterpCx<'tcx, Self>,
532    ) -> &'a mut Vec<Frame<'tcx, Self::Provenance, Self::FrameExtra>>;
533
534    /// Called immediately after a stack frame got pushed and its locals got initialized.
535    fn after_stack_push(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
536        interp_ok(())
537    }
538
539    /// Called just before the frame is removed from the stack (followed by return value copy and
540    /// local cleanup).
541    fn before_stack_pop(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
542        interp_ok(())
543    }
544
545    /// Called immediately after a stack frame got popped, but before jumping back to the caller.
546    /// The `locals` have already been destroyed!
547    #[inline(always)]
548    fn after_stack_pop(
549        _ecx: &mut InterpCx<'tcx, Self>,
550        _frame: Frame<'tcx, Self::Provenance, Self::FrameExtra>,
551        unwinding: bool,
552    ) -> InterpResult<'tcx, ReturnAction> {
553        // By default, we do not support unwinding from panics
554        assert!(!unwinding);
555        interp_ok(ReturnAction::Normal)
556    }
557
558    /// Called immediately after an "immediate" local variable is read in a given frame
559    /// (i.e., this is called for reads that do not end up accessing addressable memory).
560    #[inline(always)]
561    fn after_local_read(
562        _ecx: &InterpCx<'tcx, Self>,
563        _frame: &Frame<'tcx, Self::Provenance, Self::FrameExtra>,
564        _local: mir::Local,
565    ) -> InterpResult<'tcx> {
566        interp_ok(())
567    }
568
569    /// Called immediately after an "immediate" local variable is assigned a new value
570    /// (i.e., this is called for writes that do not end up in memory).
571    /// `storage_live` indicates whether this is the initial write upon `StorageLive`.
572    #[inline(always)]
573    fn after_local_write(
574        _ecx: &mut InterpCx<'tcx, Self>,
575        _local: mir::Local,
576        _storage_live: bool,
577    ) -> InterpResult<'tcx> {
578        interp_ok(())
579    }
580
581    /// Called immediately after actual memory was allocated for a local
582    /// but before the local's stack frame is updated to point to that memory.
583    #[inline(always)]
584    fn after_local_moved_to_memory(
585        _ecx: &mut InterpCx<'tcx, Self>,
586        _local: mir::Local,
587        _mplace: &MPlaceTy<'tcx, Self::Provenance>,
588    ) -> InterpResult<'tcx> {
589        interp_ok(())
590    }
591
592    /// Evaluate the given constant. The `eval` function will do all the required evaluation,
593    /// but this hook has the chance to do some pre/postprocessing.
594    #[inline(always)]
595    fn eval_mir_constant<F>(
596        ecx: &InterpCx<'tcx, Self>,
597        val: mir::Const<'tcx>,
598        span: Span,
599        layout: Option<TyAndLayout<'tcx>>,
600        eval: F,
601    ) -> InterpResult<'tcx, OpTy<'tcx, Self::Provenance>>
602    where
603        F: Fn(
604            &InterpCx<'tcx, Self>,
605            mir::Const<'tcx>,
606            Span,
607            Option<TyAndLayout<'tcx>>,
608        ) -> InterpResult<'tcx, OpTy<'tcx, Self::Provenance>>,
609    {
610        eval(ecx, val, span, layout)
611    }
612
613    /// Returns the salt to be used for a deduplicated global alloation.
614    /// If the allocation is for a function, the instance is provided as well
615    /// (this lets Miri ensure unique addresses for some functions).
616    fn get_global_alloc_salt(
617        ecx: &InterpCx<'tcx, Self>,
618        instance: Option<ty::Instance<'tcx>>,
619    ) -> usize;
620
621    fn cached_union_data_range<'e>(
622        _ecx: &'e mut InterpCx<'tcx, Self>,
623        _ty: Ty<'tcx>,
624        compute_range: impl FnOnce() -> RangeSet,
625    ) -> Cow<'e, RangeSet> {
626        // Default to no caching.
627        Cow::Owned(compute_range())
628    }
629
630    /// Compute the value passed to the constructors of the `AllocBytes` type for
631    /// abstract machine allocations.
632    fn get_default_alloc_params(&self) -> <Self::Bytes as AllocBytes>::AllocParams;
633}
634
635/// A lot of the flexibility above is just needed for `Miri`, but all "compile-time" machines
636/// (CTFE and ConstProp) use the same instance. Here, we share that code.
637pub macro compile_time_machine(<$tcx: lifetime>) {
638    type Provenance = CtfeProvenance;
639    type ProvenanceExtra = bool; // the "immutable" flag
640
641    type ExtraFnVal = !;
642
643    type MemoryMap =
644        rustc_data_structures::fx::FxIndexMap<AllocId, (MemoryKind<Self::MemoryKind>, Allocation)>;
645    const GLOBAL_KIND: Option<Self::MemoryKind> = None; // no copying of globals from `tcx` to machine memory
646
647    type AllocExtra = ();
648    type FrameExtra = ();
649    type Bytes = Box<[u8]>;
650
651    #[inline(always)]
652    fn ignore_optional_overflow_checks(_ecx: &InterpCx<$tcx, Self>) -> bool {
653        false
654    }
655
656    #[inline(always)]
657    fn unwind_terminate(
658        _ecx: &mut InterpCx<$tcx, Self>,
659        _reason: mir::UnwindTerminateReason,
660    ) -> InterpResult<$tcx> {
661        unreachable!("unwinding cannot happen during compile-time evaluation")
662    }
663
664    #[inline(always)]
665    fn check_fn_target_features(
666        _ecx: &InterpCx<$tcx, Self>,
667        _instance: ty::Instance<$tcx>,
668    ) -> InterpResult<$tcx> {
669        // For now we don't do any checking here. We can't use `tcx.sess` because that can differ
670        // between crates, and we need to ensure that const-eval always behaves the same.
671        interp_ok(())
672    }
673
674    #[inline(always)]
675    fn call_extra_fn(
676        _ecx: &mut InterpCx<$tcx, Self>,
677        fn_val: !,
678        _abi: &FnAbi<$tcx, Ty<$tcx>>,
679        _args: &[FnArg<$tcx>],
680        _destination: &PlaceTy<$tcx, Self::Provenance>,
681        _target: Option<mir::BasicBlock>,
682        _unwind: mir::UnwindAction,
683    ) -> InterpResult<$tcx> {
684        match fn_val {}
685    }
686
687    #[inline(always)]
688    fn ub_checks(_ecx: &InterpCx<$tcx, Self>) -> InterpResult<$tcx, bool> {
689        // We can't look at `tcx.sess` here as that can differ across crates, which can lead to
690        // unsound differences in evaluating the same constant at different instantiation sites.
691        interp_ok(true)
692    }
693
694    #[inline(always)]
695    fn contract_checks(_ecx: &InterpCx<$tcx, Self>) -> InterpResult<$tcx, bool> {
696        // We can't look at `tcx.sess` here as that can differ across crates, which can lead to
697        // unsound differences in evaluating the same constant at different instantiation sites.
698        interp_ok(true)
699    }
700
701    #[inline(always)]
702    fn adjust_global_allocation<'b>(
703        _ecx: &InterpCx<$tcx, Self>,
704        _id: AllocId,
705        alloc: &'b Allocation,
706    ) -> InterpResult<$tcx, Cow<'b, Allocation<Self::Provenance>>> {
707        // Overwrite default implementation: no need to adjust anything.
708        interp_ok(Cow::Borrowed(alloc))
709    }
710
711    fn init_local_allocation(
712        _ecx: &InterpCx<$tcx, Self>,
713        _id: AllocId,
714        _kind: MemoryKind<Self::MemoryKind>,
715        _size: Size,
716        _align: Align,
717    ) -> InterpResult<$tcx, Self::AllocExtra> {
718        interp_ok(())
719    }
720
721    fn extern_static_pointer(
722        ecx: &InterpCx<$tcx, Self>,
723        def_id: DefId,
724    ) -> InterpResult<$tcx, Pointer> {
725        // Use the `AllocId` associated with the `DefId`. Any actual *access* will fail.
726        interp_ok(Pointer::new(ecx.tcx.reserve_and_set_static_alloc(def_id).into(), Size::ZERO))
727    }
728
729    #[inline(always)]
730    fn adjust_alloc_root_pointer(
731        _ecx: &InterpCx<$tcx, Self>,
732        ptr: Pointer<CtfeProvenance>,
733        _kind: Option<MemoryKind<Self::MemoryKind>>,
734    ) -> InterpResult<$tcx, Pointer<CtfeProvenance>> {
735        interp_ok(ptr)
736    }
737
738    #[inline(always)]
739    fn ptr_from_addr_cast(
740        _ecx: &InterpCx<$tcx, Self>,
741        addr: u64,
742    ) -> InterpResult<$tcx, Pointer<Option<CtfeProvenance>>> {
743        // Allow these casts, but make the pointer not dereferenceable.
744        // (I.e., they behave like transmutation.)
745        // This is correct because no pointers can ever be exposed in compile-time evaluation.
746        interp_ok(Pointer::from_addr_invalid(addr))
747    }
748
749    #[inline(always)]
750    fn ptr_get_alloc(
751        _ecx: &InterpCx<$tcx, Self>,
752        ptr: Pointer<CtfeProvenance>,
753        _size: i64,
754    ) -> Option<(AllocId, Size, Self::ProvenanceExtra)> {
755        // We know `offset` is relative to the allocation, so we can use `into_parts`.
756        let (prov, offset) = ptr.into_parts();
757        Some((prov.alloc_id(), offset, prov.immutable()))
758    }
759
760    #[inline(always)]
761    fn get_global_alloc_salt(
762        _ecx: &InterpCx<$tcx, Self>,
763        _instance: Option<ty::Instance<$tcx>>,
764    ) -> usize {
765        CTFE_ALLOC_SALT
766    }
767}