]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/place.rs
Move def_id out add substsref
[rust.git] / src / librustc_mir / interpret / place.rs
1 //! Computations on places -- field projections, going from mir::Place, and writing
2 //! into a place.
3 //! All high-level functions to write to memory work on places as destinations.
4
5 use std::convert::TryFrom;
6 use std::hash::Hash;
7
8 use rustc::mir;
9 use rustc::mir::interpret::truncate;
10 use rustc::ty::{self, Ty};
11 use rustc::ty::layout::{self, Size, Align, LayoutOf, TyLayout, HasDataLayout, VariantIdx};
12 use rustc::ty::TypeFoldable;
13
14 use super::{
15     GlobalId, AllocId, Allocation, Scalar, InterpResult, Pointer, PointerArithmetic,
16     InterpCx, Machine, AllocMap, AllocationExtra,
17     RawConst, Immediate, ImmTy, ScalarMaybeUndef, Operand, OpTy, MemoryKind, LocalValue,
18 };
19
20 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
21 pub struct MemPlace<Tag=(), Id=AllocId> {
22     /// A place may have an integral pointer for ZSTs, and since it might
23     /// be turned back into a reference before ever being dereferenced.
24     /// However, it may never be undef.
25     pub ptr: Scalar<Tag, Id>,
26     pub align: Align,
27     /// Metadata for unsized places. Interpretation is up to the type.
28     /// Must not be present for sized types, but can be missing for unsized types
29     /// (e.g., `extern type`).
30     pub meta: Option<Scalar<Tag, Id>>,
31 }
32
33 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
34 pub enum Place<Tag=(), Id=AllocId> {
35     /// A place referring to a value allocated in the `Memory` system.
36     Ptr(MemPlace<Tag, Id>),
37
38     /// To support alloc-free locals, we are able to write directly to a local.
39     /// (Without that optimization, we'd just always be a `MemPlace`.)
40     Local {
41         frame: usize,
42         local: mir::Local,
43     },
44 }
45
46 #[derive(Copy, Clone, Debug)]
47 pub struct PlaceTy<'tcx, Tag=()> {
48     place: Place<Tag>, // Keep this private, it helps enforce invariants
49     pub layout: TyLayout<'tcx>,
50 }
51
52 impl<'tcx, Tag> ::std::ops::Deref for PlaceTy<'tcx, Tag> {
53     type Target = Place<Tag>;
54     #[inline(always)]
55     fn deref(&self) -> &Place<Tag> {
56         &self.place
57     }
58 }
59
60 /// A MemPlace with its layout. Constructing it is only possible in this module.
61 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
62 pub struct MPlaceTy<'tcx, Tag=()> {
63     mplace: MemPlace<Tag>,
64     pub layout: TyLayout<'tcx>,
65 }
66
67 impl<'tcx, Tag> ::std::ops::Deref for MPlaceTy<'tcx, Tag> {
68     type Target = MemPlace<Tag>;
69     #[inline(always)]
70     fn deref(&self) -> &MemPlace<Tag> {
71         &self.mplace
72     }
73 }
74
75 impl<'tcx, Tag> From<MPlaceTy<'tcx, Tag>> for PlaceTy<'tcx, Tag> {
76     #[inline(always)]
77     fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
78         PlaceTy {
79             place: Place::Ptr(mplace.mplace),
80             layout: mplace.layout
81         }
82     }
83 }
84
85 impl<Tag> MemPlace<Tag> {
86     /// Replace ptr tag, maintain vtable tag (if any)
87     #[inline]
88     pub fn replace_tag(self, new_tag: Tag) -> Self {
89         MemPlace {
90             ptr: self.ptr.erase_tag().with_tag(new_tag),
91             align: self.align,
92             meta: self.meta,
93         }
94     }
95
96     #[inline]
97     pub fn erase_tag(self) -> MemPlace {
98         MemPlace {
99             ptr: self.ptr.erase_tag(),
100             align: self.align,
101             meta: self.meta.map(Scalar::erase_tag),
102         }
103     }
104
105     #[inline(always)]
106     pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
107         MemPlace {
108             ptr,
109             align,
110             meta: None,
111         }
112     }
113
114     /// Produces a Place that will error if attempted to be read from or written to
115     #[inline(always)]
116     pub fn null(cx: &impl HasDataLayout) -> Self {
117         Self::from_scalar_ptr(Scalar::ptr_null(cx), Align::from_bytes(1).unwrap())
118     }
119
120     #[inline(always)]
121     pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
122         Self::from_scalar_ptr(ptr.into(), align)
123     }
124
125     /// Turn a mplace into a (thin or fat) pointer, as a reference, pointing to the same space.
126     /// This is the inverse of `ref_to_mplace`.
127     #[inline(always)]
128     pub fn to_ref(self) -> Immediate<Tag> {
129         match self.meta {
130             None => Immediate::Scalar(self.ptr.into()),
131             Some(meta) => Immediate::ScalarPair(self.ptr.into(), meta.into()),
132         }
133     }
134
135     pub fn offset(
136         self,
137         offset: Size,
138         meta: Option<Scalar<Tag>>,
139         cx: &impl HasDataLayout,
140     ) -> InterpResult<'tcx, Self> {
141         Ok(MemPlace {
142             ptr: self.ptr.ptr_offset(offset, cx)?,
143             align: self.align.restrict_for_offset(offset),
144             meta,
145         })
146     }
147 }
148
149 impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
150     /// Produces a MemPlace that works for ZST but nothing else
151     #[inline]
152     pub fn dangling(layout: TyLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
153         MPlaceTy {
154             mplace: MemPlace::from_scalar_ptr(
155                 Scalar::from_uint(layout.align.abi.bytes(), cx.pointer_size()),
156                 layout.align.abi
157             ),
158             layout
159         }
160     }
161
162     /// Replace ptr tag, maintain vtable tag (if any)
163     #[inline]
164     pub fn replace_tag(self, new_tag: Tag) -> Self {
165         MPlaceTy {
166             mplace: self.mplace.replace_tag(new_tag),
167             layout: self.layout,
168         }
169     }
170
171     #[inline]
172     pub fn offset(
173         self,
174         offset: Size,
175         meta: Option<Scalar<Tag>>,
176         layout: TyLayout<'tcx>,
177         cx: &impl HasDataLayout,
178     ) -> InterpResult<'tcx, Self> {
179         Ok(MPlaceTy {
180             mplace: self.mplace.offset(offset, meta, cx)?,
181             layout,
182         })
183     }
184
185     #[inline]
186     fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyLayout<'tcx>) -> Self {
187         MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
188     }
189
190     #[inline]
191     pub(super) fn len(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
192         if self.layout.is_unsized() {
193             // We need to consult `meta` metadata
194             match self.layout.ty.sty {
195                 ty::Slice(..) | ty::Str =>
196                     return self.mplace.meta.unwrap().to_usize(cx),
197                 _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
198             }
199         } else {
200             // Go through the layout.  There are lots of types that support a length,
201             // e.g., SIMD types.
202             match self.layout.fields {
203                 layout::FieldPlacement::Array { count, .. } => Ok(count),
204                 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
205             }
206         }
207     }
208
209     #[inline]
210     pub(super) fn vtable(self) -> Scalar<Tag> {
211         match self.layout.ty.sty {
212             ty::Dynamic(..) => self.mplace.meta.unwrap(),
213             _ => bug!("vtable not supported on type {:?}", self.layout.ty),
214         }
215     }
216 }
217
218 // These are defined here because they produce a place.
219 impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
220     #[inline(always)]
221     pub fn try_as_mplace(self) -> Result<MPlaceTy<'tcx, Tag>, ImmTy<'tcx, Tag>> {
222         match *self {
223             Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
224             Operand::Immediate(imm) => Err(ImmTy { imm, layout: self.layout }),
225         }
226     }
227
228     #[inline(always)]
229     pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
230         self.try_as_mplace().unwrap()
231     }
232 }
233
234 impl<Tag: ::std::fmt::Debug> Place<Tag> {
235     /// Produces a Place that will error if attempted to be read from or written to
236     #[inline(always)]
237     pub fn null(cx: &impl HasDataLayout) -> Self {
238         Place::Ptr(MemPlace::null(cx))
239     }
240
241     #[inline(always)]
242     pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
243         Place::Ptr(MemPlace::from_scalar_ptr(ptr, align))
244     }
245
246     #[inline(always)]
247     pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
248         Place::Ptr(MemPlace::from_ptr(ptr, align))
249     }
250
251     #[inline]
252     pub fn assert_mem_place(self) -> MemPlace<Tag> {
253         match self {
254             Place::Ptr(mplace) => mplace,
255             _ => bug!("assert_mem_place: expected Place::Ptr, got {:?}", self),
256
257         }
258     }
259 }
260
261 impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
262     #[inline]
263     pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
264         MPlaceTy { mplace: self.place.assert_mem_place(), layout: self.layout }
265     }
266 }
267
268 // separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
269 impl<'mir, 'tcx, Tag, M> InterpCx<'mir, 'tcx, M>
270 where
271     // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
272     Tag: ::std::fmt::Debug + Copy + Eq + Hash + 'static,
273     M: Machine<'mir, 'tcx, PointerTag = Tag>,
274     // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
275     M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation<Tag, M::AllocExtra>)>,
276     M::AllocExtra: AllocationExtra<Tag>,
277 {
278     /// Take a value, which represents a (thin or fat) reference, and make it a place.
279     /// Alignment is just based on the type.  This is the inverse of `MemPlace::to_ref()`.
280     ///
281     /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
282     /// want to ever use the place for memory access!
283     /// Generally prefer `deref_operand`.
284     pub fn ref_to_mplace(
285         &self,
286         val: ImmTy<'tcx, M::PointerTag>,
287     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
288         let pointee_type = val.layout.ty.builtin_deref(true).unwrap().ty;
289         let layout = self.layout_of(pointee_type)?;
290
291         let mplace = MemPlace {
292             ptr: val.to_scalar_ptr()?,
293             // We could use the run-time alignment here. For now, we do not, because
294             // the point of tracking the alignment here is to make sure that the *static*
295             // alignment information emitted with the loads is correct. The run-time
296             // alignment can only be more restrictive.
297             align: layout.align.abi,
298             meta: val.to_meta()?,
299         };
300         Ok(MPlaceTy { mplace, layout })
301     }
302
303     /// Take an operand, representing a pointer, and dereference it to a place -- that
304     /// will always be a MemPlace.  Lives in `place.rs` because it creates a place.
305     pub fn deref_operand(
306         &self,
307         src: OpTy<'tcx, M::PointerTag>,
308     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
309         let val = self.read_immediate(src)?;
310         trace!("deref to {} on {:?}", val.layout.ty, *val);
311         let place = self.ref_to_mplace(val)?;
312         self.mplace_access_checked(place)
313     }
314
315     /// Check if the given place is good for memory access with the given
316     /// size, falling back to the layout's size if `None` (in the latter case,
317     /// this must be a statically sized type).
318     ///
319     /// On success, returns `None` for zero-sized accesses (where nothing else is
320     /// left to do) and a `Pointer` to use for the actual access otherwise.
321     #[inline]
322     pub fn check_mplace_access(
323         &self,
324         place: MPlaceTy<'tcx, M::PointerTag>,
325         size: Option<Size>,
326     ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
327         let size = size.unwrap_or_else(|| {
328             assert!(!place.layout.is_unsized());
329             assert!(place.meta.is_none());
330             place.layout.size
331         });
332         self.memory.check_ptr_access(place.ptr, size, place.align)
333     }
334
335     /// Return the "access-checked" version of this `MPlace`, where for non-ZST
336     /// this is definitely a `Pointer`.
337     pub fn mplace_access_checked(
338         &self,
339         mut place: MPlaceTy<'tcx, M::PointerTag>,
340     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
341         let (size, align) = self.size_and_align_of_mplace(place)?
342             .unwrap_or((place.layout.size, place.layout.align.abi));
343         assert!(place.mplace.align <= align, "dynamic alignment less strict than static one?");
344         place.mplace.align = align; // maximally strict checking
345         // When dereferencing a pointer, it must be non-NULL, aligned, and live.
346         if let Some(ptr) = self.check_mplace_access(place, Some(size))? {
347             place.mplace.ptr = ptr.into();
348         }
349         Ok(place)
350     }
351
352     /// Force `place.ptr` to a `Pointer`.
353     /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
354     pub fn force_mplace_ptr(
355         &self,
356         mut place: MPlaceTy<'tcx, M::PointerTag>,
357     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
358         place.mplace.ptr = self.force_ptr(place.mplace.ptr)?.into();
359         Ok(place)
360     }
361
362     /// Offset a pointer to project to a field. Unlike `place_field`, this is always
363     /// possible without allocating, so it can take `&self`. Also return the field's layout.
364     /// This supports both struct and array fields.
365     #[inline(always)]
366     pub fn mplace_field(
367         &self,
368         base: MPlaceTy<'tcx, M::PointerTag>,
369         field: u64,
370     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
371         // Not using the layout method because we want to compute on u64
372         let offset = match base.layout.fields {
373             layout::FieldPlacement::Arbitrary { ref offsets, .. } =>
374                 offsets[usize::try_from(field).unwrap()],
375             layout::FieldPlacement::Array { stride, .. } => {
376                 let len = base.len(self)?;
377                 if field >= len {
378                     // This can be violated because this runs during promotion on code where the
379                     // type system has not yet ensured that such things don't happen.
380                     debug!("tried to access element {} of array/slice with length {}", field, len);
381                     throw_panic!(BoundsCheck { len, index: field });
382                 }
383                 stride * field
384             }
385             layout::FieldPlacement::Union(count) => {
386                 assert!(field < count as u64,
387                         "Tried to access field {} of union with {} fields", field, count);
388                 // Offset is always 0
389                 Size::from_bytes(0)
390             }
391         };
392         // the only way conversion can fail if is this is an array (otherwise we already panicked
393         // above). In that case, all fields are equal.
394         let field_layout = base.layout.field(self, usize::try_from(field).unwrap_or(0))?;
395
396         // Offset may need adjustment for unsized fields.
397         let (meta, offset) = if field_layout.is_unsized() {
398             // Re-use parent metadata to determine dynamic field layout.
399             // With custom DSTS, this *will* execute user-defined code, but the same
400             // happens at run-time so that's okay.
401             let align = match self.size_and_align_of(base.meta, field_layout)? {
402                 Some((_, align)) => align,
403                 None if offset == Size::ZERO =>
404                     // An extern type at offset 0, we fall back to its static alignment.
405                     // FIXME: Once we have made decisions for how to handle size and alignment
406                     // of `extern type`, this should be adapted.  It is just a temporary hack
407                     // to get some code to work that probably ought to work.
408                     field_layout.align.abi,
409                 None =>
410                     bug!("Cannot compute offset for extern type field at non-0 offset"),
411             };
412             (base.meta, offset.align_to(align))
413         } else {
414             // base.meta could be present; we might be accessing a sized field of an unsized
415             // struct.
416             (None, offset)
417         };
418
419         // We do not look at `base.layout.align` nor `field_layout.align`, unlike
420         // codegen -- mostly to see if we can get away with that
421         base.offset(offset, meta, field_layout, self)
422     }
423
424     // Iterates over all fields of an array. Much more efficient than doing the
425     // same by repeatedly calling `mplace_array`.
426     pub fn mplace_array_fields(
427         &self,
428         base: MPlaceTy<'tcx, Tag>,
429     ) -> InterpResult<'tcx, impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'tcx>
430     {
431         let len = base.len(self)?; // also asserts that we have a type where this makes sense
432         let stride = match base.layout.fields {
433             layout::FieldPlacement::Array { stride, .. } => stride,
434             _ => bug!("mplace_array_fields: expected an array layout"),
435         };
436         let layout = base.layout.field(self, 0)?;
437         let dl = &self.tcx.data_layout;
438         Ok((0..len).map(move |i| base.offset(i * stride, None, layout, dl)))
439     }
440
441     pub fn mplace_subslice(
442         &self,
443         base: MPlaceTy<'tcx, M::PointerTag>,
444         from: u64,
445         to: u64,
446     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
447         let len = base.len(self)?; // also asserts that we have a type where this makes sense
448         assert!(from <= len - to);
449
450         // Not using layout method because that works with usize, and does not work with slices
451         // (that have count 0 in their layout).
452         let from_offset = match base.layout.fields {
453             layout::FieldPlacement::Array { stride, .. } =>
454                 stride * from,
455             _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
456         };
457
458         // Compute meta and new layout
459         let inner_len = len - to - from;
460         let (meta, ty) = match base.layout.ty.sty {
461             // It is not nice to match on the type, but that seems to be the only way to
462             // implement this.
463             ty::Array(inner, _) =>
464                 (None, self.tcx.mk_array(inner, inner_len)),
465             ty::Slice(..) => {
466                 let len = Scalar::from_uint(inner_len, self.pointer_size());
467                 (Some(len), base.layout.ty)
468             }
469             _ =>
470                 bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
471         };
472         let layout = self.layout_of(ty)?;
473         base.offset(from_offset, meta, layout, self)
474     }
475
476     pub fn mplace_downcast(
477         &self,
478         base: MPlaceTy<'tcx, M::PointerTag>,
479         variant: VariantIdx,
480     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
481         // Downcasts only change the layout
482         assert!(base.meta.is_none());
483         Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
484     }
485
486     /// Project into an mplace
487     pub fn mplace_projection(
488         &self,
489         base: MPlaceTy<'tcx, M::PointerTag>,
490         proj_elem: &mir::PlaceElem<'tcx>,
491     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
492         use rustc::mir::ProjectionElem::*;
493         Ok(match *proj_elem {
494             Field(field, _) => self.mplace_field(base, field.index() as u64)?,
495             Downcast(_, variant) => self.mplace_downcast(base, variant)?,
496             Deref => self.deref_operand(base.into())?,
497
498             Index(local) => {
499                 let layout = self.layout_of(self.tcx.types.usize)?;
500                 let n = self.access_local(self.frame(), local, Some(layout))?;
501                 let n = self.read_scalar(n)?;
502                 let n = self.force_bits(n.not_undef()?, self.tcx.data_layout.pointer_size)?;
503                 self.mplace_field(base, u64::try_from(n).unwrap())?
504             }
505
506             ConstantIndex {
507                 offset,
508                 min_length,
509                 from_end,
510             } => {
511                 let n = base.len(self)?;
512                 assert!(n >= min_length as u64);
513
514                 let index = if from_end {
515                     n - u64::from(offset)
516                 } else {
517                     u64::from(offset)
518                 };
519
520                 self.mplace_field(base, index)?
521             }
522
523             Subslice { from, to } =>
524                 self.mplace_subslice(base, u64::from(from), u64::from(to))?,
525         })
526     }
527
528     /// Gets the place of a field inside the place, and also the field's type.
529     /// Just a convenience function, but used quite a bit.
530     /// This is the only projection that might have a side-effect: We cannot project
531     /// into the field of a local `ScalarPair`, we have to first allocate it.
532     pub fn place_field(
533         &mut self,
534         base: PlaceTy<'tcx, M::PointerTag>,
535         field: u64,
536     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
537         // FIXME: We could try to be smarter and avoid allocation for fields that span the
538         // entire place.
539         let mplace = self.force_allocation(base)?;
540         Ok(self.mplace_field(mplace, field)?.into())
541     }
542
543     pub fn place_downcast(
544         &self,
545         base: PlaceTy<'tcx, M::PointerTag>,
546         variant: VariantIdx,
547     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
548         // Downcast just changes the layout
549         Ok(match base.place {
550             Place::Ptr(mplace) =>
551                 self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into(),
552             Place::Local { .. } => {
553                 let layout = base.layout.for_variant(self, variant);
554                 PlaceTy { layout, ..base }
555             }
556         })
557     }
558
559     /// Projects into a place.
560     pub fn place_projection(
561         &mut self,
562         base: PlaceTy<'tcx, M::PointerTag>,
563         proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
564     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
565         use rustc::mir::ProjectionElem::*;
566         Ok(match *proj_elem {
567             Field(field, _) =>  self.place_field(base, field.index() as u64)?,
568             Downcast(_, variant) => self.place_downcast(base, variant)?,
569             Deref => self.deref_operand(self.place_to_op(base)?)?.into(),
570             // For the other variants, we have to force an allocation.
571             // This matches `operand_projection`.
572             Subslice { .. } | ConstantIndex { .. } | Index(_) => {
573                 let mplace = self.force_allocation(base)?;
574                 self.mplace_projection(mplace, proj_elem)?.into()
575             }
576         })
577     }
578
579     /// Evaluate statics and promoteds to an `MPlace`. Used to share some code between
580     /// `eval_place` and `eval_place_to_op`.
581     pub(super) fn eval_static_to_mplace(
582         &self,
583         place_static: &mir::Static<'tcx>
584     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
585         use rustc::mir::StaticKind;
586
587         Ok(match place_static.kind {
588             StaticKind::Promoted(promoted, _) => {
589                 let instance = self.frame().instance;
590                 self.const_eval_raw(GlobalId {
591                     instance,
592                     promoted: Some(promoted),
593                 })?
594             }
595
596             StaticKind::Static => {
597                 let ty = place_static.ty;
598                 assert!(!ty.needs_subst());
599                 let layout = self.layout_of(ty)?;
600                 let instance = ty::Instance::mono(*self.tcx, place_static.def_id);
601                 let cid = GlobalId {
602                     instance,
603                     promoted: None
604                 };
605                 // Just create a lazy reference, so we can support recursive statics.
606                 // tcx takes care of assigning every static one and only one unique AllocId.
607                 // When the data here is ever actually used, memory will notice,
608                 // and it knows how to deal with alloc_id that are present in the
609                 // global table but not in its local memory: It calls back into tcx through
610                 // a query, triggering the CTFE machinery to actually turn this lazy reference
611                 // into a bunch of bytes.  IOW, statics are evaluated with CTFE even when
612                 // this InterpCx uses another Machine (e.g., in miri).  This is what we
613                 // want!  This way, computing statics works consistently between codegen
614                 // and miri: They use the same query to eventually obtain a `ty::Const`
615                 // and use that for further computation.
616                 //
617                 // Notice that statics have *two* AllocIds: the lazy one, and the resolved
618                 // one.  Here we make sure that the interpreted program never sees the
619                 // resolved ID.  Also see the doc comment of `Memory::get_static_alloc`.
620                 let alloc_id = self.tcx.alloc_map.lock().create_static_alloc(cid.instance.def_id());
621                 let ptr = self.tag_static_base_pointer(Pointer::from(alloc_id));
622                 MPlaceTy::from_aligned_ptr(ptr, layout)
623             }
624         })
625     }
626
627     /// Computes a place. You should only use this if you intend to write into this
628     /// place; for reading, a more efficient alternative is `eval_place_for_read`.
629     pub fn eval_place(
630         &mut self,
631         mir_place: &mir::Place<'tcx>,
632     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
633         use rustc::mir::PlaceBase;
634
635         mir_place.iterate(|place_base, place_projection| {
636             let mut place = match place_base {
637                 PlaceBase::Local(mir::RETURN_PLACE) => match self.frame().return_place {
638                     Some(return_place) => {
639                         // We use our layout to verify our assumption; caller will validate
640                         // their layout on return.
641                         PlaceTy {
642                             place: *return_place,
643                             layout: self.layout_of(
644                                 self.subst_from_frame_and_normalize_erasing_regions(
645                                     self.frame().body.return_ty()
646                                 )
647                             )?,
648                         }
649                     }
650                     None => throw_unsup!(InvalidNullPointerUsage),
651                 },
652                 PlaceBase::Local(local) => PlaceTy {
653                     // This works even for dead/uninitialized locals; we check further when writing
654                     place: Place::Local {
655                         frame: self.cur_frame(),
656                         local: *local,
657                     },
658                     layout: self.layout_of_local(self.frame(), *local, None)?,
659                 },
660                 PlaceBase::Static(place_static) => self.eval_static_to_mplace(place_static)?.into(),
661             };
662
663             for proj in place_projection {
664                 place = self.place_projection(place, &proj.elem)?
665             }
666
667             self.dump_place(place.place);
668             Ok(place)
669         })
670     }
671
672     /// Write a scalar to a place
673     pub fn write_scalar(
674         &mut self,
675         val: impl Into<ScalarMaybeUndef<M::PointerTag>>,
676         dest: PlaceTy<'tcx, M::PointerTag>,
677     ) -> InterpResult<'tcx> {
678         self.write_immediate(Immediate::Scalar(val.into()), dest)
679     }
680
681     /// Write an immediate to a place
682     #[inline(always)]
683     pub fn write_immediate(
684         &mut self,
685         src: Immediate<M::PointerTag>,
686         dest: PlaceTy<'tcx, M::PointerTag>,
687     ) -> InterpResult<'tcx> {
688         self.write_immediate_no_validate(src, dest)?;
689
690         if M::enforce_validity(self) {
691             // Data got changed, better make sure it matches the type!
692             self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
693         }
694
695         Ok(())
696     }
697
698     /// Write an `Immediate` to memory.
699     #[inline(always)]
700     pub fn write_immediate_to_mplace(
701         &mut self,
702         src: Immediate<M::PointerTag>,
703         dest: MPlaceTy<'tcx, M::PointerTag>,
704     ) -> InterpResult<'tcx> {
705         self.write_immediate_to_mplace_no_validate(src, dest)?;
706
707         if M::enforce_validity(self) {
708             // Data got changed, better make sure it matches the type!
709             self.validate_operand(dest.into(), vec![], None)?;
710         }
711
712         Ok(())
713     }
714
715     /// Write an immediate to a place.
716     /// If you use this you are responsible for validating that things got copied at the
717     /// right type.
718     fn write_immediate_no_validate(
719         &mut self,
720         src: Immediate<M::PointerTag>,
721         dest: PlaceTy<'tcx, M::PointerTag>,
722     ) -> InterpResult<'tcx> {
723         if cfg!(debug_assertions) {
724             // This is a very common path, avoid some checks in release mode
725             assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
726             match src {
727                 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Ptr(_))) =>
728                     assert_eq!(self.pointer_size(), dest.layout.size,
729                         "Size mismatch when writing pointer"),
730                 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Raw { size, .. })) =>
731                     assert_eq!(Size::from_bytes(size.into()), dest.layout.size,
732                         "Size mismatch when writing bits"),
733                 Immediate::Scalar(ScalarMaybeUndef::Undef) => {}, // undef can have any size
734                 Immediate::ScalarPair(_, _) => {
735                     // FIXME: Can we check anything here?
736                 }
737             }
738         }
739         trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
740
741         // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
742         // but not factored as a separate function.
743         let mplace = match dest.place {
744             Place::Local { frame, local } => {
745                 match self.stack[frame].locals[local].access_mut()? {
746                     Ok(local) => {
747                         // Local can be updated in-place.
748                         *local = LocalValue::Live(Operand::Immediate(src));
749                         return Ok(());
750                     }
751                     Err(mplace) => {
752                         // The local is in memory, go on below.
753                         mplace
754                     }
755                 }
756             },
757             Place::Ptr(mplace) => mplace, // already referring to memory
758         };
759         let dest = MPlaceTy { mplace, layout: dest.layout };
760
761         // This is already in memory, write there.
762         self.write_immediate_to_mplace_no_validate(src, dest)
763     }
764
765     /// Write an immediate to memory.
766     /// If you use this you are responsible for validating that things got copied at the
767     /// right type.
768     fn write_immediate_to_mplace_no_validate(
769         &mut self,
770         value: Immediate<M::PointerTag>,
771         dest: MPlaceTy<'tcx, M::PointerTag>,
772     ) -> InterpResult<'tcx> {
773         // Note that it is really important that the type here is the right one, and matches the
774         // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
775         // to handle padding properly, which is only correct if we never look at this data with the
776         // wrong type.
777
778         let ptr = match self.check_mplace_access(dest, None)
779             .expect("places should be checked on creation")
780         {
781             Some(ptr) => ptr,
782             None => return Ok(()), // zero-sized access
783         };
784
785         let tcx = &*self.tcx;
786         // FIXME: We should check that there are dest.layout.size many bytes available in
787         // memory.  The code below is not sufficient, with enough padding it might not
788         // cover all the bytes!
789         match value {
790             Immediate::Scalar(scalar) => {
791                 match dest.layout.abi {
792                     layout::Abi::Scalar(_) => {}, // fine
793                     _ => bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}",
794                             dest.layout)
795                 }
796                 self.memory.get_mut(ptr.alloc_id)?.write_scalar(
797                     tcx, ptr, scalar, dest.layout.size
798                 )
799             }
800             Immediate::ScalarPair(a_val, b_val) => {
801                 // We checked `ptr_align` above, so all fields will have the alignment they need.
802                 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
803                 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
804                 let (a, b) = match dest.layout.abi {
805                     layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
806                     _ => bug!("write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
807                               dest.layout)
808                 };
809                 let (a_size, b_size) = (a.size(self), b.size(self));
810                 let b_offset = a_size.align_to(b.align(self).abi);
811                 let b_ptr = ptr.offset(b_offset, self)?;
812
813                 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
814                 // but that does not work: We could be a newtype around a pair, then the
815                 // fields do not match the `ScalarPair` components.
816
817                 self.memory
818                     .get_mut(ptr.alloc_id)?
819                     .write_scalar(tcx, ptr, a_val, a_size)?;
820                 self.memory
821                     .get_mut(b_ptr.alloc_id)?
822                     .write_scalar(tcx, b_ptr, b_val, b_size)
823             }
824         }
825     }
826
827     /// Copies the data from an operand to a place. This does not support transmuting!
828     /// Use `copy_op_transmute` if the layouts could disagree.
829     #[inline(always)]
830     pub fn copy_op(
831         &mut self,
832         src: OpTy<'tcx, M::PointerTag>,
833         dest: PlaceTy<'tcx, M::PointerTag>,
834     ) -> InterpResult<'tcx> {
835         self.copy_op_no_validate(src, dest)?;
836
837         if M::enforce_validity(self) {
838             // Data got changed, better make sure it matches the type!
839             self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
840         }
841
842         Ok(())
843     }
844
845     /// Copies the data from an operand to a place. This does not support transmuting!
846     /// Use `copy_op_transmute` if the layouts could disagree.
847     /// Also, if you use this you are responsible for validating that things get copied at the
848     /// right type.
849     fn copy_op_no_validate(
850         &mut self,
851         src: OpTy<'tcx, M::PointerTag>,
852         dest: PlaceTy<'tcx, M::PointerTag>,
853     ) -> InterpResult<'tcx> {
854         // We do NOT compare the types for equality, because well-typed code can
855         // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
856         assert!(src.layout.details == dest.layout.details,
857             "Layout mismatch when copying!\nsrc: {:#?}\ndest: {:#?}", src, dest);
858
859         // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
860         let src = match self.try_read_immediate(src)? {
861             Ok(src_val) => {
862                 assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
863                 // Yay, we got a value that we can write directly.
864                 // FIXME: Add a check to make sure that if `src` is indirect,
865                 // it does not overlap with `dest`.
866                 return self.write_immediate_no_validate(*src_val, dest);
867             }
868             Err(mplace) => mplace,
869         };
870         // Slow path, this does not fit into an immediate. Just memcpy.
871         trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
872
873         // This interprets `src.meta` with the `dest` local's layout, if an unsized local
874         // is being initialized!
875         let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?;
876         let size = size.unwrap_or_else(|| {
877             assert!(!dest.layout.is_unsized(),
878                 "Cannot copy into already initialized unsized place");
879             dest.layout.size
880         });
881         assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
882
883         let src = self.check_mplace_access(src, Some(size))
884             .expect("places should be checked on creation");
885         let dest = self.check_mplace_access(dest, Some(size))
886             .expect("places should be checked on creation");
887         let (src_ptr, dest_ptr) = match (src, dest) {
888             (Some(src_ptr), Some(dest_ptr)) => (src_ptr, dest_ptr),
889             (None, None) => return Ok(()), // zero-sized copy
890             _ => bug!("The pointers should both be Some or both None"),
891         };
892
893         self.memory.copy(
894             src_ptr,
895             dest_ptr,
896             size,
897             /*nonoverlapping*/ true,
898         )
899     }
900
901     /// Copies the data from an operand to a place. The layouts may disagree, but they must
902     /// have the same size.
903     pub fn copy_op_transmute(
904         &mut self,
905         src: OpTy<'tcx, M::PointerTag>,
906         dest: PlaceTy<'tcx, M::PointerTag>,
907     ) -> InterpResult<'tcx> {
908         if src.layout.details == dest.layout.details {
909             // Fast path: Just use normal `copy_op`
910             return self.copy_op(src, dest);
911         }
912         // We still require the sizes to match.
913         assert!(src.layout.size == dest.layout.size,
914             "Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
915         // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
916         // to avoid that here.
917         assert!(!src.layout.is_unsized() && !dest.layout.is_unsized(),
918             "Cannot transmute unsized data");
919
920         // The hard case is `ScalarPair`.  `src` is already read from memory in this case,
921         // using `src.layout` to figure out which bytes to use for the 1st and 2nd field.
922         // We have to write them to `dest` at the offsets they were *read at*, which is
923         // not necessarily the same as the offsets in `dest.layout`!
924         // Hence we do the copy with the source layout on both sides.  We also make sure to write
925         // into memory, because if `dest` is a local we would not even have a way to write
926         // at the `src` offsets; the fact that we came from a different layout would
927         // just be lost.
928         let dest = self.force_allocation(dest)?;
929         self.copy_op_no_validate(
930             src,
931             PlaceTy::from(MPlaceTy { mplace: *dest, layout: src.layout }),
932         )?;
933
934         if M::enforce_validity(self) {
935             // Data got changed, better make sure it matches the type!
936             self.validate_operand(dest.into(), vec![], None)?;
937         }
938
939         Ok(())
940     }
941
942     /// Ensures that a place is in memory, and returns where it is.
943     /// If the place currently refers to a local that doesn't yet have a matching allocation,
944     /// create such an allocation.
945     /// This is essentially `force_to_memplace`.
946     ///
947     /// This supports unsized types and returns the computed size to avoid some
948     /// redundant computation when copying; use `force_allocation` for a simpler, sized-only
949     /// version.
950     pub fn force_allocation_maybe_sized(
951         &mut self,
952         place: PlaceTy<'tcx, M::PointerTag>,
953         meta: Option<Scalar<M::PointerTag>>,
954     ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
955         let (mplace, size) = match place.place {
956             Place::Local { frame, local } => {
957                 match self.stack[frame].locals[local].access_mut()? {
958                     Ok(local_val) => {
959                         // We need to make an allocation.
960                         // FIXME: Consider not doing anything for a ZST, and just returning
961                         // a fake pointer?  Are we even called for ZST?
962
963                         // We cannot hold on to the reference `local_val` while allocating,
964                         // but we can hold on to the value in there.
965                         let old_val =
966                             if let LocalValue::Live(Operand::Immediate(value)) = *local_val {
967                                 Some(value)
968                             } else {
969                                 None
970                             };
971
972                         // We need the layout of the local.  We can NOT use the layout we got,
973                         // that might e.g., be an inner field of a struct with `Scalar` layout,
974                         // that has different alignment than the outer field.
975                         // We also need to support unsized types, and hence cannot use `allocate`.
976                         let local_layout = self.layout_of_local(&self.stack[frame], local, None)?;
977                         let (size, align) = self.size_and_align_of(meta, local_layout)?
978                             .expect("Cannot allocate for non-dyn-sized type");
979                         let ptr = self.memory.allocate(size, align, MemoryKind::Stack);
980                         let mplace = MemPlace { ptr: ptr.into(), align, meta };
981                         if let Some(value) = old_val {
982                             // Preserve old value.
983                             // We don't have to validate as we can assume the local
984                             // was already valid for its type.
985                             let mplace = MPlaceTy { mplace, layout: local_layout };
986                             self.write_immediate_to_mplace_no_validate(value, mplace)?;
987                         }
988                         // Now we can call `access_mut` again, asserting it goes well,
989                         // and actually overwrite things.
990                         *self.stack[frame].locals[local].access_mut().unwrap().unwrap() =
991                             LocalValue::Live(Operand::Indirect(mplace));
992                         (mplace, Some(size))
993                     }
994                     Err(mplace) => (mplace, None), // this already was an indirect local
995                 }
996             }
997             Place::Ptr(mplace) => (mplace, None)
998         };
999         // Return with the original layout, so that the caller can go on
1000         Ok((MPlaceTy { mplace, layout: place.layout }, size))
1001     }
1002
1003     #[inline(always)]
1004     pub fn force_allocation(
1005         &mut self,
1006         place: PlaceTy<'tcx, M::PointerTag>,
1007     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1008         Ok(self.force_allocation_maybe_sized(place, None)?.0)
1009     }
1010
1011     pub fn allocate(
1012         &mut self,
1013         layout: TyLayout<'tcx>,
1014         kind: MemoryKind<M::MemoryKinds>,
1015     ) -> MPlaceTy<'tcx, M::PointerTag> {
1016         let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
1017         MPlaceTy::from_aligned_ptr(ptr, layout)
1018     }
1019
1020     pub fn write_discriminant_index(
1021         &mut self,
1022         variant_index: VariantIdx,
1023         dest: PlaceTy<'tcx, M::PointerTag>,
1024     ) -> InterpResult<'tcx> {
1025         match dest.layout.variants {
1026             layout::Variants::Single { index } => {
1027                 assert_eq!(index, variant_index);
1028             }
1029             layout::Variants::Multiple {
1030                 discr_kind: layout::DiscriminantKind::Tag,
1031                 ref discr,
1032                 discr_index,
1033                 ..
1034             } => {
1035                 assert!(dest.layout.ty.variant_range(*self.tcx).unwrap().contains(&variant_index));
1036                 let discr_val =
1037                     dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
1038
1039                 // raw discriminants for enums are isize or bigger during
1040                 // their computation, but the in-memory tag is the smallest possible
1041                 // representation
1042                 let size = discr.value.size(self);
1043                 let discr_val = truncate(discr_val, size);
1044
1045                 let discr_dest = self.place_field(dest, discr_index as u64)?;
1046                 self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
1047             }
1048             layout::Variants::Multiple {
1049                 discr_kind: layout::DiscriminantKind::Niche {
1050                     dataful_variant,
1051                     ref niche_variants,
1052                     niche_start,
1053                 },
1054                 discr_index,
1055                 ..
1056             } => {
1057                 assert!(
1058                     variant_index.as_usize() < dest.layout.ty.ty_adt_def().unwrap().variants.len(),
1059                 );
1060                 if variant_index != dataful_variant {
1061                     let niche_dest =
1062                         self.place_field(dest, discr_index as u64)?;
1063                     let niche_value = variant_index.as_u32() - niche_variants.start().as_u32();
1064                     let niche_value = (niche_value as u128)
1065                         .wrapping_add(niche_start);
1066                     self.write_scalar(
1067                         Scalar::from_uint(niche_value, niche_dest.layout.size),
1068                         niche_dest
1069                     )?;
1070                 }
1071             }
1072         }
1073
1074         Ok(())
1075     }
1076
1077     pub fn raw_const_to_mplace(
1078         &self,
1079         raw: RawConst<'tcx>,
1080     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1081         // This must be an allocation in `tcx`
1082         assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1083         let ptr = self.tag_static_base_pointer(Pointer::from(raw.alloc_id));
1084         let layout = self.layout_of(raw.ty)?;
1085         Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
1086     }
1087
1088     /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
1089     /// Also return some more information so drop doesn't have to run the same code twice.
1090     pub(super) fn unpack_dyn_trait(&self, mplace: MPlaceTy<'tcx, M::PointerTag>)
1091     -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1092         let vtable = mplace.vtable(); // also sanity checks the type
1093         let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
1094         let layout = self.layout_of(ty)?;
1095
1096         // More sanity checks
1097         if cfg!(debug_assertions) {
1098             let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
1099             assert_eq!(size, layout.size);
1100             // only ABI alignment is preserved
1101             assert_eq!(align, layout.align.abi);
1102         }
1103
1104         let mplace = MPlaceTy {
1105             mplace: MemPlace { meta: None, ..*mplace },
1106             layout
1107         };
1108         Ok((instance, mplace))
1109     }
1110 }