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::layout::{
11 self, Align, HasDataLayout, LayoutOf, PrimitiveExt, Size, TyLayout, VariantIdx,
13 use rustc::ty::TypeFoldable;
14 use rustc::ty::{self, Ty};
15 use rustc_macros::HashStable;
18 AllocId, AllocMap, Allocation, AllocationExtra, GlobalId, ImmTy, Immediate, InterpCx,
19 InterpResult, LocalValue, Machine, MemoryKind, OpTy, Operand, Pointer, PointerArithmetic,
20 RawConst, Scalar, ScalarMaybeUndef,
23 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
24 pub struct MemPlace<Tag = (), Id = AllocId> {
25 /// A place may have an integral pointer for ZSTs, and since it might
26 /// be turned back into a reference before ever being dereferenced.
27 /// However, it may never be undef.
28 pub ptr: Scalar<Tag, Id>,
30 /// Metadata for unsized places. Interpretation is up to the type.
31 /// Must not be present for sized types, but can be missing for unsized types
32 /// (e.g., `extern type`).
33 pub meta: Option<Scalar<Tag, Id>>,
36 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
37 pub enum Place<Tag = (), Id = AllocId> {
38 /// A place referring to a value allocated in the `Memory` system.
39 Ptr(MemPlace<Tag, Id>),
41 /// To support alloc-free locals, we are able to write directly to a local.
42 /// (Without that optimization, we'd just always be a `MemPlace`.)
43 Local { frame: usize, local: mir::Local },
46 #[derive(Copy, Clone, Debug)]
47 pub struct PlaceTy<'tcx, Tag = ()> {
48 place: Place<Tag>, // Keep this private; it helps enforce invariants.
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 {
78 PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout }
82 impl<Tag> MemPlace<Tag> {
83 /// Replace ptr tag, maintain vtable tag (if any)
85 pub fn replace_tag(self, new_tag: Tag) -> Self {
86 MemPlace { ptr: self.ptr.erase_tag().with_tag(new_tag), align: self.align, meta: self.meta }
90 pub fn erase_tag(self) -> MemPlace {
92 ptr: self.ptr.erase_tag(),
94 meta: self.meta.map(Scalar::erase_tag),
99 pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
100 MemPlace { ptr, align, meta: None }
103 /// Produces a Place that will error if attempted to be read from or written to
105 pub fn null(cx: &impl HasDataLayout) -> Self {
106 Self::from_scalar_ptr(Scalar::ptr_null(cx), Align::from_bytes(1).unwrap())
110 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
111 Self::from_scalar_ptr(ptr.into(), align)
114 /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
115 /// This is the inverse of `ref_to_mplace`.
117 pub fn to_ref(self) -> Immediate<Tag> {
119 None => Immediate::Scalar(self.ptr.into()),
120 Some(meta) => Immediate::ScalarPair(self.ptr.into(), meta.into()),
127 meta: Option<Scalar<Tag>>,
128 cx: &impl HasDataLayout,
129 ) -> InterpResult<'tcx, Self> {
131 ptr: self.ptr.ptr_offset(offset, cx)?,
132 align: self.align.restrict_for_offset(offset),
138 impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
139 /// Produces a MemPlace that works for ZST but nothing else
141 pub fn dangling(layout: TyLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
143 mplace: MemPlace::from_scalar_ptr(
144 Scalar::from_uint(layout.align.abi.bytes(), cx.pointer_size()),
151 /// Replace ptr tag, maintain vtable tag (if any)
153 pub fn replace_tag(self, new_tag: Tag) -> Self {
154 MPlaceTy { mplace: self.mplace.replace_tag(new_tag), layout: self.layout }
161 meta: Option<Scalar<Tag>>,
162 layout: TyLayout<'tcx>,
163 cx: &impl HasDataLayout,
164 ) -> InterpResult<'tcx, Self> {
165 Ok(MPlaceTy { mplace: self.mplace.offset(offset, meta, cx)?, layout })
169 fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyLayout<'tcx>) -> Self {
170 MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
174 pub(super) fn len(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
175 if self.layout.is_unsized() {
176 // We need to consult `meta` metadata
177 match self.layout.ty.kind {
178 ty::Slice(..) | ty::Str => return self.mplace.meta.unwrap().to_machine_usize(cx),
179 _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
182 // Go through the layout. There are lots of types that support a length,
184 match self.layout.fields {
185 layout::FieldPlacement::Array { count, .. } => Ok(count),
186 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
192 pub(super) fn vtable(self) -> Scalar<Tag> {
193 match self.layout.ty.kind {
194 ty::Dynamic(..) => self.mplace.meta.unwrap(),
195 _ => bug!("vtable not supported on type {:?}", self.layout.ty),
200 // These are defined here because they produce a place.
201 impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
203 pub fn try_as_mplace(self) -> Result<MPlaceTy<'tcx, Tag>, ImmTy<'tcx, Tag>> {
205 Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
206 Operand::Immediate(imm) => Err(ImmTy { imm, layout: self.layout }),
211 pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
212 self.try_as_mplace().unwrap()
216 impl<Tag: ::std::fmt::Debug> Place<Tag> {
217 /// Produces a Place that will error if attempted to be read from or written to
219 pub fn null(cx: &impl HasDataLayout) -> Self {
220 Place::Ptr(MemPlace::null(cx))
224 pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
225 Place::Ptr(MemPlace::from_scalar_ptr(ptr, align))
229 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
230 Place::Ptr(MemPlace::from_ptr(ptr, align))
234 pub fn assert_mem_place(self) -> MemPlace<Tag> {
236 Place::Ptr(mplace) => mplace,
237 _ => bug!("assert_mem_place: expected Place::Ptr, got {:?}", self),
242 impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
244 pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
245 MPlaceTy { mplace: self.place.assert_mem_place(), layout: self.layout }
249 // separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
250 impl<'mir, 'tcx, Tag, M> InterpCx<'mir, 'tcx, M>
252 // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
253 Tag: ::std::fmt::Debug + Copy + Eq + Hash + 'static,
254 M: Machine<'mir, 'tcx, PointerTag = Tag>,
255 // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
256 M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation<Tag, M::AllocExtra>)>,
257 M::AllocExtra: AllocationExtra<Tag>,
259 /// Take a value, which represents a (thin or wide) reference, and make it a place.
260 /// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`.
262 /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
263 /// want to ever use the place for memory access!
264 /// Generally prefer `deref_operand`.
265 pub fn ref_to_mplace(
267 val: ImmTy<'tcx, M::PointerTag>,
268 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
270 val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty;
271 let layout = self.layout_of(pointee_type)?;
272 let (ptr, meta) = match *val {
273 Immediate::Scalar(ptr) => (ptr.not_undef()?, None),
274 Immediate::ScalarPair(ptr, meta) => (ptr.not_undef()?, Some(meta.not_undef()?)),
277 let mplace = MemPlace {
279 // We could use the run-time alignment here. For now, we do not, because
280 // the point of tracking the alignment here is to make sure that the *static*
281 // alignment information emitted with the loads is correct. The run-time
282 // alignment can only be more restrictive.
283 align: layout.align.abi,
286 Ok(MPlaceTy { mplace, layout })
289 /// Take an operand, representing a pointer, and dereference it to a place -- that
290 /// will always be a MemPlace. Lives in `place.rs` because it creates a place.
291 pub fn deref_operand(
293 src: OpTy<'tcx, M::PointerTag>,
294 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
295 let val = self.read_immediate(src)?;
296 trace!("deref to {} on {:?}", val.layout.ty, *val);
297 let place = self.ref_to_mplace(val)?;
298 self.mplace_access_checked(place)
301 /// Check if the given place is good for memory access with the given
302 /// size, falling back to the layout's size if `None` (in the latter case,
303 /// this must be a statically sized type).
305 /// On success, returns `None` for zero-sized accesses (where nothing else is
306 /// left to do) and a `Pointer` to use for the actual access otherwise.
308 pub fn check_mplace_access(
310 place: MPlaceTy<'tcx, M::PointerTag>,
312 ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
313 let size = size.unwrap_or_else(|| {
314 assert!(!place.layout.is_unsized());
315 assert!(place.meta.is_none());
318 self.memory.check_ptr_access(place.ptr, size, place.align)
321 /// Return the "access-checked" version of this `MPlace`, where for non-ZST
322 /// this is definitely a `Pointer`.
323 pub fn mplace_access_checked(
325 mut place: MPlaceTy<'tcx, M::PointerTag>,
326 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
327 let (size, align) = self
328 .size_and_align_of_mplace(place)?
329 .unwrap_or((place.layout.size, place.layout.align.abi));
330 assert!(place.mplace.align <= align, "dynamic alignment less strict than static one?");
331 place.mplace.align = align; // maximally strict checking
332 // When dereferencing a pointer, it must be non-NULL, aligned, and live.
333 if let Some(ptr) = self.check_mplace_access(place, Some(size))? {
334 place.mplace.ptr = ptr.into();
339 /// Force `place.ptr` to a `Pointer`.
340 /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
341 pub fn force_mplace_ptr(
343 mut place: MPlaceTy<'tcx, M::PointerTag>,
344 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
345 place.mplace.ptr = self.force_ptr(place.mplace.ptr)?.into();
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.
355 base: MPlaceTy<'tcx, M::PointerTag>,
357 ) -> InterpResult<'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()]
363 layout::FieldPlacement::Array { stride, .. } => {
364 let len = base.len(self)?;
366 // This can only be reached in ConstProp and non-rustc-MIR.
367 throw_ub!(BoundsCheckFailed { len, index: field });
371 layout::FieldPlacement::Union(count) => {
373 field < count as u64,
374 "Tried to access field {} of union {:#?} with {} fields",
379 // Offset is always 0
383 // the only way conversion can fail if is this is an array (otherwise we already panicked
384 // above). In that case, all fields are equal.
385 let field_layout = base.layout.field(self, usize::try_from(field).unwrap_or(0))?;
387 // Offset may need adjustment for unsized fields.
388 let (meta, offset) = if field_layout.is_unsized() {
389 // Re-use parent metadata to determine dynamic field layout.
390 // With custom DSTS, this *will* execute user-defined code, but the same
391 // happens at run-time so that's okay.
392 let align = match self.size_and_align_of(base.meta, field_layout)? {
393 Some((_, align)) => align,
394 None if offset == Size::ZERO =>
395 // An extern type at offset 0, we fall back to its static alignment.
396 // FIXME: Once we have made decisions for how to handle size and alignment
397 // of `extern type`, this should be adapted. It is just a temporary hack
398 // to get some code to work that probably ought to work.
400 field_layout.align.abi
402 None => bug!("Cannot compute offset for extern type field at non-0 offset"),
404 (base.meta, offset.align_to(align))
406 // base.meta could be present; we might be accessing a sized field of an unsized
411 // We do not look at `base.layout.align` nor `field_layout.align`, unlike
412 // codegen -- mostly to see if we can get away with that
413 base.offset(offset, meta, field_layout, self)
416 // Iterates over all fields of an array. Much more efficient than doing the
417 // same by repeatedly calling `mplace_array`.
418 pub fn mplace_array_fields(
420 base: MPlaceTy<'tcx, Tag>,
421 ) -> InterpResult<'tcx, impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'tcx>
423 let len = base.len(self)?; // also asserts that we have a type where this makes sense
424 let stride = match base.layout.fields {
425 layout::FieldPlacement::Array { stride, .. } => stride,
426 _ => bug!("mplace_array_fields: expected an array layout"),
428 let layout = base.layout.field(self, 0)?;
429 let dl = &self.tcx.data_layout;
430 Ok((0..len).map(move |i| base.offset(i * stride, None, layout, dl)))
433 pub fn mplace_subslice(
435 base: MPlaceTy<'tcx, M::PointerTag>,
439 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
440 let len = base.len(self)?; // also asserts that we have a type where this makes sense
441 let actual_to = if from_end {
443 // This can only be reached in ConstProp and non-rustc-MIR.
444 throw_ub!(BoundsCheckFailed { len: len as u64, index: from as u64 + to as u64 });
451 // Not using layout method because that works with usize, and does not work with slices
452 // (that have count 0 in their layout).
453 let from_offset = match base.layout.fields {
454 layout::FieldPlacement::Array { stride, .. } => stride * from,
455 _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
458 // Compute meta and new layout
459 let inner_len = actual_to - from;
460 let (meta, ty) = match base.layout.ty.kind {
461 // It is not nice to match on the type, but that seems to be the only way to
463 ty::Array(inner, _) => (None, self.tcx.mk_array(inner, inner_len)),
465 let len = Scalar::from_uint(inner_len, self.pointer_size());
466 (Some(len), base.layout.ty)
468 _ => bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
470 let layout = self.layout_of(ty)?;
471 base.offset(from_offset, meta, layout, self)
474 pub fn mplace_downcast(
476 base: MPlaceTy<'tcx, M::PointerTag>,
478 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
479 // Downcasts only change the layout
480 assert!(base.meta.is_none());
481 Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
484 /// Project into an mplace
485 pub fn mplace_projection(
487 base: MPlaceTy<'tcx, M::PointerTag>,
488 proj_elem: &mir::PlaceElem<'tcx>,
489 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
490 use rustc::mir::ProjectionElem::*;
491 Ok(match *proj_elem {
492 Field(field, _) => self.mplace_field(base, field.index() as u64)?,
493 Downcast(_, variant) => self.mplace_downcast(base, variant)?,
494 Deref => self.deref_operand(base.into())?,
497 let layout = self.layout_of(self.tcx.types.usize)?;
498 let n = self.access_local(self.frame(), local, Some(layout))?;
499 let n = self.read_scalar(n)?;
500 let n = self.force_bits(n.not_undef()?, self.tcx.data_layout.pointer_size)?;
501 self.mplace_field(base, u64::try_from(n).unwrap())?
504 ConstantIndex { offset, min_length, from_end } => {
505 let n = base.len(self)?;
506 if n < min_length as u64 {
507 // This can only be reached in ConstProp and non-rustc-MIR.
508 throw_ub!(BoundsCheckFailed { len: min_length as u64, index: n as u64 });
511 let index = if from_end {
512 assert!(0 < offset && offset - 1 < min_length);
513 n - u64::from(offset)
515 assert!(offset < min_length);
519 self.mplace_field(base, index)?
522 Subslice { from, to, from_end } => {
523 self.mplace_subslice(base, u64::from(from), u64::from(to), from_end)?
528 /// Gets the place of a field inside the place, and also the field's type.
529 /// Just a convenience function, but used quite a bit.
530 /// This is the only projection that might have a side-effect: We cannot project
531 /// into the field of a local `ScalarPair`, we have to first allocate it.
534 base: PlaceTy<'tcx, M::PointerTag>,
536 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
537 // FIXME: We could try to be smarter and avoid allocation for fields that span the
539 let mplace = self.force_allocation(base)?;
540 Ok(self.mplace_field(mplace, field)?.into())
543 pub fn place_downcast(
545 base: PlaceTy<'tcx, M::PointerTag>,
547 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
548 // Downcast just changes the layout
549 Ok(match base.place {
550 Place::Ptr(mplace) => {
551 self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into()
553 Place::Local { .. } => {
554 let layout = base.layout.for_variant(self, variant);
555 PlaceTy { layout, ..base }
560 /// Projects into a place.
561 pub fn place_projection(
563 base: PlaceTy<'tcx, M::PointerTag>,
564 proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
565 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
566 use rustc::mir::ProjectionElem::*;
567 Ok(match *proj_elem {
568 Field(field, _) => self.place_field(base, field.index() as u64)?,
569 Downcast(_, variant) => self.place_downcast(base, variant)?,
570 Deref => self.deref_operand(self.place_to_op(base)?)?.into(),
571 // For the other variants, we have to force an allocation.
572 // This matches `operand_projection`.
573 Subslice { .. } | ConstantIndex { .. } | Index(_) => {
574 let mplace = self.force_allocation(base)?;
575 self.mplace_projection(mplace, proj_elem)?.into()
580 /// Evaluate statics and promoteds to an `MPlace`. Used to share some code between
581 /// `eval_place` and `eval_place_to_op`.
582 pub(super) fn eval_static_to_mplace(
584 place_static: &mir::Static<'tcx>,
585 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
586 use rustc::mir::StaticKind;
588 Ok(match place_static.kind {
589 StaticKind::Promoted(promoted, promoted_substs) => {
590 let substs = self.subst_from_frame_and_normalize_erasing_regions(promoted_substs);
591 let instance = ty::Instance::new(place_static.def_id, substs);
593 // Even after getting `substs` from the frame, this instance may still be
594 // polymorphic because `ConstProp` will try to promote polymorphic MIR.
595 if instance.needs_subst() {
596 throw_inval!(TooGeneric);
599 self.const_eval_raw(GlobalId { instance, promoted: Some(promoted) })?
602 StaticKind::Static => {
603 let ty = place_static.ty;
604 assert!(!ty.needs_subst());
605 let layout = self.layout_of(ty)?;
606 // Just create a lazy reference, so we can support recursive statics.
607 // tcx takes care of assigning every static one and only one unique AllocId.
608 // When the data here is ever actually used, memory will notice,
609 // and it knows how to deal with alloc_id that are present in the
610 // global table but not in its local memory: It calls back into tcx through
611 // a query, triggering the CTFE machinery to actually turn this lazy reference
612 // into a bunch of bytes. IOW, statics are evaluated with CTFE even when
613 // this InterpCx uses another Machine (e.g., in miri). This is what we
614 // want! This way, computing statics works consistently between codegen
615 // and miri: They use the same query to eventually obtain a `ty::Const`
616 // and use that for further computation.
618 // Notice that statics have *two* AllocIds: the lazy one, and the resolved
619 // one. Here we make sure that the interpreted program never sees the
620 // resolved ID. Also see the doc comment of `Memory::get_static_alloc`.
621 let alloc_id = self.tcx.alloc_map.lock().create_static_alloc(place_static.def_id);
622 let ptr = self.tag_static_base_pointer(Pointer::from(alloc_id));
623 MPlaceTy::from_aligned_ptr(ptr, layout)
628 /// Computes a place. You should only use this if you intend to write into this
629 /// place; for reading, a more efficient alternative is `eval_place_for_read`.
632 place: &mir::Place<'tcx>,
633 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
634 use rustc::mir::PlaceBase;
636 let mut place_ty = match &place.base {
637 PlaceBase::Local(mir::RETURN_PLACE) => {
638 // `return_place` has the *caller* layout, but we want to use our
639 // `layout to verify our assumption. The caller will validate
640 // their layout on return.
642 place: match self.frame().return_place {
644 // Even if we don't have a return place, we sometimes need to
645 // create this place, but any attempt to read from / write to it
646 // (even a ZST read/write) needs to error, so let us make this
649 // FIXME: Ideally we'd make sure that the place projections also
651 None => Place::null(&*self),
653 layout: self.layout_of(self.subst_from_frame_and_normalize_erasing_regions(
654 self.frame().body.return_ty(),
658 PlaceBase::Local(local) => PlaceTy {
659 // This works even for dead/uninitialized locals; we check further when writing
660 place: Place::Local { frame: self.cur_frame(), local: *local },
661 layout: self.layout_of_local(self.frame(), *local, None)?,
663 PlaceBase::Static(place_static) => self.eval_static_to_mplace(&place_static)?.into(),
666 for elem in place.projection.iter() {
667 place_ty = self.place_projection(place_ty, elem)?
670 self.dump_place(place_ty.place);
674 /// Write a scalar to a place
678 val: impl Into<ScalarMaybeUndef<M::PointerTag>>,
679 dest: PlaceTy<'tcx, M::PointerTag>,
680 ) -> InterpResult<'tcx> {
681 self.write_immediate(Immediate::Scalar(val.into()), dest)
684 /// Write an immediate to a place
686 pub fn write_immediate(
688 src: Immediate<M::PointerTag>,
689 dest: PlaceTy<'tcx, M::PointerTag>,
690 ) -> InterpResult<'tcx> {
691 self.write_immediate_no_validate(src, dest)?;
693 if M::enforce_validity(self) {
694 // Data got changed, better make sure it matches the type!
695 self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
701 /// Write an `Immediate` to memory.
703 pub fn write_immediate_to_mplace(
705 src: Immediate<M::PointerTag>,
706 dest: MPlaceTy<'tcx, M::PointerTag>,
707 ) -> InterpResult<'tcx> {
708 self.write_immediate_to_mplace_no_validate(src, dest)?;
710 if M::enforce_validity(self) {
711 // Data got changed, better make sure it matches the type!
712 self.validate_operand(dest.into(), vec![], None)?;
718 /// Write an immediate to a place.
719 /// If you use this you are responsible for validating that things got copied at the
721 fn write_immediate_no_validate(
723 src: Immediate<M::PointerTag>,
724 dest: PlaceTy<'tcx, M::PointerTag>,
725 ) -> InterpResult<'tcx> {
726 if cfg!(debug_assertions) {
727 // This is a very common path, avoid some checks in release mode
728 assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
730 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Ptr(_))) => assert_eq!(
733 "Size mismatch when writing pointer"
735 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Raw { size, .. })) => {
737 Size::from_bytes(size.into()),
739 "Size mismatch when writing bits"
742 Immediate::Scalar(ScalarMaybeUndef::Undef) => {} // undef can have any size
743 Immediate::ScalarPair(_, _) => {
744 // FIXME: Can we check anything here?
748 trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
750 // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
751 // but not factored as a separate function.
752 let mplace = match dest.place {
753 Place::Local { frame, local } => {
754 match self.stack[frame].locals[local].access_mut()? {
756 // Local can be updated in-place.
757 *local = LocalValue::Live(Operand::Immediate(src));
761 // The local is in memory, go on below.
766 Place::Ptr(mplace) => mplace, // already referring to memory
768 let dest = MPlaceTy { mplace, layout: dest.layout };
770 // This is already in memory, write there.
771 self.write_immediate_to_mplace_no_validate(src, dest)
774 /// Write an immediate to memory.
775 /// If you use this you are responsible for validating that things got copied at the
777 fn write_immediate_to_mplace_no_validate(
779 value: Immediate<M::PointerTag>,
780 dest: MPlaceTy<'tcx, M::PointerTag>,
781 ) -> InterpResult<'tcx> {
782 // Note that it is really important that the type here is the right one, and matches the
783 // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
784 // to handle padding properly, which is only correct if we never look at this data with the
787 // Invalid places are a thing: the return place of a diverging function
788 let ptr = match self.check_mplace_access(dest, None)? {
790 None => return Ok(()), // zero-sized access
793 let tcx = &*self.tcx;
794 // FIXME: We should check that there are dest.layout.size many bytes available in
795 // memory. The code below is not sufficient, with enough padding it might not
796 // cover all the bytes!
798 Immediate::Scalar(scalar) => {
799 match dest.layout.abi {
800 layout::Abi::Scalar(_) => {} // fine
802 bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}", dest.layout)
805 self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(
812 Immediate::ScalarPair(a_val, b_val) => {
813 // We checked `ptr_align` above, so all fields will have the alignment they need.
814 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
815 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
816 let (a, b) = match dest.layout.abi {
817 layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
819 "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
823 let (a_size, b_size) = (a.size(self), b.size(self));
824 let b_offset = a_size.align_to(b.align(self).abi);
825 let b_ptr = ptr.offset(b_offset, self)?;
827 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
828 // but that does not work: We could be a newtype around a pair, then the
829 // fields do not match the `ScalarPair` components.
831 self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(tcx, ptr, a_val, a_size)?;
832 self.memory.get_raw_mut(b_ptr.alloc_id)?.write_scalar(tcx, b_ptr, b_val, b_size)
837 /// Copies the data from an operand to a place. This does not support transmuting!
838 /// Use `copy_op_transmute` if the layouts could disagree.
842 src: OpTy<'tcx, M::PointerTag>,
843 dest: PlaceTy<'tcx, M::PointerTag>,
844 ) -> InterpResult<'tcx> {
845 self.copy_op_no_validate(src, dest)?;
847 if M::enforce_validity(self) {
848 // Data got changed, better make sure it matches the type!
849 self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
855 /// Copies the data from an operand to a place. This does not support transmuting!
856 /// Use `copy_op_transmute` if the layouts could disagree.
857 /// Also, if you use this you are responsible for validating that things get copied at the
859 fn copy_op_no_validate(
861 src: OpTy<'tcx, M::PointerTag>,
862 dest: PlaceTy<'tcx, M::PointerTag>,
863 ) -> InterpResult<'tcx> {
864 // We do NOT compare the types for equality, because well-typed code can
865 // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
867 src.layout.details == dest.layout.details,
868 "Layout mismatch when copying!\nsrc: {:#?}\ndest: {:#?}",
873 // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
874 let src = match self.try_read_immediate(src)? {
876 assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
877 // Yay, we got a value that we can write directly.
878 // FIXME: Add a check to make sure that if `src` is indirect,
879 // it does not overlap with `dest`.
880 return self.write_immediate_no_validate(*src_val, dest);
882 Err(mplace) => mplace,
884 // Slow path, this does not fit into an immediate. Just memcpy.
885 trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
887 // This interprets `src.meta` with the `dest` local's layout, if an unsized local
888 // is being initialized!
889 let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?;
890 let size = size.unwrap_or_else(|| {
892 !dest.layout.is_unsized(),
893 "Cannot copy into already initialized unsized place"
897 assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
900 .check_mplace_access(src, Some(size))
901 .expect("places should be checked on creation");
903 .check_mplace_access(dest, Some(size))
904 .expect("places should be checked on creation");
905 let (src_ptr, dest_ptr) = match (src, dest) {
906 (Some(src_ptr), Some(dest_ptr)) => (src_ptr, dest_ptr),
907 (None, None) => return Ok(()), // zero-sized copy
908 _ => bug!("The pointers should both be Some or both None"),
911 self.memory.copy(src_ptr, dest_ptr, size, /*nonoverlapping*/ true)
914 /// Copies the data from an operand to a place. The layouts may disagree, but they must
915 /// have the same size.
916 pub fn copy_op_transmute(
918 src: OpTy<'tcx, M::PointerTag>,
919 dest: PlaceTy<'tcx, M::PointerTag>,
920 ) -> InterpResult<'tcx> {
921 if src.layout.details == dest.layout.details {
922 // Fast path: Just use normal `copy_op`
923 return self.copy_op(src, dest);
925 // We still require the sizes to match.
927 src.layout.size == dest.layout.size,
928 "Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}",
932 // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
933 // to avoid that here.
935 !src.layout.is_unsized() && !dest.layout.is_unsized(),
936 "Cannot transmute unsized data"
939 // The hard case is `ScalarPair`. `src` is already read from memory in this case,
940 // using `src.layout` to figure out which bytes to use for the 1st and 2nd field.
941 // We have to write them to `dest` at the offsets they were *read at*, which is
942 // not necessarily the same as the offsets in `dest.layout`!
943 // Hence we do the copy with the source layout on both sides. We also make sure to write
944 // into memory, because if `dest` is a local we would not even have a way to write
945 // at the `src` offsets; the fact that we came from a different layout would
947 let dest = self.force_allocation(dest)?;
948 self.copy_op_no_validate(
950 PlaceTy::from(MPlaceTy { mplace: *dest, layout: src.layout }),
953 if M::enforce_validity(self) {
954 // Data got changed, better make sure it matches the type!
955 self.validate_operand(dest.into(), vec![], None)?;
961 /// Ensures that a place is in memory, and returns where it is.
962 /// If the place currently refers to a local that doesn't yet have a matching allocation,
963 /// create such an allocation.
964 /// This is essentially `force_to_memplace`.
966 /// This supports unsized types and returns the computed size to avoid some
967 /// redundant computation when copying; use `force_allocation` for a simpler, sized-only
969 pub fn force_allocation_maybe_sized(
971 place: PlaceTy<'tcx, M::PointerTag>,
972 meta: Option<Scalar<M::PointerTag>>,
973 ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
974 let (mplace, size) = match place.place {
975 Place::Local { frame, local } => {
976 match self.stack[frame].locals[local].access_mut()? {
977 Ok(&mut local_val) => {
978 // We need to make an allocation.
980 // We need the layout of the local. We can NOT use the layout we got,
981 // that might e.g., be an inner field of a struct with `Scalar` layout,
982 // that has different alignment than the outer field.
983 let local_layout = self.layout_of_local(&self.stack[frame], local, None)?;
984 // We also need to support unsized types, and hence cannot use `allocate`.
985 let (size, align) = self
986 .size_and_align_of(meta, local_layout)?
987 .expect("Cannot allocate for non-dyn-sized type");
988 let ptr = self.memory.allocate(size, align, MemoryKind::Stack);
989 let mplace = MemPlace { ptr: ptr.into(), align, meta };
990 if let LocalValue::Live(Operand::Immediate(value)) = local_val {
991 // Preserve old value.
992 // We don't have to validate as we can assume the local
993 // was already valid for its type.
994 let mplace = MPlaceTy { mplace, layout: local_layout };
995 self.write_immediate_to_mplace_no_validate(value, mplace)?;
997 // Now we can call `access_mut` again, asserting it goes well,
998 // and actually overwrite things.
999 *self.stack[frame].locals[local].access_mut().unwrap().unwrap() =
1000 LocalValue::Live(Operand::Indirect(mplace));
1001 (mplace, Some(size))
1003 Err(mplace) => (mplace, None), // this already was an indirect local
1006 Place::Ptr(mplace) => (mplace, None),
1008 // Return with the original layout, so that the caller can go on
1009 Ok((MPlaceTy { mplace, layout: place.layout }, size))
1013 pub fn force_allocation(
1015 place: PlaceTy<'tcx, M::PointerTag>,
1016 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1017 Ok(self.force_allocation_maybe_sized(place, None)?.0)
1022 layout: TyLayout<'tcx>,
1023 kind: MemoryKind<M::MemoryKinds>,
1024 ) -> MPlaceTy<'tcx, M::PointerTag> {
1025 let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
1026 MPlaceTy::from_aligned_ptr(ptr, layout)
1029 /// Returns a wide MPlace.
1030 pub fn allocate_str(
1033 kind: MemoryKind<M::MemoryKinds>,
1034 ) -> MPlaceTy<'tcx, M::PointerTag> {
1035 let ptr = self.memory.allocate_static_bytes(str.as_bytes(), kind);
1036 let meta = Scalar::from_uint(str.len() as u128, self.pointer_size());
1038 MemPlace { ptr: ptr.into(), align: Align::from_bytes(1).unwrap(), meta: Some(meta) };
1040 let layout = self.layout_of(self.tcx.mk_static_str()).unwrap();
1041 MPlaceTy { mplace, layout }
1044 pub fn write_discriminant_index(
1046 variant_index: VariantIdx,
1047 dest: PlaceTy<'tcx, M::PointerTag>,
1048 ) -> InterpResult<'tcx> {
1049 // Layout computation excludes uninhabited variants from consideration
1050 // therefore there's no way to represent those variants in the given layout.
1051 if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() {
1052 throw_ub!(Unreachable);
1055 match dest.layout.variants {
1056 layout::Variants::Single { index } => {
1057 assert_eq!(index, variant_index);
1059 layout::Variants::Multiple {
1060 discr_kind: layout::DiscriminantKind::Tag,
1061 discr: ref discr_layout,
1065 // No need to validate that the discriminant here because the
1066 // `TyLayout::for_variant()` call earlier already checks the variant is valid.
1069 dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
1071 // raw discriminants for enums are isize or bigger during
1072 // their computation, but the in-memory tag is the smallest possible
1074 let size = discr_layout.value.size(self);
1075 let discr_val = truncate(discr_val, size);
1077 let discr_dest = self.place_field(dest, discr_index as u64)?;
1078 self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
1080 layout::Variants::Multiple {
1082 layout::DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start },
1083 discr: ref discr_layout,
1087 // No need to validate that the discriminant here because the
1088 // `TyLayout::for_variant()` call earlier already checks the variant is valid.
1090 if variant_index != dataful_variant {
1091 let variants_start = niche_variants.start().as_u32();
1092 let variant_index_relative = variant_index
1094 .checked_sub(variants_start)
1095 .expect("overflow computing relative variant idx");
1096 // We need to use machine arithmetic when taking into account `niche_start`:
1097 // discr_val = variant_index_relative + niche_start_val
1098 let discr_layout = self.layout_of(discr_layout.value.to_int_ty(*self.tcx))?;
1099 let niche_start_val = ImmTy::from_uint(niche_start, discr_layout);
1100 let variant_index_relative_val =
1101 ImmTy::from_uint(variant_index_relative, discr_layout);
1102 let discr_val = self.binary_op(
1104 variant_index_relative_val,
1108 let niche_dest = self.place_field(dest, discr_index as u64)?;
1109 self.write_immediate(*discr_val, niche_dest)?;
1117 pub fn raw_const_to_mplace(
1119 raw: RawConst<'tcx>,
1120 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1121 // This must be an allocation in `tcx`
1122 assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1123 let ptr = self.tag_static_base_pointer(Pointer::from(raw.alloc_id));
1124 let layout = self.layout_of(raw.ty)?;
1125 Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
1128 /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
1129 /// Also return some more information so drop doesn't have to run the same code twice.
1130 pub(super) fn unpack_dyn_trait(
1132 mplace: MPlaceTy<'tcx, M::PointerTag>,
1133 ) -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1134 let vtable = mplace.vtable(); // also sanity checks the type
1135 let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
1136 let layout = self.layout_of(ty)?;
1138 // More sanity checks
1139 if cfg!(debug_assertions) {
1140 let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
1141 assert_eq!(size, layout.size);
1142 // only ABI alignment is preserved
1143 assert_eq!(align, layout.align.abi);
1146 let mplace = MPlaceTy { mplace: MemPlace { meta: None, ..*mplace }, layout };
1147 Ok((instance, mplace))