]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/place.rs
Rollup merge of #63153 - varkor:remove-resolve_const_var, r=cramertj
[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>,
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     pub fn ref_to_mplace(
281         &self,
282         val: ImmTy<'tcx, M::PointerTag>,
283     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
284         let pointee_type = val.layout.ty.builtin_deref(true).unwrap().ty;
285         let layout = self.layout_of(pointee_type)?;
286
287         let mplace = MemPlace {
288             ptr: val.to_scalar_ptr()?,
289             // We could use the run-time alignment here. For now, we do not, because
290             // the point of tracking the alignment here is to make sure that the *static*
291             // alignment information emitted with the loads is correct. The run-time
292             // alignment can only be more restrictive.
293             align: layout.align.abi,
294             meta: val.to_meta()?,
295         };
296         Ok(MPlaceTy { mplace, layout })
297     }
298
299     /// Take an operand, representing a pointer, and dereference it to a place -- that
300     /// will always be a MemPlace.  Lives in `place.rs` because it creates a place.
301     pub fn deref_operand(
302         &self,
303         src: OpTy<'tcx, M::PointerTag>,
304     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
305         let val = self.read_immediate(src)?;
306         trace!("deref to {} on {:?}", val.layout.ty, *val);
307         self.ref_to_mplace(val)
308     }
309
310     /// Check if the given place is good for memory access with the given
311     /// size, falling back to the layout's size if `None` (in the latter case,
312     /// this must be a statically sized type).
313     ///
314     /// On success, returns `None` for zero-sized accesses (where nothing else is
315     /// left to do) and a `Pointer` to use for the actual access otherwise.
316     #[inline]
317     pub fn check_mplace_access(
318         &self,
319         place: MPlaceTy<'tcx, M::PointerTag>,
320         size: Option<Size>,
321     ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
322         let size = size.unwrap_or_else(|| {
323             assert!(!place.layout.is_unsized());
324             assert!(place.meta.is_none());
325             place.layout.size
326         });
327         self.memory.check_ptr_access(place.ptr, size, place.align)
328     }
329
330     /// Force `place.ptr` to a `Pointer`.
331     /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
332     pub fn force_mplace_ptr(
333         &self,
334         mut place: MPlaceTy<'tcx, M::PointerTag>,
335     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
336         place.mplace.ptr = self.force_ptr(place.mplace.ptr)?.into();
337         Ok(place)
338     }
339
340     /// Offset a pointer to project to a field. Unlike `place_field`, this is always
341     /// possible without allocating, so it can take `&self`. Also return the field's layout.
342     /// This supports both struct and array fields.
343     #[inline(always)]
344     pub fn mplace_field(
345         &self,
346         base: MPlaceTy<'tcx, M::PointerTag>,
347         field: u64,
348     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
349         // Not using the layout method because we want to compute on u64
350         let offset = match base.layout.fields {
351             layout::FieldPlacement::Arbitrary { ref offsets, .. } =>
352                 offsets[usize::try_from(field).unwrap()],
353             layout::FieldPlacement::Array { stride, .. } => {
354                 let len = base.len(self)?;
355                 if field >= len {
356                     // This can be violated because this runs during promotion on code where the
357                     // type system has not yet ensured that such things don't happen.
358                     debug!("tried to access element {} of array/slice with length {}", field, len);
359                     throw_panic!(BoundsCheck { len, index: field });
360                 }
361                 stride * field
362             }
363             layout::FieldPlacement::Union(count) => {
364                 assert!(field < count as u64,
365                         "Tried to access field {} of union with {} fields", field, count);
366                 // Offset is always 0
367                 Size::from_bytes(0)
368             }
369         };
370         // the only way conversion can fail if is this is an array (otherwise we already panicked
371         // above). In that case, all fields are equal.
372         let field_layout = base.layout.field(self, usize::try_from(field).unwrap_or(0))?;
373
374         // Offset may need adjustment for unsized fields.
375         let (meta, offset) = if field_layout.is_unsized() {
376             // Re-use parent metadata to determine dynamic field layout.
377             // With custom DSTS, this *will* execute user-defined code, but the same
378             // happens at run-time so that's okay.
379             let align = match self.size_and_align_of(base.meta, field_layout)? {
380                 Some((_, align)) => align,
381                 None if offset == Size::ZERO =>
382                     // An extern type at offset 0, we fall back to its static alignment.
383                     // FIXME: Once we have made decisions for how to handle size and alignment
384                     // of `extern type`, this should be adapted.  It is just a temporary hack
385                     // to get some code to work that probably ought to work.
386                     field_layout.align.abi,
387                 None =>
388                     bug!("Cannot compute offset for extern type field at non-0 offset"),
389             };
390             (base.meta, offset.align_to(align))
391         } else {
392             // base.meta could be present; we might be accessing a sized field of an unsized
393             // struct.
394             (None, offset)
395         };
396
397         // We do not look at `base.layout.align` nor `field_layout.align`, unlike
398         // codegen -- mostly to see if we can get away with that
399         base.offset(offset, meta, field_layout, self)
400     }
401
402     // Iterates over all fields of an array. Much more efficient than doing the
403     // same by repeatedly calling `mplace_array`.
404     pub fn mplace_array_fields(
405         &self,
406         base: MPlaceTy<'tcx, Tag>,
407     ) -> InterpResult<'tcx, impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'tcx>
408     {
409         let len = base.len(self)?; // also asserts that we have a type where this makes sense
410         let stride = match base.layout.fields {
411             layout::FieldPlacement::Array { stride, .. } => stride,
412             _ => bug!("mplace_array_fields: expected an array layout"),
413         };
414         let layout = base.layout.field(self, 0)?;
415         let dl = &self.tcx.data_layout;
416         Ok((0..len).map(move |i| base.offset(i * stride, None, layout, dl)))
417     }
418
419     pub fn mplace_subslice(
420         &self,
421         base: MPlaceTy<'tcx, M::PointerTag>,
422         from: u64,
423         to: u64,
424     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
425         let len = base.len(self)?; // also asserts that we have a type where this makes sense
426         assert!(from <= len - to);
427
428         // Not using layout method because that works with usize, and does not work with slices
429         // (that have count 0 in their layout).
430         let from_offset = match base.layout.fields {
431             layout::FieldPlacement::Array { stride, .. } =>
432                 stride * from,
433             _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
434         };
435
436         // Compute meta and new layout
437         let inner_len = len - to - from;
438         let (meta, ty) = match base.layout.ty.sty {
439             // It is not nice to match on the type, but that seems to be the only way to
440             // implement this.
441             ty::Array(inner, _) =>
442                 (None, self.tcx.mk_array(inner, inner_len)),
443             ty::Slice(..) => {
444                 let len = Scalar::from_uint(inner_len, self.pointer_size());
445                 (Some(len), base.layout.ty)
446             }
447             _ =>
448                 bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
449         };
450         let layout = self.layout_of(ty)?;
451         base.offset(from_offset, meta, layout, self)
452     }
453
454     pub fn mplace_downcast(
455         &self,
456         base: MPlaceTy<'tcx, M::PointerTag>,
457         variant: VariantIdx,
458     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
459         // Downcasts only change the layout
460         assert!(base.meta.is_none());
461         Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
462     }
463
464     /// Project into an mplace
465     pub fn mplace_projection(
466         &self,
467         base: MPlaceTy<'tcx, M::PointerTag>,
468         proj_elem: &mir::PlaceElem<'tcx>,
469     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
470         use rustc::mir::ProjectionElem::*;
471         Ok(match *proj_elem {
472             Field(field, _) => self.mplace_field(base, field.index() as u64)?,
473             Downcast(_, variant) => self.mplace_downcast(base, variant)?,
474             Deref => self.deref_operand(base.into())?,
475
476             Index(local) => {
477                 let layout = self.layout_of(self.tcx.types.usize)?;
478                 let n = self.access_local(self.frame(), local, Some(layout))?;
479                 let n = self.read_scalar(n)?;
480                 let n = self.force_bits(n.not_undef()?, self.tcx.data_layout.pointer_size)?;
481                 self.mplace_field(base, u64::try_from(n).unwrap())?
482             }
483
484             ConstantIndex {
485                 offset,
486                 min_length,
487                 from_end,
488             } => {
489                 let n = base.len(self)?;
490                 assert!(n >= min_length as u64);
491
492                 let index = if from_end {
493                     n - u64::from(offset)
494                 } else {
495                     u64::from(offset)
496                 };
497
498                 self.mplace_field(base, index)?
499             }
500
501             Subslice { from, to } =>
502                 self.mplace_subslice(base, u64::from(from), u64::from(to))?,
503         })
504     }
505
506     /// Gets the place of a field inside the place, and also the field's type.
507     /// Just a convenience function, but used quite a bit.
508     /// This is the only projection that might have a side-effect: We cannot project
509     /// into the field of a local `ScalarPair`, we have to first allocate it.
510     pub fn place_field(
511         &mut self,
512         base: PlaceTy<'tcx, M::PointerTag>,
513         field: u64,
514     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
515         // FIXME: We could try to be smarter and avoid allocation for fields that span the
516         // entire place.
517         let mplace = self.force_allocation(base)?;
518         Ok(self.mplace_field(mplace, field)?.into())
519     }
520
521     pub fn place_downcast(
522         &self,
523         base: PlaceTy<'tcx, M::PointerTag>,
524         variant: VariantIdx,
525     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
526         // Downcast just changes the layout
527         Ok(match base.place {
528             Place::Ptr(mplace) =>
529                 self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into(),
530             Place::Local { .. } => {
531                 let layout = base.layout.for_variant(self, variant);
532                 PlaceTy { layout, ..base }
533             }
534         })
535     }
536
537     /// Projects into a place.
538     pub fn place_projection(
539         &mut self,
540         base: PlaceTy<'tcx, M::PointerTag>,
541         proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
542     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
543         use rustc::mir::ProjectionElem::*;
544         Ok(match *proj_elem {
545             Field(field, _) =>  self.place_field(base, field.index() as u64)?,
546             Downcast(_, variant) => self.place_downcast(base, variant)?,
547             Deref => self.deref_operand(self.place_to_op(base)?)?.into(),
548             // For the other variants, we have to force an allocation.
549             // This matches `operand_projection`.
550             Subslice { .. } | ConstantIndex { .. } | Index(_) => {
551                 let mplace = self.force_allocation(base)?;
552                 self.mplace_projection(mplace, proj_elem)?.into()
553             }
554         })
555     }
556
557     /// Evaluate statics and promoteds to an `MPlace`. Used to share some code between
558     /// `eval_place` and `eval_place_to_op`.
559     pub(super) fn eval_static_to_mplace(
560         &self,
561         place_static: &mir::Static<'tcx>
562     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
563         use rustc::mir::StaticKind;
564
565         Ok(match place_static.kind {
566             StaticKind::Promoted(promoted) => {
567                 let instance = self.frame().instance;
568                 self.const_eval_raw(GlobalId {
569                     instance,
570                     promoted: Some(promoted),
571                 })?
572             }
573
574             StaticKind::Static(def_id) => {
575                 let ty = place_static.ty;
576                 assert!(!ty.needs_subst());
577                 let layout = self.layout_of(ty)?;
578                 let instance = ty::Instance::mono(*self.tcx, def_id);
579                 let cid = GlobalId {
580                     instance,
581                     promoted: None
582                 };
583                 // Just create a lazy reference, so we can support recursive statics.
584                 // tcx takes care of assigning every static one and only one unique AllocId.
585                 // When the data here is ever actually used, memory will notice,
586                 // and it knows how to deal with alloc_id that are present in the
587                 // global table but not in its local memory: It calls back into tcx through
588                 // a query, triggering the CTFE machinery to actually turn this lazy reference
589                 // into a bunch of bytes.  IOW, statics are evaluated with CTFE even when
590                 // this InterpCx uses another Machine (e.g., in miri).  This is what we
591                 // want!  This way, computing statics works consistently between codegen
592                 // and miri: They use the same query to eventually obtain a `ty::Const`
593                 // and use that for further computation.
594                 //
595                 // Notice that statics have *two* AllocIds: the lazy one, and the resolved
596                 // one.  Here we make sure that the interpreted program never sees the
597                 // resolved ID.  Also see the doc comment of `Memory::get_static_alloc`.
598                 let alloc_id = self.tcx.alloc_map.lock().create_static_alloc(cid.instance.def_id());
599                 let ptr = self.tag_static_base_pointer(Pointer::from(alloc_id));
600                 MPlaceTy::from_aligned_ptr(ptr, layout)
601             }
602         })
603     }
604
605     /// Computes a place. You should only use this if you intend to write into this
606     /// place; for reading, a more efficient alternative is `eval_place_for_read`.
607     pub fn eval_place(
608         &mut self,
609         mir_place: &mir::Place<'tcx>,
610     ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
611         use rustc::mir::PlaceBase;
612
613         mir_place.iterate(|place_base, place_projection| {
614             let mut place = match place_base {
615                 PlaceBase::Local(mir::RETURN_PLACE) => match self.frame().return_place {
616                     Some(return_place) => {
617                         // We use our layout to verify our assumption; caller will validate
618                         // their layout on return.
619                         PlaceTy {
620                             place: *return_place,
621                             layout: self
622                                 .layout_of(self.monomorphize(self.frame().body.return_ty())?)?,
623                         }
624                     }
625                     None => throw_unsup!(InvalidNullPointerUsage),
626                 },
627                 PlaceBase::Local(local) => PlaceTy {
628                     // This works even for dead/uninitialized locals; we check further when writing
629                     place: Place::Local {
630                         frame: self.cur_frame(),
631                         local: *local,
632                     },
633                     layout: self.layout_of_local(self.frame(), *local, None)?,
634                 },
635                 PlaceBase::Static(place_static) => self.eval_static_to_mplace(place_static)?.into(),
636             };
637
638             for proj in place_projection {
639                 place = self.place_projection(place, &proj.elem)?
640             }
641
642             self.dump_place(place.place);
643             Ok(place)
644         })
645     }
646
647     /// Write a scalar to a place
648     pub fn write_scalar(
649         &mut self,
650         val: impl Into<ScalarMaybeUndef<M::PointerTag>>,
651         dest: PlaceTy<'tcx, M::PointerTag>,
652     ) -> InterpResult<'tcx> {
653         self.write_immediate(Immediate::Scalar(val.into()), dest)
654     }
655
656     /// Write an immediate to a place
657     #[inline(always)]
658     pub fn write_immediate(
659         &mut self,
660         src: Immediate<M::PointerTag>,
661         dest: PlaceTy<'tcx, M::PointerTag>,
662     ) -> InterpResult<'tcx> {
663         self.write_immediate_no_validate(src, dest)?;
664
665         if M::enforce_validity(self) {
666             // Data got changed, better make sure it matches the type!
667             self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
668         }
669
670         Ok(())
671     }
672
673     /// Write an `Immediate` to memory.
674     #[inline(always)]
675     pub fn write_immediate_to_mplace(
676         &mut self,
677         src: Immediate<M::PointerTag>,
678         dest: MPlaceTy<'tcx, M::PointerTag>,
679     ) -> InterpResult<'tcx> {
680         self.write_immediate_to_mplace_no_validate(src, dest)?;
681
682         if M::enforce_validity(self) {
683             // Data got changed, better make sure it matches the type!
684             self.validate_operand(dest.into(), vec![], None)?;
685         }
686
687         Ok(())
688     }
689
690     /// Write an immediate to a place.
691     /// If you use this you are responsible for validating that things got copied at the
692     /// right type.
693     fn write_immediate_no_validate(
694         &mut self,
695         src: Immediate<M::PointerTag>,
696         dest: PlaceTy<'tcx, M::PointerTag>,
697     ) -> InterpResult<'tcx> {
698         if cfg!(debug_assertions) {
699             // This is a very common path, avoid some checks in release mode
700             assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
701             match src {
702                 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Ptr(_))) =>
703                     assert_eq!(self.pointer_size(), dest.layout.size,
704                         "Size mismatch when writing pointer"),
705                 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Raw { size, .. })) =>
706                     assert_eq!(Size::from_bytes(size.into()), dest.layout.size,
707                         "Size mismatch when writing bits"),
708                 Immediate::Scalar(ScalarMaybeUndef::Undef) => {}, // undef can have any size
709                 Immediate::ScalarPair(_, _) => {
710                     // FIXME: Can we check anything here?
711                 }
712             }
713         }
714         trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
715
716         // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
717         // but not factored as a separate function.
718         let mplace = match dest.place {
719             Place::Local { frame, local } => {
720                 match self.stack[frame].locals[local].access_mut()? {
721                     Ok(local) => {
722                         // Local can be updated in-place.
723                         *local = LocalValue::Live(Operand::Immediate(src));
724                         return Ok(());
725                     }
726                     Err(mplace) => {
727                         // The local is in memory, go on below.
728                         mplace
729                     }
730                 }
731             },
732             Place::Ptr(mplace) => mplace, // already referring to memory
733         };
734         let dest = MPlaceTy { mplace, layout: dest.layout };
735
736         // This is already in memory, write there.
737         self.write_immediate_to_mplace_no_validate(src, dest)
738     }
739
740     /// Write an immediate to memory.
741     /// If you use this you are responsible for validating that things got copied at the
742     /// right type.
743     fn write_immediate_to_mplace_no_validate(
744         &mut self,
745         value: Immediate<M::PointerTag>,
746         dest: MPlaceTy<'tcx, M::PointerTag>,
747     ) -> InterpResult<'tcx> {
748         // Note that it is really important that the type here is the right one, and matches the
749         // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
750         // to handle padding properly, which is only correct if we never look at this data with the
751         // wrong type.
752
753         let ptr = match self.check_mplace_access(dest, None)? {
754             Some(ptr) => ptr,
755             None => return Ok(()), // zero-sized access
756         };
757
758         let tcx = &*self.tcx;
759         // FIXME: We should check that there are dest.layout.size many bytes available in
760         // memory.  The code below is not sufficient, with enough padding it might not
761         // cover all the bytes!
762         match value {
763             Immediate::Scalar(scalar) => {
764                 match dest.layout.abi {
765                     layout::Abi::Scalar(_) => {}, // fine
766                     _ => bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}",
767                             dest.layout)
768                 }
769                 self.memory.get_mut(ptr.alloc_id)?.write_scalar(
770                     tcx, ptr, scalar, dest.layout.size
771                 )
772             }
773             Immediate::ScalarPair(a_val, b_val) => {
774                 // We checked `ptr_align` above, so all fields will have the alignment they need.
775                 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
776                 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
777                 let (a, b) = match dest.layout.abi {
778                     layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
779                     _ => bug!("write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
780                               dest.layout)
781                 };
782                 let (a_size, b_size) = (a.size(self), b.size(self));
783                 let b_offset = a_size.align_to(b.align(self).abi);
784                 let b_ptr = ptr.offset(b_offset, self)?;
785
786                 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
787                 // but that does not work: We could be a newtype around a pair, then the
788                 // fields do not match the `ScalarPair` components.
789
790                 self.memory
791                     .get_mut(ptr.alloc_id)?
792                     .write_scalar(tcx, ptr, a_val, a_size)?;
793                 self.memory
794                     .get_mut(b_ptr.alloc_id)?
795                     .write_scalar(tcx, b_ptr, b_val, b_size)
796             }
797         }
798     }
799
800     /// Copies the data from an operand to a place. This does not support transmuting!
801     /// Use `copy_op_transmute` if the layouts could disagree.
802     #[inline(always)]
803     pub fn copy_op(
804         &mut self,
805         src: OpTy<'tcx, M::PointerTag>,
806         dest: PlaceTy<'tcx, M::PointerTag>,
807     ) -> InterpResult<'tcx> {
808         self.copy_op_no_validate(src, dest)?;
809
810         if M::enforce_validity(self) {
811             // Data got changed, better make sure it matches the type!
812             self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
813         }
814
815         Ok(())
816     }
817
818     /// Copies the data from an operand to a place. This does not support transmuting!
819     /// Use `copy_op_transmute` if the layouts could disagree.
820     /// Also, if you use this you are responsible for validating that things get copied at the
821     /// right type.
822     fn copy_op_no_validate(
823         &mut self,
824         src: OpTy<'tcx, M::PointerTag>,
825         dest: PlaceTy<'tcx, M::PointerTag>,
826     ) -> InterpResult<'tcx> {
827         // We do NOT compare the types for equality, because well-typed code can
828         // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
829         assert!(src.layout.details == dest.layout.details,
830             "Layout mismatch when copying!\nsrc: {:#?}\ndest: {:#?}", src, dest);
831
832         // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
833         let src = match self.try_read_immediate(src)? {
834             Ok(src_val) => {
835                 assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
836                 // Yay, we got a value that we can write directly.
837                 // FIXME: Add a check to make sure that if `src` is indirect,
838                 // it does not overlap with `dest`.
839                 return self.write_immediate_no_validate(*src_val, dest);
840             }
841             Err(mplace) => mplace,
842         };
843         // Slow path, this does not fit into an immediate. Just memcpy.
844         trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
845
846         // This interprets `src.meta` with the `dest` local's layout, if an unsized local
847         // is being initialized!
848         let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?;
849         let size = size.unwrap_or_else(|| {
850             assert!(!dest.layout.is_unsized(),
851                 "Cannot copy into already initialized unsized place");
852             dest.layout.size
853         });
854         assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
855
856         let src = self.check_mplace_access(src, Some(size))?;
857         let dest = self.check_mplace_access(dest, Some(size))?;
858         let (src_ptr, dest_ptr) = match (src, dest) {
859             (Some(src_ptr), Some(dest_ptr)) => (src_ptr, dest_ptr),
860             (None, None) => return Ok(()), // zero-sized copy
861             _ => bug!("The pointers should both be Some or both None"),
862         };
863
864         self.memory.copy(
865             src_ptr,
866             dest_ptr,
867             size,
868             /*nonoverlapping*/ true,
869         )
870     }
871
872     /// Copies the data from an operand to a place. The layouts may disagree, but they must
873     /// have the same size.
874     pub fn copy_op_transmute(
875         &mut self,
876         src: OpTy<'tcx, M::PointerTag>,
877         dest: PlaceTy<'tcx, M::PointerTag>,
878     ) -> InterpResult<'tcx> {
879         if src.layout.details == dest.layout.details {
880             // Fast path: Just use normal `copy_op`
881             return self.copy_op(src, dest);
882         }
883         // We still require the sizes to match.
884         assert!(src.layout.size == dest.layout.size,
885             "Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
886         // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
887         // to avoid that here.
888         assert!(!src.layout.is_unsized() && !dest.layout.is_unsized(),
889             "Cannot transmute unsized data");
890
891         // The hard case is `ScalarPair`.  `src` is already read from memory in this case,
892         // using `src.layout` to figure out which bytes to use for the 1st and 2nd field.
893         // We have to write them to `dest` at the offsets they were *read at*, which is
894         // not necessarily the same as the offsets in `dest.layout`!
895         // Hence we do the copy with the source layout on both sides.  We also make sure to write
896         // into memory, because if `dest` is a local we would not even have a way to write
897         // at the `src` offsets; the fact that we came from a different layout would
898         // just be lost.
899         let dest = self.force_allocation(dest)?;
900         self.copy_op_no_validate(
901             src,
902             PlaceTy::from(MPlaceTy { mplace: *dest, layout: src.layout }),
903         )?;
904
905         if M::enforce_validity(self) {
906             // Data got changed, better make sure it matches the type!
907             self.validate_operand(dest.into(), vec![], None)?;
908         }
909
910         Ok(())
911     }
912
913     /// Ensures that a place is in memory, and returns where it is.
914     /// If the place currently refers to a local that doesn't yet have a matching allocation,
915     /// create such an allocation.
916     /// This is essentially `force_to_memplace`.
917     ///
918     /// This supports unsized types and returns the computed size to avoid some
919     /// redundant computation when copying; use `force_allocation` for a simpler, sized-only
920     /// version.
921     pub fn force_allocation_maybe_sized(
922         &mut self,
923         place: PlaceTy<'tcx, M::PointerTag>,
924         meta: Option<Scalar<M::PointerTag>>,
925     ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
926         let (mplace, size) = match place.place {
927             Place::Local { frame, local } => {
928                 match self.stack[frame].locals[local].access_mut()? {
929                     Ok(local_val) => {
930                         // We need to make an allocation.
931                         // FIXME: Consider not doing anything for a ZST, and just returning
932                         // a fake pointer?  Are we even called for ZST?
933
934                         // We cannot hold on to the reference `local_val` while allocating,
935                         // but we can hold on to the value in there.
936                         let old_val =
937                             if let LocalValue::Live(Operand::Immediate(value)) = *local_val {
938                                 Some(value)
939                             } else {
940                                 None
941                             };
942
943                         // We need the layout of the local.  We can NOT use the layout we got,
944                         // that might e.g., be an inner field of a struct with `Scalar` layout,
945                         // that has different alignment than the outer field.
946                         // We also need to support unsized types, and hence cannot use `allocate`.
947                         let local_layout = self.layout_of_local(&self.stack[frame], local, None)?;
948                         let (size, align) = self.size_and_align_of(meta, local_layout)?
949                             .expect("Cannot allocate for non-dyn-sized type");
950                         let ptr = self.memory.allocate(size, align, MemoryKind::Stack);
951                         let mplace = MemPlace { ptr: ptr.into(), align, meta };
952                         if let Some(value) = old_val {
953                             // Preserve old value.
954                             // We don't have to validate as we can assume the local
955                             // was already valid for its type.
956                             let mplace = MPlaceTy { mplace, layout: local_layout };
957                             self.write_immediate_to_mplace_no_validate(value, mplace)?;
958                         }
959                         // Now we can call `access_mut` again, asserting it goes well,
960                         // and actually overwrite things.
961                         *self.stack[frame].locals[local].access_mut().unwrap().unwrap() =
962                             LocalValue::Live(Operand::Indirect(mplace));
963                         (mplace, Some(size))
964                     }
965                     Err(mplace) => (mplace, None), // this already was an indirect local
966                 }
967             }
968             Place::Ptr(mplace) => (mplace, None)
969         };
970         // Return with the original layout, so that the caller can go on
971         Ok((MPlaceTy { mplace, layout: place.layout }, size))
972     }
973
974     #[inline(always)]
975     pub fn force_allocation(
976         &mut self,
977         place: PlaceTy<'tcx, M::PointerTag>,
978     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
979         Ok(self.force_allocation_maybe_sized(place, None)?.0)
980     }
981
982     pub fn allocate(
983         &mut self,
984         layout: TyLayout<'tcx>,
985         kind: MemoryKind<M::MemoryKinds>,
986     ) -> MPlaceTy<'tcx, M::PointerTag> {
987         let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
988         MPlaceTy::from_aligned_ptr(ptr, layout)
989     }
990
991     pub fn write_discriminant_index(
992         &mut self,
993         variant_index: VariantIdx,
994         dest: PlaceTy<'tcx, M::PointerTag>,
995     ) -> InterpResult<'tcx> {
996         match dest.layout.variants {
997             layout::Variants::Single { index } => {
998                 assert_eq!(index, variant_index);
999             }
1000             layout::Variants::Multiple {
1001                 discr_kind: layout::DiscriminantKind::Tag,
1002                 ref discr,
1003                 discr_index,
1004                 ..
1005             } => {
1006                 assert!(dest.layout.ty.variant_range(*self.tcx).unwrap().contains(&variant_index));
1007                 let discr_val =
1008                     dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
1009
1010                 // raw discriminants for enums are isize or bigger during
1011                 // their computation, but the in-memory tag is the smallest possible
1012                 // representation
1013                 let size = discr.value.size(self);
1014                 let discr_val = truncate(discr_val, size);
1015
1016                 let discr_dest = self.place_field(dest, discr_index as u64)?;
1017                 self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
1018             }
1019             layout::Variants::Multiple {
1020                 discr_kind: layout::DiscriminantKind::Niche {
1021                     dataful_variant,
1022                     ref niche_variants,
1023                     niche_start,
1024                 },
1025                 discr_index,
1026                 ..
1027             } => {
1028                 assert!(
1029                     variant_index.as_usize() < dest.layout.ty.ty_adt_def().unwrap().variants.len(),
1030                 );
1031                 if variant_index != dataful_variant {
1032                     let niche_dest =
1033                         self.place_field(dest, discr_index as u64)?;
1034                     let niche_value = variant_index.as_u32() - niche_variants.start().as_u32();
1035                     let niche_value = (niche_value as u128)
1036                         .wrapping_add(niche_start);
1037                     self.write_scalar(
1038                         Scalar::from_uint(niche_value, niche_dest.layout.size),
1039                         niche_dest
1040                     )?;
1041                 }
1042             }
1043         }
1044
1045         Ok(())
1046     }
1047
1048     pub fn raw_const_to_mplace(
1049         &self,
1050         raw: RawConst<'tcx>,
1051     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1052         // This must be an allocation in `tcx`
1053         assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1054         let ptr = self.tag_static_base_pointer(Pointer::from(raw.alloc_id));
1055         let layout = self.layout_of(raw.ty)?;
1056         Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
1057     }
1058
1059     /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
1060     /// Also return some more information so drop doesn't have to run the same code twice.
1061     pub(super) fn unpack_dyn_trait(&self, mplace: MPlaceTy<'tcx, M::PointerTag>)
1062     -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1063         let vtable = mplace.vtable(); // also sanity checks the type
1064         let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
1065         let layout = self.layout_of(ty)?;
1066
1067         // More sanity checks
1068         if cfg!(debug_assertions) {
1069             let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
1070             assert_eq!(size, layout.size);
1071             // only ABI alignment is preserved
1072             assert_eq!(align, layout.align.abi);
1073         }
1074
1075         let mplace = MPlaceTy {
1076             mplace: MemPlace { meta: None, ..*mplace },
1077             layout
1078         };
1079         Ok((instance, mplace))
1080     }
1081 }