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