]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/eval_context.rs
d4431806c4a3900bd1076eeaa021298ef68050bb
[rust.git] / src / librustc_mir / interpret / eval_context.rs
1 use std::cell::Cell;
2 use std::fmt::Write;
3 use std::mem;
4
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,
15 };
16 use rustc_middle::ty::layout::{self, TyAndLayout};
17 use rustc_middle::ty::{
18     self, fold::BottomUpFolder, query::TyCtxtAt, subst::SubstsRef, Ty, TyCtxt, TypeFoldable,
19 };
20 use rustc_span::{source_map::DUMMY_SP, Span};
21 use rustc_target::abi::{Align, HasDataLayout, LayoutOf, Size, TargetDataLayout};
22
23 use super::{
24     Immediate, MPlaceTy, Machine, MemPlace, MemPlaceMeta, Memory, OpTy, Operand, Place, PlaceTy,
25     ScalarMaybeUndef, StackPopJump,
26 };
27 use crate::util::storage::AlwaysLiveLocals;
28
29 pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
30     /// Stores the `Machine` instance.
31     ///
32     /// Note: the stack is provided by the machine.
33     pub machine: M,
34
35     /// The results of the type checker, from rustc.
36     pub tcx: TyCtxtAt<'tcx>,
37
38     /// Bounds in scope for polymorphic evaluations.
39     pub(crate) param_env: ty::ParamEnv<'tcx>,
40
41     /// The virtual memory system.
42     pub memory: Memory<'mir, 'tcx, M>,
43
44     /// A cache for deduplicating vtables
45     pub(super) vtables:
46         FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), Pointer<M::PointerTag>>,
47 }
48
49 /// A stack frame.
50 #[derive(Clone)]
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>,
57
58     /// The def_id and substs of the current function.
59     pub instance: ty::Instance<'tcx>,
60
61     /// Extra data for the machine.
62     pub extra: Extra,
63
64     ////////////////////////////////////////////////////////////////////////////////
65     // Return place and locals
66     ////////////////////////////////////////////////////////////////////////////////
67     /// Work to perform when returning from this function.
68     pub return_to_block: StackPopCleanup,
69
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>>,
73
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>>,
80
81     ////////////////////////////////////////////////////////////////////////////////
82     // Current position within the function
83     ////////////////////////////////////////////////////////////////////////////////
84     /// The block that is currently executed (or will be executed after the above call stacks
85     /// return).
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>,
89
90     /// The index of the currently evaluated statement.
91     pub stmt: usize,
92 }
93
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 },
107 }
108
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>>>,
116 }
117
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.
122     Dead,
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
126     /// before that.
127     Uninitialized,
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>),
134 }
135
136 impl<'tcx, Tag: Copy + 'static> LocalState<'tcx, Tag> {
137     pub fn access(&self) -> InterpResult<'tcx, Operand<Tag>> {
138         match self.value {
139             LocalValue::Dead => throw_ub!(DeadLocal),
140             LocalValue::Uninitialized => {
141                 bug!("The type checker should prevent reading from a never-written local")
142             }
143             LocalValue::Live(val) => Ok(val),
144         }
145     }
146
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.
149     pub fn access_mut(
150         &mut self,
151     ) -> InterpResult<'tcx, Result<&mut LocalValue<Tag>, MemPlace<Tag>>> {
152         match self.value {
153             LocalValue::Dead => throw_ub!(DeadLocal),
154             LocalValue::Live(Operand::Indirect(mplace)) => Ok(Err(mplace)),
155             ref mut
156             local @ (LocalValue::Live(Operand::Immediate(_)) | LocalValue::Uninitialized) => {
157                 Ok(Ok(local))
158             }
159         }
160     }
161 }
162
163 impl<'mir, 'tcx, Tag> Frame<'mir, 'tcx, Tag> {
164     pub fn with_extra<Extra>(self, extra: Extra) -> Frame<'mir, 'tcx, Tag, Extra> {
165         Frame {
166             body: self.body,
167             instance: self.instance,
168             return_to_block: self.return_to_block,
169             return_place: self.return_place,
170             locals: self.locals,
171             block: self.block,
172             stmt: self.stmt,
173             extra,
174         }
175     }
176 }
177
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
185             } else {
186                 block.terminator().source_info
187             }
188         })
189     }
190 }
191
192 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for InterpCx<'mir, 'tcx, M> {
193     #[inline]
194     fn data_layout(&self) -> &TargetDataLayout {
195         &self.tcx.data_layout
196     }
197 }
198
199 impl<'mir, 'tcx, M> layout::HasTyCtxt<'tcx> for InterpCx<'mir, 'tcx, M>
200 where
201     M: Machine<'mir, 'tcx>,
202 {
203     #[inline]
204     fn tcx(&self) -> TyCtxt<'tcx> {
205         *self.tcx
206     }
207 }
208
209 impl<'mir, 'tcx, M> layout::HasParamEnv<'tcx> for InterpCx<'mir, 'tcx, M>
210 where
211     M: Machine<'mir, 'tcx>,
212 {
213     fn param_env(&self) -> ty::ParamEnv<'tcx> {
214         self.param_env
215     }
216 }
217
218 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> LayoutOf for InterpCx<'mir, 'tcx, M> {
219     type Ty = Ty<'tcx>;
220     type TyAndLayout = InterpResult<'tcx, TyAndLayout<'tcx>>;
221
222     #[inline]
223     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
224         self.tcx
225             .layout_of(self.param_env.and(ty))
226             .map_err(|layout| err_inval!(Layout(layout)).into())
227     }
228 }
229
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>(
233     tcx: TyCtxt<'tcx>,
234     src: TyAndLayout<'tcx>,
235     dest: TyAndLayout<'tcx>,
236 ) -> bool {
237     if src.ty == dest.ty {
238         // Equal types, all is good.
239         return true;
240     }
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
244         // assignments.
245         return false;
246     }
247
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 {
255             tcx,
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),
259                 _ => ty,
260             },
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.
266             ct_op: |ct| ct,
267         })
268     };
269     normalize(src.ty) == normalize(dest.ty)
270 }
271
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>(
276     tcx: TyCtxtAt<'tcx>,
277     known_layout: Option<TyAndLayout<'tcx>>,
278     compute: impl FnOnce() -> InterpResult<'tcx, TyAndLayout<'tcx>>,
279 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
280     match known_layout {
281         None => compute(),
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) {
286                     span_bug!(
287                         tcx.span,
288                         "expected type differs from actual type.\nexpected: {:?}\nactual: {:?}",
289                         known_layout.ty,
290                         check_layout.ty,
291                     );
292                 }
293             }
294             Ok(known_layout)
295         }
296     }
297 }
298
299 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
300     pub fn new(
301         tcx: TyCtxtAt<'tcx>,
302         param_env: ty::ParamEnv<'tcx>,
303         machine: M,
304         memory_extra: M::MemoryExtra,
305     ) -> Self {
306         InterpCx {
307             machine,
308             tcx,
309             param_env,
310             memory: Memory::new(tcx, memory_extra),
311             vtables: FxHashMap::default(),
312         }
313     }
314
315     #[inline(always)]
316     pub fn set_span(&mut self, span: Span) {
317         self.tcx.span = span;
318         self.memory.tcx.span = span;
319     }
320
321     #[inline(always)]
322     pub fn force_ptr(
323         &self,
324         scalar: Scalar<M::PointerTag>,
325     ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
326         self.memory.force_ptr(scalar)
327     }
328
329     #[inline(always)]
330     pub fn force_bits(
331         &self,
332         scalar: Scalar<M::PointerTag>,
333         size: Size,
334     ) -> InterpResult<'tcx, u128> {
335         self.memory.force_bits(scalar, size)
336     }
337
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!
341     ///
342     /// This represents a *direct* access to that memory, as opposed to access
343     /// through a pointer that was created by the program.
344     #[inline(always)]
345     pub fn tag_global_base_pointer(&self, ptr: Pointer) -> Pointer<M::PointerTag> {
346         self.memory.tag_global_base_pointer(ptr)
347     }
348
349     #[inline(always)]
350     pub(crate) fn stack(&self) -> &[Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>] {
351         M::stack(self)
352     }
353
354     #[inline(always)]
355     pub(crate) fn stack_mut(
356         &mut self,
357     ) -> &mut Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>> {
358         M::stack_mut(self)
359     }
360
361     #[inline(always)]
362     pub fn frame_idx(&self) -> usize {
363         let stack = self.stack();
364         assert!(!stack.is_empty());
365         stack.len() - 1
366     }
367
368     #[inline(always)]
369     pub fn frame(&self) -> &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
370         self.stack().last().expect("no call frames exist")
371     }
372
373     #[inline(always)]
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")
376     }
377
378     #[inline(always)]
379     pub(super) fn body(&self) -> &'mir mir::Body<'tcx> {
380         self.frame().body
381     }
382
383     #[inline(always)]
384     pub fn sign_extend(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
385         assert!(ty.abi.is_signed());
386         sign_extend(value, ty.size)
387     }
388
389     #[inline(always)]
390     pub fn truncate(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
391         truncate(value, ty.size)
392     }
393
394     #[inline]
395     pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
396         ty.is_sized(self.tcx, self.param_env)
397     }
398
399     #[inline]
400     pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
401         ty.is_freeze(*self.tcx, self.param_env, DUMMY_SP)
402     }
403
404     pub fn load_mir(
405         &self,
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))
414             }
415         }
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());
419         }
420         match instance {
421             ty::InstanceDef::Item(def_id) => {
422                 if self.tcx.is_mir_available(did) {
423                     Ok(self.tcx.optimized_mir(did).unwrap_read_only())
424                 } else {
425                     throw_unsup!(NoMirFor(def_id))
426                 }
427             }
428             _ => Ok(self.tcx.instance_mir(instance)),
429         }
430     }
431
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>>(
435         &self,
436         value: T,
437     ) -> T {
438         self.subst_from_frame_and_normalize_erasing_regions(self.frame(), value)
439     }
440
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>>(
444         &self,
445         frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
446         value: T,
447     ) -> T {
448         if let Some(substs) = frame.instance.substs_for_mir_body() {
449             self.tcx.subst_and_normalize_erasing_regions(substs, self.param_env, &value)
450         } else {
451             self.tcx.normalize_erasing_regions(self.param_env, value)
452         }
453     }
454
455     /// The `substs` are assumed to already be in our interpreter "universe" (param_env).
456     pub(super) fn resolve(
457         &self,
458         def_id: DefId,
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())
466     }
467
468     pub fn layout_of_local(
469         &self,
470         frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
471         local: mir::Local,
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()) {
477             None => {
478                 let layout = from_known_layout(self.tcx, layout, || {
479                     let local_ty = frame.body.local_decls[local].ty;
480                     let local_ty =
481                         self.subst_from_frame_and_normalize_erasing_regions(frame, local_ty);
482                     self.layout_of(local_ty)
483                 })?;
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));
487                 }
488                 Ok(layout)
489             }
490             Some(layout) => Ok(layout),
491         }
492     }
493
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(
498         &self,
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)));
504         }
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);
514
515                 let sized_size = layout.fields.offset(layout.fields.count() - 1);
516                 let sized_align = layout.align.abi;
517                 trace!(
518                     "DST {} statically sized prefix size: {:?} align: {:?}",
519                     layout.ty,
520                     sized_size,
521                     sized_align
522                 );
523
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,
530                     None => {
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 {
537                             return Ok(None);
538                         } else {
539                             bug!("Fields cannot be extern types, unless they are at offset 0")
540                         }
541                     }
542                 };
543
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.)
550
551                 // Return the sum of sizes and max of aligns.
552                 let size = sized_size + unsized_size; // `Size` addition
553
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);
557
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);
561
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"));
565                 }
566                 Ok(Some((size, align)))
567             }
568             ty::Dynamic(..) => {
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)?))
572             }
573
574             ty::Slice(_) | ty::Str => {
575                 let len = metadata.unwrap_meta().to_machine_usize(self)?;
576                 let elem = layout.field(self, 0)?;
577
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"))
581                 })?;
582                 Ok(Some((size, elem.align.abi)))
583             }
584
585             ty::Foreign(_) => Ok(None),
586
587             _ => bug!("size_and_align_of::<{:?}> not supported", layout.ty),
588         }
589     }
590     #[inline]
591     pub fn size_and_align_of_mplace(
592         &self,
593         mplace: MPlaceTy<'tcx, M::PointerTag>,
594     ) -> InterpResult<'tcx, Option<(Size, Align)>> {
595         self.size_and_align_of(mplace.meta, mplace.layout)
596     }
597
598     pub fn push_stack_frame(
599         &mut self,
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);
607         }
608         ::log_settings::settings().indentation += 1;
609
610         // first push a stack frame so we have access to the local substs
611         let pre_frame = Frame {
612             body,
613             block: Some(mir::START_BLOCK),
614             return_to_block,
615             return_place,
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(),
619             instance,
620             stmt: 0,
621             extra: (),
622         };
623         let frame = M::init_frame_extra(self, pre_frame)?;
624         self.stack_mut().push(frame);
625
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);
629
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
633             //
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) => {}
638             _ => {
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;
644                     }
645                 }
646             }
647         }
648         // done
649         self.frame_mut().locals = locals;
650
651         M::after_stack_push(self)?;
652         info!("ENTERING({}) {}", self.frame_idx(), self.frame().instance);
653
654         if self.stack().len() > *self.tcx.sess.recursion_limit.get() {
655             throw_exhaust!(StackFrameLimitReached)
656         } else {
657             Ok(())
658         }
659     }
660
661     /// Jump to the given block.
662     #[inline]
663     pub fn go_to_block(&mut self, target: mir::BasicBlock) {
664         let frame = self.frame_mut();
665         frame.block = Some(target);
666         frame.stmt = 0;
667     }
668
669     /// *Return* to the given `target` basic block.
670     /// Do *not* use for unwinding! Use `unwind_to_block` instead.
671     ///
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);
676             Ok(())
677         } else {
678             throw_ub!(Unreachable)
679         }
680     }
681
682     /// *Unwind* to the given `target` basic block.
683     /// Do *not* use for returning! Use `return_to_block` instead.
684     ///
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;
690         frame.stmt = 0;
691     }
692
693     /// Pops the current frame from the stack, deallocating the
694     /// memory for allocated locals.
695     ///
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.
699     ///
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> {
707         info!(
708             "LEAVING({}) {} (unwinding = {})",
709             self.frame_idx(),
710             self.frame().instance,
711             unwinding
712         );
713
714         // Sanity check `unwinding`.
715         assert_eq!(
716             unwinding,
717             match self.frame().block {
718                 None => true,
719                 Some(block) => self.body().basic_blocks()[block].is_cleanup,
720             }
721         );
722
723         ::log_settings::settings().indentation -= 1;
724         let frame =
725             self.stack_mut().pop().expect("tried to pop a stack frame, but there were none");
726
727         if !unwinding {
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);
733             } else {
734                 throw_ub!(Unreachable);
735             }
736         }
737
738         // Now where do we jump next?
739
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 }))
746             }
747             StackPopCleanup::None { cleanup, .. } => (cleanup, None),
748         };
749
750         if !cleanup {
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.
755             return Ok(());
756         }
757
758         // Cleanup: deallocate all locals that are backed by an allocation.
759         for local in &frame.locals {
760             self.deallocate_local(local.value)?;
761         }
762
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.
767             return Ok(());
768         }
769         // Normal return, figure out where to jump.
770         if unwinding {
771             // Follow the unwind edge.
772             let unwind = next_block.expect("Encountered StackPopCleanup::None when unwinding!");
773             self.unwind_to_block(unwind);
774         } else {
775             // Follow the normal return edge.
776             if let Some(ret) = next_block {
777                 self.return_to_block(ret)?;
778             }
779         }
780
781         if !self.stack().is_empty() {
782             info!(
783                 "CONTINUING({}) {} (unwinding = {})",
784                 self.frame_idx(),
785                 self.frame().instance,
786                 unwinding
787             );
788         }
789
790         Ok(())
791     }
792
793     /// Mark a storage as live, killing the previous content and returning it.
794     /// Remember to deallocate that!
795     pub fn storage_live(
796         &mut self,
797         local: mir::Local,
798     ) -> InterpResult<'tcx, LocalValue<M::PointerTag>> {
799         assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
800         trace!("{:?} is now live", local);
801
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))
807     }
808
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);
814
815         mem::replace(&mut self.frame_mut().locals[local].value, LocalValue::Dead)
816     }
817
818     pub(super) fn deallocate_local(
819         &mut self,
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);
830             }
831             self.memory.deallocate_local(ptr)?;
832         };
833         Ok(())
834     }
835
836     pub(super) fn const_eval(
837         &self,
838         gid: GlobalId<'tcx>,
839         ty: Ty<'tcx>,
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
845         // multiple times.
846         let param_env = if self.tcx.is_static(gid.instance.def_id()) {
847             ty::ParamEnv::reveal_all()
848         } else {
849             self.param_env
850         };
851         let val = self.tcx.const_eval_global_id(param_env, gid, Some(self.tcx.span))?;
852
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
856         // `ecx.const_eval`.
857         let const_ = ty::Const { val: ty::ConstKind::Value(val), ty };
858         self.eval_const_to_op(&const_, None)
859     }
860
861     pub fn const_eval_raw(
862         &self,
863         gid: GlobalId<'tcx>,
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
869         // multiple times.
870         let param_env = if self.tcx.is_static(gid.instance.def_id()) {
871             ty::ParamEnv::reveal_all()
872         } else {
873             self.param_env
874         };
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)
881     }
882
883     pub fn dump_place(&self, place: Place<M::PointerTag>) {
884         // Debug output
885         if !log_enabled!(::log::Level::Trace) {
886             return;
887         }
888         match place {
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();
894                 }
895                 write!(msg, ":").unwrap();
896
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) => {
902                             write!(
903                                 msg,
904                                 " by align({}){} ref:",
905                                 mplace.align.bytes(),
906                                 match mplace.meta {
907                                     MemPlaceMeta::Meta(meta) => format!(" meta({:?})", meta),
908                                     MemPlaceMeta::Poison | MemPlaceMeta::None => String::new(),
909                                 }
910                             )
911                             .unwrap();
912                             allocs.push(ptr.alloc_id);
913                         }
914                         ptr => write!(msg, " by integral ref: {:?}", ptr).unwrap(),
915                     },
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);
920                         }
921                     }
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);
926                         }
927                         if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val2 {
928                             allocs.push(ptr.alloc_id);
929                         }
930                     }
931                 }
932
933                 trace!("{}", msg);
934                 self.memory.dump_allocs(allocs);
935             }
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);
940                 }
941                 ptr => trace!(" integral by ref: {:?}", ptr),
942             },
943         }
944     }
945
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,
954                 }
955             });
956             let span = source_info.map_or(DUMMY_SP, |source_info| source_info.span);
957
958             frames.push(FrameInfo { span, instance: frame.instance, lint_root });
959         }
960         trace!("generate stacktrace: {:#?}", frames);
961         frames
962     }
963 }
964
965 impl<'ctx, 'mir, 'tcx, Tag, Extra> HashStable<StableHashingContext<'ctx>>
966     for Frame<'mir, 'tcx, Tag, Extra>
967 where
968     Extra: HashStable<StableHashingContext<'ctx>>,
969     Tag: HashStable<StableHashingContext<'ctx>>,
970 {
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);
980     }
981 }