rustc_const_eval/interpret/
eval_context.rs

1use std::assert_matches::debug_assert_matches;
2
3use either::{Left, Right};
4use rustc_abi::{Align, HasDataLayout, Size, TargetDataLayout};
5use rustc_errors::DiagCtxtHandle;
6use rustc_hir::def_id::DefId;
7use rustc_middle::mir::interpret::{ErrorHandled, InvalidMetaKind, ReportedErrorInfo};
8use rustc_middle::query::TyCtxtAt;
9use rustc_middle::ty::layout::{
10    self, FnAbiError, FnAbiOf, FnAbiOfHelpers, FnAbiRequest, LayoutError, LayoutOf,
11    LayoutOfHelpers, TyAndLayout,
12};
13use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypingEnv, Variance};
14use rustc_middle::{mir, span_bug};
15use rustc_session::Limit;
16use rustc_span::Span;
17use rustc_target::callconv::FnAbi;
18use tracing::{debug, trace};
19
20use super::{
21    Frame, FrameInfo, GlobalId, InterpErrorInfo, InterpErrorKind, InterpResult, MPlaceTy, Machine,
22    MemPlaceMeta, Memory, OpTy, Place, PlaceTy, PointerArithmetic, Projectable, Provenance,
23    err_inval, interp_ok, throw_inval, throw_ub, throw_ub_custom,
24};
25use crate::{ReportErrorExt, enter_trace_span, fluent_generated as fluent, util};
26
27pub struct InterpCx<'tcx, M: Machine<'tcx>> {
28    /// Stores the `Machine` instance.
29    ///
30    /// Note: the stack is provided by the machine.
31    pub machine: M,
32
33    /// The results of the type checker, from rustc.
34    /// The span in this is the "root" of the evaluation, i.e., the const
35    /// we are evaluating (if this is CTFE).
36    pub tcx: TyCtxtAt<'tcx>,
37
38    /// The current context in case we're evaluating in a
39    /// polymorphic context. This always uses `ty::TypingMode::PostAnalysis`.
40    pub(super) typing_env: ty::TypingEnv<'tcx>,
41
42    /// The virtual memory system.
43    pub memory: Memory<'tcx, M>,
44
45    /// The recursion limit (cached from `tcx.recursion_limit(())`)
46    pub recursion_limit: Limit,
47}
48
49impl<'tcx, M: Machine<'tcx>> HasDataLayout for InterpCx<'tcx, M> {
50    #[inline]
51    fn data_layout(&self) -> &TargetDataLayout {
52        &self.tcx.data_layout
53    }
54}
55
56impl<'tcx, M> layout::HasTyCtxt<'tcx> for InterpCx<'tcx, M>
57where
58    M: Machine<'tcx>,
59{
60    #[inline]
61    fn tcx(&self) -> TyCtxt<'tcx> {
62        *self.tcx
63    }
64}
65
66impl<'tcx, M> layout::HasTypingEnv<'tcx> for InterpCx<'tcx, M>
67where
68    M: Machine<'tcx>,
69{
70    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
71        self.typing_env
72    }
73}
74
75impl<'tcx, M: Machine<'tcx>> LayoutOfHelpers<'tcx> for InterpCx<'tcx, M> {
76    type LayoutOfResult = Result<TyAndLayout<'tcx>, InterpErrorKind<'tcx>>;
77
78    #[inline]
79    fn layout_tcx_at_span(&self) -> Span {
80        // Using the cheap root span for performance.
81        self.tcx.span
82    }
83
84    #[inline]
85    fn handle_layout_err(
86        &self,
87        err: LayoutError<'tcx>,
88        _: Span,
89        _: Ty<'tcx>,
90    ) -> InterpErrorKind<'tcx> {
91        err_inval!(Layout(err))
92    }
93}
94
95impl<'tcx, M: Machine<'tcx>> FnAbiOfHelpers<'tcx> for InterpCx<'tcx, M> {
96    type FnAbiOfResult = Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, InterpErrorKind<'tcx>>;
97
98    fn handle_fn_abi_err(
99        &self,
100        err: FnAbiError<'tcx>,
101        _span: Span,
102        _fn_abi_request: FnAbiRequest<'tcx>,
103    ) -> InterpErrorKind<'tcx> {
104        match err {
105            FnAbiError::Layout(err) => err_inval!(Layout(err)),
106        }
107    }
108}
109
110impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
111    /// This inherent method takes priority over the trait method with the same name in LayoutOf,
112    /// and allows wrapping the actual [LayoutOf::layout_of] with a tracing span.
113    /// See [LayoutOf::layout_of] for the original documentation.
114    #[inline(always)]
115    pub fn layout_of(&self, ty: Ty<'tcx>) -> <Self as LayoutOfHelpers<'tcx>>::LayoutOfResult {
116        let _span = enter_trace_span!(M, layouting::layout_of, ty = ?ty.kind());
117        LayoutOf::layout_of(self, ty)
118    }
119
120    /// This inherent method takes priority over the trait method with the same name in FnAbiOf,
121    /// and allows wrapping the actual [FnAbiOf::fn_abi_of_fn_ptr] with a tracing span.
122    /// See [FnAbiOf::fn_abi_of_fn_ptr] for the original documentation.
123    #[inline(always)]
124    pub fn fn_abi_of_fn_ptr(
125        &self,
126        sig: ty::PolyFnSig<'tcx>,
127        extra_args: &'tcx ty::List<Ty<'tcx>>,
128    ) -> <Self as FnAbiOfHelpers<'tcx>>::FnAbiOfResult {
129        let _span = enter_trace_span!(M, layouting::fn_abi_of_fn_ptr, ?sig, ?extra_args);
130        FnAbiOf::fn_abi_of_fn_ptr(self, sig, extra_args)
131    }
132
133    /// This inherent method takes priority over the trait method with the same name in FnAbiOf,
134    /// and allows wrapping the actual [FnAbiOf::fn_abi_of_instance] with a tracing span.
135    /// See [FnAbiOf::fn_abi_of_instance] for the original documentation.
136    #[inline(always)]
137    pub fn fn_abi_of_instance(
138        &self,
139        instance: ty::Instance<'tcx>,
140        extra_args: &'tcx ty::List<Ty<'tcx>>,
141    ) -> <Self as FnAbiOfHelpers<'tcx>>::FnAbiOfResult {
142        let _span = enter_trace_span!(M, layouting::fn_abi_of_instance, ?instance, ?extra_args);
143        FnAbiOf::fn_abi_of_instance(self, instance, extra_args)
144    }
145}
146
147/// Test if it is valid for a MIR assignment to assign `src`-typed place to `dest`-typed value.
148/// This test should be symmetric, as it is primarily about layout compatibility.
149pub(super) fn mir_assign_valid_types<'tcx>(
150    tcx: TyCtxt<'tcx>,
151    typing_env: TypingEnv<'tcx>,
152    src: TyAndLayout<'tcx>,
153    dest: TyAndLayout<'tcx>,
154) -> bool {
155    // Type-changing assignments can happen when subtyping is used. While
156    // all normal lifetimes are erased, higher-ranked types with their
157    // late-bound lifetimes are still around and can lead to type
158    // differences.
159    if util::relate_types(tcx, typing_env, Variance::Covariant, src.ty, dest.ty) {
160        // Make sure the layout is equal, too -- just to be safe. Miri really
161        // needs layout equality. For performance reason we skip this check when
162        // the types are equal. Equal types *can* have different layouts when
163        // enum downcast is involved (as enum variants carry the type of the
164        // enum), but those should never occur in assignments.
165        if cfg!(debug_assertions) || src.ty != dest.ty {
166            assert_eq!(src.layout, dest.layout);
167        }
168        true
169    } else {
170        false
171    }
172}
173
174/// Use the already known layout if given (but sanity check in debug mode),
175/// or compute the layout.
176#[cfg_attr(not(debug_assertions), inline(always))]
177pub(super) fn from_known_layout<'tcx>(
178    tcx: TyCtxtAt<'tcx>,
179    typing_env: TypingEnv<'tcx>,
180    known_layout: Option<TyAndLayout<'tcx>>,
181    compute: impl FnOnce() -> InterpResult<'tcx, TyAndLayout<'tcx>>,
182) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
183    match known_layout {
184        None => compute(),
185        Some(known_layout) => {
186            if cfg!(debug_assertions) {
187                let check_layout = compute()?;
188                if !mir_assign_valid_types(tcx.tcx, typing_env, check_layout, known_layout) {
189                    span_bug!(
190                        tcx.span,
191                        "expected type differs from actual type.\nexpected: {}\nactual: {}",
192                        known_layout.ty,
193                        check_layout.ty,
194                    );
195                }
196            }
197            interp_ok(known_layout)
198        }
199    }
200}
201
202/// Turn the given error into a human-readable string. Expects the string to be printed, so if
203/// `RUSTC_CTFE_BACKTRACE` is set this will show a backtrace of the rustc internals that
204/// triggered the error.
205///
206/// This is NOT the preferred way to render an error; use `report` from `const_eval` instead.
207/// However, this is useful when error messages appear in ICEs.
208pub fn format_interp_error<'tcx>(dcx: DiagCtxtHandle<'_>, e: InterpErrorInfo<'tcx>) -> String {
209    let (e, backtrace) = e.into_parts();
210    backtrace.print_backtrace();
211    // FIXME(fee1-dead), HACK: we want to use the error as title therefore we can just extract the
212    // label and arguments from the InterpError.
213    #[allow(rustc::untranslatable_diagnostic)]
214    let mut diag = dcx.struct_allow("");
215    let msg = e.diagnostic_message();
216    e.add_args(&mut diag);
217    let s = dcx.eagerly_translate_to_string(msg, diag.args.iter());
218    diag.cancel();
219    s
220}
221
222impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
223    pub fn new(
224        tcx: TyCtxt<'tcx>,
225        root_span: Span,
226        typing_env: ty::TypingEnv<'tcx>,
227        machine: M,
228    ) -> Self {
229        // Const eval always happens in post analysis mode in order to be able to use the hidden types of
230        // opaque types. This is needed for trivial things like `size_of`, but also for using associated
231        // types that are not specified in the opaque type. We also use MIR bodies whose opaque types have
232        // already been revealed, so we'd be able to at least partially observe the hidden types anyways.
233        debug_assert_matches!(typing_env.typing_mode, ty::TypingMode::PostAnalysis);
234        InterpCx {
235            machine,
236            tcx: tcx.at(root_span),
237            typing_env,
238            memory: Memory::new(),
239            recursion_limit: tcx.recursion_limit(),
240        }
241    }
242
243    /// Returns the span of the currently executed statement/terminator.
244    /// This is the span typically used for error reporting.
245    #[inline(always)]
246    pub fn cur_span(&self) -> Span {
247        // This deliberately does *not* honor `requires_caller_location` since it is used for much
248        // more than just panics.
249        self.stack().last().map_or(self.tcx.span, |f| f.current_span())
250    }
251
252    pub(crate) fn stack(&self) -> &[Frame<'tcx, M::Provenance, M::FrameExtra>] {
253        M::stack(self)
254    }
255
256    #[inline(always)]
257    pub(crate) fn stack_mut(&mut self) -> &mut Vec<Frame<'tcx, M::Provenance, M::FrameExtra>> {
258        M::stack_mut(self)
259    }
260
261    #[inline(always)]
262    pub fn frame_idx(&self) -> usize {
263        let stack = self.stack();
264        assert!(!stack.is_empty());
265        stack.len() - 1
266    }
267
268    #[inline(always)]
269    pub fn frame(&self) -> &Frame<'tcx, M::Provenance, M::FrameExtra> {
270        self.stack().last().expect("no call frames exist")
271    }
272
273    #[inline(always)]
274    pub fn frame_mut(&mut self) -> &mut Frame<'tcx, M::Provenance, M::FrameExtra> {
275        self.stack_mut().last_mut().expect("no call frames exist")
276    }
277
278    #[inline(always)]
279    pub fn body(&self) -> &'tcx mir::Body<'tcx> {
280        self.frame().body
281    }
282
283    #[inline]
284    pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
285        ty.is_freeze(*self.tcx, self.typing_env)
286    }
287
288    pub fn load_mir(
289        &self,
290        instance: ty::InstanceKind<'tcx>,
291        promoted: Option<mir::Promoted>,
292    ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
293        trace!("load mir(instance={:?}, promoted={:?})", instance, promoted);
294        let body = if let Some(promoted) = promoted {
295            let def = instance.def_id();
296            &self.tcx.promoted_mir(def)[promoted]
297        } else {
298            M::load_mir(self, instance)
299        };
300        // do not continue if typeck errors occurred (can only occur in local crate)
301        if let Some(err) = body.tainted_by_errors {
302            throw_inval!(AlreadyReported(ReportedErrorInfo::non_const_eval_error(err)));
303        }
304        interp_ok(body)
305    }
306
307    /// Call this on things you got out of the MIR (so it is as generic as the current
308    /// stack frame), to bring it into the proper environment for this interpreter.
309    pub fn instantiate_from_current_frame_and_normalize_erasing_regions<
310        T: TypeFoldable<TyCtxt<'tcx>>,
311    >(
312        &self,
313        value: T,
314    ) -> Result<T, ErrorHandled> {
315        self.instantiate_from_frame_and_normalize_erasing_regions(self.frame(), value)
316    }
317
318    /// Call this on things you got out of the MIR (so it is as generic as the provided
319    /// stack frame), to bring it into the proper environment for this interpreter.
320    pub fn instantiate_from_frame_and_normalize_erasing_regions<T: TypeFoldable<TyCtxt<'tcx>>>(
321        &self,
322        frame: &Frame<'tcx, M::Provenance, M::FrameExtra>,
323        value: T,
324    ) -> Result<T, ErrorHandled> {
325        let _span = enter_trace_span!(
326            M,
327            "instantiate_from_frame_and_normalize_erasing_regions",
328            "{}",
329            frame.instance
330        );
331        frame
332            .instance
333            .try_instantiate_mir_and_normalize_erasing_regions(
334                *self.tcx,
335                self.typing_env,
336                ty::EarlyBinder::bind(value),
337            )
338            .map_err(|_| ErrorHandled::TooGeneric(self.cur_span()))
339    }
340
341    /// The `args` are assumed to already be in our interpreter "universe".
342    pub(super) fn resolve(
343        &self,
344        def: DefId,
345        args: GenericArgsRef<'tcx>,
346    ) -> InterpResult<'tcx, ty::Instance<'tcx>> {
347        trace!("resolve: {:?}, {:#?}", def, args);
348        trace!("typing_env: {:#?}", self.typing_env);
349        trace!("args: {:#?}", args);
350        match ty::Instance::try_resolve(*self.tcx, self.typing_env, def, args) {
351            Ok(Some(instance)) => interp_ok(instance),
352            Ok(None) => throw_inval!(TooGeneric),
353
354            // FIXME(eddyb) this could be a bit more specific than `AlreadyReported`.
355            Err(error_guaranteed) => throw_inval!(AlreadyReported(
356                ReportedErrorInfo::non_const_eval_error(error_guaranteed)
357            )),
358        }
359    }
360
361    /// Walks up the callstack from the intrinsic's callsite, searching for the first callsite in a
362    /// frame which is not `#[track_caller]`. This matches the `caller_location` intrinsic,
363    /// and is primarily intended for the panic machinery.
364    pub(crate) fn find_closest_untracked_caller_location(&self) -> Span {
365        for frame in self.stack().iter().rev() {
366            debug!("find_closest_untracked_caller_location: checking frame {:?}", frame.instance);
367
368            // Assert that the frame we look at is actually executing code currently
369            // (`loc` is `Right` when we are unwinding and the frame does not require cleanup).
370            let loc = frame.loc.left().unwrap();
371
372            // This could be a non-`Call` terminator (such as `Drop`), or not a terminator at all
373            // (such as `box`). Use the normal span by default.
374            let mut source_info = *frame.body.source_info(loc);
375
376            // If this is a `Call` terminator, use the `fn_span` instead.
377            let block = &frame.body.basic_blocks[loc.block];
378            if loc.statement_index == block.statements.len() {
379                debug!(
380                    "find_closest_untracked_caller_location: got terminator {:?} ({:?})",
381                    block.terminator(),
382                    block.terminator().kind,
383                );
384                if let mir::TerminatorKind::Call { fn_span, .. } = block.terminator().kind {
385                    source_info.span = fn_span;
386                }
387            }
388
389            let caller_location = if frame.instance.def.requires_caller_location(*self.tcx) {
390                // We use `Err(())` as indication that we should continue up the call stack since
391                // this is a `#[track_caller]` function.
392                Some(Err(()))
393            } else {
394                None
395            };
396            if let Ok(span) =
397                frame.body.caller_location_span(source_info, caller_location, *self.tcx, Ok)
398            {
399                return span;
400            }
401        }
402
403        span_bug!(self.cur_span(), "no non-`#[track_caller]` frame found")
404    }
405
406    /// Returns the actual dynamic size and alignment of the place at the given type.
407    /// Only the "meta" (metadata) part of the place matters.
408    /// This can fail to provide an answer for extern types.
409    pub(super) fn size_and_align_from_meta(
410        &self,
411        metadata: &MemPlaceMeta<M::Provenance>,
412        layout: &TyAndLayout<'tcx>,
413    ) -> InterpResult<'tcx, Option<(Size, Align)>> {
414        if layout.is_sized() {
415            return interp_ok(Some((layout.size, layout.align.abi)));
416        }
417        match layout.ty.kind() {
418            ty::Adt(..) | ty::Tuple(..) => {
419                // First get the size of all statically known fields.
420                // Don't use type_of::sizing_type_of because that expects t to be sized,
421                // and it also rounds up to alignment, which we want to avoid,
422                // as the unsized field's alignment could be smaller.
423                assert!(!layout.ty.is_simd());
424                assert!(layout.fields.count() > 0);
425                trace!("DST layout: {:?}", layout);
426
427                let unsized_offset_unadjusted = layout.fields.offset(layout.fields.count() - 1);
428                let sized_align = layout.align.abi;
429
430                // Recurse to get the size of the dynamically sized field (must be
431                // the last field). Can't have foreign types here, how would we
432                // adjust alignment and size for them?
433                let field = layout.field(self, layout.fields.count() - 1);
434                let Some((unsized_size, mut unsized_align)) =
435                    self.size_and_align_from_meta(metadata, &field)?
436                else {
437                    // A field with an extern type. We don't know the actual dynamic size
438                    // or the alignment.
439                    return interp_ok(None);
440                };
441
442                // # First compute the dynamic alignment
443
444                // Packed type alignment needs to be capped.
445                if let ty::Adt(def, _) = layout.ty.kind()
446                    && let Some(packed) = def.repr().pack
447                {
448                    unsized_align = unsized_align.min(packed);
449                }
450
451                // Choose max of two known alignments (combined value must
452                // be aligned according to more restrictive of the two).
453                let full_align = sized_align.max(unsized_align);
454
455                // # Then compute the dynamic size
456
457                let unsized_offset_adjusted = unsized_offset_unadjusted.align_to(unsized_align);
458                let full_size = (unsized_offset_adjusted + unsized_size).align_to(full_align);
459
460                // Just for our sanitiy's sake, assert that this is equal to what codegen would compute.
461                assert_eq!(
462                    full_size,
463                    (unsized_offset_unadjusted + unsized_size).align_to(full_align)
464                );
465
466                // Check if this brought us over the size limit.
467                if full_size > self.max_size_of_val() {
468                    throw_ub!(InvalidMeta(InvalidMetaKind::TooBig));
469                }
470                interp_ok(Some((full_size, full_align)))
471            }
472            ty::Dynamic(expected_trait, _, ty::Dyn) => {
473                let vtable = metadata.unwrap_meta().to_pointer(self)?;
474                // Read size and align from vtable (already checks size).
475                interp_ok(Some(self.get_vtable_size_and_align(vtable, Some(expected_trait))?))
476            }
477
478            ty::Slice(_) | ty::Str => {
479                let len = metadata.unwrap_meta().to_target_usize(self)?;
480                let elem = layout.field(self, 0);
481
482                // Make sure the slice is not too big.
483                let size = elem.size.bytes().saturating_mul(len); // we rely on `max_size_of_val` being smaller than `u64::MAX`.
484                let size = Size::from_bytes(size);
485                if size > self.max_size_of_val() {
486                    throw_ub!(InvalidMeta(InvalidMetaKind::SliceTooBig));
487                }
488                interp_ok(Some((size, elem.align.abi)))
489            }
490
491            ty::Foreign(_) => interp_ok(None),
492
493            _ => span_bug!(self.cur_span(), "size_and_align_of::<{}> not supported", layout.ty),
494        }
495    }
496    #[inline]
497    pub fn size_and_align_of_val(
498        &self,
499        val: &impl Projectable<'tcx, M::Provenance>,
500    ) -> InterpResult<'tcx, Option<(Size, Align)>> {
501        self.size_and_align_from_meta(&val.meta(), &val.layout())
502    }
503
504    /// Jump to the given block.
505    #[inline]
506    pub fn go_to_block(&mut self, target: mir::BasicBlock) {
507        self.frame_mut().loc = Left(mir::Location { block: target, statement_index: 0 });
508    }
509
510    /// *Return* to the given `target` basic block.
511    /// Do *not* use for unwinding! Use `unwind_to_block` instead.
512    ///
513    /// If `target` is `None`, that indicates the function cannot return, so we raise UB.
514    pub fn return_to_block(&mut self, target: Option<mir::BasicBlock>) -> InterpResult<'tcx> {
515        if let Some(target) = target {
516            self.go_to_block(target);
517            interp_ok(())
518        } else {
519            throw_ub!(Unreachable)
520        }
521    }
522
523    /// *Unwind* to the given `target` basic block.
524    /// Do *not* use for returning! Use `return_to_block` instead.
525    ///
526    /// If `target` is `UnwindAction::Continue`, that indicates the function does not need cleanup
527    /// during unwinding, and we will just keep propagating that upwards.
528    ///
529    /// If `target` is `UnwindAction::Unreachable`, that indicates the function does not allow
530    /// unwinding, and doing so is UB.
531    #[cold] // usually we have normal returns, not unwinding
532    pub fn unwind_to_block(&mut self, target: mir::UnwindAction) -> InterpResult<'tcx> {
533        self.frame_mut().loc = match target {
534            mir::UnwindAction::Cleanup(block) => Left(mir::Location { block, statement_index: 0 }),
535            mir::UnwindAction::Continue => Right(self.frame_mut().body.span),
536            mir::UnwindAction::Unreachable => {
537                throw_ub_custom!(fluent::const_eval_unreachable_unwind);
538            }
539            mir::UnwindAction::Terminate(reason) => {
540                self.frame_mut().loc = Right(self.frame_mut().body.span);
541                M::unwind_terminate(self, reason)?;
542                // This might have pushed a new stack frame, or it terminated execution.
543                // Either way, `loc` will not be updated.
544                return interp_ok(());
545            }
546        };
547        interp_ok(())
548    }
549
550    /// Call a query that can return `ErrorHandled`. Should be used for statics and other globals.
551    /// (`mir::Const`/`ty::Const` have `eval` methods that can be used directly instead.)
552    pub fn ctfe_query<T>(
553        &self,
554        query: impl FnOnce(TyCtxtAt<'tcx>) -> Result<T, ErrorHandled>,
555    ) -> Result<T, ErrorHandled> {
556        // Use a precise span for better cycle errors.
557        query(self.tcx.at(self.cur_span())).map_err(|err| {
558            err.emit_note(*self.tcx);
559            err
560        })
561    }
562
563    pub fn eval_global(
564        &self,
565        instance: ty::Instance<'tcx>,
566    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
567        let gid = GlobalId { instance, promoted: None };
568        let val = if self.tcx.is_static(gid.instance.def_id()) {
569            let alloc_id = self.tcx.reserve_and_set_static_alloc(gid.instance.def_id());
570
571            let ty = instance.ty(self.tcx.tcx, self.typing_env);
572            mir::ConstAlloc { alloc_id, ty }
573        } else {
574            self.ctfe_query(|tcx| tcx.eval_to_allocation_raw(self.typing_env.as_query_input(gid)))?
575        };
576        self.raw_const_to_mplace(val)
577    }
578
579    pub fn eval_mir_constant(
580        &self,
581        val: &mir::Const<'tcx>,
582        span: Span,
583        layout: Option<TyAndLayout<'tcx>>,
584    ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
585        let const_val = val.eval(*self.tcx, self.typing_env, span).map_err(|err| {
586                if M::ALL_CONSTS_ARE_PRECHECKED {
587                    match err {
588                        ErrorHandled::TooGeneric(..) => {},
589                        ErrorHandled::Reported(reported, span) => {
590                            if reported.is_allowed_in_infallible() {
591                                // These errors can just sometimes happen, even when the expression
592                                // is nominally "infallible", e.g. when running out of memory
593                                // or when some layout could not be computed.
594                            } else {
595                                // Looks like the const is not captured by `required_consts`, that's bad.
596                                span_bug!(span, "interpret const eval failure of {val:?} which is not in required_consts");
597                            }
598                        }
599                    }
600                }
601                err.emit_note(*self.tcx);
602                err
603            })?;
604        self.const_val_to_op(const_val, val.ty(), layout)
605    }
606
607    #[must_use]
608    pub fn dump_place(&self, place: &PlaceTy<'tcx, M::Provenance>) -> PlacePrinter<'_, 'tcx, M> {
609        PlacePrinter { ecx: self, place: *place.place() }
610    }
611
612    #[must_use]
613    pub fn generate_stacktrace(&self) -> Vec<FrameInfo<'tcx>> {
614        Frame::generate_stacktrace_from_stack(self.stack())
615    }
616
617    pub fn adjust_nan<F1, F2>(&self, f: F2, inputs: &[F1]) -> F2
618    where
619        F1: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F2>,
620        F2: rustc_apfloat::Float,
621    {
622        if f.is_nan() { M::generate_nan(self, inputs) } else { f }
623    }
624}
625
626#[doc(hidden)]
627/// Helper struct for the `dump_place` function.
628pub struct PlacePrinter<'a, 'tcx, M: Machine<'tcx>> {
629    ecx: &'a InterpCx<'tcx, M>,
630    place: Place<M::Provenance>,
631}
632
633impl<'a, 'tcx, M: Machine<'tcx>> std::fmt::Debug for PlacePrinter<'a, 'tcx, M> {
634    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
635        match self.place {
636            Place::Local { local, offset, locals_addr } => {
637                debug_assert_eq!(locals_addr, self.ecx.frame().locals_addr());
638                let mut allocs = Vec::new();
639                write!(fmt, "{local:?}")?;
640                if let Some(offset) = offset {
641                    write!(fmt, "+{:#x}", offset.bytes())?;
642                }
643                write!(fmt, ":")?;
644
645                self.ecx.frame().locals[local].print(&mut allocs, fmt)?;
646
647                write!(fmt, ": {:?}", self.ecx.dump_allocs(allocs.into_iter().flatten().collect()))
648            }
649            Place::Ptr(mplace) => match mplace.ptr.provenance.and_then(Provenance::get_alloc_id) {
650                Some(alloc_id) => {
651                    write!(fmt, "by ref {:?}: {:?}", mplace.ptr, self.ecx.dump_alloc(alloc_id))
652                }
653                ptr => write!(fmt, " integral by ref: {ptr:?}"),
654            },
655        }
656    }
657}