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