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