1 //! Computations on places -- field projections, going from mir::Place, and writing
3 //! All high-level functions to write to memory work on places as destinations.
5 use std::convert::TryFrom;
9 use rustc::mir::interpret::truncate;
10 use rustc::ty::{self, Ty};
11 use rustc::ty::layout::{self, Size, Align, LayoutOf, TyLayout, HasDataLayout, VariantIdx};
12 use rustc::ty::TypeFoldable;
15 GlobalId, AllocId, Allocation, Scalar, EvalResult, Pointer, PointerArithmetic,
16 InterpretCx, Machine, AllocMap, AllocationExtra,
17 RawConst, Immediate, ImmTy, ScalarMaybeUndef, Operand, OpTy, MemoryKind, LocalValue
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>,
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>>,
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>),
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`.)
46 #[derive(Copy, Clone, Debug)]
47 pub struct PlaceTy<'tcx, Tag=()> {
49 pub layout: TyLayout<'tcx>,
52 impl<'tcx, Tag> ::std::ops::Deref for PlaceTy<'tcx, Tag> {
53 type Target = Place<Tag>;
55 fn deref(&self) -> &Place<Tag> {
60 /// A MemPlace with its layout. Constructing it is only possible in this module.
61 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
62 pub struct MPlaceTy<'tcx, Tag=()> {
63 mplace: MemPlace<Tag>,
64 pub layout: TyLayout<'tcx>,
67 impl<'tcx, Tag> ::std::ops::Deref for MPlaceTy<'tcx, Tag> {
68 type Target = MemPlace<Tag>;
70 fn deref(&self) -> &MemPlace<Tag> {
75 impl<'tcx, Tag> From<MPlaceTy<'tcx, Tag>> for PlaceTy<'tcx, Tag> {
77 fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
79 place: Place::Ptr(mplace.mplace),
85 impl<Tag> MemPlace<Tag> {
86 /// Replace ptr tag, maintain vtable tag (if any)
88 pub fn replace_tag(self, new_tag: Tag) -> Self {
90 ptr: self.ptr.erase_tag().with_tag(new_tag),
97 pub fn erase_tag(self) -> MemPlace {
99 ptr: self.ptr.erase_tag(),
101 meta: self.meta.map(Scalar::erase_tag),
106 pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
114 /// Produces a Place that will error if attempted to be read from or written to
116 pub fn null(cx: &impl HasDataLayout) -> Self {
117 Self::from_scalar_ptr(Scalar::ptr_null(cx), Align::from_bytes(1).unwrap())
121 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
122 Self::from_scalar_ptr(ptr.into(), align)
126 pub fn to_scalar_ptr_align(self) -> (Scalar<Tag>, Align) {
127 assert!(self.meta.is_none());
128 (self.ptr, self.align)
131 /// metact the ptr part of the mplace
133 pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
134 // At this point, we forget about the alignment information --
135 // the place has been turned into a reference, and no matter where it came from,
136 // it now must be aligned.
137 self.to_scalar_ptr_align().0.to_ptr()
140 /// Turn a mplace into a (thin or fat) pointer, as a reference, pointing to the same space.
141 /// This is the inverse of `ref_to_mplace`.
143 pub fn to_ref(self) -> Immediate<Tag> {
145 None => Immediate::Scalar(self.ptr.into()),
146 Some(meta) => Immediate::ScalarPair(self.ptr.into(), meta.into()),
153 meta: Option<Scalar<Tag>>,
154 cx: &impl HasDataLayout,
155 ) -> EvalResult<'tcx, Self> {
157 ptr: self.ptr.ptr_offset(offset, cx)?,
158 align: self.align.restrict_for_offset(offset),
164 impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
165 /// Produces a MemPlace that works for ZST but nothing else
167 pub fn dangling(layout: TyLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
169 mplace: MemPlace::from_scalar_ptr(
170 Scalar::from_uint(layout.align.abi.bytes(), cx.pointer_size()),
177 /// Replace ptr tag, maintain vtable tag (if any)
179 pub fn replace_tag(self, new_tag: Tag) -> Self {
181 mplace: self.mplace.replace_tag(new_tag),
190 meta: Option<Scalar<Tag>>,
191 layout: TyLayout<'tcx>,
192 cx: &impl HasDataLayout,
193 ) -> EvalResult<'tcx, Self> {
195 mplace: self.mplace.offset(offset, meta, cx)?,
201 fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyLayout<'tcx>) -> Self {
202 MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
206 pub(super) fn len(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, u64> {
207 if self.layout.is_unsized() {
208 // We need to consult `meta` metadata
209 match self.layout.ty.sty {
210 ty::Slice(..) | ty::Str =>
211 return self.mplace.meta.unwrap().to_usize(cx),
212 _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
215 // Go through the layout. There are lots of types that support a length,
217 match self.layout.fields {
218 layout::FieldPlacement::Array { count, .. } => Ok(count),
219 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
225 pub(super) fn vtable(self) -> EvalResult<'tcx, Pointer<Tag>> {
226 match self.layout.ty.sty {
227 ty::Dynamic(..) => self.mplace.meta.unwrap().to_ptr(),
228 _ => bug!("vtable not supported on type {:?}", self.layout.ty),
233 impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
235 pub fn try_as_mplace(self) -> Result<MPlaceTy<'tcx, Tag>, Immediate<Tag>> {
237 Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
238 Operand::Immediate(imm) => Err(imm),
243 pub fn to_mem_place(self) -> MPlaceTy<'tcx, Tag> {
244 self.try_as_mplace().unwrap()
248 impl<'tcx, Tag: ::std::fmt::Debug> Place<Tag> {
249 /// Produces a Place that will error if attempted to be read from or written to
251 pub fn null(cx: &impl HasDataLayout) -> Self {
252 Place::Ptr(MemPlace::null(cx))
256 pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
257 Place::Ptr(MemPlace::from_scalar_ptr(ptr, align))
261 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
262 Place::Ptr(MemPlace::from_ptr(ptr, align))
266 pub fn to_mem_place(self) -> MemPlace<Tag> {
268 Place::Ptr(mplace) => mplace,
269 _ => bug!("to_mem_place: expected Place::Ptr, got {:?}", self),
275 pub fn to_scalar_ptr_align(self) -> (Scalar<Tag>, Align) {
276 self.to_mem_place().to_scalar_ptr_align()
280 pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
281 self.to_mem_place().to_ptr()
285 impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
287 pub fn to_mem_place(self) -> MPlaceTy<'tcx, Tag> {
288 MPlaceTy { mplace: self.place.to_mem_place(), layout: self.layout }
292 // separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
293 impl<'a, 'mir, 'tcx, Tag, M> InterpretCx<'a, 'mir, 'tcx, M>
295 // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
296 Tag: ::std::fmt::Debug + Copy + Eq + Hash + 'static,
297 M: Machine<'a, 'mir, 'tcx, PointerTag=Tag>,
298 // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
299 M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation<Tag, M::AllocExtra>)>,
300 M::AllocExtra: AllocationExtra<Tag>,
302 /// Take a value, which represents a (thin or fat) reference, and make it a place.
303 /// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`.
304 /// This does NOT call the "deref" machine hook, so it does NOT count as a
305 /// deref as far as Stacked Borrows is concerned. Use `deref_operand` for that!
306 pub fn ref_to_mplace(
308 val: ImmTy<'tcx, M::PointerTag>,
309 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
310 let pointee_type = val.layout.ty.builtin_deref(true).unwrap().ty;
311 let layout = self.layout_of(pointee_type)?;
313 let mplace = MemPlace {
314 ptr: val.to_scalar_ptr()?,
315 // We could use the run-time alignment here. For now, we do not, because
316 // the point of tracking the alignment here is to make sure that the *static*
317 // alignment information emitted with the loads is correct. The run-time
318 // alignment can only be more restrictive.
319 align: layout.align.abi,
320 meta: val.to_meta()?,
322 Ok(MPlaceTy { mplace, layout })
325 // Take an operand, representing a pointer, and dereference it to a place -- that
326 // will always be a MemPlace. Lives in `place.rs` because it creates a place.
327 pub fn deref_operand(
329 src: OpTy<'tcx, M::PointerTag>,
330 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
331 let val = self.read_immediate(src)?;
332 trace!("deref to {} on {:?}", val.layout.ty, *val);
333 self.ref_to_mplace(val)
336 /// Offset a pointer to project to a field. Unlike `place_field`, this is always
337 /// possible without allocating, so it can take `&self`. Also return the field's layout.
338 /// This supports both struct and array fields.
342 base: MPlaceTy<'tcx, M::PointerTag>,
344 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
345 // Not using the layout method because we want to compute on u64
346 let offset = match base.layout.fields {
347 layout::FieldPlacement::Arbitrary { ref offsets, .. } =>
348 offsets[usize::try_from(field).unwrap()],
349 layout::FieldPlacement::Array { stride, .. } => {
350 let len = base.len(self)?;
351 assert!(field < len, "Tried to access element {} of array/slice with length {}",
355 layout::FieldPlacement::Union(count) => {
356 assert!(field < count as u64,
357 "Tried to access field {} of union with {} fields", field, count);
358 // Offset is always 0
362 // the only way conversion can fail if is this is an array (otherwise we already panicked
363 // above). In that case, all fields are equal.
364 let field_layout = base.layout.field(self, usize::try_from(field).unwrap_or(0))?;
366 // Offset may need adjustment for unsized fields.
367 let (meta, offset) = if field_layout.is_unsized() {
368 // Re-use parent metadata to determine dynamic field layout.
369 // With custom DSTS, this *will* execute user-defined code, but the same
370 // happens at run-time so that's okay.
371 let align = match self.size_and_align_of(base.meta, field_layout)? {
372 Some((_, align)) => align,
373 None if offset == Size::ZERO =>
374 // An extern type at offset 0, we fall back to its static alignment.
375 // FIXME: Once we have made decisions for how to handle size and alignment
376 // of `extern type`, this should be adapted. It is just a temporary hack
377 // to get some code to work that probably ought to work.
378 field_layout.align.abi,
380 bug!("Cannot compute offset for extern type field at non-0 offset"),
382 (base.meta, offset.align_to(align))
384 // base.meta could be present; we might be accessing a sized field of an unsized
389 // We do not look at `base.layout.align` nor `field_layout.align`, unlike
390 // codegen -- mostly to see if we can get away with that
391 base.offset(offset, meta, field_layout, self)
394 // Iterates over all fields of an array. Much more efficient than doing the
395 // same by repeatedly calling `mplace_array`.
396 pub fn mplace_array_fields(
398 base: MPlaceTy<'tcx, Tag>,
400 EvalResult<'tcx, impl Iterator<Item=EvalResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'a>
402 let len = base.len(self)?; // also asserts that we have a type where this makes sense
403 let stride = match base.layout.fields {
404 layout::FieldPlacement::Array { stride, .. } => stride,
405 _ => bug!("mplace_array_fields: expected an array layout"),
407 let layout = base.layout.field(self, 0)?;
408 let dl = &self.tcx.data_layout;
409 Ok((0..len).map(move |i| base.offset(i * stride, None, layout, dl)))
412 pub fn mplace_subslice(
414 base: MPlaceTy<'tcx, M::PointerTag>,
417 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
418 let len = base.len(self)?; // also asserts that we have a type where this makes sense
419 assert!(from <= len - to);
421 // Not using layout method because that works with usize, and does not work with slices
422 // (that have count 0 in their layout).
423 let from_offset = match base.layout.fields {
424 layout::FieldPlacement::Array { stride, .. } =>
426 _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
429 // Compute meta and new layout
430 let inner_len = len - to - from;
431 let (meta, ty) = match base.layout.ty.sty {
432 // It is not nice to match on the type, but that seems to be the only way to
434 ty::Array(inner, _) =>
435 (None, self.tcx.mk_array(inner, inner_len)),
437 let len = Scalar::from_uint(inner_len, self.pointer_size());
438 (Some(len), base.layout.ty)
441 bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
443 let layout = self.layout_of(ty)?;
444 base.offset(from_offset, meta, layout, self)
447 pub fn mplace_downcast(
449 base: MPlaceTy<'tcx, M::PointerTag>,
451 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
452 // Downcasts only change the layout
453 assert!(base.meta.is_none());
454 Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
457 /// Project into an mplace
458 pub fn mplace_projection(
460 base: MPlaceTy<'tcx, M::PointerTag>,
461 proj_elem: &mir::PlaceElem<'tcx>,
462 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
463 use rustc::mir::ProjectionElem::*;
464 Ok(match *proj_elem {
465 Field(field, _) => self.mplace_field(base, field.index() as u64)?,
466 Downcast(_, variant) => self.mplace_downcast(base, variant)?,
467 Deref => self.deref_operand(base.into())?,
470 let layout = self.layout_of(self.tcx.types.usize)?;
471 let n = self.access_local(self.frame(), local, Some(layout))?;
472 let n = self.read_scalar(n)?;
473 let n = n.to_bits(self.tcx.data_layout.pointer_size)?;
474 self.mplace_field(base, u64::try_from(n).unwrap())?
482 let n = base.len(self)?;
483 assert!(n >= min_length as u64);
485 let index = if from_end {
486 n - u64::from(offset)
491 self.mplace_field(base, index)?
494 Subslice { from, to } =>
495 self.mplace_subslice(base, u64::from(from), u64::from(to))?,
499 /// Gets the place of a field inside the place, and also the field's type.
500 /// Just a convenience function, but used quite a bit.
501 /// This is the only projection that might have a side-effect: We cannot project
502 /// into the field of a local `ScalarPair`, we have to first allocate it.
505 base: PlaceTy<'tcx, M::PointerTag>,
507 ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
508 // FIXME: We could try to be smarter and avoid allocation for fields that span the
510 let mplace = self.force_allocation(base)?;
511 Ok(self.mplace_field(mplace, field)?.into())
514 pub fn place_downcast(
516 base: PlaceTy<'tcx, M::PointerTag>,
518 ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
519 // Downcast just changes the layout
520 Ok(match base.place {
521 Place::Ptr(mplace) =>
522 self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into(),
523 Place::Local { .. } => {
524 let layout = base.layout.for_variant(self, variant);
525 PlaceTy { layout, ..base }
530 /// Projects into a place.
531 pub fn place_projection(
533 base: PlaceTy<'tcx, M::PointerTag>,
534 proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
535 ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
536 use rustc::mir::ProjectionElem::*;
537 Ok(match *proj_elem {
538 Field(field, _) => self.place_field(base, field.index() as u64)?,
539 Downcast(_, variant) => self.place_downcast(base, variant)?,
540 Deref => self.deref_operand(self.place_to_op(base)?)?.into(),
541 // For the other variants, we have to force an allocation.
542 // This matches `operand_projection`.
543 Subslice { .. } | ConstantIndex { .. } | Index(_) => {
544 let mplace = self.force_allocation(base)?;
545 self.mplace_projection(mplace, proj_elem)?.into()
550 /// Evaluate statics and promoteds to an `MPlace`. Used to share some code between
551 /// `eval_place` and `eval_place_to_op`.
552 pub(super) fn eval_static_to_mplace(
554 place_static: &mir::Static<'tcx>
555 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
556 use rustc::mir::StaticKind;
558 Ok(match place_static.kind {
559 StaticKind::Promoted(promoted) => {
560 let instance = self.frame().instance;
561 self.const_eval_raw(GlobalId {
563 promoted: Some(promoted),
567 StaticKind::Static(def_id) => {
568 let ty = place_static.ty;
569 assert!(!ty.needs_subst());
570 let layout = self.layout_of(ty)?;
571 let instance = ty::Instance::mono(*self.tcx, def_id);
576 // Just create a lazy reference, so we can support recursive statics.
577 // tcx takes care of assigning every static one and only one unique AllocId.
578 // When the data here is ever actually used, memory will notice,
579 // and it knows how to deal with alloc_id that are present in the
580 // global table but not in its local memory: It calls back into tcx through
581 // a query, triggering the CTFE machinery to actually turn this lazy reference
582 // into a bunch of bytes. IOW, statics are evaluated with CTFE even when
583 // this InterpretCx uses another Machine (e.g., in miri). This is what we
584 // want! This way, computing statics works consistently between codegen
585 // and miri: They use the same query to eventually obtain a `ty::Const`
586 // and use that for further computation.
588 // Notice that statics have *two* AllocIds: the lazy one, and the resolved
589 // one. Here we make sure that the interpreted program never sees the
590 // resolved ID. Also see the doc comment of `Memory::get_static_alloc`.
591 let alloc_id = self.tcx.alloc_map.lock().create_static_alloc(cid.instance.def_id());
592 let ptr = self.tag_static_base_pointer(Pointer::from(alloc_id));
593 MPlaceTy::from_aligned_ptr(ptr, layout)
598 /// Computes a place. You should only use this if you intend to write into this
599 /// place; for reading, a more efficient alternative is `eval_place_for_read`.
602 mir_place: &mir::Place<'tcx>,
603 ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
604 use rustc::mir::PlaceBase;
606 mir_place.iterate(|place_base, place_projection| {
607 let mut place = match place_base {
608 PlaceBase::Local(mir::RETURN_PLACE) => match self.frame().return_place {
609 Some(return_place) => {
610 // We use our layout to verify our assumption; caller will validate
611 // their layout on return.
613 place: *return_place,
615 .layout_of(self.monomorphize(self.frame().mir.return_ty())?)?,
618 None => return err!(InvalidNullPointerUsage),
620 PlaceBase::Local(local) => PlaceTy {
621 // This works even for dead/uninitialized locals; we check further when writing
622 place: Place::Local {
623 frame: self.cur_frame(),
626 layout: self.layout_of_local(self.frame(), *local, None)?,
628 PlaceBase::Static(place_static) => self.eval_static_to_mplace(place_static)?.into(),
631 for proj in place_projection {
632 place = self.place_projection(place, &proj.elem)?
635 self.dump_place(place.place);
640 /// Write a scalar to a place
643 val: impl Into<ScalarMaybeUndef<M::PointerTag>>,
644 dest: PlaceTy<'tcx, M::PointerTag>,
645 ) -> EvalResult<'tcx> {
646 self.write_immediate(Immediate::Scalar(val.into()), dest)
649 /// Write an immediate to a place
651 pub fn write_immediate(
653 src: Immediate<M::PointerTag>,
654 dest: PlaceTy<'tcx, M::PointerTag>,
655 ) -> EvalResult<'tcx> {
656 self.write_immediate_no_validate(src, dest)?;
658 if M::enforce_validity(self) {
659 // Data got changed, better make sure it matches the type!
660 self.validate_operand(self.place_to_op(dest)?, vec![], None, /*const_mode*/false)?;
666 /// Write an immediate to a place.
667 /// If you use this you are responsible for validating that things got copied at the
669 fn write_immediate_no_validate(
671 src: Immediate<M::PointerTag>,
672 dest: PlaceTy<'tcx, M::PointerTag>,
673 ) -> EvalResult<'tcx> {
674 if cfg!(debug_assertions) {
675 // This is a very common path, avoid some checks in release mode
676 assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
678 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Ptr(_))) =>
679 assert_eq!(self.pointer_size(), dest.layout.size,
680 "Size mismatch when writing pointer"),
681 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Raw { size, .. })) =>
682 assert_eq!(Size::from_bytes(size.into()), dest.layout.size,
683 "Size mismatch when writing bits"),
684 Immediate::Scalar(ScalarMaybeUndef::Undef) => {}, // undef can have any size
685 Immediate::ScalarPair(_, _) => {
686 // FIXME: Can we check anything here?
690 trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
692 // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
693 // but not factored as a separate function.
694 let mplace = match dest.place {
695 Place::Local { frame, local } => {
696 match self.stack[frame].locals[local].access_mut()? {
698 // Local can be updated in-place.
699 *local = LocalValue::Live(Operand::Immediate(src));
703 // The local is in memory, go on below.
708 Place::Ptr(mplace) => mplace, // already referring to memory
710 let dest = MPlaceTy { mplace, layout: dest.layout };
712 // This is already in memory, write there.
713 self.write_immediate_to_mplace_no_validate(src, dest)
716 /// Write an immediate to memory.
717 /// If you use this you are responsible for validating that things got copied at the
719 fn write_immediate_to_mplace_no_validate(
721 value: Immediate<M::PointerTag>,
722 dest: MPlaceTy<'tcx, M::PointerTag>,
723 ) -> EvalResult<'tcx> {
724 let (ptr, ptr_align) = dest.to_scalar_ptr_align();
725 // Note that it is really important that the type here is the right one, and matches the
726 // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
727 // to handle padding properly, which is only correct if we never look at this data with the
730 // Nothing to do for ZSTs, other than checking alignment
731 if dest.layout.is_zst() {
732 return self.memory.check_align(ptr, ptr_align);
735 // check for integer pointers before alignment to report better errors
736 let ptr = ptr.to_ptr()?;
737 self.memory.check_align(ptr.into(), ptr_align)?;
738 let tcx = &*self.tcx;
739 // FIXME: We should check that there are dest.layout.size many bytes available in
740 // memory. The code below is not sufficient, with enough padding it might not
741 // cover all the bytes!
743 Immediate::Scalar(scalar) => {
744 match dest.layout.abi {
745 layout::Abi::Scalar(_) => {}, // fine
746 _ => bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}",
749 self.memory.get_mut(ptr.alloc_id)?.write_scalar(
750 tcx, ptr, scalar, dest.layout.size
753 Immediate::ScalarPair(a_val, b_val) => {
754 let (a, b) = match dest.layout.abi {
755 layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
756 _ => bug!("write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
759 let (a_size, b_size) = (a.size(self), b.size(self));
760 let b_offset = a_size.align_to(b.align(self).abi);
761 let b_align = ptr_align.restrict_for_offset(b_offset);
762 let b_ptr = ptr.offset(b_offset, self)?;
764 self.memory.check_align(b_ptr.into(), b_align)?;
766 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
767 // but that does not work: We could be a newtype around a pair, then the
768 // fields do not match the `ScalarPair` components.
771 .get_mut(ptr.alloc_id)?
772 .write_scalar(tcx, ptr, a_val, a_size)?;
774 .get_mut(b_ptr.alloc_id)?
775 .write_scalar(tcx, b_ptr, b_val, b_size)
780 /// Copies the data from an operand to a place. This does not support transmuting!
781 /// Use `copy_op_transmute` if the layouts could disagree.
785 src: OpTy<'tcx, M::PointerTag>,
786 dest: PlaceTy<'tcx, M::PointerTag>,
787 ) -> EvalResult<'tcx> {
788 self.copy_op_no_validate(src, dest)?;
790 if M::enforce_validity(self) {
791 // Data got changed, better make sure it matches the type!
792 self.validate_operand(self.place_to_op(dest)?, vec![], None, /*const_mode*/false)?;
798 /// Copies the data from an operand to a place. This does not support transmuting!
799 /// Use `copy_op_transmute` if the layouts could disagree.
800 /// Also, if you use this you are responsible for validating that things get copied at the
802 fn copy_op_no_validate(
804 src: OpTy<'tcx, M::PointerTag>,
805 dest: PlaceTy<'tcx, M::PointerTag>,
806 ) -> EvalResult<'tcx> {
807 // We do NOT compare the types for equality, because well-typed code can
808 // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
809 assert!(src.layout.details == dest.layout.details,
810 "Layout mismatch when copying!\nsrc: {:#?}\ndest: {:#?}", src, dest);
812 // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
813 let src = match self.try_read_immediate(src)? {
815 assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
816 // Yay, we got a value that we can write directly.
817 // FIXME: Add a check to make sure that if `src` is indirect,
818 // it does not overlap with `dest`.
819 return self.write_immediate_no_validate(src_val, dest);
821 Err(mplace) => mplace,
823 // Slow path, this does not fit into an immediate. Just memcpy.
824 trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
826 // This interprets `src.meta` with the `dest` local's layout, if an unsized local
827 // is being initialized!
828 let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?;
829 let size = size.unwrap_or_else(|| {
830 assert!(!dest.layout.is_unsized(),
831 "Cannot copy into already initialized unsized place");
834 assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
837 dest.ptr, dest.align,
839 /*nonoverlapping*/ true,
845 /// Copies the data from an operand to a place. The layouts may disagree, but they must
846 /// have the same size.
847 pub fn copy_op_transmute(
849 src: OpTy<'tcx, M::PointerTag>,
850 dest: PlaceTy<'tcx, M::PointerTag>,
851 ) -> EvalResult<'tcx> {
852 if src.layout.details == dest.layout.details {
853 // Fast path: Just use normal `copy_op`
854 return self.copy_op(src, dest);
856 // We still require the sizes to match.
857 assert!(src.layout.size == dest.layout.size,
858 "Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
859 // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
860 // to avoid that here.
861 assert!(!src.layout.is_unsized() && !dest.layout.is_unsized(),
862 "Cannot transmute unsized data");
864 // The hard case is `ScalarPair`. `src` is already read from memory in this case,
865 // using `src.layout` to figure out which bytes to use for the 1st and 2nd field.
866 // We have to write them to `dest` at the offsets they were *read at*, which is
867 // not necessarily the same as the offsets in `dest.layout`!
868 // Hence we do the copy with the source layout on both sides. We also make sure to write
869 // into memory, because if `dest` is a local we would not even have a way to write
870 // at the `src` offsets; the fact that we came from a different layout would
872 let dest = self.force_allocation(dest)?;
873 self.copy_op_no_validate(
875 PlaceTy::from(MPlaceTy { mplace: *dest, layout: src.layout }),
878 if M::enforce_validity(self) {
879 // Data got changed, better make sure it matches the type!
880 self.validate_operand(dest.into(), vec![], None, /*const_mode*/false)?;
886 /// Ensures that a place is in memory, and returns where it is.
887 /// If the place currently refers to a local that doesn't yet have a matching allocation,
888 /// create such an allocation.
889 /// This is essentially `force_to_memplace`.
891 /// This supports unsized types and returns the computed size to avoid some
892 /// redundant computation when copying; use `force_allocation` for a simpler, sized-only
894 pub fn force_allocation_maybe_sized(
896 place: PlaceTy<'tcx, M::PointerTag>,
897 meta: Option<Scalar<M::PointerTag>>,
898 ) -> EvalResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
899 let (mplace, size) = match place.place {
900 Place::Local { frame, local } => {
901 match self.stack[frame].locals[local].access_mut()? {
903 // We need to make an allocation.
904 // FIXME: Consider not doing anything for a ZST, and just returning
905 // a fake pointer? Are we even called for ZST?
907 // We cannot hold on to the reference `local_val` while allocating,
908 // but we can hold on to the value in there.
910 if let LocalValue::Live(Operand::Immediate(value)) = *local_val {
916 // We need the layout of the local. We can NOT use the layout we got,
917 // that might e.g., be an inner field of a struct with `Scalar` layout,
918 // that has different alignment than the outer field.
919 // We also need to support unsized types, and hence cannot use `allocate`.
920 let local_layout = self.layout_of_local(&self.stack[frame], local, None)?;
921 let (size, align) = self.size_and_align_of(meta, local_layout)?
922 .expect("Cannot allocate for non-dyn-sized type");
923 let ptr = self.memory.allocate(size, align, MemoryKind::Stack);
924 let mplace = MemPlace { ptr: ptr.into(), align, meta };
925 if let Some(value) = old_val {
926 // Preserve old value.
927 // We don't have to validate as we can assume the local
928 // was already valid for its type.
929 let mplace = MPlaceTy { mplace, layout: local_layout };
930 self.write_immediate_to_mplace_no_validate(value, mplace)?;
932 // Now we can call `access_mut` again, asserting it goes well,
933 // and actually overwrite things.
934 *self.stack[frame].locals[local].access_mut().unwrap().unwrap() =
935 LocalValue::Live(Operand::Indirect(mplace));
938 Err(mplace) => (mplace, None), // this already was an indirect local
941 Place::Ptr(mplace) => (mplace, None)
943 // Return with the original layout, so that the caller can go on
944 Ok((MPlaceTy { mplace, layout: place.layout }, size))
948 pub fn force_allocation(
950 place: PlaceTy<'tcx, M::PointerTag>,
951 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
952 Ok(self.force_allocation_maybe_sized(place, None)?.0)
957 layout: TyLayout<'tcx>,
958 kind: MemoryKind<M::MemoryKinds>,
959 ) -> MPlaceTy<'tcx, M::PointerTag> {
960 let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
961 MPlaceTy::from_aligned_ptr(ptr, layout)
964 pub fn write_discriminant_index(
966 variant_index: VariantIdx,
967 dest: PlaceTy<'tcx, M::PointerTag>,
968 ) -> EvalResult<'tcx> {
969 match dest.layout.variants {
970 layout::Variants::Single { index } => {
971 assert_eq!(index, variant_index);
973 layout::Variants::Multiple {
974 discr_kind: layout::DiscriminantKind::Tag,
979 assert!(dest.layout.ty.variant_range(*self.tcx).unwrap().contains(&variant_index));
981 dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
983 // raw discriminants for enums are isize or bigger during
984 // their computation, but the in-memory tag is the smallest possible
986 let size = discr.value.size(self);
987 let discr_val = truncate(discr_val, size);
989 let discr_dest = self.place_field(dest, discr_index as u64)?;
990 self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
992 layout::Variants::Multiple {
993 discr_kind: layout::DiscriminantKind::Niche {
1002 variant_index.as_usize() < dest.layout.ty.ty_adt_def().unwrap().variants.len(),
1004 if variant_index != dataful_variant {
1006 self.place_field(dest, discr_index as u64)?;
1007 let niche_value = variant_index.as_u32() - niche_variants.start().as_u32();
1008 let niche_value = (niche_value as u128)
1009 .wrapping_add(niche_start);
1011 Scalar::from_uint(niche_value, niche_dest.layout.size),
1021 pub fn raw_const_to_mplace(
1023 raw: RawConst<'tcx>,
1024 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1025 // This must be an allocation in `tcx`
1026 assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1027 let ptr = self.tag_static_base_pointer(Pointer::from(raw.alloc_id));
1028 let layout = self.layout_of(raw.ty)?;
1029 Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
1032 /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
1033 /// Also return some more information so drop doesn't have to run the same code twice.
1034 pub(super) fn unpack_dyn_trait(&self, mplace: MPlaceTy<'tcx, M::PointerTag>)
1035 -> EvalResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1036 let vtable = mplace.vtable()?; // also sanity checks the type
1037 let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
1038 let layout = self.layout_of(ty)?;
1040 // More sanity checks
1041 if cfg!(debug_assertions) {
1042 let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
1043 assert_eq!(size, layout.size);
1044 // only ABI alignment is preserved
1045 assert_eq!(align, layout.align.abi);
1048 let mplace = MPlaceTy {
1049 mplace: MemPlace { meta: None, ..*mplace },
1052 Ok((instance, mplace))