]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/eval_context.rs
Rollup merge of #66918 - makotokato:aarch32-crc-crypto, r=petrochenkov
[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 syntax::source_map::{self, Span, DUMMY_SP};
6 use rustc::ich::StableHashingContext;
7 use rustc::hir::def_id::DefId;
8 use rustc::hir::def::DefKind;
9 use rustc::mir;
10 use rustc::ty::layout::{
11     self, Size, Align, HasDataLayout, LayoutOf, TyLayout
12 };
13 use rustc::ty::subst::SubstsRef;
14 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
15 use rustc::ty::query::TyCtxtAt;
16 use rustc_index::vec::IndexVec;
17 use rustc::mir::interpret::{
18     GlobalId, Scalar, Pointer, FrameInfo, AllocId,
19     InterpResult, truncate, sign_extend,
20 };
21 use rustc_data_structures::fx::FxHashMap;
22 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
23 use rustc_macros::HashStable;
24
25 use super::{
26     Immediate, Operand, MemPlace, MPlaceTy, Place, PlaceTy, ScalarMaybeUndef,
27     Memory, Machine, StackPopInfo
28 };
29
30 pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
31     /// Stores the `Machine` instance.
32     pub machine: M,
33
34     /// The results of the type checker, from rustc.
35     pub tcx: TyCtxtAt<'tcx>,
36
37     /// Bounds in scope for polymorphic evaluations.
38     pub(crate) param_env: ty::ParamEnv<'tcx>,
39
40     /// The virtual memory system.
41     pub memory: Memory<'mir, 'tcx, M>,
42
43     /// The virtual call stack.
44     pub(crate) stack: Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>>,
45
46     /// A cache for deduplicating vtables
47     pub(super) vtables:
48         FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), Pointer<M::PointerTag>>,
49 }
50
51 /// A stack frame.
52 #[derive(Clone)]
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>,
59
60     /// The def_id and substs of the current function.
61     pub instance: ty::Instance<'tcx>,
62
63     /// The span of the call site.
64     pub span: source_map::Span,
65
66     /// Extra data for the machine.
67     pub extra: Extra,
68
69     ////////////////////////////////////////////////////////////////////////////////
70     // Return place and locals
71     ////////////////////////////////////////////////////////////////////////////////
72     /// Work to perform when returning from this function.
73     pub return_to_block: StackPopCleanup,
74
75     /// The location where the result of the current stack frame should be written to,
76     /// and its layout in the caller.
77     pub return_place: Option<PlaceTy<'tcx, Tag>>,
78
79     /// The list of locals for this stack frame, stored in order as
80     /// `[return_ptr, arguments..., variables..., temporaries...]`.
81     /// The locals are stored as `Option<Value>`s.
82     /// `None` represents a local that is currently dead, while a live local
83     /// can either directly contain `Scalar` or refer to some part of an `Allocation`.
84     pub locals: IndexVec<mir::Local, LocalState<'tcx, Tag>>,
85
86     ////////////////////////////////////////////////////////////////////////////////
87     // Current position within the function
88     ////////////////////////////////////////////////////////////////////////////////
89     /// The block that is currently executed (or will be executed after the above call stacks
90     /// return).
91     /// If this is `None`, we are unwinding and this function doesn't need any clean-up.
92     /// Just continue the same as with `Resume`.
93     pub block: Option<mir::BasicBlock>,
94
95     /// The index of the currently evaluated statement.
96     pub stmt: usize,
97 }
98
99 #[derive(Clone, Eq, PartialEq, Debug, HashStable)] // Miri debug-prints these
100 pub enum StackPopCleanup {
101     /// Jump to the next block in the caller, or cause UB if None (that's a function
102     /// that may never return). Also store layout of return place so
103     /// we can validate it at that layout.
104     /// `ret` stores the block we jump to on a normal return, while 'unwind'
105     /// stores the block used for cleanup during unwinding
106     Goto { ret: Option<mir::BasicBlock>, unwind: Option<mir::BasicBlock> },
107     /// Just do nohing: Used by Main and for the box_alloc hook in miri.
108     /// `cleanup` says whether locals are deallocated. Static computation
109     /// wants them leaked to intern what they need (and just throw away
110     /// the entire `ecx` when it is done).
111     None { cleanup: bool },
112 }
113
114 /// State of a local variable including a memoized layout
115 #[derive(Clone, PartialEq, Eq, HashStable)]
116 pub struct LocalState<'tcx, Tag=(), Id=AllocId> {
117     pub value: LocalValue<Tag, Id>,
118     /// Don't modify if `Some`, this is only used to prevent computing the layout twice
119     #[stable_hasher(ignore)]
120     pub layout: Cell<Option<TyLayout<'tcx>>>,
121 }
122
123 /// Current value of a local variable
124 #[derive(Clone, PartialEq, Eq, Debug, HashStable)] // Miri debug-prints these
125 pub enum LocalValue<Tag=(), Id=AllocId> {
126     /// This local is not currently alive, and cannot be used at all.
127     Dead,
128     /// This local is alive but not yet initialized. It can be written to
129     /// but not read from or its address taken. Locals get initialized on
130     /// first write because for unsized locals, we do not know their size
131     /// before that.
132     Uninitialized,
133     /// A normal, live local.
134     /// Mostly for convenience, we re-use the `Operand` type here.
135     /// This is an optimization over just always having a pointer here;
136     /// we can thus avoid doing an allocation when the local just stores
137     /// immediate values *and* never has its address taken.
138     Live(Operand<Tag, Id>),
139 }
140
141 impl<'tcx, Tag: Copy + 'static> LocalState<'tcx, Tag> {
142     pub fn access(&self) -> InterpResult<'tcx, Operand<Tag>> {
143         match self.value {
144             LocalValue::Dead => throw_unsup!(DeadLocal),
145             LocalValue::Uninitialized =>
146                 bug!("The type checker should prevent reading from a never-written local"),
147             LocalValue::Live(val) => Ok(val),
148         }
149     }
150
151     /// Overwrite the local.  If the local can be overwritten in place, return a reference
152     /// to do so; otherwise return the `MemPlace` to consult instead.
153     pub fn access_mut(
154         &mut self,
155     ) -> InterpResult<'tcx, Result<&mut LocalValue<Tag>, MemPlace<Tag>>> {
156         match self.value {
157             LocalValue::Dead => throw_unsup!(DeadLocal),
158             LocalValue::Live(Operand::Indirect(mplace)) => Ok(Err(mplace)),
159             ref mut local @ LocalValue::Live(Operand::Immediate(_)) |
160             ref mut local @ LocalValue::Uninitialized => {
161                 Ok(Ok(local))
162             }
163         }
164     }
165 }
166
167 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for InterpCx<'mir, 'tcx, M> {
168     #[inline]
169     fn data_layout(&self) -> &layout::TargetDataLayout {
170         &self.tcx.data_layout
171     }
172 }
173
174 impl<'mir, 'tcx, M> layout::HasTyCtxt<'tcx> for InterpCx<'mir, 'tcx, M>
175 where
176     M: Machine<'mir, 'tcx>,
177 {
178     #[inline]
179     fn tcx(&self) -> TyCtxt<'tcx> {
180         *self.tcx
181     }
182 }
183
184 impl<'mir, 'tcx, M> layout::HasParamEnv<'tcx> for InterpCx<'mir, 'tcx, M>
185 where
186     M: Machine<'mir, 'tcx>,
187 {
188     fn param_env(&self) -> ty::ParamEnv<'tcx> {
189         self.param_env
190     }
191 }
192
193 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> LayoutOf for InterpCx<'mir, 'tcx, M> {
194     type Ty = Ty<'tcx>;
195     type TyLayout = InterpResult<'tcx, TyLayout<'tcx>>;
196
197     #[inline]
198     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
199         self.tcx
200             .layout_of(self.param_env.and(ty))
201             .map_err(|layout| err_inval!(Layout(layout)).into())
202     }
203 }
204
205 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
206     pub fn new(
207         tcx: TyCtxtAt<'tcx>,
208         param_env: ty::ParamEnv<'tcx>,
209         machine: M,
210         memory_extra: M::MemoryExtra,
211     ) -> Self {
212         InterpCx {
213             machine,
214             tcx,
215             param_env,
216             memory: Memory::new(tcx, memory_extra),
217             stack: Vec::new(),
218             vtables: FxHashMap::default(),
219         }
220     }
221
222     #[inline(always)]
223     pub fn force_ptr(
224         &self,
225         scalar: Scalar<M::PointerTag>,
226     ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
227         self.memory.force_ptr(scalar)
228     }
229
230     #[inline(always)]
231     pub fn force_bits(
232         &self,
233         scalar: Scalar<M::PointerTag>,
234         size: Size
235     ) -> InterpResult<'tcx, u128> {
236         self.memory.force_bits(scalar, size)
237     }
238
239     #[inline(always)]
240     pub fn tag_static_base_pointer(&self, ptr: Pointer) -> Pointer<M::PointerTag> {
241         self.memory.tag_static_base_pointer(ptr)
242     }
243
244     #[inline(always)]
245     pub fn stack(&self) -> &[Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>] {
246         &self.stack
247     }
248
249     #[inline(always)]
250     pub fn cur_frame(&self) -> usize {
251         assert!(self.stack.len() > 0);
252         self.stack.len() - 1
253     }
254
255     #[inline(always)]
256     pub fn frame(&self) -> &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
257         self.stack.last().expect("no call frames exist")
258     }
259
260     #[inline(always)]
261     pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
262         self.stack.last_mut().expect("no call frames exist")
263     }
264
265     #[inline(always)]
266     pub(super) fn body(&self) -> &'mir mir::Body<'tcx> {
267         self.frame().body
268     }
269
270     #[inline(always)]
271     pub fn sign_extend(&self, value: u128, ty: TyLayout<'_>) -> u128 {
272         assert!(ty.abi.is_signed());
273         sign_extend(value, ty.size)
274     }
275
276     #[inline(always)]
277     pub fn truncate(&self, value: u128, ty: TyLayout<'_>) -> u128 {
278         truncate(value, ty.size)
279     }
280
281     #[inline]
282     pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
283         ty.is_sized(self.tcx, self.param_env)
284     }
285
286     #[inline]
287     pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
288         ty.is_freeze(*self.tcx, self.param_env, DUMMY_SP)
289     }
290
291     pub fn load_mir(
292         &self,
293         instance: ty::InstanceDef<'tcx>,
294         promoted: Option<mir::Promoted>,
295     ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
296         // do not continue if typeck errors occurred (can only occur in local crate)
297         let did = instance.def_id();
298         if did.is_local()
299             && self.tcx.has_typeck_tables(did)
300             && self.tcx.typeck_tables_of(did).tainted_by_errors
301         {
302             throw_inval!(TypeckError)
303         }
304         trace!("load mir(instance={:?}, promoted={:?})", instance, promoted);
305         if let Some(promoted) = promoted {
306             return Ok(&self.tcx.promoted_mir(did)[promoted]);
307         }
308         match instance {
309             ty::InstanceDef::Item(def_id) => if self.tcx.is_mir_available(did) {
310                 Ok(self.tcx.optimized_mir(did))
311             } else {
312                 throw_unsup!(NoMirFor(self.tcx.def_path_str(def_id)))
313             },
314             _ => Ok(self.tcx.instance_mir(instance)),
315         }
316     }
317
318     /// Call this on things you got out of the MIR (so it is as generic as the current
319     /// stack frame), to bring it into the proper environment for this interpreter.
320     pub(super) fn subst_from_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
321         &self,
322         value: T,
323     ) -> T {
324         self.tcx.subst_and_normalize_erasing_regions(
325             self.frame().instance.substs,
326             self.param_env,
327             &value,
328         )
329     }
330
331     /// The `substs` are assumed to already be in our interpreter "universe" (param_env).
332     pub(super) fn resolve(
333         &self,
334         def_id: DefId,
335         substs: SubstsRef<'tcx>
336     ) -> InterpResult<'tcx, ty::Instance<'tcx>> {
337         trace!("resolve: {:?}, {:#?}", def_id, substs);
338         trace!("param_env: {:#?}", self.param_env);
339         trace!("substs: {:#?}", substs);
340         ty::Instance::resolve(
341             *self.tcx,
342             self.param_env,
343             def_id,
344             substs,
345         ).ok_or_else(|| err_inval!(TooGeneric).into())
346     }
347
348     pub fn layout_of_local(
349         &self,
350         frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
351         local: mir::Local,
352         layout: Option<TyLayout<'tcx>>,
353     ) -> InterpResult<'tcx, TyLayout<'tcx>> {
354         // `const_prop` runs into this with an invalid (empty) frame, so we
355         // have to support that case (mostly by skipping all caching).
356         match frame.locals.get(local).and_then(|state| state.layout.get()) {
357             None => {
358                 let layout = crate::interpret::operand::from_known_layout(layout, || {
359                     let local_ty = frame.body.local_decls[local].ty;
360                     let local_ty = self.tcx.subst_and_normalize_erasing_regions(
361                         frame.instance.substs,
362                         self.param_env,
363                         &local_ty,
364                     );
365                     self.layout_of(local_ty)
366                 })?;
367                 if let Some(state) = frame.locals.get(local) {
368                     // Layouts of locals are requested a lot, so we cache them.
369                     state.layout.set(Some(layout));
370                 }
371                 Ok(layout)
372             }
373             Some(layout) => Ok(layout),
374         }
375     }
376
377     /// Returns the actual dynamic size and alignment of the place at the given type.
378     /// Only the "meta" (metadata) part of the place matters.
379     /// This can fail to provide an answer for extern types.
380     pub(super) fn size_and_align_of(
381         &self,
382         metadata: Option<Scalar<M::PointerTag>>,
383         layout: TyLayout<'tcx>,
384     ) -> InterpResult<'tcx, Option<(Size, Align)>> {
385         if !layout.is_unsized() {
386             return Ok(Some((layout.size, layout.align.abi)));
387         }
388         match layout.ty.kind {
389             ty::Adt(..) | ty::Tuple(..) => {
390                 // First get the size of all statically known fields.
391                 // Don't use type_of::sizing_type_of because that expects t to be sized,
392                 // and it also rounds up to alignment, which we want to avoid,
393                 // as the unsized field's alignment could be smaller.
394                 assert!(!layout.ty.is_simd());
395                 trace!("DST layout: {:?}", layout);
396
397                 let sized_size = layout.fields.offset(layout.fields.count() - 1);
398                 let sized_align = layout.align.abi;
399                 trace!(
400                     "DST {} statically sized prefix size: {:?} align: {:?}",
401                     layout.ty,
402                     sized_size,
403                     sized_align
404                 );
405
406                 // Recurse to get the size of the dynamically sized field (must be
407                 // the last field).  Can't have foreign types here, how would we
408                 // adjust alignment and size for them?
409                 let field = layout.field(self, layout.fields.count() - 1)?;
410                 let (unsized_size, unsized_align) = match self.size_and_align_of(metadata, field)? {
411                     Some(size_and_align) => size_and_align,
412                     None => {
413                         // A field with extern type.  If this field is at offset 0, we behave
414                         // like the underlying extern type.
415                         // FIXME: Once we have made decisions for how to handle size and alignment
416                         // of `extern type`, this should be adapted.  It is just a temporary hack
417                         // to get some code to work that probably ought to work.
418                         if sized_size == Size::ZERO {
419                             return Ok(None)
420                         } else {
421                             bug!("Fields cannot be extern types, unless they are at offset 0")
422                         }
423                     }
424                 };
425
426                 // FIXME (#26403, #27023): We should be adding padding
427                 // to `sized_size` (to accommodate the `unsized_align`
428                 // required of the unsized field that follows) before
429                 // summing it with `sized_size`. (Note that since #26403
430                 // is unfixed, we do not yet add the necessary padding
431                 // here. But this is where the add would go.)
432
433                 // Return the sum of sizes and max of aligns.
434                 let size = sized_size + unsized_size;
435
436                 // Choose max of two known alignments (combined value must
437                 // be aligned according to more restrictive of the two).
438                 let align = sized_align.max(unsized_align);
439
440                 // Issue #27023: must add any necessary padding to `size`
441                 // (to make it a multiple of `align`) before returning it.
442                 let size = size.align_to(align);
443
444                 // Check if this brought us over the size limit.
445                 if size.bytes() >= self.tcx.data_layout().obj_size_bound() {
446                     throw_ub_format!("wide pointer metadata contains invalid information: \
447                         total size is bigger than largest supported object");
448                 }
449                 Ok(Some((size, align)))
450             }
451             ty::Dynamic(..) => {
452                 let vtable = metadata.expect("dyn trait fat ptr must have vtable");
453                 // Read size and align from vtable (already checks size).
454                 Ok(Some(self.read_size_and_align_from_vtable(vtable)?))
455             }
456
457             ty::Slice(_) | ty::Str => {
458                 let len = metadata.expect("slice fat ptr must have length").to_machine_usize(self)?;
459                 let elem = layout.field(self, 0)?;
460
461                 // Make sure the slice is not too big.
462                 let size = elem.size.checked_mul(len, &*self.tcx)
463                     .ok_or_else(|| err_ub_format!("invalid slice: \
464                         total size is bigger than largest supported object"))?;
465                 Ok(Some((size, elem.align.abi)))
466             }
467
468             ty::Foreign(_) => {
469                 Ok(None)
470             }
471
472             _ => bug!("size_and_align_of::<{:?}> not supported", layout.ty),
473         }
474     }
475     #[inline]
476     pub fn size_and_align_of_mplace(
477         &self,
478         mplace: MPlaceTy<'tcx, M::PointerTag>
479     ) -> InterpResult<'tcx, Option<(Size, Align)>> {
480         self.size_and_align_of(mplace.meta, mplace.layout)
481     }
482
483     pub fn push_stack_frame(
484         &mut self,
485         instance: ty::Instance<'tcx>,
486         span: Span,
487         body: &'mir mir::Body<'tcx>,
488         return_place: Option<PlaceTy<'tcx, M::PointerTag>>,
489         return_to_block: StackPopCleanup,
490     ) -> InterpResult<'tcx> {
491         if self.stack.len() > 0 {
492             info!("PAUSING({}) {}", self.cur_frame(), self.frame().instance);
493         }
494         ::log_settings::settings().indentation += 1;
495
496         // first push a stack frame so we have access to the local substs
497         let extra = M::stack_push(self)?;
498         self.stack.push(Frame {
499             body,
500             block: Some(mir::START_BLOCK),
501             return_to_block,
502             return_place,
503             // empty local array, we fill it in below, after we are inside the stack frame and
504             // all methods actually know about the frame
505             locals: IndexVec::new(),
506             span,
507             instance,
508             stmt: 0,
509             extra,
510         });
511
512         // don't allocate at all for trivial constants
513         if body.local_decls.len() > 1 {
514             // Locals are initially uninitialized.
515             let dummy = LocalState {
516                 value: LocalValue::Uninitialized,
517                 layout: Cell::new(None),
518             };
519             let mut locals = IndexVec::from_elem(dummy, &body.local_decls);
520             // Return place is handled specially by the `eval_place` functions, and the
521             // entry in `locals` should never be used. Make it dead, to be sure.
522             locals[mir::RETURN_PLACE].value = LocalValue::Dead;
523             // Now mark those locals as dead that we do not want to initialize
524             match self.tcx.def_kind(instance.def_id()) {
525                 // statics and constants don't have `Storage*` statements, no need to look for them
526                 Some(DefKind::Static)
527                 | Some(DefKind::Const)
528                 | Some(DefKind::AssocConst) => {},
529                 _ => {
530                     trace!("push_stack_frame: {:?}: num_bbs: {}", span, body.basic_blocks().len());
531                     for block in body.basic_blocks() {
532                         for stmt in block.statements.iter() {
533                             use rustc::mir::StatementKind::{StorageDead, StorageLive};
534                             match stmt.kind {
535                                 StorageLive(local) |
536                                 StorageDead(local) => {
537                                     locals[local].value = LocalValue::Dead;
538                                 }
539                                 _ => {}
540                             }
541                         }
542                     }
543                 },
544             }
545             // done
546             self.frame_mut().locals = locals;
547         }
548
549         info!("ENTERING({}) {}", self.cur_frame(), self.frame().instance);
550
551         if self.stack.len() > *self.tcx.sess.recursion_limit.get() {
552             throw_exhaust!(StackFrameLimitReached)
553         } else {
554             Ok(())
555         }
556     }
557
558     /// Jump to the given block.
559     #[inline]
560     pub fn go_to_block(&mut self, target: mir::BasicBlock) {
561         let frame = self.frame_mut();
562         frame.block = Some(target);
563         frame.stmt = 0;
564     }
565
566     /// *Return* to the given `target` basic block.
567     /// Do *not* use for unwinding! Use `unwind_to_block` instead.
568     ///
569     /// If `target` is `None`, that indicates the function cannot return, so we raise UB.
570     pub fn return_to_block(&mut self, target: Option<mir::BasicBlock>) -> InterpResult<'tcx> {
571         if let Some(target) = target {
572             Ok(self.go_to_block(target))
573         } else {
574             throw_ub!(Unreachable)
575         }
576     }
577
578     /// *Unwind* to the given `target` basic block.
579     /// Do *not* use for returning! Use `return_to_block` instead.
580     ///
581     /// If `target` is `None`, that indicates the function does not need cleanup during
582     /// unwinding, and we will just keep propagating that upwards.
583     pub fn unwind_to_block(&mut self, target: Option<mir::BasicBlock>) {
584         let frame = self.frame_mut();
585         frame.block = target;
586         frame.stmt = 0;
587     }
588
589     /// Pops the current frame from the stack, deallocating the
590     /// memory for allocated locals.
591     ///
592     /// If `unwinding` is `false`, then we are performing a normal return
593     /// from a function. In this case, we jump back into the frame of the caller,
594     /// and continue execution as normal.
595     ///
596     /// If `unwinding` is `true`, then we are in the middle of a panic,
597     /// and need to unwind this frame. In this case, we jump to the
598     /// `cleanup` block for the function, which is responsible for running
599     /// `Drop` impls for any locals that have been initialized at this point.
600     /// The cleanup block ends with a special `Resume` terminator, which will
601     /// cause us to continue unwinding.
602     pub(super) fn pop_stack_frame(
603         &mut self,
604         unwinding: bool
605     ) -> InterpResult<'tcx> {
606         info!("LEAVING({}) {} (unwinding = {})",
607             self.cur_frame(), self.frame().instance, unwinding);
608
609         // Sanity check `unwinding`.
610         assert_eq!(
611             unwinding,
612             match self.frame().block {
613                 None => true,
614                 Some(block) => self.body().basic_blocks()[block].is_cleanup
615             }
616         );
617
618         ::log_settings::settings().indentation -= 1;
619         let frame = self.stack.pop().expect(
620             "tried to pop a stack frame, but there were none",
621         );
622         let stack_pop_info = M::stack_pop(self, frame.extra, unwinding)?;
623         if let (false, StackPopInfo::StopUnwinding) = (unwinding, stack_pop_info) {
624             bug!("Attempted to stop unwinding while there is no unwinding!");
625         }
626
627         // Now where do we jump next?
628
629         // Determine if we leave this function normally or via unwinding.
630         let cur_unwinding = if let StackPopInfo::StopUnwinding = stack_pop_info {
631             false
632         } else {
633             unwinding
634         };
635
636         // Usually we want to clean up (deallocate locals), but in a few rare cases we don't.
637         // In that case, we return early. We also avoid validation in that case,
638         // because this is CTFE and the final value will be thoroughly validated anyway.
639         let (cleanup, next_block) = match frame.return_to_block {
640             StackPopCleanup::Goto { ret, unwind } => {
641                 (true, Some(if cur_unwinding { unwind } else { ret }))
642             },
643             StackPopCleanup::None { cleanup, .. } => (cleanup, None)
644         };
645
646         if !cleanup {
647             assert!(self.stack.is_empty(), "only the topmost frame should ever be leaked");
648             assert!(next_block.is_none(), "tried to skip cleanup when we have a next block!");
649             // Leak the locals, skip validation.
650             return Ok(());
651         }
652
653         // Cleanup: deallocate all locals that are backed by an allocation.
654         for local in frame.locals {
655             self.deallocate_local(local.value)?;
656         }
657
658
659         trace!("StackPopCleanup: {:?} StackPopInfo: {:?} cur_unwinding = {:?}",
660                frame.return_to_block, stack_pop_info, cur_unwinding);
661         if cur_unwinding {
662             // Follow the unwind edge.
663             let unwind = next_block.expect("Encounted StackPopCleanup::None when unwinding!");
664             self.unwind_to_block(unwind);
665         } else {
666             // Follow the normal return edge.
667             // Validate the return value. Do this after deallocating so that we catch dangling
668             // references.
669             if let Some(return_place) = frame.return_place {
670                 if M::enforce_validity(self) {
671                     // Data got changed, better make sure it matches the type!
672                     // It is still possible that the return place held invalid data while
673                     // the function is running, but that's okay because nobody could have
674                     // accessed that same data from the "outside" to observe any broken
675                     // invariant -- that is, unless a function somehow has a ptr to
676                     // its return place... but the way MIR is currently generated, the
677                     // return place is always a local and then this cannot happen.
678                     self.validate_operand(
679                         self.place_to_op(return_place)?,
680                         vec![],
681                         None,
682                     )?;
683                 }
684             } else {
685                 // Uh, that shouldn't happen... the function did not intend to return
686                 throw_ub!(Unreachable);
687             }
688
689             // Jump to new block -- *after* validation so that the spans make more sense.
690             if let Some(ret) = next_block {
691                 self.return_to_block(ret)?;
692             }
693         }
694
695         if self.stack.len() > 0 {
696             info!("CONTINUING({}) {} (unwinding = {})",
697                 self.cur_frame(), self.frame().instance, cur_unwinding);
698         }
699
700         Ok(())
701     }
702
703     /// Mark a storage as live, killing the previous content and returning it.
704     /// Remember to deallocate that!
705     pub fn storage_live(
706         &mut self,
707         local: mir::Local
708     ) -> InterpResult<'tcx, LocalValue<M::PointerTag>> {
709         assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
710         trace!("{:?} is now live", local);
711
712         let local_val = LocalValue::Uninitialized;
713         // StorageLive *always* kills the value that's currently stored.
714         // However, we do not error if the variable already is live;
715         // see <https://github.com/rust-lang/rust/issues/42371>.
716         Ok(mem::replace(&mut self.frame_mut().locals[local].value, local_val))
717     }
718
719     /// Returns the old value of the local.
720     /// Remember to deallocate that!
721     pub fn storage_dead(&mut self, local: mir::Local) -> LocalValue<M::PointerTag> {
722         assert!(local != mir::RETURN_PLACE, "Cannot make return place dead");
723         trace!("{:?} is now dead", local);
724
725         mem::replace(&mut self.frame_mut().locals[local].value, LocalValue::Dead)
726     }
727
728     pub(super) fn deallocate_local(
729         &mut self,
730         local: LocalValue<M::PointerTag>,
731     ) -> InterpResult<'tcx> {
732         // FIXME: should we tell the user that there was a local which was never written to?
733         if let LocalValue::Live(Operand::Indirect(MemPlace { ptr, .. })) = local {
734             trace!("deallocating local");
735             let ptr = ptr.to_ptr()?;
736             if log_enabled!(::log::Level::Trace) {
737                 self.memory.dump_alloc(ptr.alloc_id);
738             }
739             self.memory.deallocate_local(ptr)?;
740         };
741         Ok(())
742     }
743
744     pub fn const_eval_raw(
745         &self,
746         gid: GlobalId<'tcx>,
747     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
748         // FIXME(oli-obk): make this check an assertion that it's not a static here
749         // FIXME(RalfJ, oli-obk): document that `Place::Static` can never be anything but a static
750         // and `ConstValue::Unevaluated` can never be a static
751         let param_env = if self.tcx.is_static(gid.instance.def_id()) {
752             ty::ParamEnv::reveal_all()
753         } else {
754             self.param_env
755         };
756         // We use `const_eval_raw` here, and get an unvalidated result.  That is okay:
757         // Our result will later be validated anyway, and there seems no good reason
758         // to have to fail early here.  This is also more consistent with
759         // `Memory::get_static_alloc` which has to use `const_eval_raw` to avoid cycles.
760         let val = self.tcx.const_eval_raw(param_env.and(gid))?;
761         self.raw_const_to_mplace(val)
762     }
763
764     pub fn dump_place(&self, place: Place<M::PointerTag>) {
765         // Debug output
766         if !log_enabled!(::log::Level::Trace) {
767             return;
768         }
769         match place {
770             Place::Local { frame, local } => {
771                 let mut allocs = Vec::new();
772                 let mut msg = format!("{:?}", local);
773                 if frame != self.cur_frame() {
774                     write!(msg, " ({} frames up)", self.cur_frame() - frame).unwrap();
775                 }
776                 write!(msg, ":").unwrap();
777
778                 match self.stack[frame].locals[local].value {
779                     LocalValue::Dead => write!(msg, " is dead").unwrap(),
780                     LocalValue::Uninitialized => write!(msg, " is uninitialized").unwrap(),
781                     LocalValue::Live(Operand::Indirect(mplace)) => {
782                         match mplace.ptr {
783                             Scalar::Ptr(ptr) => {
784                                 write!(msg, " by align({}){} ref:",
785                                     mplace.align.bytes(),
786                                     match mplace.meta {
787                                         Some(meta) => format!(" meta({:?})", meta),
788                                         None => String::new()
789                                     }
790                                 ).unwrap();
791                                 allocs.push(ptr.alloc_id);
792                             }
793                             ptr => write!(msg, " by integral ref: {:?}", ptr).unwrap(),
794                         }
795                     }
796                     LocalValue::Live(Operand::Immediate(Immediate::Scalar(val))) => {
797                         write!(msg, " {:?}", val).unwrap();
798                         if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val {
799                             allocs.push(ptr.alloc_id);
800                         }
801                     }
802                     LocalValue::Live(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
803                         write!(msg, " ({:?}, {:?})", val1, val2).unwrap();
804                         if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val1 {
805                             allocs.push(ptr.alloc_id);
806                         }
807                         if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val2 {
808                             allocs.push(ptr.alloc_id);
809                         }
810                     }
811                 }
812
813                 trace!("{}", msg);
814                 self.memory.dump_allocs(allocs);
815             }
816             Place::Ptr(mplace) => {
817                 match mplace.ptr {
818                     Scalar::Ptr(ptr) => {
819                         trace!("by align({}) ref:", mplace.align.bytes());
820                         self.memory.dump_alloc(ptr.alloc_id);
821                     }
822                     ptr => trace!(" integral by ref: {:?}", ptr),
823                 }
824             }
825         }
826     }
827
828     pub fn generate_stacktrace(&self, explicit_span: Option<Span>) -> Vec<FrameInfo<'tcx>> {
829         let mut last_span = None;
830         let mut frames = Vec::new();
831         for &Frame { instance, span, body, block, stmt, .. } in self.stack().iter().rev() {
832             // make sure we don't emit frames that are duplicates of the previous
833             if explicit_span == Some(span) {
834                 last_span = Some(span);
835                 continue;
836             }
837             if let Some(last) = last_span {
838                 if last == span {
839                     continue;
840                 }
841             } else {
842                 last_span = Some(span);
843             }
844
845             let lint_root = block.and_then(|block| {
846                 let block = &body.basic_blocks()[block];
847                 let source_info = if stmt < block.statements.len() {
848                     block.statements[stmt].source_info
849                 } else {
850                     block.terminator().source_info
851                 };
852                 match &body.source_scopes[source_info.scope].local_data {
853                     mir::ClearCrossCrate::Set(data) => Some(data.lint_root),
854                     mir::ClearCrossCrate::Clear => None,
855                 }
856             });
857
858             frames.push(FrameInfo { call_site: span, instance, lint_root });
859         }
860         trace!("generate stacktrace: {:#?}, {:?}", frames, explicit_span);
861         frames
862     }
863 }
864
865 impl<'ctx, 'mir, 'tcx, Tag, Extra> HashStable<StableHashingContext<'ctx>>
866 for Frame<'mir, 'tcx, Tag, Extra>
867     where Extra: HashStable<StableHashingContext<'ctx>>,
868           Tag:   HashStable<StableHashingContext<'ctx>>
869 {
870     fn hash_stable(&self, hcx: &mut StableHashingContext<'ctx>, hasher: &mut StableHasher) {
871         self.body.hash_stable(hcx, hasher);
872         self.instance.hash_stable(hcx, hasher);
873         self.span.hash_stable(hcx, hasher);
874         self.return_to_block.hash_stable(hcx, hasher);
875         self.return_place.as_ref().map(|r| &**r).hash_stable(hcx, hasher);
876         self.locals.hash_stable(hcx, hasher);
877         self.block.hash_stable(hcx, hasher);
878         self.stmt.hash_stable(hcx, hasher);
879         self.extra.hash_stable(hcx, hasher);
880     }
881 }