5 use rustc_data_structures
::fx
::FxHashMap
;
6 use rustc_data_structures
::stable_hasher
::{HashStable, StableHasher}
;
7 use rustc_hir
::{self as hir, def::DefKind, def_id::DefId, definitions::DefPathData}
;
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
, 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
::{Pos, Span}
;
20 use rustc_target
::abi
::{Align, HasDataLayout, LayoutOf, Size, TargetDataLayout}
;
23 Immediate
, MPlaceTy
, Machine
, MemPlace
, MemPlaceMeta
, Memory
, 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 `Err`, we are not currently executing any particular statement in
87 /// this frame (can happen e.g. during frame initialization, and during unwinding on
88 /// frames without cleanup code).
89 /// We basically abuse `Result` as `Either`.
90 pub(super) loc
: Result
<mir
::Location
, Span
>,
93 /// What we store about a frame in an interpreter backtrace.
95 pub struct FrameInfo
<'tcx
> {
96 pub instance
: ty
::Instance
<'tcx
>,
98 pub lint_root
: Option
<hir
::HirId
>,
101 #[derive(Clone, Eq, PartialEq, Debug, HashStable)] // Miri debug-prints these
102 pub enum StackPopCleanup
{
103 /// Jump to the next block in the caller, or cause UB if None (that's a function
104 /// that may never return). Also store layout of return place so
105 /// we can validate it at that layout.
106 /// `ret` stores the block we jump to on a normal return, while `unwind`
107 /// stores the block used for cleanup during unwinding.
108 Goto { ret: Option<mir::BasicBlock>, unwind: Option<mir::BasicBlock> }
,
109 /// Just do nothing: Used by Main and for the `box_alloc` hook in miri.
110 /// `cleanup` says whether locals are deallocated. Static computation
111 /// wants them leaked to intern what they need (and just throw away
112 /// the entire `ecx` when it is done).
113 None { cleanup: bool }
,
116 /// State of a local variable including a memoized layout
117 #[derive(Clone, PartialEq, Eq, HashStable)]
118 pub struct LocalState
<'tcx
, Tag
= ()> {
119 pub value
: LocalValue
<Tag
>,
120 /// Don't modify if `Some`, this is only used to prevent computing the layout twice
121 #[stable_hasher(ignore)]
122 pub layout
: Cell
<Option
<TyAndLayout
<'tcx
>>>,
125 /// Current value of a local variable
126 #[derive(Copy, Clone, PartialEq, Eq, Debug, HashStable)] // Miri debug-prints these
127 pub enum LocalValue
<Tag
= ()> {
128 /// This local is not currently alive, and cannot be used at all.
130 /// This local is alive but not yet initialized. It can be written to
131 /// but not read from or its address taken. Locals get initialized on
132 /// first write because for unsized locals, we do not know their size
135 /// A normal, live local.
136 /// Mostly for convenience, we re-use the `Operand` type here.
137 /// This is an optimization over just always having a pointer here;
138 /// we can thus avoid doing an allocation when the local just stores
139 /// immediate values *and* never has its address taken.
143 impl<'tcx
, Tag
: Copy
+ '
static> LocalState
<'tcx
, Tag
> {
144 /// Read the local's value or error if the local is not yet live or not live anymore.
146 /// Note: This may only be invoked from the `Machine::access_local` hook and not from
147 /// anywhere else. You may be invalidating machine invariants if you do!
148 pub fn access(&self) -> InterpResult
<'tcx
, Operand
<Tag
>> {
150 LocalValue
::Dead
=> throw_ub
!(DeadLocal
),
151 LocalValue
::Uninitialized
=> {
152 bug
!("The type checker should prevent reading from a never-written local")
154 LocalValue
::Live(val
) => Ok(val
),
158 /// Overwrite the local. If the local can be overwritten in place, return a reference
159 /// to do so; otherwise return the `MemPlace` to consult instead.
161 /// Note: This may only be invoked from the `Machine::access_local_mut` hook and not from
162 /// anywhere else. You may be invalidating machine invariants if you do!
165 ) -> InterpResult
<'tcx
, Result
<&mut LocalValue
<Tag
>, MemPlace
<Tag
>>> {
167 LocalValue
::Dead
=> throw_ub
!(DeadLocal
),
168 LocalValue
::Live(Operand
::Indirect(mplace
)) => Ok(Err(mplace
)),
170 local @
(LocalValue
::Live(Operand
::Immediate(_
)) | LocalValue
::Uninitialized
) => {
177 impl<'mir
, 'tcx
, Tag
> Frame
<'mir
, 'tcx
, Tag
> {
178 pub fn with_extra
<Extra
>(self, extra
: Extra
) -> Frame
<'mir
, 'tcx
, Tag
, Extra
> {
181 instance
: self.instance
,
182 return_to_block
: self.return_to_block
,
183 return_place
: self.return_place
,
191 impl<'mir
, 'tcx
, Tag
, Extra
> Frame
<'mir
, 'tcx
, Tag
, Extra
> {
192 /// Return the `SourceInfo` of the current instruction.
193 pub fn current_source_info(&self) -> Option
<&mir
::SourceInfo
> {
194 self.loc
.ok().map(|loc
| self.body
.source_info(loc
))
197 pub fn current_span(&self) -> Span
{
199 Ok(loc
) => self.body
.source_info(loc
).span
,
205 impl<'tcx
> fmt
::Display
for FrameInfo
<'tcx
> {
206 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
207 ty
::tls
::with(|tcx
| {
208 if tcx
.def_key(self.instance
.def_id()).disambiguated_data
.data
209 == DefPathData
::ClosureExpr
211 write
!(f
, "inside closure")?
;
213 write
!(f
, "inside `{}`", self.instance
)?
;
215 if !self.span
.is_dummy() {
216 let lo
= tcx
.sess
.source_map().lookup_char_pos(self.span
.lo());
217 write
!(f
, " at {}:{}:{}", lo
.file
.name
, lo
.line
, lo
.col
.to_usize() + 1)?
;
224 impl<'mir
, 'tcx
, M
: Machine
<'mir
, 'tcx
>> HasDataLayout
for InterpCx
<'mir
, 'tcx
, M
> {
226 fn data_layout(&self) -> &TargetDataLayout
{
227 &self.tcx
.data_layout
231 impl<'mir
, 'tcx
, M
> layout
::HasTyCtxt
<'tcx
> for InterpCx
<'mir
, 'tcx
, M
>
233 M
: Machine
<'mir
, 'tcx
>,
236 fn tcx(&self) -> TyCtxt
<'tcx
> {
241 impl<'mir
, 'tcx
, M
> layout
::HasParamEnv
<'tcx
> for InterpCx
<'mir
, 'tcx
, M
>
243 M
: Machine
<'mir
, 'tcx
>,
245 fn param_env(&self) -> ty
::ParamEnv
<'tcx
> {
250 impl<'mir
, 'tcx
: 'mir
, M
: Machine
<'mir
, 'tcx
>> LayoutOf
for InterpCx
<'mir
, 'tcx
, M
> {
252 type TyAndLayout
= InterpResult
<'tcx
, TyAndLayout
<'tcx
>>;
255 fn layout_of(&self, ty
: Ty
<'tcx
>) -> Self::TyAndLayout
{
257 .layout_of(self.param_env
.and(ty
))
258 .map_err(|layout
| err_inval
!(Layout(layout
)).into())
262 /// Test if it is valid for a MIR assignment to assign `src`-typed place to `dest`-typed value.
263 /// This test should be symmetric, as it is primarily about layout compatibility.
264 pub(super) fn mir_assign_valid_types
<'tcx
>(
266 param_env
: ParamEnv
<'tcx
>,
267 src
: TyAndLayout
<'tcx
>,
268 dest
: TyAndLayout
<'tcx
>,
270 // Type-changing assignments can happen when subtyping is used. While
271 // all normal lifetimes are erased, higher-ranked types with their
272 // late-bound lifetimes are still around and can lead to type
273 // differences. So we compare ignoring lifetimes.
274 if equal_up_to_regions(tcx
, param_env
, src
.ty
, dest
.ty
) {
275 // Make sure the layout is equal, too -- just to be safe. Miri really
276 // needs layout equality. For performance reason we skip this check when
277 // the types are equal. Equal types *can* have different layouts when
278 // enum downcast is involved (as enum variants carry the type of the
279 // enum), but those should never occur in assignments.
280 if cfg
!(debug_assertions
) || src
.ty
!= dest
.ty
{
281 assert_eq
!(src
.layout
, dest
.layout
);
289 /// Use the already known layout if given (but sanity check in debug mode),
290 /// or compute the layout.
291 #[cfg_attr(not(debug_assertions), inline(always))]
292 pub(super) fn from_known_layout
<'tcx
>(
294 param_env
: ParamEnv
<'tcx
>,
295 known_layout
: Option
<TyAndLayout
<'tcx
>>,
296 compute
: impl FnOnce() -> InterpResult
<'tcx
, TyAndLayout
<'tcx
>>,
297 ) -> InterpResult
<'tcx
, TyAndLayout
<'tcx
>> {
300 Some(known_layout
) => {
301 if cfg
!(debug_assertions
) {
302 let check_layout
= compute()?
;
303 if !mir_assign_valid_types(tcx
.tcx
, param_env
, check_layout
, known_layout
) {
306 "expected type differs from actual type.\nexpected: {:?}\nactual: {:?}",
317 impl<'mir
, 'tcx
: 'mir
, M
: Machine
<'mir
, 'tcx
>> InterpCx
<'mir
, 'tcx
, M
> {
321 param_env
: ty
::ParamEnv
<'tcx
>,
323 memory_extra
: M
::MemoryExtra
,
327 tcx
: tcx
.at(root_span
),
329 memory
: Memory
::new(tcx
, memory_extra
),
330 vtables
: FxHashMap
::default(),
335 pub fn cur_span(&self) -> Span
{
336 self.stack().last().map(|f
| f
.current_span()).unwrap_or(self.tcx
.span
)
342 scalar
: Scalar
<M
::PointerTag
>,
343 ) -> InterpResult
<'tcx
, Pointer
<M
::PointerTag
>> {
344 self.memory
.force_ptr(scalar
)
350 scalar
: Scalar
<M
::PointerTag
>,
352 ) -> InterpResult
<'tcx
, u128
> {
353 self.memory
.force_bits(scalar
, size
)
356 /// Call this to turn untagged "global" pointers (obtained via `tcx`) into
357 /// the machine pointer to the allocation. Must never be used
358 /// for any other pointers, nor for TLS statics.
360 /// Using the resulting pointer represents a *direct* access to that memory
361 /// (e.g. by directly using a `static`),
362 /// as opposed to access through a pointer that was created by the program.
364 /// This function can fail only if `ptr` points to an `extern static`.
366 pub fn global_base_pointer(&self, ptr
: Pointer
) -> InterpResult
<'tcx
, Pointer
<M
::PointerTag
>> {
367 self.memory
.global_base_pointer(ptr
)
371 pub(crate) fn stack(&self) -> &[Frame
<'mir
, 'tcx
, M
::PointerTag
, M
::FrameExtra
>] {
376 pub(crate) fn stack_mut(
378 ) -> &mut Vec
<Frame
<'mir
, 'tcx
, M
::PointerTag
, M
::FrameExtra
>> {
383 pub fn frame_idx(&self) -> usize {
384 let stack
= self.stack();
385 assert
!(!stack
.is_empty());
390 pub fn frame(&self) -> &Frame
<'mir
, 'tcx
, M
::PointerTag
, M
::FrameExtra
> {
391 self.stack().last().expect("no call frames exist")
395 pub fn frame_mut(&mut self) -> &mut Frame
<'mir
, 'tcx
, M
::PointerTag
, M
::FrameExtra
> {
396 self.stack_mut().last_mut().expect("no call frames exist")
400 pub(super) fn body(&self) -> &'mir mir
::Body
<'tcx
> {
405 pub fn sign_extend(&self, value
: u128
, ty
: TyAndLayout
<'_
>) -> u128
{
406 assert
!(ty
.abi
.is_signed());
407 sign_extend(value
, ty
.size
)
411 pub fn truncate(&self, value
: u128
, ty
: TyAndLayout
<'_
>) -> u128
{
412 truncate(value
, ty
.size
)
416 pub fn type_is_sized(&self, ty
: Ty
<'tcx
>) -> bool
{
417 ty
.is_sized(self.tcx
, self.param_env
)
421 pub fn type_is_freeze(&self, ty
: Ty
<'tcx
>) -> bool
{
422 ty
.is_freeze(self.tcx
, self.param_env
)
427 instance
: ty
::InstanceDef
<'tcx
>,
428 promoted
: Option
<mir
::Promoted
>,
429 ) -> InterpResult
<'tcx
, &'tcx mir
::Body
<'tcx
>> {
430 // do not continue if typeck errors occurred (can only occur in local crate)
431 let def
= instance
.with_opt_param();
432 if let Some(def
) = def
.as_local() {
433 if self.tcx
.has_typeck_results(def
.did
) {
434 if let Some(error_reported
) = self.tcx
.typeck_opt_const_arg(def
).tainted_by_errors
{
435 throw_inval
!(TypeckError(error_reported
))
439 trace
!("load mir(instance={:?}, promoted={:?})", instance
, promoted
);
440 if let Some(promoted
) = promoted
{
441 return Ok(&self.tcx
.promoted_mir_of_opt_const_arg(def
)[promoted
]);
444 ty
::InstanceDef
::Item(def
) => {
445 if self.tcx
.is_mir_available(def
.did
) {
446 if let Some((did
, param_did
)) = def
.as_const_arg() {
447 Ok(self.tcx
.optimized_mir_of_const_arg((did
, param_did
)))
449 Ok(self.tcx
.optimized_mir(def
.did
))
452 throw_unsup
!(NoMirFor(def
.did
))
455 _
=> Ok(self.tcx
.instance_mir(instance
)),
459 /// Call this on things you got out of the MIR (so it is as generic as the current
460 /// stack frame), to bring it into the proper environment for this interpreter.
461 pub(super) fn subst_from_current_frame_and_normalize_erasing_regions
<T
: TypeFoldable
<'tcx
>>(
465 self.subst_from_frame_and_normalize_erasing_regions(self.frame(), value
)
468 /// Call this on things you got out of the MIR (so it is as generic as the provided
469 /// stack frame), to bring it into the proper environment for this interpreter.
470 pub(super) fn subst_from_frame_and_normalize_erasing_regions
<T
: TypeFoldable
<'tcx
>>(
472 frame
: &Frame
<'mir
, 'tcx
, M
::PointerTag
, M
::FrameExtra
>,
475 if let Some(substs
) = frame
.instance
.substs_for_mir_body() {
476 self.tcx
.subst_and_normalize_erasing_regions(substs
, self.param_env
, &value
)
478 self.tcx
.normalize_erasing_regions(self.param_env
, value
)
482 /// The `substs` are assumed to already be in our interpreter "universe" (param_env).
483 pub(super) fn resolve(
485 def
: ty
::WithOptConstParam
<DefId
>,
486 substs
: SubstsRef
<'tcx
>,
487 ) -> InterpResult
<'tcx
, ty
::Instance
<'tcx
>> {
488 trace
!("resolve: {:?}, {:#?}", def
, substs
);
489 trace
!("param_env: {:#?}", self.param_env
);
490 trace
!("substs: {:#?}", substs
);
491 match ty
::Instance
::resolve_opt_const_arg(*self.tcx
, self.param_env
, def
, substs
) {
492 Ok(Some(instance
)) => Ok(instance
),
493 Ok(None
) => throw_inval
!(TooGeneric
),
495 // FIXME(eddyb) this could be a bit more specific than `TypeckError`.
496 Err(error_reported
) => throw_inval
!(TypeckError(error_reported
)),
500 pub fn layout_of_local(
502 frame
: &Frame
<'mir
, 'tcx
, M
::PointerTag
, M
::FrameExtra
>,
504 layout
: Option
<TyAndLayout
<'tcx
>>,
505 ) -> InterpResult
<'tcx
, TyAndLayout
<'tcx
>> {
506 // `const_prop` runs into this with an invalid (empty) frame, so we
507 // have to support that case (mostly by skipping all caching).
508 match frame
.locals
.get(local
).and_then(|state
| state
.layout
.get()) {
510 let layout
= from_known_layout(self.tcx
, self.param_env
, layout
, || {
511 let local_ty
= frame
.body
.local_decls
[local
].ty
;
513 self.subst_from_frame_and_normalize_erasing_regions(frame
, local_ty
);
514 self.layout_of(local_ty
)
516 if let Some(state
) = frame
.locals
.get(local
) {
517 // Layouts of locals are requested a lot, so we cache them.
518 state
.layout
.set(Some(layout
));
522 Some(layout
) => Ok(layout
),
526 /// Returns the actual dynamic size and alignment of the place at the given type.
527 /// Only the "meta" (metadata) part of the place matters.
528 /// This can fail to provide an answer for extern types.
529 pub(super) fn size_and_align_of(
531 metadata
: MemPlaceMeta
<M
::PointerTag
>,
532 layout
: TyAndLayout
<'tcx
>,
533 ) -> InterpResult
<'tcx
, Option
<(Size
, Align
)>> {
534 if !layout
.is_unsized() {
535 return Ok(Some((layout
.size
, layout
.align
.abi
)));
537 match layout
.ty
.kind() {
538 ty
::Adt(..) | ty
::Tuple(..) => {
539 // First get the size of all statically known fields.
540 // Don't use type_of::sizing_type_of because that expects t to be sized,
541 // and it also rounds up to alignment, which we want to avoid,
542 // as the unsized field's alignment could be smaller.
543 assert
!(!layout
.ty
.is_simd());
544 assert
!(layout
.fields
.count() > 0);
545 trace
!("DST layout: {:?}", layout
);
547 let sized_size
= layout
.fields
.offset(layout
.fields
.count() - 1);
548 let sized_align
= layout
.align
.abi
;
550 "DST {} statically sized prefix size: {:?} align: {:?}",
556 // Recurse to get the size of the dynamically sized field (must be
557 // the last field). Can't have foreign types here, how would we
558 // adjust alignment and size for them?
559 let field
= layout
.field(self, layout
.fields
.count() - 1)?
;
560 let (unsized_size
, unsized_align
) = match self.size_and_align_of(metadata
, field
)?
{
561 Some(size_and_align
) => size_and_align
,
563 // A field with extern type. If this field is at offset 0, we behave
564 // like the underlying extern type.
565 // FIXME: Once we have made decisions for how to handle size and alignment
566 // of `extern type`, this should be adapted. It is just a temporary hack
567 // to get some code to work that probably ought to work.
568 if sized_size
== Size
::ZERO
{
573 "Fields cannot be extern types, unless they are at offset 0"
579 // FIXME (#26403, #27023): We should be adding padding
580 // to `sized_size` (to accommodate the `unsized_align`
581 // required of the unsized field that follows) before
582 // summing it with `sized_size`. (Note that since #26403
583 // is unfixed, we do not yet add the necessary padding
584 // here. But this is where the add would go.)
586 // Return the sum of sizes and max of aligns.
587 let size
= sized_size
+ unsized_size
; // `Size` addition
589 // Choose max of two known alignments (combined value must
590 // be aligned according to more restrictive of the two).
591 let align
= sized_align
.max(unsized_align
);
593 // Issue #27023: must add any necessary padding to `size`
594 // (to make it a multiple of `align`) before returning it.
595 let size
= size
.align_to(align
);
597 // Check if this brought us over the size limit.
598 if size
.bytes() >= self.tcx
.data_layout
.obj_size_bound() {
599 throw_ub
!(InvalidMeta("total size is bigger than largest supported object"));
601 Ok(Some((size
, align
)))
604 let vtable
= metadata
.unwrap_meta();
605 // Read size and align from vtable (already checks size).
606 Ok(Some(self.read_size_and_align_from_vtable(vtable
)?
))
609 ty
::Slice(_
) | ty
::Str
=> {
610 let len
= metadata
.unwrap_meta().to_machine_usize(self)?
;
611 let elem
= layout
.field(self, 0)?
;
613 // Make sure the slice is not too big.
614 let size
= elem
.size
.checked_mul(len
, self).ok_or_else(|| {
615 err_ub
!(InvalidMeta("slice is bigger than largest supported object"))
617 Ok(Some((size
, elem
.align
.abi
)))
620 ty
::Foreign(_
) => Ok(None
),
622 _
=> span_bug
!(self.cur_span(), "size_and_align_of::<{:?}> not supported", layout
.ty
),
626 pub fn size_and_align_of_mplace(
628 mplace
: MPlaceTy
<'tcx
, M
::PointerTag
>,
629 ) -> InterpResult
<'tcx
, Option
<(Size
, Align
)>> {
630 self.size_and_align_of(mplace
.meta
, mplace
.layout
)
633 pub fn push_stack_frame(
635 instance
: ty
::Instance
<'tcx
>,
636 body
: &'mir mir
::Body
<'tcx
>,
637 return_place
: Option
<PlaceTy
<'tcx
, M
::PointerTag
>>,
638 return_to_block
: StackPopCleanup
,
639 ) -> InterpResult
<'tcx
> {
640 if !self.stack().is_empty() {
641 info
!("PAUSING({}) {}", self.frame_idx(), self.frame().instance
);
643 ::log_settings
::settings().indentation
+= 1;
645 // first push a stack frame so we have access to the local substs
646 let pre_frame
= Frame
{
648 loc
: Err(body
.span
), // Span used for errors caused during preamble.
651 // empty local array, we fill it in below, after we are inside the stack frame and
652 // all methods actually know about the frame
653 locals
: IndexVec
::new(),
657 let frame
= M
::init_frame_extra(self, pre_frame
)?
;
658 self.stack_mut().push(frame
);
660 // Make sure all the constants required by this frame evaluate successfully (post-monomorphization check).
661 for const_
in &body
.required_consts
{
662 let span
= const_
.span
;
664 self.subst_from_current_frame_and_normalize_erasing_regions(const_
.literal
);
665 self.const_to_op(const_
, None
).map_err(|err
| {
666 // If there was an error, set the span of the current frame to this constant.
667 // Avoiding doing this when evaluation succeeds.
668 self.frame_mut().loc
= Err(span
);
673 // Locals are initially uninitialized.
674 let dummy
= LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) }
;
675 let mut locals
= IndexVec
::from_elem(dummy
, &body
.local_decls
);
677 // Now mark those locals as dead that we do not want to initialize
678 match self.tcx
.def_kind(instance
.def_id()) {
679 // statics and constants don't have `Storage*` statements, no need to look for them
681 // FIXME: The above is likely untrue. See
682 // <https://github.com/rust-lang/rust/pull/70004#issuecomment-602022110>. Is it
683 // okay to ignore `StorageDead`/`StorageLive` annotations during CTFE?
684 DefKind
::Static
| DefKind
::Const
| DefKind
::AssocConst
=> {}
686 // Mark locals that use `Storage*` annotations as dead on function entry.
687 let always_live
= AlwaysLiveLocals
::new(self.body());
688 for local
in locals
.indices() {
689 if !always_live
.contains(local
) {
690 locals
[local
].value
= LocalValue
::Dead
;
696 self.frame_mut().locals
= locals
;
697 M
::after_stack_push(self)?
;
698 self.frame_mut().loc
= Ok(mir
::Location
::START
);
699 info
!("ENTERING({}) {}", self.frame_idx(), self.frame().instance
);
704 /// Jump to the given block.
706 pub fn go_to_block(&mut self, target
: mir
::BasicBlock
) {
707 self.frame_mut().loc
= Ok(mir
::Location { block: target, statement_index: 0 }
);
710 /// *Return* to the given `target` basic block.
711 /// Do *not* use for unwinding! Use `unwind_to_block` instead.
713 /// If `target` is `None`, that indicates the function cannot return, so we raise UB.
714 pub fn return_to_block(&mut self, target
: Option
<mir
::BasicBlock
>) -> InterpResult
<'tcx
> {
715 if let Some(target
) = target
{
716 self.go_to_block(target
);
719 throw_ub
!(Unreachable
)
723 /// *Unwind* to the given `target` basic block.
724 /// Do *not* use for returning! Use `return_to_block` instead.
726 /// If `target` is `None`, that indicates the function does not need cleanup during
727 /// unwinding, and we will just keep propagating that upwards.
728 pub fn unwind_to_block(&mut self, target
: Option
<mir
::BasicBlock
>) {
729 self.frame_mut().loc
= match target
{
730 Some(block
) => Ok(mir
::Location { block, statement_index: 0 }
),
731 None
=> Err(self.frame_mut().body
.span
),
735 /// Pops the current frame from the stack, deallocating the
736 /// memory for allocated locals.
738 /// If `unwinding` is `false`, then we are performing a normal return
739 /// from a function. In this case, we jump back into the frame of the caller,
740 /// and continue execution as normal.
742 /// If `unwinding` is `true`, then we are in the middle of a panic,
743 /// and need to unwind this frame. In this case, we jump to the
744 /// `cleanup` block for the function, which is responsible for running
745 /// `Drop` impls for any locals that have been initialized at this point.
746 /// The cleanup block ends with a special `Resume` terminator, which will
747 /// cause us to continue unwinding.
748 pub(super) fn pop_stack_frame(&mut self, unwinding
: bool
) -> InterpResult
<'tcx
> {
750 "LEAVING({}) {} (unwinding = {})",
752 self.frame().instance
,
756 // Sanity check `unwinding`.
759 match self.frame().loc
{
760 Ok(loc
) => self.body().basic_blocks()[loc
.block
].is_cleanup
,
765 if unwinding
&& self.frame_idx() == 0 {
766 throw_ub_format
!("unwinding past the topmost frame of the stack");
769 ::log_settings
::settings().indentation
-= 1;
771 self.stack_mut().pop().expect("tried to pop a stack frame, but there were none");
774 // Copy the return value to the caller's stack frame.
775 if let Some(return_place
) = frame
.return_place
{
776 let op
= self.access_local(&frame
, mir
::RETURN_PLACE
, None
)?
;
777 self.copy_op_transmute(op
, return_place
)?
;
778 trace
!("{:?}", self.dump_place(*return_place
));
780 throw_ub
!(Unreachable
);
784 // Now where do we jump next?
786 // Usually we want to clean up (deallocate locals), but in a few rare cases we don't.
787 // In that case, we return early. We also avoid validation in that case,
788 // because this is CTFE and the final value will be thoroughly validated anyway.
789 let (cleanup
, next_block
) = match frame
.return_to_block
{
790 StackPopCleanup
::Goto { ret, unwind }
=> {
791 (true, Some(if unwinding { unwind }
else { ret }
))
793 StackPopCleanup
::None { cleanup, .. }
=> (cleanup
, None
),
797 assert
!(self.stack().is_empty(), "only the topmost frame should ever be leaked");
798 assert
!(next_block
.is_none(), "tried to skip cleanup when we have a next block!");
799 assert
!(!unwinding
, "tried to skip cleanup during unwinding");
800 // Leak the locals, skip validation, skip machine hook.
804 // Cleanup: deallocate all locals that are backed by an allocation.
805 for local
in &frame
.locals
{
806 self.deallocate_local(local
.value
)?
;
809 if M
::after_stack_pop(self, frame
, unwinding
)?
== StackPopJump
::NoJump
{
810 // The hook already did everything.
811 // We want to skip the `info!` below, hence early return.
814 // Normal return, figure out where to jump.
816 // Follow the unwind edge.
817 let unwind
= next_block
.expect("Encountered StackPopCleanup::None when unwinding!");
818 self.unwind_to_block(unwind
);
820 // Follow the normal return edge.
821 if let Some(ret
) = next_block
{
822 self.return_to_block(ret
)?
;
826 if !self.stack().is_empty() {
828 "CONTINUING({}) {} (unwinding = {})",
830 self.frame().instance
,
838 /// Mark a storage as live, killing the previous content and returning it.
839 /// Remember to deallocate that!
843 ) -> InterpResult
<'tcx
, LocalValue
<M
::PointerTag
>> {
844 assert
!(local
!= mir
::RETURN_PLACE
, "Cannot make return place live");
845 trace
!("{:?} is now live", local
);
847 let local_val
= LocalValue
::Uninitialized
;
848 // StorageLive *always* kills the value that's currently stored.
849 // However, we do not error if the variable already is live;
850 // see <https://github.com/rust-lang/rust/issues/42371>.
851 Ok(mem
::replace(&mut self.frame_mut().locals
[local
].value
, local_val
))
854 /// Returns the old value of the local.
855 /// Remember to deallocate that!
856 pub fn storage_dead(&mut self, local
: mir
::Local
) -> LocalValue
<M
::PointerTag
> {
857 assert
!(local
!= mir
::RETURN_PLACE
, "Cannot make return place dead");
858 trace
!("{:?} is now dead", local
);
860 mem
::replace(&mut self.frame_mut().locals
[local
].value
, LocalValue
::Dead
)
863 pub(super) fn deallocate_local(
865 local
: LocalValue
<M
::PointerTag
>,
866 ) -> InterpResult
<'tcx
> {
867 // FIXME: should we tell the user that there was a local which was never written to?
868 if let LocalValue
::Live(Operand
::Indirect(MemPlace { ptr, .. }
)) = local
{
869 // All locals have a backing allocation, even if the allocation is empty
870 // due to the local having ZST type.
871 let ptr
= ptr
.assert_ptr();
872 trace
!("deallocating local: {:?}", self.memory
.dump_alloc(ptr
.alloc_id
));
873 self.memory
.deallocate_local(ptr
)?
;
878 pub fn eval_to_allocation(
881 ) -> InterpResult
<'tcx
, MPlaceTy
<'tcx
, M
::PointerTag
>> {
882 // For statics we pick `ParamEnv::reveal_all`, because statics don't have generics
883 // and thus don't care about the parameter environment. While we could just use
884 // `self.param_env`, that would mean we invoke the query to evaluate the static
885 // with different parameter environments, thus causing the static to be evaluated
887 let param_env
= if self.tcx
.is_static(gid
.instance
.def_id()) {
888 ty
::ParamEnv
::reveal_all()
892 let val
= self.tcx
.eval_to_allocation_raw(param_env
.and(gid
))?
;
893 self.raw_const_to_mplace(val
)
897 pub fn dump_place(&'a
self, place
: Place
<M
::PointerTag
>) -> PlacePrinter
<'a
, 'mir
, 'tcx
, M
> {
898 PlacePrinter { ecx: self, place }
902 pub fn generate_stacktrace(&self) -> Vec
<FrameInfo
<'tcx
>> {
903 let mut frames
= Vec
::new();
904 for frame
in self.stack().iter().rev() {
905 let lint_root
= frame
.current_source_info().and_then(|source_info
| {
906 match &frame
.body
.source_scopes
[source_info
.scope
].local_data
{
907 mir
::ClearCrossCrate
::Set(data
) => Some(data
.lint_root
),
908 mir
::ClearCrossCrate
::Clear
=> None
,
911 let span
= frame
.current_span();
913 frames
.push(FrameInfo { span, instance: frame.instance, lint_root }
);
915 trace
!("generate stacktrace: {:#?}", frames
);
921 /// Helper struct for the `dump_place` function.
922 pub struct PlacePrinter
<'a
, 'mir
, 'tcx
, M
: Machine
<'mir
, 'tcx
>> {
923 ecx
: &'a InterpCx
<'mir
, 'tcx
, M
>,
924 place
: Place
<M
::PointerTag
>,
927 impl<'a
, 'mir
, 'tcx
: 'mir
, M
: Machine
<'mir
, 'tcx
>> std
::fmt
::Debug
928 for PlacePrinter
<'a
, 'mir
, 'tcx
, M
>
930 fn fmt(&self, fmt
: &mut std
::fmt
::Formatter
<'_
>) -> std
::fmt
::Result
{
932 Place
::Local { frame, local }
=> {
933 let mut allocs
= Vec
::new();
934 write
!(fmt
, "{:?}", local
)?
;
935 if frame
!= self.ecx
.frame_idx() {
936 write
!(fmt
, " ({} frames up)", self.ecx
.frame_idx() - frame
)?
;
940 match self.ecx
.stack()[frame
].locals
[local
].value
{
941 LocalValue
::Dead
=> write
!(fmt
, " is dead")?
,
942 LocalValue
::Uninitialized
=> write
!(fmt
, " is uninitialized")?
,
943 LocalValue
::Live(Operand
::Indirect(mplace
)) => match mplace
.ptr
{
944 Scalar
::Ptr(ptr
) => {
947 " by align({}){} ref:",
948 mplace
.align
.bytes(),
950 MemPlaceMeta
::Meta(meta
) => format
!(" meta({:?})", meta
),
951 MemPlaceMeta
::Poison
| MemPlaceMeta
::None
=> String
::new(),
954 allocs
.push(ptr
.alloc_id
);
956 ptr
=> write
!(fmt
, " by integral ref: {:?}", ptr
)?
,
958 LocalValue
::Live(Operand
::Immediate(Immediate
::Scalar(val
))) => {
959 write
!(fmt
, " {:?}", val
)?
;
960 if let ScalarMaybeUninit
::Scalar(Scalar
::Ptr(ptr
)) = val
{
961 allocs
.push(ptr
.alloc_id
);
964 LocalValue
::Live(Operand
::Immediate(Immediate
::ScalarPair(val1
, val2
))) => {
965 write
!(fmt
, " ({:?}, {:?})", val1
, val2
)?
;
966 if let ScalarMaybeUninit
::Scalar(Scalar
::Ptr(ptr
)) = val1
{
967 allocs
.push(ptr
.alloc_id
);
969 if let ScalarMaybeUninit
::Scalar(Scalar
::Ptr(ptr
)) = val2
{
970 allocs
.push(ptr
.alloc_id
);
975 write
!(fmt
, ": {:?}", self.ecx
.memory
.dump_allocs(allocs
))
977 Place
::Ptr(mplace
) => match mplace
.ptr
{
978 Scalar
::Ptr(ptr
) => write
!(
980 "by align({}) ref: {:?}",
981 mplace
.align
.bytes(),
982 self.ecx
.memory
.dump_alloc(ptr
.alloc_id
)
984 ptr
=> write
!(fmt
, " integral by ref: {:?}", ptr
),
990 impl<'ctx
, 'mir
, 'tcx
, Tag
, Extra
> HashStable
<StableHashingContext
<'ctx
>>
991 for Frame
<'mir
, 'tcx
, Tag
, Extra
>
993 Extra
: HashStable
<StableHashingContext
<'ctx
>>,
994 Tag
: HashStable
<StableHashingContext
<'ctx
>>,
996 fn hash_stable(&self, hcx
: &mut StableHashingContext
<'ctx
>, hasher
: &mut StableHasher
) {
997 // Exhaustive match on fields to make sure we forget no field.
998 let Frame { body, instance, return_to_block, return_place, locals, loc, extra }
= self;
999 body
.hash_stable(hcx
, hasher
);
1000 instance
.hash_stable(hcx
, hasher
);
1001 return_to_block
.hash_stable(hcx
, hasher
);
1002 return_place
.as_ref().map(|r
| &**r
).hash_stable(hcx
, hasher
);
1003 locals
.hash_stable(hcx
, hasher
);
1004 loc
.hash_stable(hcx
, hasher
);
1005 extra
.hash_stable(hcx
, hasher
);