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