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