5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
7 use rustc_hir::def::DefKind;
8 use rustc_hir::def_id::DefId;
9 use rustc_index::vec::IndexVec;
10 use rustc_macros::HashStable;
11 use rustc_middle::ich::StableHashingContext;
12 use rustc_middle::mir;
13 use rustc_middle::mir::interpret::{
14 sign_extend, truncate, AllocId, FrameInfo, GlobalId, InterpResult, Pointer, Scalar,
16 use rustc_middle::ty::layout::{self, TyAndLayout};
17 use rustc_middle::ty::{
18 self, fold::BottomUpFolder, query::TyCtxtAt, subst::SubstsRef, Ty, TyCtxt, TypeFoldable,
20 use rustc_span::{source_map::DUMMY_SP, Span};
21 use rustc_target::abi::{Align, HasDataLayout, LayoutOf, Size, TargetDataLayout};
24 Immediate, MPlaceTy, Machine, MemPlace, MemPlaceMeta, Memory, OpTy, Operand, Place, PlaceTy,
25 ScalarMaybeUndef, StackPopJump,
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 pub tcx: TyCtxtAt<'tcx>,
38 /// Bounds in scope for polymorphic evaluations.
39 pub(crate) param_env: ty::ParamEnv<'tcx>,
41 /// The virtual memory system.
42 pub memory: Memory<'mir, 'tcx, M>,
44 /// A cache for deduplicating vtables
46 FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), Pointer<M::PointerTag>>,
51 pub struct Frame<'mir, 'tcx, Tag = (), Extra = ()> {
52 ////////////////////////////////////////////////////////////////////////////////
53 // Function and callsite information
54 ////////////////////////////////////////////////////////////////////////////////
55 /// The MIR for the function called on this frame.
56 pub body: &'mir mir::Body<'tcx>,
58 /// The def_id and substs of the current function.
59 pub instance: ty::Instance<'tcx>,
61 /// Extra data for the machine.
64 ////////////////////////////////////////////////////////////////////////////////
65 // Return place and locals
66 ////////////////////////////////////////////////////////////////////////////////
67 /// Work to perform when returning from this function.
68 pub return_to_block: StackPopCleanup,
70 /// The location where the result of the current stack frame should be written to,
71 /// and its layout in the caller.
72 pub return_place: Option<PlaceTy<'tcx, Tag>>,
74 /// The list of locals for this stack frame, stored in order as
75 /// `[return_ptr, arguments..., variables..., temporaries...]`.
76 /// The locals are stored as `Option<Value>`s.
77 /// `None` represents a local that is currently dead, while a live local
78 /// can either directly contain `Scalar` or refer to some part of an `Allocation`.
79 pub locals: IndexVec<mir::Local, LocalState<'tcx, Tag>>,
81 ////////////////////////////////////////////////////////////////////////////////
82 // Current position within the function
83 ////////////////////////////////////////////////////////////////////////////////
84 /// The block that is currently executed (or will be executed after the above call stacks
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 block: Option<mir::BasicBlock>,
90 /// The index of the currently evaluated statement.
94 #[derive(Clone, Eq, PartialEq, Debug, HashStable)] // Miri debug-prints these
95 pub enum StackPopCleanup {
96 /// Jump to the next block in the caller, or cause UB if None (that's a function
97 /// that may never return). Also store layout of return place so
98 /// we can validate it at that layout.
99 /// `ret` stores the block we jump to on a normal return, while `unwind`
100 /// stores the block used for cleanup during unwinding.
101 Goto { ret: Option<mir::BasicBlock>, unwind: Option<mir::BasicBlock> },
102 /// Just do nothing: Used by Main and for the `box_alloc` hook in miri.
103 /// `cleanup` says whether locals are deallocated. Static computation
104 /// wants them leaked to intern what they need (and just throw away
105 /// the entire `ecx` when it is done).
106 None { cleanup: bool },
109 /// State of a local variable including a memoized layout
110 #[derive(Clone, PartialEq, Eq, HashStable)]
111 pub struct LocalState<'tcx, Tag = (), Id = AllocId> {
112 pub value: LocalValue<Tag, Id>,
113 /// Don't modify if `Some`, this is only used to prevent computing the layout twice
114 #[stable_hasher(ignore)]
115 pub layout: Cell<Option<TyAndLayout<'tcx>>>,
118 /// Current value of a local variable
119 #[derive(Copy, Clone, PartialEq, Eq, Debug, HashStable)] // Miri debug-prints these
120 pub enum LocalValue<Tag = (), Id = AllocId> {
121 /// This local is not currently alive, and cannot be used at all.
123 /// This local is alive but not yet initialized. It can be written to
124 /// but not read from or its address taken. Locals get initialized on
125 /// first write because for unsized locals, we do not know their size
128 /// A normal, live local.
129 /// Mostly for convenience, we re-use the `Operand` type here.
130 /// This is an optimization over just always having a pointer here;
131 /// we can thus avoid doing an allocation when the local just stores
132 /// immediate values *and* never has its address taken.
133 Live(Operand<Tag, Id>),
136 impl<'tcx, Tag: Copy + 'static> LocalState<'tcx, Tag> {
137 pub fn access(&self) -> InterpResult<'tcx, Operand<Tag>> {
139 LocalValue::Dead => throw_ub!(DeadLocal),
140 LocalValue::Uninitialized => {
141 bug!("The type checker should prevent reading from a never-written local")
143 LocalValue::Live(val) => Ok(val),
147 /// Overwrite the local. If the local can be overwritten in place, return a reference
148 /// to do so; otherwise return the `MemPlace` to consult instead.
151 ) -> InterpResult<'tcx, Result<&mut LocalValue<Tag>, MemPlace<Tag>>> {
153 LocalValue::Dead => throw_ub!(DeadLocal),
154 LocalValue::Live(Operand::Indirect(mplace)) => Ok(Err(mplace)),
156 local @ (LocalValue::Live(Operand::Immediate(_)) | LocalValue::Uninitialized) => {
163 impl<'mir, 'tcx, Tag> Frame<'mir, 'tcx, Tag> {
164 pub fn with_extra<Extra>(self, extra: Extra) -> Frame<'mir, 'tcx, Tag, Extra> {
167 instance: self.instance,
168 return_to_block: self.return_to_block,
169 return_place: self.return_place,
178 impl<'mir, 'tcx, Tag, Extra> Frame<'mir, 'tcx, Tag, Extra> {
179 /// Return the `SourceInfo` of the current instruction.
180 pub fn current_source_info(&self) -> Option<mir::SourceInfo> {
181 self.block.map(|block| {
182 let block = &self.body.basic_blocks()[block];
183 if self.stmt < block.statements.len() {
184 block.statements[self.stmt].source_info
186 block.terminator().source_info
192 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for InterpCx<'mir, 'tcx, M> {
194 fn data_layout(&self) -> &TargetDataLayout {
195 &self.tcx.data_layout
199 impl<'mir, 'tcx, M> layout::HasTyCtxt<'tcx> for InterpCx<'mir, 'tcx, M>
201 M: Machine<'mir, 'tcx>,
204 fn tcx(&self) -> TyCtxt<'tcx> {
209 impl<'mir, 'tcx, M> layout::HasParamEnv<'tcx> for InterpCx<'mir, 'tcx, M>
211 M: Machine<'mir, 'tcx>,
213 fn param_env(&self) -> ty::ParamEnv<'tcx> {
218 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> LayoutOf for InterpCx<'mir, 'tcx, M> {
220 type TyAndLayout = InterpResult<'tcx, TyAndLayout<'tcx>>;
223 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
225 .layout_of(self.param_env.and(ty))
226 .map_err(|layout| err_inval!(Layout(layout)).into())
230 /// Test if it is valid for a MIR assignment to assign `src`-typed place to `dest`-typed value.
231 /// This test should be symmetric, as it is primarily about layout compatibility.
232 pub(super) fn mir_assign_valid_types<'tcx>(
234 src: TyAndLayout<'tcx>,
235 dest: TyAndLayout<'tcx>,
237 if src.ty == dest.ty {
238 // Equal types, all is good.
241 if src.layout != dest.layout {
242 // Layout differs, definitely not equal.
243 // We do this here because Miri would *do the wrong thing* if we allowed layout-changing
248 // Type-changing assignments can happen for (at least) two reasons:
249 // 1. `&mut T` -> `&T` gets optimized from a reborrow to a mere assignment.
250 // 2. Subtyping is used. While all normal lifetimes are erased, higher-ranked types
251 // with their late-bound lifetimes are still around and can lead to type differences.
252 // Normalize both of them away.
253 let normalize = |ty: Ty<'tcx>| {
254 ty.fold_with(&mut BottomUpFolder {
256 // Normalize all references to immutable.
257 ty_op: |ty| match ty.kind {
258 ty::Ref(_, pointee, _) => tcx.mk_imm_ref(tcx.lifetimes.re_erased, pointee),
261 // We just erase all late-bound lifetimes, but this is not fully correct (FIXME):
262 // lifetimes in invariant positions could matter (e.g. through associated types).
263 // We rely on the fact that layout was confirmed to be equal above.
264 lt_op: |_| tcx.lifetimes.re_erased,
265 // Leave consts unchanged.
269 normalize(src.ty) == normalize(dest.ty)
272 /// Use the already known layout if given (but sanity check in debug mode),
273 /// or compute the layout.
274 #[cfg_attr(not(debug_assertions), inline(always))]
275 pub(super) fn from_known_layout<'tcx>(
277 known_layout: Option<TyAndLayout<'tcx>>,
278 compute: impl FnOnce() -> InterpResult<'tcx, TyAndLayout<'tcx>>,
279 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
282 Some(known_layout) => {
283 if cfg!(debug_assertions) {
284 let check_layout = compute()?;
285 if !mir_assign_valid_types(tcx.tcx, check_layout, known_layout) {
288 "expected type differs from actual type.\nexpected: {:?}\nactual: {:?}",
299 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
302 param_env: ty::ParamEnv<'tcx>,
304 memory_extra: M::MemoryExtra,
310 memory: Memory::new(tcx, memory_extra),
311 vtables: FxHashMap::default(),
316 pub fn set_span(&mut self, span: Span) {
317 self.tcx.span = span;
318 self.memory.tcx.span = span;
324 scalar: Scalar<M::PointerTag>,
325 ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
326 self.memory.force_ptr(scalar)
332 scalar: Scalar<M::PointerTag>,
334 ) -> InterpResult<'tcx, u128> {
335 self.memory.force_bits(scalar, size)
338 /// Call this to turn untagged "global" pointers (obtained via `tcx`) into
339 /// the *canonical* machine pointer to the allocation. Must never be used
340 /// for any other pointers!
342 /// This represents a *direct* access to that memory, as opposed to access
343 /// through a pointer that was created by the program.
345 pub fn tag_global_base_pointer(&self, ptr: Pointer) -> Pointer<M::PointerTag> {
346 self.memory.tag_global_base_pointer(ptr)
350 pub(crate) fn stack(&self) -> &[Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>] {
355 pub(crate) fn stack_mut(
357 ) -> &mut Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>> {
362 pub fn frame_idx(&self) -> usize {
363 let stack = self.stack();
364 assert!(!stack.is_empty());
369 pub fn frame(&self) -> &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
370 self.stack().last().expect("no call frames exist")
374 pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
375 self.stack_mut().last_mut().expect("no call frames exist")
379 pub(super) fn body(&self) -> &'mir mir::Body<'tcx> {
384 pub fn sign_extend(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
385 assert!(ty.abi.is_signed());
386 sign_extend(value, ty.size)
390 pub fn truncate(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
391 truncate(value, ty.size)
395 pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
396 ty.is_sized(self.tcx, self.param_env)
400 pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
401 ty.is_freeze(*self.tcx, self.param_env, DUMMY_SP)
406 instance: ty::InstanceDef<'tcx>,
407 promoted: Option<mir::Promoted>,
408 ) -> InterpResult<'tcx, mir::ReadOnlyBodyAndCache<'tcx, 'tcx>> {
409 // do not continue if typeck errors occurred (can only occur in local crate)
410 let did = instance.def_id();
411 if did.is_local() && self.tcx.has_typeck_tables(did) {
412 if let Some(error_reported) = self.tcx.typeck_tables_of(did).tainted_by_errors {
413 throw_inval!(TypeckError(error_reported))
416 trace!("load mir(instance={:?}, promoted={:?})", instance, promoted);
417 if let Some(promoted) = promoted {
418 return Ok(self.tcx.promoted_mir(did)[promoted].unwrap_read_only());
421 ty::InstanceDef::Item(def_id) => {
422 if self.tcx.is_mir_available(did) {
423 Ok(self.tcx.optimized_mir(did).unwrap_read_only())
425 throw_unsup!(NoMirFor(def_id))
428 _ => Ok(self.tcx.instance_mir(instance)),
432 /// Call this on things you got out of the MIR (so it is as generic as the current
433 /// stack frame), to bring it into the proper environment for this interpreter.
434 pub(super) fn subst_from_current_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
438 self.subst_from_frame_and_normalize_erasing_regions(self.frame(), value)
441 /// Call this on things you got out of the MIR (so it is as generic as the provided
442 /// stack frame), to bring it into the proper environment for this interpreter.
443 pub(super) fn subst_from_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
445 frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
448 if let Some(substs) = frame.instance.substs_for_mir_body() {
449 self.tcx.subst_and_normalize_erasing_regions(substs, self.param_env, &value)
451 self.tcx.normalize_erasing_regions(self.param_env, value)
455 /// The `substs` are assumed to already be in our interpreter "universe" (param_env).
456 pub(super) fn resolve(
459 substs: SubstsRef<'tcx>,
460 ) -> InterpResult<'tcx, ty::Instance<'tcx>> {
461 trace!("resolve: {:?}, {:#?}", def_id, substs);
462 trace!("param_env: {:#?}", self.param_env);
463 trace!("substs: {:#?}", substs);
464 ty::Instance::resolve(*self.tcx, self.param_env, def_id, substs)
465 .ok_or_else(|| err_inval!(TooGeneric).into())
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, 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 {
539 bug!("Fields cannot be extern types, unless they are at offset 0")
544 // FIXME (#26403, #27023): We should be adding padding
545 // to `sized_size` (to accommodate the `unsized_align`
546 // required of the unsized field that follows) before
547 // summing it with `sized_size`. (Note that since #26403
548 // is unfixed, we do not yet add the necessary padding
549 // here. But this is where the add would go.)
551 // Return the sum of sizes and max of aligns.
552 let size = sized_size + unsized_size; // `Size` addition
554 // Choose max of two known alignments (combined value must
555 // be aligned according to more restrictive of the two).
556 let align = sized_align.max(unsized_align);
558 // Issue #27023: must add any necessary padding to `size`
559 // (to make it a multiple of `align`) before returning it.
560 let size = size.align_to(align);
562 // Check if this brought us over the size limit.
563 if size.bytes() >= self.tcx.data_layout().obj_size_bound() {
564 throw_ub!(InvalidMeta("total size is bigger than largest supported object"));
566 Ok(Some((size, align)))
569 let vtable = metadata.unwrap_meta();
570 // Read size and align from vtable (already checks size).
571 Ok(Some(self.read_size_and_align_from_vtable(vtable)?))
574 ty::Slice(_) | ty::Str => {
575 let len = metadata.unwrap_meta().to_machine_usize(self)?;
576 let elem = layout.field(self, 0)?;
578 // Make sure the slice is not too big.
579 let size = elem.size.checked_mul(len, &*self.tcx).ok_or_else(|| {
580 err_ub!(InvalidMeta("slice is bigger than largest supported object"))
582 Ok(Some((size, elem.align.abi)))
585 ty::Foreign(_) => Ok(None),
587 _ => bug!("size_and_align_of::<{:?}> not supported", layout.ty),
591 pub fn size_and_align_of_mplace(
593 mplace: MPlaceTy<'tcx, M::PointerTag>,
594 ) -> InterpResult<'tcx, Option<(Size, Align)>> {
595 self.size_and_align_of(mplace.meta, mplace.layout)
598 pub fn push_stack_frame(
600 instance: ty::Instance<'tcx>,
601 body: &'mir mir::Body<'tcx>,
602 return_place: Option<PlaceTy<'tcx, M::PointerTag>>,
603 return_to_block: StackPopCleanup,
604 ) -> InterpResult<'tcx> {
605 if !self.stack().is_empty() {
606 info!("PAUSING({}) {}", self.frame_idx(), self.frame().instance);
608 ::log_settings::settings().indentation += 1;
610 // first push a stack frame so we have access to the local substs
611 let pre_frame = Frame {
613 block: Some(mir::START_BLOCK),
616 // empty local array, we fill it in below, after we are inside the stack frame and
617 // all methods actually know about the frame
618 locals: IndexVec::new(),
623 let frame = M::init_frame_extra(self, pre_frame)?;
624 self.stack_mut().push(frame);
626 // Locals are initially uninitialized.
627 let dummy = LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) };
628 let mut locals = IndexVec::from_elem(dummy, &body.local_decls);
630 // Now mark those locals as dead that we do not want to initialize
631 match self.tcx.def_kind(instance.def_id()) {
632 // statics and constants don't have `Storage*` statements, no need to look for them
634 // FIXME: The above is likely untrue. See
635 // <https://github.com/rust-lang/rust/pull/70004#issuecomment-602022110>. Is it
636 // okay to ignore `StorageDead`/`StorageLive` annotations during CTFE?
637 Some(DefKind::Static | DefKind::Const | DefKind::AssocConst) => {}
639 // Mark locals that use `Storage*` annotations as dead on function entry.
640 let always_live = AlwaysLiveLocals::new(self.body());
641 for local in locals.indices() {
642 if !always_live.contains(local) {
643 locals[local].value = LocalValue::Dead;
649 self.frame_mut().locals = locals;
651 M::after_stack_push(self)?;
652 info!("ENTERING({}) {}", self.frame_idx(), self.frame().instance);
654 if self.stack().len() > *self.tcx.sess.recursion_limit.get() {
655 throw_exhaust!(StackFrameLimitReached)
661 /// Jump to the given block.
663 pub fn go_to_block(&mut self, target: mir::BasicBlock) {
664 let frame = self.frame_mut();
665 frame.block = Some(target);
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 let frame = self.frame_mut();
689 frame.block = target;
693 /// Pops the current frame from the stack, deallocating the
694 /// memory for allocated locals.
696 /// If `unwinding` is `false`, then we are performing a normal return
697 /// from a function. In this case, we jump back into the frame of the caller,
698 /// and continue execution as normal.
700 /// If `unwinding` is `true`, then we are in the middle of a panic,
701 /// and need to unwind this frame. In this case, we jump to the
702 /// `cleanup` block for the function, which is responsible for running
703 /// `Drop` impls for any locals that have been initialized at this point.
704 /// The cleanup block ends with a special `Resume` terminator, which will
705 /// cause us to continue unwinding.
706 pub(super) fn pop_stack_frame(&mut self, unwinding: bool) -> InterpResult<'tcx> {
708 "LEAVING({}) {} (unwinding = {})",
710 self.frame().instance,
714 // Sanity check `unwinding`.
717 match self.frame().block {
719 Some(block) => self.body().basic_blocks()[block].is_cleanup,
723 ::log_settings::settings().indentation -= 1;
725 self.stack_mut().pop().expect("tried to pop a stack frame, but there were none");
728 // Copy the return value to the caller's stack frame.
729 if let Some(return_place) = frame.return_place {
730 let op = self.access_local(&frame, mir::RETURN_PLACE, None)?;
731 self.copy_op(op, return_place)?;
732 self.dump_place(*return_place);
734 throw_ub!(Unreachable);
738 // Now where do we jump next?
740 // Usually we want to clean up (deallocate locals), but in a few rare cases we don't.
741 // In that case, we return early. We also avoid validation in that case,
742 // because this is CTFE and the final value will be thoroughly validated anyway.
743 let (cleanup, next_block) = match frame.return_to_block {
744 StackPopCleanup::Goto { ret, unwind } => {
745 (true, Some(if unwinding { unwind } else { ret }))
747 StackPopCleanup::None { cleanup, .. } => (cleanup, None),
751 assert!(self.stack().is_empty(), "only the topmost frame should ever be leaked");
752 assert!(next_block.is_none(), "tried to skip cleanup when we have a next block!");
753 assert!(!unwinding, "tried to skip cleanup during unwinding");
754 // Leak the locals, skip validation, skip machine hook.
758 // Cleanup: deallocate all locals that are backed by an allocation.
759 for local in &frame.locals {
760 self.deallocate_local(local.value)?;
763 let return_place = frame.return_place;
764 if M::after_stack_pop(self, frame, unwinding)? == StackPopJump::NoJump {
765 // The hook already did everything.
766 // We want to skip the `info!` below, hence early return.
769 // Normal return, figure out where to jump.
771 // Follow the unwind edge.
772 let unwind = next_block.expect("Encountered StackPopCleanup::None when unwinding!");
773 self.unwind_to_block(unwind);
775 // Follow the normal return edge.
776 if let Some(ret) = next_block {
777 self.return_to_block(ret)?;
781 if !self.stack().is_empty() {
783 "CONTINUING({}) {} (unwinding = {})",
785 self.frame().instance,
793 /// Mark a storage as live, killing the previous content and returning it.
794 /// Remember to deallocate that!
798 ) -> InterpResult<'tcx, LocalValue<M::PointerTag>> {
799 assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
800 trace!("{:?} is now live", local);
802 let local_val = LocalValue::Uninitialized;
803 // StorageLive *always* kills the value that's currently stored.
804 // However, we do not error if the variable already is live;
805 // see <https://github.com/rust-lang/rust/issues/42371>.
806 Ok(mem::replace(&mut self.frame_mut().locals[local].value, local_val))
809 /// Returns the old value of the local.
810 /// Remember to deallocate that!
811 pub fn storage_dead(&mut self, local: mir::Local) -> LocalValue<M::PointerTag> {
812 assert!(local != mir::RETURN_PLACE, "Cannot make return place dead");
813 trace!("{:?} is now dead", local);
815 mem::replace(&mut self.frame_mut().locals[local].value, LocalValue::Dead)
818 pub(super) fn deallocate_local(
820 local: LocalValue<M::PointerTag>,
821 ) -> InterpResult<'tcx> {
822 // FIXME: should we tell the user that there was a local which was never written to?
823 if let LocalValue::Live(Operand::Indirect(MemPlace { ptr, .. })) = local {
824 trace!("deallocating local");
825 // All locals have a backing allocation, even if the allocation is empty
826 // due to the local having ZST type.
827 let ptr = ptr.assert_ptr();
828 if log_enabled!(::log::Level::Trace) {
829 self.memory.dump_alloc(ptr.alloc_id);
831 self.memory.deallocate_local(ptr)?;
836 pub(super) fn const_eval(
840 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
841 // For statics we pick `ParamEnv::reveal_all`, because statics don't have generics
842 // and thus don't care about the parameter environment. While we could just use
843 // `self.param_env`, that would mean we invoke the query to evaluate the static
844 // with different parameter environments, thus causing the static to be evaluated
846 let param_env = if self.tcx.is_static(gid.instance.def_id()) {
847 ty::ParamEnv::reveal_all()
851 let val = self.tcx.const_eval_global_id(param_env, gid, Some(self.tcx.span))?;
853 // Even though `ecx.const_eval` is called from `eval_const_to_op` we can never have a
854 // recursion deeper than one level, because the `tcx.const_eval` above is guaranteed to not
855 // return `ConstValue::Unevaluated`, which is the only way that `eval_const_to_op` will call
857 let const_ = ty::Const { val: ty::ConstKind::Value(val), ty };
858 self.eval_const_to_op(&const_, None)
861 pub fn const_eval_raw(
864 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
865 // For statics we pick `ParamEnv::reveal_all`, because statics don't have generics
866 // and thus don't care about the parameter environment. While we could just use
867 // `self.param_env`, that would mean we invoke the query to evaluate the static
868 // with different parameter environments, thus causing the static to be evaluated
870 let param_env = if self.tcx.is_static(gid.instance.def_id()) {
871 ty::ParamEnv::reveal_all()
875 // We use `const_eval_raw` here, and get an unvalidated result. That is okay:
876 // Our result will later be validated anyway, and there seems no good reason
877 // to have to fail early here. This is also more consistent with
878 // `Memory::get_static_alloc` which has to use `const_eval_raw` to avoid cycles.
879 let val = self.tcx.const_eval_raw(param_env.and(gid))?;
880 self.raw_const_to_mplace(val)
883 pub fn dump_place(&self, place: Place<M::PointerTag>) {
885 if !log_enabled!(::log::Level::Trace) {
889 Place::Local { frame, local } => {
890 let mut allocs = Vec::new();
891 let mut msg = format!("{:?}", local);
892 if frame != self.frame_idx() {
893 write!(msg, " ({} frames up)", self.frame_idx() - frame).unwrap();
895 write!(msg, ":").unwrap();
897 match self.stack()[frame].locals[local].value {
898 LocalValue::Dead => write!(msg, " is dead").unwrap(),
899 LocalValue::Uninitialized => write!(msg, " is uninitialized").unwrap(),
900 LocalValue::Live(Operand::Indirect(mplace)) => match mplace.ptr {
901 Scalar::Ptr(ptr) => {
904 " by align({}){} ref:",
905 mplace.align.bytes(),
907 MemPlaceMeta::Meta(meta) => format!(" meta({:?})", meta),
908 MemPlaceMeta::Poison | MemPlaceMeta::None => String::new(),
912 allocs.push(ptr.alloc_id);
914 ptr => write!(msg, " by integral ref: {:?}", ptr).unwrap(),
916 LocalValue::Live(Operand::Immediate(Immediate::Scalar(val))) => {
917 write!(msg, " {:?}", val).unwrap();
918 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val {
919 allocs.push(ptr.alloc_id);
922 LocalValue::Live(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
923 write!(msg, " ({:?}, {:?})", val1, val2).unwrap();
924 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val1 {
925 allocs.push(ptr.alloc_id);
927 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val2 {
928 allocs.push(ptr.alloc_id);
934 self.memory.dump_allocs(allocs);
936 Place::Ptr(mplace) => match mplace.ptr {
937 Scalar::Ptr(ptr) => {
938 trace!("by align({}) ref:", mplace.align.bytes());
939 self.memory.dump_alloc(ptr.alloc_id);
941 ptr => trace!(" integral by ref: {:?}", ptr),
946 pub fn generate_stacktrace(&self) -> Vec<FrameInfo<'tcx>> {
947 let mut frames = Vec::new();
948 for frame in self.stack().iter().rev() {
949 let source_info = frame.current_source_info();
950 let lint_root = source_info.and_then(|source_info| {
951 match &frame.body.source_scopes[source_info.scope].local_data {
952 mir::ClearCrossCrate::Set(data) => Some(data.lint_root),
953 mir::ClearCrossCrate::Clear => None,
956 let span = source_info.map_or(DUMMY_SP, |source_info| source_info.span);
958 frames.push(FrameInfo { span, instance: frame.instance, lint_root });
960 trace!("generate stacktrace: {:#?}", frames);
965 impl<'ctx, 'mir, 'tcx, Tag, Extra> HashStable<StableHashingContext<'ctx>>
966 for Frame<'mir, 'tcx, Tag, Extra>
968 Extra: HashStable<StableHashingContext<'ctx>>,
969 Tag: HashStable<StableHashingContext<'ctx>>,
971 fn hash_stable(&self, hcx: &mut StableHashingContext<'ctx>, hasher: &mut StableHasher) {
972 self.body.hash_stable(hcx, hasher);
973 self.instance.hash_stable(hcx, hasher);
974 self.return_to_block.hash_stable(hcx, hasher);
975 self.return_place.as_ref().map(|r| &**r).hash_stable(hcx, hasher);
976 self.locals.hash_stable(hcx, hasher);
977 self.block.hash_stable(hcx, hasher);
978 self.stmt.hash_stable(hcx, hasher);
979 self.extra.hash_stable(hcx, hasher);