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