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