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