4 use rustc_data_structures::fx::FxHashMap;
5 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
6 use rustc_hir::def::DefKind;
7 use rustc_hir::def_id::DefId;
8 use rustc_index::vec::IndexVec;
9 use rustc_macros::HashStable;
10 use rustc_middle::ich::StableHashingContext;
11 use rustc_middle::mir;
12 use rustc_middle::mir::interpret::{
13 sign_extend, truncate, FrameInfo, GlobalId, InterpResult, Pointer, Scalar,
15 use rustc_middle::ty::layout::{self, TyAndLayout};
16 use rustc_middle::ty::{
17 self, query::TyCtxtAt, subst::SubstsRef, ParamEnv, Ty, TyCtxt, TypeFoldable,
19 use rustc_span::{source_map::DUMMY_SP, Span};
20 use rustc_target::abi::{Align, HasDataLayout, LayoutOf, Size, TargetDataLayout};
23 Immediate, MPlaceTy, Machine, MemPlace, MemPlaceMeta, Memory, OpTy, Operand, Place, PlaceTy,
24 ScalarMaybeUninit, StackPopJump,
26 use crate::transform::validate::equal_up_to_regions;
27 use crate::util::storage::AlwaysLiveLocals;
29 pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
30 /// Stores the `Machine` instance.
32 /// Note: the stack is provided by the machine.
35 /// The results of the type checker, from rustc.
36 /// The span in this is the "root" of the evaluation, i.e., the const
37 /// we are evaluating (if this is CTFE).
38 pub tcx: TyCtxtAt<'tcx>,
40 /// Bounds in scope for polymorphic evaluations.
41 pub(crate) param_env: ty::ParamEnv<'tcx>,
43 /// The virtual memory system.
44 pub memory: Memory<'mir, 'tcx, M>,
46 /// A cache for deduplicating vtables
48 FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), Pointer<M::PointerTag>>,
53 pub struct Frame<'mir, 'tcx, Tag = (), Extra = ()> {
54 ////////////////////////////////////////////////////////////////////////////////
55 // Function and callsite information
56 ////////////////////////////////////////////////////////////////////////////////
57 /// The MIR for the function called on this frame.
58 pub body: &'mir mir::Body<'tcx>,
60 /// The def_id and substs of the current function.
61 pub instance: ty::Instance<'tcx>,
63 /// Extra data for the machine.
66 ////////////////////////////////////////////////////////////////////////////////
67 // Return place and locals
68 ////////////////////////////////////////////////////////////////////////////////
69 /// Work to perform when returning from this function.
70 pub return_to_block: StackPopCleanup,
72 /// The location where the result of the current stack frame should be written to,
73 /// and its layout in the caller.
74 pub return_place: Option<PlaceTy<'tcx, Tag>>,
76 /// The list of locals for this stack frame, stored in order as
77 /// `[return_ptr, arguments..., variables..., temporaries...]`.
78 /// The locals are stored as `Option<Value>`s.
79 /// `None` represents a local that is currently dead, while a live local
80 /// can either directly contain `Scalar` or refer to some part of an `Allocation`.
81 pub locals: IndexVec<mir::Local, LocalState<'tcx, Tag>>,
83 ////////////////////////////////////////////////////////////////////////////////
84 // Current position within the function
85 ////////////////////////////////////////////////////////////////////////////////
86 /// If this is `None`, we are unwinding and this function doesn't need any clean-up.
87 /// Just continue the same as with `Resume`.
88 pub loc: Option<mir::Location>,
91 #[derive(Clone, Eq, PartialEq, Debug, HashStable)] // Miri debug-prints these
92 pub enum StackPopCleanup {
93 /// Jump to the next block in the caller, or cause UB if None (that's a function
94 /// that may never return). Also store layout of return place so
95 /// we can validate it at that layout.
96 /// `ret` stores the block we jump to on a normal return, while `unwind`
97 /// stores the block used for cleanup during unwinding.
98 Goto { ret: Option<mir::BasicBlock>, unwind: Option<mir::BasicBlock> },
99 /// Just do nothing: Used by Main and for the `box_alloc` hook in miri.
100 /// `cleanup` says whether locals are deallocated. Static computation
101 /// wants them leaked to intern what they need (and just throw away
102 /// the entire `ecx` when it is done).
103 None { cleanup: bool },
106 /// State of a local variable including a memoized layout
107 #[derive(Clone, PartialEq, Eq, HashStable)]
108 pub struct LocalState<'tcx, Tag = ()> {
109 pub value: LocalValue<Tag>,
110 /// Don't modify if `Some`, this is only used to prevent computing the layout twice
111 #[stable_hasher(ignore)]
112 pub layout: Cell<Option<TyAndLayout<'tcx>>>,
115 /// Current value of a local variable
116 #[derive(Copy, Clone, PartialEq, Eq, Debug, HashStable)] // Miri debug-prints these
117 pub enum LocalValue<Tag = ()> {
118 /// This local is not currently alive, and cannot be used at all.
120 /// This local is alive but not yet initialized. It can be written to
121 /// but not read from or its address taken. Locals get initialized on
122 /// first write because for unsized locals, we do not know their size
125 /// A normal, live local.
126 /// Mostly for convenience, we re-use the `Operand` type here.
127 /// This is an optimization over just always having a pointer here;
128 /// we can thus avoid doing an allocation when the local just stores
129 /// immediate values *and* never has its address taken.
133 impl<'tcx, Tag: Copy + 'static> LocalState<'tcx, Tag> {
134 /// Read the local's value or error if the local is not yet live or not live anymore.
136 /// Note: This may only be invoked from the `Machine::access_local` hook and not from
137 /// anywhere else. You may be invalidating machine invariants if you do!
138 pub fn access(&self) -> InterpResult<'tcx, Operand<Tag>> {
140 LocalValue::Dead => throw_ub!(DeadLocal),
141 LocalValue::Uninitialized => {
142 bug!("The type checker should prevent reading from a never-written local")
144 LocalValue::Live(val) => Ok(val),
148 /// Overwrite the local. If the local can be overwritten in place, return a reference
149 /// to do so; otherwise return the `MemPlace` to consult instead.
151 /// Note: This may only be invoked from the `Machine::access_local_mut` hook and not from
152 /// anywhere else. You may be invalidating machine invariants if you do!
155 ) -> InterpResult<'tcx, Result<&mut LocalValue<Tag>, MemPlace<Tag>>> {
157 LocalValue::Dead => throw_ub!(DeadLocal),
158 LocalValue::Live(Operand::Indirect(mplace)) => Ok(Err(mplace)),
160 local @ (LocalValue::Live(Operand::Immediate(_)) | LocalValue::Uninitialized) => {
167 impl<'mir, 'tcx, Tag> Frame<'mir, 'tcx, Tag> {
168 pub fn with_extra<Extra>(self, extra: Extra) -> Frame<'mir, 'tcx, Tag, Extra> {
171 instance: self.instance,
172 return_to_block: self.return_to_block,
173 return_place: self.return_place,
181 impl<'mir, 'tcx, Tag, Extra> Frame<'mir, 'tcx, Tag, Extra> {
182 /// Return the `SourceInfo` of the current instruction.
183 pub fn current_source_info(&self) -> Option<&mir::SourceInfo> {
184 self.loc.map(|loc| self.body.source_info(loc))
188 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for InterpCx<'mir, 'tcx, M> {
190 fn data_layout(&self) -> &TargetDataLayout {
191 &self.tcx.data_layout
195 impl<'mir, 'tcx, M> layout::HasTyCtxt<'tcx> for InterpCx<'mir, 'tcx, M>
197 M: Machine<'mir, 'tcx>,
200 fn tcx(&self) -> TyCtxt<'tcx> {
205 impl<'mir, 'tcx, M> layout::HasParamEnv<'tcx> for InterpCx<'mir, 'tcx, M>
207 M: Machine<'mir, 'tcx>,
209 fn param_env(&self) -> ty::ParamEnv<'tcx> {
214 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> LayoutOf for InterpCx<'mir, 'tcx, M> {
216 type TyAndLayout = InterpResult<'tcx, TyAndLayout<'tcx>>;
219 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
221 .layout_of(self.param_env.and(ty))
222 .map_err(|layout| err_inval!(Layout(layout)).into())
226 /// Test if it is valid for a MIR assignment to assign `src`-typed place to `dest`-typed value.
227 /// This test should be symmetric, as it is primarily about layout compatibility.
228 pub(super) fn mir_assign_valid_types<'tcx>(
230 param_env: ParamEnv<'tcx>,
231 src: TyAndLayout<'tcx>,
232 dest: TyAndLayout<'tcx>,
234 // Type-changing assignments can happen when subtyping is used. While
235 // all normal lifetimes are erased, higher-ranked types with their
236 // late-bound lifetimes are still around and can lead to type
237 // differences. So we compare ignoring lifetimes.
238 if equal_up_to_regions(tcx, param_env, src.ty, dest.ty) {
239 // Make sure the layout is equal, too -- just to be safe. Miri really
240 // needs layout equality. For performance reason we skip this check when
241 // the types are equal. Equal types *can* have different layouts when
242 // enum downcast is involved (as enum variants carry the type of the
243 // enum), but those should never occur in assignments.
244 if cfg!(debug_assertions) || src.ty != dest.ty {
245 assert_eq!(src.layout, dest.layout);
253 /// Use the already known layout if given (but sanity check in debug mode),
254 /// or compute the layout.
255 #[cfg_attr(not(debug_assertions), inline(always))]
256 pub(super) fn from_known_layout<'tcx>(
258 param_env: ParamEnv<'tcx>,
259 known_layout: Option<TyAndLayout<'tcx>>,
260 compute: impl FnOnce() -> InterpResult<'tcx, TyAndLayout<'tcx>>,
261 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
264 Some(known_layout) => {
265 if cfg!(debug_assertions) {
266 let check_layout = compute()?;
267 if !mir_assign_valid_types(tcx.tcx, param_env, check_layout, known_layout) {
270 "expected type differs from actual type.\nexpected: {:?}\nactual: {:?}",
281 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
285 param_env: ty::ParamEnv<'tcx>,
287 memory_extra: M::MemoryExtra,
291 tcx: tcx.at(root_span),
293 memory: Memory::new(tcx, memory_extra),
294 vtables: FxHashMap::default(),
299 pub fn cur_span(&self) -> Span {
302 .and_then(|f| f.current_source_info())
304 .unwrap_or(self.tcx.span)
310 scalar: Scalar<M::PointerTag>,
311 ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
312 self.memory.force_ptr(scalar)
318 scalar: Scalar<M::PointerTag>,
320 ) -> InterpResult<'tcx, u128> {
321 self.memory.force_bits(scalar, size)
324 /// Call this to turn untagged "global" pointers (obtained via `tcx`) into
325 /// the machine pointer to the allocation. Must never be used
326 /// for any other pointers, nor for TLS statics.
328 /// Using the resulting pointer represents a *direct* access to that memory
329 /// (e.g. by directly using a `static`),
330 /// as opposed to access through a pointer that was created by the program.
332 /// This function can fail only if `ptr` points to an `extern static`.
334 pub fn global_base_pointer(&self, ptr: Pointer) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
335 self.memory.global_base_pointer(ptr)
339 pub(crate) fn stack(&self) -> &[Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>] {
344 pub(crate) fn stack_mut(
346 ) -> &mut Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>> {
351 pub fn frame_idx(&self) -> usize {
352 let stack = self.stack();
353 assert!(!stack.is_empty());
358 pub fn frame(&self) -> &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
359 self.stack().last().expect("no call frames exist")
363 pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
364 self.stack_mut().last_mut().expect("no call frames exist")
368 pub(super) fn body(&self) -> &'mir mir::Body<'tcx> {
373 pub fn sign_extend(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
374 assert!(ty.abi.is_signed());
375 sign_extend(value, ty.size)
379 pub fn truncate(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
380 truncate(value, ty.size)
384 pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
385 ty.is_sized(self.tcx, self.param_env)
389 pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
390 ty.is_freeze(self.tcx, self.param_env)
395 instance: ty::InstanceDef<'tcx>,
396 promoted: Option<mir::Promoted>,
397 ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
398 // do not continue if typeck errors occurred (can only occur in local crate)
399 let def = instance.with_opt_param();
400 if let Some(def) = def.as_local() {
401 if self.tcx.has_typeck_results(def.did) {
402 if let Some(error_reported) = self.tcx.typeck_opt_const_arg(def).tainted_by_errors {
403 throw_inval!(TypeckError(error_reported))
407 trace!("load mir(instance={:?}, promoted={:?})", instance, promoted);
408 if let Some(promoted) = promoted {
409 return Ok(&self.tcx.promoted_mir_of_opt_const_arg(def)[promoted]);
412 ty::InstanceDef::Item(def) => {
413 if self.tcx.is_mir_available(def.did) {
414 if let Some((did, param_did)) = def.as_const_arg() {
415 Ok(self.tcx.optimized_mir_of_const_arg((did, param_did)))
417 Ok(self.tcx.optimized_mir(def.did))
420 throw_unsup!(NoMirFor(def.did))
423 _ => Ok(self.tcx.instance_mir(instance)),
427 /// Call this on things you got out of the MIR (so it is as generic as the current
428 /// stack frame), to bring it into the proper environment for this interpreter.
429 pub(super) fn subst_from_current_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
433 self.subst_from_frame_and_normalize_erasing_regions(self.frame(), value)
436 /// Call this on things you got out of the MIR (so it is as generic as the provided
437 /// stack frame), to bring it into the proper environment for this interpreter.
438 pub(super) fn subst_from_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
440 frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
443 if let Some(substs) = frame.instance.substs_for_mir_body() {
444 self.tcx.subst_and_normalize_erasing_regions(substs, self.param_env, &value)
446 self.tcx.normalize_erasing_regions(self.param_env, value)
450 /// The `substs` are assumed to already be in our interpreter "universe" (param_env).
451 pub(super) fn resolve(
454 substs: SubstsRef<'tcx>,
455 ) -> InterpResult<'tcx, ty::Instance<'tcx>> {
456 trace!("resolve: {:?}, {:#?}", def_id, substs);
457 trace!("param_env: {:#?}", self.param_env);
458 trace!("substs: {:#?}", substs);
459 match ty::Instance::resolve(*self.tcx, self.param_env, def_id, substs) {
460 Ok(Some(instance)) => Ok(instance),
461 Ok(None) => throw_inval!(TooGeneric),
463 // FIXME(eddyb) this could be a bit more specific than `TypeckError`.
464 Err(error_reported) => throw_inval!(TypeckError(error_reported)),
468 pub fn layout_of_local(
470 frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
472 layout: Option<TyAndLayout<'tcx>>,
473 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
474 // `const_prop` runs into this with an invalid (empty) frame, so we
475 // have to support that case (mostly by skipping all caching).
476 match frame.locals.get(local).and_then(|state| state.layout.get()) {
478 let layout = from_known_layout(self.tcx, self.param_env, layout, || {
479 let local_ty = frame.body.local_decls[local].ty;
481 self.subst_from_frame_and_normalize_erasing_regions(frame, local_ty);
482 self.layout_of(local_ty)
484 if let Some(state) = frame.locals.get(local) {
485 // Layouts of locals are requested a lot, so we cache them.
486 state.layout.set(Some(layout));
490 Some(layout) => Ok(layout),
494 /// Returns the actual dynamic size and alignment of the place at the given type.
495 /// Only the "meta" (metadata) part of the place matters.
496 /// This can fail to provide an answer for extern types.
497 pub(super) fn size_and_align_of(
499 metadata: MemPlaceMeta<M::PointerTag>,
500 layout: TyAndLayout<'tcx>,
501 ) -> InterpResult<'tcx, Option<(Size, Align)>> {
502 if !layout.is_unsized() {
503 return Ok(Some((layout.size, layout.align.abi)));
505 match layout.ty.kind {
506 ty::Adt(..) | ty::Tuple(..) => {
507 // First get the size of all statically known fields.
508 // Don't use type_of::sizing_type_of because that expects t to be sized,
509 // and it also rounds up to alignment, which we want to avoid,
510 // as the unsized field's alignment could be smaller.
511 assert!(!layout.ty.is_simd());
512 assert!(layout.fields.count() > 0);
513 trace!("DST layout: {:?}", layout);
515 let sized_size = layout.fields.offset(layout.fields.count() - 1);
516 let sized_align = layout.align.abi;
518 "DST {} statically sized prefix size: {:?} align: {:?}",
524 // Recurse to get the size of the dynamically sized field (must be
525 // the last field). Can't have foreign types here, how would we
526 // adjust alignment and size for them?
527 let field = layout.field(self, layout.fields.count() - 1)?;
528 let (unsized_size, unsized_align) = match self.size_and_align_of(metadata, field)? {
529 Some(size_and_align) => size_and_align,
531 // A field with extern type. If this field is at offset 0, we behave
532 // like the underlying extern type.
533 // FIXME: Once we have made decisions for how to handle size and alignment
534 // of `extern type`, this should be adapted. It is just a temporary hack
535 // to get some code to work that probably ought to work.
536 if sized_size == Size::ZERO {
541 "Fields cannot be extern types, unless they are at offset 0"
547 // FIXME (#26403, #27023): We should be adding padding
548 // to `sized_size` (to accommodate the `unsized_align`
549 // required of the unsized field that follows) before
550 // summing it with `sized_size`. (Note that since #26403
551 // is unfixed, we do not yet add the necessary padding
552 // here. But this is where the add would go.)
554 // Return the sum of sizes and max of aligns.
555 let size = sized_size + unsized_size; // `Size` addition
557 // Choose max of two known alignments (combined value must
558 // be aligned according to more restrictive of the two).
559 let align = sized_align.max(unsized_align);
561 // Issue #27023: must add any necessary padding to `size`
562 // (to make it a multiple of `align`) before returning it.
563 let size = size.align_to(align);
565 // Check if this brought us over the size limit.
566 if size.bytes() >= self.tcx.data_layout.obj_size_bound() {
567 throw_ub!(InvalidMeta("total size is bigger than largest supported object"));
569 Ok(Some((size, align)))
572 let vtable = metadata.unwrap_meta();
573 // Read size and align from vtable (already checks size).
574 Ok(Some(self.read_size_and_align_from_vtable(vtable)?))
577 ty::Slice(_) | ty::Str => {
578 let len = metadata.unwrap_meta().to_machine_usize(self)?;
579 let elem = layout.field(self, 0)?;
581 // Make sure the slice is not too big.
582 let size = elem.size.checked_mul(len, self).ok_or_else(|| {
583 err_ub!(InvalidMeta("slice is bigger than largest supported object"))
585 Ok(Some((size, elem.align.abi)))
588 ty::Foreign(_) => Ok(None),
590 _ => span_bug!(self.cur_span(), "size_and_align_of::<{:?}> not supported", layout.ty),
594 pub fn size_and_align_of_mplace(
596 mplace: MPlaceTy<'tcx, M::PointerTag>,
597 ) -> InterpResult<'tcx, Option<(Size, Align)>> {
598 self.size_and_align_of(mplace.meta, mplace.layout)
601 pub fn push_stack_frame(
603 instance: ty::Instance<'tcx>,
604 body: &'mir mir::Body<'tcx>,
605 return_place: Option<PlaceTy<'tcx, M::PointerTag>>,
606 return_to_block: StackPopCleanup,
607 ) -> InterpResult<'tcx> {
608 if !self.stack().is_empty() {
609 info!("PAUSING({}) {}", self.frame_idx(), self.frame().instance);
611 ::log_settings::settings().indentation += 1;
613 // first push a stack frame so we have access to the local substs
614 let pre_frame = Frame {
616 loc: Some(mir::Location::START),
619 // empty local array, we fill it in below, after we are inside the stack frame and
620 // all methods actually know about the frame
621 locals: IndexVec::new(),
625 let frame = M::init_frame_extra(self, pre_frame)?;
626 self.stack_mut().push(frame);
628 // Locals are initially uninitialized.
629 let dummy = LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) };
630 let mut locals = IndexVec::from_elem(dummy, &body.local_decls);
632 // Now mark those locals as dead that we do not want to initialize
633 match self.tcx.def_kind(instance.def_id()) {
634 // statics and constants don't have `Storage*` statements, no need to look for them
636 // FIXME: The above is likely untrue. See
637 // <https://github.com/rust-lang/rust/pull/70004#issuecomment-602022110>. Is it
638 // okay to ignore `StorageDead`/`StorageLive` annotations during CTFE?
639 DefKind::Static | DefKind::Const | DefKind::AssocConst => {}
641 // Mark locals that use `Storage*` annotations as dead on function entry.
642 let always_live = AlwaysLiveLocals::new(self.body());
643 for local in locals.indices() {
644 if !always_live.contains(local) {
645 locals[local].value = LocalValue::Dead;
651 self.frame_mut().locals = locals;
653 M::after_stack_push(self)?;
654 info!("ENTERING({}) {}", self.frame_idx(), self.frame().instance);
656 if !self.tcx.sess.recursion_limit().value_within_limit(self.stack().len()) {
657 throw_exhaust!(StackFrameLimitReached)
663 /// Jump to the given block.
665 pub fn go_to_block(&mut self, target: mir::BasicBlock) {
666 self.frame_mut().loc = Some(mir::Location { block: target, statement_index: 0 });
669 /// *Return* to the given `target` basic block.
670 /// Do *not* use for unwinding! Use `unwind_to_block` instead.
672 /// If `target` is `None`, that indicates the function cannot return, so we raise UB.
673 pub fn return_to_block(&mut self, target: Option<mir::BasicBlock>) -> InterpResult<'tcx> {
674 if let Some(target) = target {
675 self.go_to_block(target);
678 throw_ub!(Unreachable)
682 /// *Unwind* to the given `target` basic block.
683 /// Do *not* use for returning! Use `return_to_block` instead.
685 /// If `target` is `None`, that indicates the function does not need cleanup during
686 /// unwinding, and we will just keep propagating that upwards.
687 pub fn unwind_to_block(&mut self, target: Option<mir::BasicBlock>) {
688 self.frame_mut().loc = target.map(|block| mir::Location { block, statement_index: 0 });
691 /// Pops the current frame from the stack, deallocating the
692 /// memory for allocated locals.
694 /// If `unwinding` is `false`, then we are performing a normal return
695 /// from a function. In this case, we jump back into the frame of the caller,
696 /// and continue execution as normal.
698 /// If `unwinding` is `true`, then we are in the middle of a panic,
699 /// and need to unwind this frame. In this case, we jump to the
700 /// `cleanup` block for the function, which is responsible for running
701 /// `Drop` impls for any locals that have been initialized at this point.
702 /// The cleanup block ends with a special `Resume` terminator, which will
703 /// cause us to continue unwinding.
704 pub(super) fn pop_stack_frame(&mut self, unwinding: bool) -> InterpResult<'tcx> {
706 "LEAVING({}) {} (unwinding = {})",
708 self.frame().instance,
712 // Sanity check `unwinding`.
715 match self.frame().loc {
717 Some(loc) => self.body().basic_blocks()[loc.block].is_cleanup,
721 if unwinding && self.frame_idx() == 0 {
722 throw_ub_format!("unwinding past the topmost frame of the stack");
725 ::log_settings::settings().indentation -= 1;
727 self.stack_mut().pop().expect("tried to pop a stack frame, but there were none");
730 // Copy the return value to the caller's stack frame.
731 if let Some(return_place) = frame.return_place {
732 let op = self.access_local(&frame, mir::RETURN_PLACE, None)?;
733 self.copy_op_transmute(op, return_place)?;
734 trace!("{:?}", self.dump_place(*return_place));
736 throw_ub!(Unreachable);
740 // Now where do we jump next?
742 // Usually we want to clean up (deallocate locals), but in a few rare cases we don't.
743 // In that case, we return early. We also avoid validation in that case,
744 // because this is CTFE and the final value will be thoroughly validated anyway.
745 let (cleanup, next_block) = match frame.return_to_block {
746 StackPopCleanup::Goto { ret, unwind } => {
747 (true, Some(if unwinding { unwind } else { ret }))
749 StackPopCleanup::None { cleanup, .. } => (cleanup, None),
753 assert!(self.stack().is_empty(), "only the topmost frame should ever be leaked");
754 assert!(next_block.is_none(), "tried to skip cleanup when we have a next block!");
755 assert!(!unwinding, "tried to skip cleanup during unwinding");
756 // Leak the locals, skip validation, skip machine hook.
760 // Cleanup: deallocate all locals that are backed by an allocation.
761 for local in &frame.locals {
762 self.deallocate_local(local.value)?;
765 if M::after_stack_pop(self, frame, unwinding)? == StackPopJump::NoJump {
766 // The hook already did everything.
767 // We want to skip the `info!` below, hence early return.
770 // Normal return, figure out where to jump.
772 // Follow the unwind edge.
773 let unwind = next_block.expect("Encountered StackPopCleanup::None when unwinding!");
774 self.unwind_to_block(unwind);
776 // Follow the normal return edge.
777 if let Some(ret) = next_block {
778 self.return_to_block(ret)?;
782 if !self.stack().is_empty() {
784 "CONTINUING({}) {} (unwinding = {})",
786 self.frame().instance,
794 /// Mark a storage as live, killing the previous content and returning it.
795 /// Remember to deallocate that!
799 ) -> InterpResult<'tcx, LocalValue<M::PointerTag>> {
800 assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
801 trace!("{:?} is now live", local);
803 let local_val = LocalValue::Uninitialized;
804 // StorageLive *always* kills the value that's currently stored.
805 // However, we do not error if the variable already is live;
806 // see <https://github.com/rust-lang/rust/issues/42371>.
807 Ok(mem::replace(&mut self.frame_mut().locals[local].value, local_val))
810 /// Returns the old value of the local.
811 /// Remember to deallocate that!
812 pub fn storage_dead(&mut self, local: mir::Local) -> LocalValue<M::PointerTag> {
813 assert!(local != mir::RETURN_PLACE, "Cannot make return place dead");
814 trace!("{:?} is now dead", local);
816 mem::replace(&mut self.frame_mut().locals[local].value, LocalValue::Dead)
819 pub(super) fn deallocate_local(
821 local: LocalValue<M::PointerTag>,
822 ) -> InterpResult<'tcx> {
823 // FIXME: should we tell the user that there was a local which was never written to?
824 if let LocalValue::Live(Operand::Indirect(MemPlace { ptr, .. })) = local {
825 trace!("deallocating local");
826 // All locals have a backing allocation, even if the allocation is empty
827 // due to the local having ZST type.
828 let ptr = ptr.assert_ptr();
829 trace!("{:?}", self.memory.dump_alloc(ptr.alloc_id));
830 self.memory.deallocate_local(ptr)?;
835 pub(super) fn const_eval(
839 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
840 // For statics we pick `ParamEnv::reveal_all`, because statics don't have generics
841 // and thus don't care about the parameter environment. While we could just use
842 // `self.param_env`, that would mean we invoke the query to evaluate the static
843 // with different parameter environments, thus causing the static to be evaluated
845 let param_env = if self.tcx.is_static(gid.instance.def_id()) {
846 ty::ParamEnv::reveal_all()
850 let val = self.tcx.const_eval_global_id(param_env, gid, Some(self.tcx.span))?;
852 // Even though `ecx.const_eval` is called from `const_to_op` we can never have a
853 // recursion deeper than one level, because the `tcx.const_eval` above is guaranteed to not
854 // return `ConstValue::Unevaluated`, which is the only way that `const_to_op` will call
856 let const_ = ty::Const { val: ty::ConstKind::Value(val), ty };
857 self.const_to_op(&const_, None)
860 pub fn const_eval_raw(
863 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
864 // For statics we pick `ParamEnv::reveal_all`, because statics don't have generics
865 // and thus don't care about the parameter environment. While we could just use
866 // `self.param_env`, that would mean we invoke the query to evaluate the static
867 // with different parameter environments, thus causing the static to be evaluated
869 let param_env = if self.tcx.is_static(gid.instance.def_id()) {
870 ty::ParamEnv::reveal_all()
874 // We use `const_eval_raw` here, and get an unvalidated result. That is okay:
875 // Our result will later be validated anyway, and there seems no good reason
876 // to have to fail early here. This is also more consistent with
877 // `Memory::get_static_alloc` which has to use `const_eval_raw` to avoid cycles.
878 // FIXME: We can hit delay_span_bug if this is an invalid const, interning finds
879 // that problem, but we never run validation to show an error. Can we ensure
880 // this does not happen?
881 let val = self.tcx.const_eval_raw(param_env.and(gid))?;
882 self.raw_const_to_mplace(val)
886 pub fn dump_place(&'a self, place: Place<M::PointerTag>) -> PlacePrinter<'a, 'mir, 'tcx, M> {
887 PlacePrinter { ecx: self, place }
891 pub fn generate_stacktrace(&self) -> Vec<FrameInfo<'tcx>> {
892 let mut frames = Vec::new();
893 for frame in self.stack().iter().rev() {
894 let source_info = frame.current_source_info();
895 let lint_root = source_info.and_then(|source_info| {
896 match &frame.body.source_scopes[source_info.scope].local_data {
897 mir::ClearCrossCrate::Set(data) => Some(data.lint_root),
898 mir::ClearCrossCrate::Clear => None,
901 let span = source_info.map_or(DUMMY_SP, |source_info| source_info.span);
903 frames.push(FrameInfo { span, instance: frame.instance, lint_root });
905 trace!("generate stacktrace: {:#?}", frames);
911 /// Helper struct for the `dump_place` function.
912 pub struct PlacePrinter<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
913 ecx: &'a InterpCx<'mir, 'tcx, M>,
914 place: Place<M::PointerTag>,
917 impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug
918 for PlacePrinter<'a, 'mir, 'tcx, M>
920 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
922 Place::Local { frame, local } => {
923 let mut allocs = Vec::new();
924 write!(fmt, "{:?}", local)?;
925 if frame != self.ecx.frame_idx() {
926 write!(fmt, " ({} frames up)", self.ecx.frame_idx() - frame)?;
930 match self.ecx.stack()[frame].locals[local].value {
931 LocalValue::Dead => write!(fmt, " is dead")?,
932 LocalValue::Uninitialized => write!(fmt, " is uninitialized")?,
933 LocalValue::Live(Operand::Indirect(mplace)) => match mplace.ptr {
934 Scalar::Ptr(ptr) => {
937 " by align({}){} ref:",
938 mplace.align.bytes(),
940 MemPlaceMeta::Meta(meta) => format!(" meta({:?})", meta),
941 MemPlaceMeta::Poison | MemPlaceMeta::None => String::new(),
944 allocs.push(ptr.alloc_id);
946 ptr => write!(fmt, " by integral ref: {:?}", ptr)?,
948 LocalValue::Live(Operand::Immediate(Immediate::Scalar(val))) => {
949 write!(fmt, " {:?}", val)?;
950 if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr)) = val {
951 allocs.push(ptr.alloc_id);
954 LocalValue::Live(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
955 write!(fmt, " ({:?}, {:?})", val1, val2)?;
956 if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr)) = val1 {
957 allocs.push(ptr.alloc_id);
959 if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr)) = val2 {
960 allocs.push(ptr.alloc_id);
965 write!(fmt, ": {:?}", self.ecx.memory.dump_allocs(allocs))
967 Place::Ptr(mplace) => match mplace.ptr {
968 Scalar::Ptr(ptr) => write!(
970 "by align({}) ref: {:?}",
971 mplace.align.bytes(),
972 self.ecx.memory.dump_alloc(ptr.alloc_id)
974 ptr => write!(fmt, " integral by ref: {:?}", ptr),
980 impl<'ctx, 'mir, 'tcx, Tag, Extra> HashStable<StableHashingContext<'ctx>>
981 for Frame<'mir, 'tcx, Tag, Extra>
983 Extra: HashStable<StableHashingContext<'ctx>>,
984 Tag: HashStable<StableHashingContext<'ctx>>,
986 fn hash_stable(&self, hcx: &mut StableHashingContext<'ctx>, hasher: &mut StableHasher) {
987 // Exhaustive match on fields to make sure we forget no field.
988 let Frame { body, instance, return_to_block, return_place, locals, loc, extra } = self;
989 body.hash_stable(hcx, hasher);
990 instance.hash_stable(hcx, hasher);
991 return_to_block.hash_stable(hcx, hasher);
992 return_place.as_ref().map(|r| &**r).hash_stable(hcx, hasher);
993 locals.hash_stable(hcx, hasher);
994 loc.hash_stable(hcx, hasher);
995 extra.hash_stable(hcx, hasher);