5 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
6 use rustc_hir::{self as hir, def_id::DefId, definitions::DefPathData};
7 use rustc_index::vec::IndexVec;
8 use rustc_macros::HashStable;
10 use rustc_middle::mir::interpret::{InterpError, InvalidProgramInfo};
11 use rustc_middle::ty::layout::{
12 self, FnAbiError, FnAbiOfHelpers, FnAbiRequest, LayoutError, LayoutOf, LayoutOfHelpers,
15 use rustc_middle::ty::{
16 self, query::TyCtxtAt, subst::SubstsRef, ParamEnv, Ty, TyCtxt, TypeFoldable,
18 use rustc_mir_dataflow::storage::always_live_locals;
19 use rustc_query_system::ich::StableHashingContext;
20 use rustc_session::Limit;
21 use rustc_span::{Pos, Span};
22 use rustc_target::abi::{call::FnAbi, Align, HasDataLayout, Size, TargetDataLayout};
25 AllocId, GlobalId, Immediate, InterpErrorInfo, InterpResult, MPlaceTy, Machine, MemPlace,
26 MemPlaceMeta, Memory, MemoryKind, Operand, Place, PlaceTy, PointerArithmetic, Provenance,
27 Scalar, ScalarMaybeUninit, StackPopJump,
29 use crate::transform::validate::equal_up_to_regions;
31 pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
32 /// Stores the `Machine` instance.
34 /// Note: the stack is provided by the machine.
37 /// The results of the type checker, from rustc.
38 /// The span in this is the "root" of the evaluation, i.e., the const
39 /// we are evaluating (if this is CTFE).
40 pub tcx: TyCtxtAt<'tcx>,
42 /// Bounds in scope for polymorphic evaluations.
43 pub(crate) param_env: ty::ParamEnv<'tcx>,
45 /// The virtual memory system.
46 pub memory: Memory<'mir, 'tcx, M>,
48 /// The recursion limit (cached from `tcx.recursion_limit(())`)
49 pub recursion_limit: Limit,
52 // The Phantomdata exists to prevent this type from being `Send`. If it were sent across a thread
53 // boundary and dropped in the other thread, it would exit the span in the other thread.
54 struct SpanGuard(tracing::Span, std::marker::PhantomData<*const u8>);
57 /// By default a `SpanGuard` does nothing.
59 Self(tracing::Span::none(), std::marker::PhantomData)
62 /// If a span is entered, we exit the previous span (if any, normally none) and enter the
63 /// new span. This is mainly so we don't have to use `Option` for the `tracing_span` field of
64 /// `Frame` by creating a dummy span to being with and then entering it once the frame has
66 fn enter(&mut self, span: tracing::Span) {
67 // This executes the destructor on the previous instance of `SpanGuard`, ensuring that
68 // we never enter or exit more spans than vice versa. Unless you `mem::leak`, then we
69 // can't protect the tracing stack, but that'll just lead to weird logging, no actual
71 *self = Self(span, std::marker::PhantomData);
72 self.0.with_subscriber(|(id, dispatch)| {
78 impl Drop for SpanGuard {
80 self.0.with_subscriber(|(id, dispatch)| {
87 pub struct Frame<'mir, 'tcx, Tag: Provenance = AllocId, Extra = ()> {
88 ////////////////////////////////////////////////////////////////////////////////
89 // Function and callsite information
90 ////////////////////////////////////////////////////////////////////////////////
91 /// The MIR for the function called on this frame.
92 pub body: &'mir mir::Body<'tcx>,
94 /// The def_id and substs of the current function.
95 pub instance: ty::Instance<'tcx>,
97 /// Extra data for the machine.
100 ////////////////////////////////////////////////////////////////////////////////
101 // Return place and locals
102 ////////////////////////////////////////////////////////////////////////////////
103 /// Work to perform when returning from this function.
104 pub return_to_block: StackPopCleanup,
106 /// The location where the result of the current stack frame should be written to,
107 /// and its layout in the caller.
108 pub return_place: PlaceTy<'tcx, Tag>,
110 /// The list of locals for this stack frame, stored in order as
111 /// `[return_ptr, arguments..., variables..., temporaries...]`.
112 /// The locals are stored as `Option<Value>`s.
113 /// `None` represents a local that is currently dead, while a live local
114 /// can either directly contain `Scalar` or refer to some part of an `Allocation`.
115 pub locals: IndexVec<mir::Local, LocalState<'tcx, Tag>>,
117 /// The span of the `tracing` crate is stored here.
118 /// When the guard is dropped, the span is exited. This gives us
119 /// a full stack trace on all tracing statements.
120 tracing_span: SpanGuard,
122 ////////////////////////////////////////////////////////////////////////////////
123 // Current position within the function
124 ////////////////////////////////////////////////////////////////////////////////
125 /// If this is `Err`, we are not currently executing any particular statement in
126 /// this frame (can happen e.g. during frame initialization, and during unwinding on
127 /// frames without cleanup code).
128 /// We basically abuse `Result` as `Either`.
130 /// Needs to be public because ConstProp does unspeakable things to it.
131 pub loc: Result<mir::Location, Span>,
134 /// What we store about a frame in an interpreter backtrace.
136 pub struct FrameInfo<'tcx> {
137 pub instance: ty::Instance<'tcx>,
139 pub lint_root: Option<hir::HirId>,
142 /// Unwind information.
143 #[derive(Clone, Copy, Eq, PartialEq, Debug, HashStable)]
144 pub enum StackPopUnwind {
145 /// The cleanup block.
146 Cleanup(mir::BasicBlock),
147 /// No cleanup needs to be done.
149 /// Unwinding is not allowed (UB).
153 #[derive(Clone, Copy, Eq, PartialEq, Debug, HashStable)] // Miri debug-prints these
154 pub enum StackPopCleanup {
155 /// Jump to the next block in the caller, or cause UB if None (that's a function
156 /// that may never return). Also store layout of return place so
157 /// we can validate it at that layout.
158 /// `ret` stores the block we jump to on a normal return, while `unwind`
159 /// stores the block used for cleanup during unwinding.
160 Goto { ret: Option<mir::BasicBlock>, unwind: StackPopUnwind },
161 /// The root frame of the stack: nowhere else to jump to.
162 /// `cleanup` says whether locals are deallocated. Static computation
163 /// wants them leaked to intern what they need (and just throw away
164 /// the entire `ecx` when it is done).
165 Root { cleanup: bool },
168 /// State of a local variable including a memoized layout
169 #[derive(Clone, Debug, PartialEq, Eq, HashStable)]
170 pub struct LocalState<'tcx, Tag: Provenance = AllocId> {
171 pub value: LocalValue<Tag>,
172 /// Don't modify if `Some`, this is only used to prevent computing the layout twice
173 #[stable_hasher(ignore)]
174 pub layout: Cell<Option<TyAndLayout<'tcx>>>,
177 /// Current value of a local variable
178 #[derive(Copy, Clone, PartialEq, Eq, HashStable, Debug)] // Miri debug-prints these
179 pub enum LocalValue<Tag: Provenance = AllocId> {
180 /// This local is not currently alive, and cannot be used at all.
182 /// This local is alive but not yet allocated. It cannot be read from or have its address taken,
183 /// and will be allocated on the first write. This is to support unsized locals, where we cannot
184 /// know their size in advance.
186 /// A normal, live local.
187 /// Mostly for convenience, we re-use the `Operand` type here.
188 /// This is an optimization over just always having a pointer here;
189 /// we can thus avoid doing an allocation when the local just stores
190 /// immediate values *and* never has its address taken.
194 impl<'tcx, Tag: Provenance + 'static> LocalState<'tcx, Tag> {
195 /// Read the local's value or error if the local is not yet live or not live anymore.
197 /// Note: This may only be invoked from the `Machine::access_local` hook and not from
198 /// anywhere else. You may be invalidating machine invariants if you do!
199 pub fn access(&self) -> InterpResult<'tcx, Operand<Tag>> {
201 LocalValue::Dead => throw_ub!(DeadLocal),
202 LocalValue::Unallocated => {
203 bug!("The type checker should prevent reading from a never-written local")
205 LocalValue::Live(val) => Ok(val),
209 /// Overwrite the local. If the local can be overwritten in place, return a reference
210 /// to do so; otherwise return the `MemPlace` to consult instead.
212 /// Note: This may only be invoked from the `Machine::access_local_mut` hook and not from
213 /// anywhere else. You may be invalidating machine invariants if you do!
216 ) -> InterpResult<'tcx, Result<&mut LocalValue<Tag>, MemPlace<Tag>>> {
218 LocalValue::Dead => throw_ub!(DeadLocal),
219 LocalValue::Live(Operand::Indirect(mplace)) => Ok(Err(mplace)),
220 ref mut local @ (LocalValue::Live(Operand::Immediate(_)) | LocalValue::Unallocated) => {
227 impl<'mir, 'tcx, Tag: Provenance> Frame<'mir, 'tcx, Tag> {
228 pub fn with_extra<Extra>(self, extra: Extra) -> Frame<'mir, 'tcx, Tag, Extra> {
231 instance: self.instance,
232 return_to_block: self.return_to_block,
233 return_place: self.return_place,
237 tracing_span: self.tracing_span,
242 impl<'mir, 'tcx, Tag: Provenance, Extra> Frame<'mir, 'tcx, Tag, Extra> {
243 /// Get the current location within the Frame.
245 /// If this is `Err`, we are not currently executing any particular statement in
246 /// this frame (can happen e.g. during frame initialization, and during unwinding on
247 /// frames without cleanup code).
248 /// We basically abuse `Result` as `Either`.
251 pub fn current_loc(&self) -> Result<mir::Location, Span> {
255 /// Return the `SourceInfo` of the current instruction.
256 pub fn current_source_info(&self) -> Option<&mir::SourceInfo> {
257 self.loc.ok().map(|loc| self.body.source_info(loc))
260 pub fn current_span(&self) -> Span {
262 Ok(loc) => self.body.source_info(loc).span,
268 impl<'tcx> fmt::Display for FrameInfo<'tcx> {
269 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270 ty::tls::with(|tcx| {
271 if tcx.def_key(self.instance.def_id()).disambiguated_data.data
272 == DefPathData::ClosureExpr
274 write!(f, "inside closure")?;
276 write!(f, "inside `{}`", self.instance)?;
278 if !self.span.is_dummy() {
279 let sm = tcx.sess.source_map();
280 let lo = sm.lookup_char_pos(self.span.lo());
284 sm.filename_for_diagnostics(&lo.file.name),
286 lo.col.to_usize() + 1
294 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for InterpCx<'mir, 'tcx, M> {
296 fn data_layout(&self) -> &TargetDataLayout {
297 &self.tcx.data_layout
301 impl<'mir, 'tcx, M> layout::HasTyCtxt<'tcx> for InterpCx<'mir, 'tcx, M>
303 M: Machine<'mir, 'tcx>,
306 fn tcx(&self) -> TyCtxt<'tcx> {
311 impl<'mir, 'tcx, M> layout::HasParamEnv<'tcx> for InterpCx<'mir, 'tcx, M>
313 M: Machine<'mir, 'tcx>,
315 fn param_env(&self) -> ty::ParamEnv<'tcx> {
320 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> LayoutOfHelpers<'tcx> for InterpCx<'mir, 'tcx, M> {
321 type LayoutOfResult = InterpResult<'tcx, TyAndLayout<'tcx>>;
324 fn layout_tcx_at_span(&self) -> Span {
325 // Using the cheap root span for performance.
330 fn handle_layout_err(
332 err: LayoutError<'tcx>,
335 ) -> InterpErrorInfo<'tcx> {
336 err_inval!(Layout(err)).into()
340 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> FnAbiOfHelpers<'tcx> for InterpCx<'mir, 'tcx, M> {
341 type FnAbiOfResult = InterpResult<'tcx, &'tcx FnAbi<'tcx, Ty<'tcx>>>;
343 fn handle_fn_abi_err(
345 err: FnAbiError<'tcx>,
347 _fn_abi_request: FnAbiRequest<'tcx>,
348 ) -> InterpErrorInfo<'tcx> {
350 FnAbiError::Layout(err) => err_inval!(Layout(err)).into(),
351 FnAbiError::AdjustForForeignAbi(err) => {
352 err_inval!(FnAbiAdjustForForeignAbi(err)).into()
358 /// Test if it is valid for a MIR assignment to assign `src`-typed place to `dest`-typed value.
359 /// This test should be symmetric, as it is primarily about layout compatibility.
360 pub(super) fn mir_assign_valid_types<'tcx>(
362 param_env: ParamEnv<'tcx>,
363 src: TyAndLayout<'tcx>,
364 dest: TyAndLayout<'tcx>,
366 // Type-changing assignments can happen when subtyping is used. While
367 // all normal lifetimes are erased, higher-ranked types with their
368 // late-bound lifetimes are still around and can lead to type
369 // differences. So we compare ignoring lifetimes.
370 if equal_up_to_regions(tcx, param_env, src.ty, dest.ty) {
371 // Make sure the layout is equal, too -- just to be safe. Miri really
372 // needs layout equality. For performance reason we skip this check when
373 // the types are equal. Equal types *can* have different layouts when
374 // enum downcast is involved (as enum variants carry the type of the
375 // enum), but those should never occur in assignments.
376 if cfg!(debug_assertions) || src.ty != dest.ty {
377 assert_eq!(src.layout, dest.layout);
385 /// Use the already known layout if given (but sanity check in debug mode),
386 /// or compute the layout.
387 #[cfg_attr(not(debug_assertions), inline(always))]
388 pub(super) fn from_known_layout<'tcx>(
390 param_env: ParamEnv<'tcx>,
391 known_layout: Option<TyAndLayout<'tcx>>,
392 compute: impl FnOnce() -> InterpResult<'tcx, TyAndLayout<'tcx>>,
393 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
396 Some(known_layout) => {
397 if cfg!(debug_assertions) {
398 let check_layout = compute()?;
399 if !mir_assign_valid_types(tcx.tcx, param_env, check_layout, known_layout) {
402 "expected type differs from actual type.\nexpected: {:?}\nactual: {:?}",
413 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
417 param_env: ty::ParamEnv<'tcx>,
422 tcx: tcx.at(root_span),
424 memory: Memory::new(),
425 recursion_limit: tcx.recursion_limit(),
430 pub fn cur_span(&self) -> Span {
431 // This deliberately does *not* honor `requires_caller_location` since it is used for much
432 // more than just panics.
433 self.stack().last().map_or(self.tcx.span, |f| f.current_span())
437 pub(crate) fn stack(&self) -> &[Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>] {
442 pub(crate) fn stack_mut(
444 ) -> &mut Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>> {
449 pub fn frame_idx(&self) -> usize {
450 let stack = self.stack();
451 assert!(!stack.is_empty());
456 pub fn frame(&self) -> &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
457 self.stack().last().expect("no call frames exist")
461 pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
462 self.stack_mut().last_mut().expect("no call frames exist")
466 pub(super) fn body(&self) -> &'mir mir::Body<'tcx> {
471 pub fn sign_extend(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
472 assert!(ty.abi.is_signed());
473 ty.size.sign_extend(value)
477 pub fn truncate(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
478 ty.size.truncate(value)
482 pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
483 ty.is_freeze(self.tcx, self.param_env)
488 instance: ty::InstanceDef<'tcx>,
489 promoted: Option<mir::Promoted>,
490 ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
491 let def = instance.with_opt_param();
492 trace!("load mir(instance={:?}, promoted={:?})", instance, promoted);
493 let body = if let Some(promoted) = promoted {
494 &self.tcx.promoted_mir_opt_const_arg(def)[promoted]
496 M::load_mir(self, instance)?
498 // do not continue if typeck errors occurred (can only occur in local crate)
499 if let Some(err) = body.tainted_by_errors {
500 throw_inval!(AlreadyReported(err));
505 /// Call this on things you got out of the MIR (so it is as generic as the current
506 /// stack frame), to bring it into the proper environment for this interpreter.
507 pub(super) fn subst_from_current_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
510 ) -> Result<T, InterpError<'tcx>> {
511 self.subst_from_frame_and_normalize_erasing_regions(self.frame(), value)
514 /// Call this on things you got out of the MIR (so it is as generic as the provided
515 /// stack frame), to bring it into the proper environment for this interpreter.
516 pub(super) fn subst_from_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
518 frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
520 ) -> Result<T, InterpError<'tcx>> {
523 .try_subst_mir_and_normalize_erasing_regions(*self.tcx, self.param_env, value)
525 self.tcx.sess.delay_span_bug(
527 format!("failed to normalize {}", e.get_type_for_failure()).as_str(),
530 InterpError::InvalidProgram(InvalidProgramInfo::TooGeneric)
534 /// The `substs` are assumed to already be in our interpreter "universe" (param_env).
535 pub(super) fn resolve(
537 def: ty::WithOptConstParam<DefId>,
538 substs: SubstsRef<'tcx>,
539 ) -> InterpResult<'tcx, ty::Instance<'tcx>> {
540 trace!("resolve: {:?}, {:#?}", def, substs);
541 trace!("param_env: {:#?}", self.param_env);
542 trace!("substs: {:#?}", substs);
543 match ty::Instance::resolve_opt_const_arg(*self.tcx, self.param_env, def, substs) {
544 Ok(Some(instance)) => Ok(instance),
545 Ok(None) => throw_inval!(TooGeneric),
547 // FIXME(eddyb) this could be a bit more specific than `AlreadyReported`.
548 Err(error_reported) => throw_inval!(AlreadyReported(error_reported)),
553 pub fn layout_of_local(
555 frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
557 layout: Option<TyAndLayout<'tcx>>,
558 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
559 // `const_prop` runs into this with an invalid (empty) frame, so we
560 // have to support that case (mostly by skipping all caching).
561 match frame.locals.get(local).and_then(|state| state.layout.get()) {
563 let layout = from_known_layout(self.tcx, self.param_env, layout, || {
564 let local_ty = frame.body.local_decls[local].ty;
566 self.subst_from_frame_and_normalize_erasing_regions(frame, local_ty)?;
567 self.layout_of(local_ty)
569 if let Some(state) = frame.locals.get(local) {
570 // Layouts of locals are requested a lot, so we cache them.
571 state.layout.set(Some(layout));
575 Some(layout) => Ok(layout),
579 /// Returns the actual dynamic size and alignment of the place at the given type.
580 /// Only the "meta" (metadata) part of the place matters.
581 /// This can fail to provide an answer for extern types.
582 pub(super) fn size_and_align_of(
584 metadata: &MemPlaceMeta<M::PointerTag>,
585 layout: &TyAndLayout<'tcx>,
586 ) -> InterpResult<'tcx, Option<(Size, Align)>> {
587 if !layout.is_unsized() {
588 return Ok(Some((layout.size, layout.align.abi)));
590 match layout.ty.kind() {
591 ty::Adt(..) | ty::Tuple(..) => {
592 // First get the size of all statically known fields.
593 // Don't use type_of::sizing_type_of because that expects t to be sized,
594 // and it also rounds up to alignment, which we want to avoid,
595 // as the unsized field's alignment could be smaller.
596 assert!(!layout.ty.is_simd());
597 assert!(layout.fields.count() > 0);
598 trace!("DST layout: {:?}", layout);
600 let sized_size = layout.fields.offset(layout.fields.count() - 1);
601 let sized_align = layout.align.abi;
603 "DST {} statically sized prefix size: {:?} align: {:?}",
609 // Recurse to get the size of the dynamically sized field (must be
610 // the last field). Can't have foreign types here, how would we
611 // adjust alignment and size for them?
612 let field = layout.field(self, layout.fields.count() - 1);
613 let Some((unsized_size, unsized_align)) = self.size_and_align_of(metadata, &field)? else {
614 // A field with an extern type. We don't know the actual dynamic size
619 // FIXME (#26403, #27023): We should be adding padding
620 // to `sized_size` (to accommodate the `unsized_align`
621 // required of the unsized field that follows) before
622 // summing it with `sized_size`. (Note that since #26403
623 // is unfixed, we do not yet add the necessary padding
624 // here. But this is where the add would go.)
626 // Return the sum of sizes and max of aligns.
627 let size = sized_size + unsized_size; // `Size` addition
629 // Choose max of two known alignments (combined value must
630 // be aligned according to more restrictive of the two).
631 let align = sized_align.max(unsized_align);
633 // Issue #27023: must add any necessary padding to `size`
634 // (to make it a multiple of `align`) before returning it.
635 let size = size.align_to(align);
637 // Check if this brought us over the size limit.
638 if size > self.max_size_of_val() {
639 throw_ub!(InvalidMeta("total size is bigger than largest supported object"));
641 Ok(Some((size, align)))
644 let vtable = self.scalar_to_ptr(metadata.unwrap_meta())?;
645 // Read size and align from vtable (already checks size).
646 Ok(Some(self.read_size_and_align_from_vtable(vtable)?))
649 ty::Slice(_) | ty::Str => {
650 let len = metadata.unwrap_meta().to_machine_usize(self)?;
651 let elem = layout.field(self, 0);
653 // Make sure the slice is not too big.
654 let size = elem.size.bytes().saturating_mul(len); // we rely on `max_size_of_val` being smaller than `u64::MAX`.
655 let size = Size::from_bytes(size);
656 if size > self.max_size_of_val() {
657 throw_ub!(InvalidMeta("slice is bigger than largest supported object"));
659 Ok(Some((size, elem.align.abi)))
662 ty::Foreign(_) => Ok(None),
664 _ => span_bug!(self.cur_span(), "size_and_align_of::<{:?}> not supported", layout.ty),
668 pub fn size_and_align_of_mplace(
670 mplace: &MPlaceTy<'tcx, M::PointerTag>,
671 ) -> InterpResult<'tcx, Option<(Size, Align)>> {
672 self.size_and_align_of(&mplace.meta, &mplace.layout)
675 #[instrument(skip(self, body, return_place, return_to_block), level = "debug")]
676 pub fn push_stack_frame(
678 instance: ty::Instance<'tcx>,
679 body: &'mir mir::Body<'tcx>,
680 return_place: &PlaceTy<'tcx, M::PointerTag>,
681 return_to_block: StackPopCleanup,
682 ) -> InterpResult<'tcx> {
683 trace!("body: {:#?}", body);
684 // first push a stack frame so we have access to the local substs
685 let pre_frame = Frame {
687 loc: Err(body.span), // Span used for errors caused during preamble.
689 return_place: *return_place,
690 // empty local array, we fill it in below, after we are inside the stack frame and
691 // all methods actually know about the frame
692 locals: IndexVec::new(),
694 tracing_span: SpanGuard::new(),
697 let frame = M::init_frame_extra(self, pre_frame)?;
698 self.stack_mut().push(frame);
700 // Make sure all the constants required by this frame evaluate successfully (post-monomorphization check).
701 for const_ in &body.required_consts {
702 let span = const_.span;
704 self.subst_from_current_frame_and_normalize_erasing_regions(const_.literal)?;
705 self.mir_const_to_op(&const_, None).map_err(|err| {
706 // If there was an error, set the span of the current frame to this constant.
707 // Avoiding doing this when evaluation succeeds.
708 self.frame_mut().loc = Err(span);
713 // Locals are initially unallocated.
714 let dummy = LocalState { value: LocalValue::Unallocated, layout: Cell::new(None) };
715 let mut locals = IndexVec::from_elem(dummy, &body.local_decls);
717 // Now mark those locals as dead that we do not want to initialize
718 // Mark locals that use `Storage*` annotations as dead on function entry.
719 let always_live = always_live_locals(self.body());
720 for local in locals.indices() {
721 if !always_live.contains(local) {
722 locals[local].value = LocalValue::Dead;
726 self.frame_mut().locals = locals;
727 M::after_stack_push(self)?;
728 self.frame_mut().loc = Ok(mir::Location::START);
730 let span = info_span!("frame", "{}", instance);
731 self.frame_mut().tracing_span.enter(span);
736 /// Jump to the given block.
738 pub fn go_to_block(&mut self, target: mir::BasicBlock) {
739 self.frame_mut().loc = Ok(mir::Location { block: target, statement_index: 0 });
742 /// *Return* to the given `target` basic block.
743 /// Do *not* use for unwinding! Use `unwind_to_block` instead.
745 /// If `target` is `None`, that indicates the function cannot return, so we raise UB.
746 pub fn return_to_block(&mut self, target: Option<mir::BasicBlock>) -> InterpResult<'tcx> {
747 if let Some(target) = target {
748 self.go_to_block(target);
751 throw_ub!(Unreachable)
755 /// *Unwind* to the given `target` basic block.
756 /// Do *not* use for returning! Use `return_to_block` instead.
758 /// If `target` is `StackPopUnwind::Skip`, that indicates the function does not need cleanup
759 /// during unwinding, and we will just keep propagating that upwards.
761 /// If `target` is `StackPopUnwind::NotAllowed`, that indicates the function does not allow
762 /// unwinding, and doing so is UB.
763 pub fn unwind_to_block(&mut self, target: StackPopUnwind) -> InterpResult<'tcx> {
764 self.frame_mut().loc = match target {
765 StackPopUnwind::Cleanup(block) => Ok(mir::Location { block, statement_index: 0 }),
766 StackPopUnwind::Skip => Err(self.frame_mut().body.span),
767 StackPopUnwind::NotAllowed => {
768 throw_ub_format!("unwinding past a stack frame that does not allow unwinding")
774 /// Pops the current frame from the stack, deallocating the
775 /// memory for allocated locals.
777 /// If `unwinding` is `false`, then we are performing a normal return
778 /// from a function. In this case, we jump back into the frame of the caller,
779 /// and continue execution as normal.
781 /// If `unwinding` is `true`, then we are in the middle of a panic,
782 /// and need to unwind this frame. In this case, we jump to the
783 /// `cleanup` block for the function, which is responsible for running
784 /// `Drop` impls for any locals that have been initialized at this point.
785 /// The cleanup block ends with a special `Resume` terminator, which will
786 /// cause us to continue unwinding.
787 #[instrument(skip(self), level = "debug")]
788 pub(super) fn pop_stack_frame(&mut self, unwinding: bool) -> InterpResult<'tcx> {
790 "popping stack frame ({})",
791 if unwinding { "during unwinding" } else { "returning from function" }
794 // Sanity check `unwinding`.
797 match self.frame().loc {
798 Ok(loc) => self.body().basic_blocks()[loc.block].is_cleanup,
803 if unwinding && self.frame_idx() == 0 {
804 throw_ub_format!("unwinding past the topmost frame of the stack");
808 self.stack_mut().pop().expect("tried to pop a stack frame, but there were none");
811 let op = self.local_to_op(&frame, mir::RETURN_PLACE, None)?;
812 self.copy_op_transmute(&op, &frame.return_place)?;
813 trace!("{:?}", self.dump_place(*frame.return_place));
816 let return_to_block = frame.return_to_block;
818 // Now where do we jump next?
820 // Usually we want to clean up (deallocate locals), but in a few rare cases we don't.
821 // In that case, we return early. We also avoid validation in that case,
822 // because this is CTFE and the final value will be thoroughly validated anyway.
823 let cleanup = match return_to_block {
824 StackPopCleanup::Goto { .. } => true,
825 StackPopCleanup::Root { cleanup, .. } => cleanup,
829 assert!(self.stack().is_empty(), "only the topmost frame should ever be leaked");
830 assert!(!unwinding, "tried to skip cleanup during unwinding");
831 // Leak the locals, skip validation, skip machine hook.
835 trace!("locals: {:#?}", frame.locals);
837 // Cleanup: deallocate all locals that are backed by an allocation.
838 for local in &frame.locals {
839 self.deallocate_local(local.value)?;
842 if M::after_stack_pop(self, frame, unwinding)? == StackPopJump::NoJump {
843 // The hook already did everything.
844 // We want to skip the `info!` below, hence early return.
847 // Normal return, figure out where to jump.
849 // Follow the unwind edge.
850 let unwind = match return_to_block {
851 StackPopCleanup::Goto { unwind, .. } => unwind,
852 StackPopCleanup::Root { .. } => {
853 panic!("encountered StackPopCleanup::Root when unwinding!")
856 self.unwind_to_block(unwind)
858 // Follow the normal return edge.
859 match return_to_block {
860 StackPopCleanup::Goto { ret, .. } => self.return_to_block(ret),
861 StackPopCleanup::Root { .. } => {
863 self.stack().is_empty(),
864 "only the topmost frame can have StackPopCleanup::Root"
872 /// Mark a storage as live, killing the previous content.
873 pub fn storage_live(&mut self, local: mir::Local) -> InterpResult<'tcx> {
874 assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
875 trace!("{:?} is now live", local);
877 let local_val = LocalValue::Unallocated;
878 // StorageLive expects the local to be dead, and marks it live.
879 let old = mem::replace(&mut self.frame_mut().locals[local].value, local_val);
880 if !matches!(old, LocalValue::Dead) {
881 throw_ub_format!("StorageLive on a local that was already live");
886 pub fn storage_dead(&mut self, local: mir::Local) -> InterpResult<'tcx> {
887 assert!(local != mir::RETURN_PLACE, "Cannot make return place dead");
888 trace!("{:?} is now dead", local);
890 // It is entirely okay for this local to be already dead (at least that's how we currently generate MIR)
891 let old = mem::replace(&mut self.frame_mut().locals[local].value, LocalValue::Dead);
892 self.deallocate_local(old)?;
896 #[instrument(skip(self), level = "debug")]
897 fn deallocate_local(&mut self, local: LocalValue<M::PointerTag>) -> InterpResult<'tcx> {
898 if let LocalValue::Live(Operand::Indirect(MemPlace { ptr, .. })) = local {
899 // All locals have a backing allocation, even if the allocation is empty
900 // due to the local having ZST type. Hence we can `unwrap`.
902 "deallocating local {:?}: {:?}",
904 // Locals always have a `alloc_id` (they are never the result of a int2ptr).
905 self.dump_alloc(ptr.provenance.unwrap().get_alloc_id().unwrap())
907 self.deallocate_ptr(ptr, None, MemoryKind::Stack)?;
912 pub fn eval_to_allocation(
915 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
916 // For statics we pick `ParamEnv::reveal_all`, because statics don't have generics
917 // and thus don't care about the parameter environment. While we could just use
918 // `self.param_env`, that would mean we invoke the query to evaluate the static
919 // with different parameter environments, thus causing the static to be evaluated
921 let param_env = if self.tcx.is_static(gid.instance.def_id()) {
922 ty::ParamEnv::reveal_all()
926 let param_env = param_env.with_const();
927 // Use a precise span for better cycle errors.
928 let val = self.tcx.at(self.cur_span()).eval_to_allocation_raw(param_env.and(gid))?;
929 self.raw_const_to_mplace(val)
933 pub fn dump_place(&self, place: Place<M::PointerTag>) -> PlacePrinter<'_, 'mir, 'tcx, M> {
934 PlacePrinter { ecx: self, place }
938 pub fn generate_stacktrace(&self) -> Vec<FrameInfo<'tcx>> {
939 let mut frames = Vec::new();
940 // This deliberately does *not* honor `requires_caller_location` since it is used for much
941 // more than just panics.
942 for frame in self.stack().iter().rev() {
943 let lint_root = frame.current_source_info().and_then(|source_info| {
944 match &frame.body.source_scopes[source_info.scope].local_data {
945 mir::ClearCrossCrate::Set(data) => Some(data.lint_root),
946 mir::ClearCrossCrate::Clear => None,
949 let span = frame.current_span();
951 frames.push(FrameInfo { span, instance: frame.instance, lint_root });
953 trace!("generate stacktrace: {:#?}", frames);
959 /// Helper struct for the `dump_place` function.
960 pub struct PlacePrinter<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
961 ecx: &'a InterpCx<'mir, 'tcx, M>,
962 place: Place<M::PointerTag>,
965 impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug
966 for PlacePrinter<'a, 'mir, 'tcx, M>
968 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
970 Place::Local { frame, local } => {
971 let mut allocs = Vec::new();
972 write!(fmt, "{:?}", local)?;
973 if frame != self.ecx.frame_idx() {
974 write!(fmt, " ({} frames up)", self.ecx.frame_idx() - frame)?;
978 match self.ecx.stack()[frame].locals[local].value {
979 LocalValue::Dead => write!(fmt, " is dead")?,
980 LocalValue::Unallocated => write!(fmt, " is unallocated")?,
981 LocalValue::Live(Operand::Indirect(mplace)) => {
986 MemPlaceMeta::Meta(meta) => format!(" meta({:?})", meta),
987 MemPlaceMeta::Poison | MemPlaceMeta::None => String::new(),
991 allocs.extend(mplace.ptr.provenance.map(Provenance::get_alloc_id));
993 LocalValue::Live(Operand::Immediate(Immediate::Scalar(val))) => {
994 write!(fmt, " {:?}", val)?;
995 if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr, _size)) = val {
996 allocs.push(ptr.provenance.get_alloc_id());
999 LocalValue::Live(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
1000 write!(fmt, " ({:?}, {:?})", val1, val2)?;
1001 if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr, _size)) = val1 {
1002 allocs.push(ptr.provenance.get_alloc_id());
1004 if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr, _size)) = val2 {
1005 allocs.push(ptr.provenance.get_alloc_id());
1010 write!(fmt, ": {:?}", self.ecx.dump_allocs(allocs.into_iter().flatten().collect()))
1012 Place::Ptr(mplace) => match mplace.ptr.provenance.and_then(Provenance::get_alloc_id) {
1014 write!(fmt, "by ref {:?}: {:?}", mplace.ptr, self.ecx.dump_alloc(alloc_id))
1016 ptr => write!(fmt, " integral by ref: {:?}", ptr),
1022 impl<'ctx, 'mir, 'tcx, Tag: Provenance, Extra> HashStable<StableHashingContext<'ctx>>
1023 for Frame<'mir, 'tcx, Tag, Extra>
1025 Extra: HashStable<StableHashingContext<'ctx>>,
1026 Tag: HashStable<StableHashingContext<'ctx>>,
1028 fn hash_stable(&self, hcx: &mut StableHashingContext<'ctx>, hasher: &mut StableHasher) {
1029 // Exhaustive match on fields to make sure we forget no field.
1040 body.hash_stable(hcx, hasher);
1041 instance.hash_stable(hcx, hasher);
1042 return_to_block.hash_stable(hcx, hasher);
1043 return_place.hash_stable(hcx, hasher);
1044 locals.hash_stable(hcx, hasher);
1045 loc.hash_stable(hcx, hasher);
1046 extra.hash_stable(hcx, hasher);