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 either::{Either, Left, Right};
7 use rustc_ast::Mutability;
10 use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
11 use rustc_target::abi::{self, Abi, Align, HasDataLayout, Size, VariantIdx};
14 alloc_range, mir_assign_valid_types, AllocId, AllocRef, AllocRefMut, CheckInAllocMsg,
15 ConstAlloc, ImmTy, Immediate, InterpCx, InterpResult, Machine, MemoryKind, OpTy, Operand,
16 Pointer, Provenance, Scalar,
19 #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
20 /// Information required for the sound usage of a `MemPlace`.
21 pub enum MemPlaceMeta<Prov: Provenance = AllocId> {
22 /// The unsized payload (e.g. length for slices or vtable pointer for trait objects).
24 /// `Sized` types or unsized `extern type`
28 impl<Prov: Provenance> MemPlaceMeta<Prov> {
29 pub fn unwrap_meta(self) -> Scalar<Prov> {
33 bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)")
38 pub fn has_meta(self) -> bool {
40 Self::Meta(_) => true,
46 #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
47 pub struct MemPlace<Prov: Provenance = AllocId> {
48 /// The pointer can be a pure integer, with the `None` provenance.
49 pub ptr: Pointer<Option<Prov>>,
50 /// Metadata for unsized places. Interpretation is up to the type.
51 /// Must not be present for sized types, but can be missing for unsized types
52 /// (e.g., `extern type`).
53 pub meta: MemPlaceMeta<Prov>,
56 /// A MemPlace with its layout. Constructing it is only possible in this module.
57 #[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
58 pub struct MPlaceTy<'tcx, Prov: Provenance = AllocId> {
59 mplace: MemPlace<Prov>,
60 pub layout: TyAndLayout<'tcx>,
61 /// rustc does not have a proper way to represent the type of a field of a `repr(packed)` struct:
62 /// it needs to have a different alignment than the field type would usually have.
63 /// So we represent this here with a separate field that "overwrites" `layout.align`.
64 /// This means `layout.align` should never be used for a `MPlaceTy`!
68 #[derive(Copy, Clone, Debug)]
69 pub enum Place<Prov: Provenance = AllocId> {
70 /// A place referring to a value allocated in the `Memory` system.
73 /// To support alloc-free locals, we are able to write directly to a local.
74 /// (Without that optimization, we'd just always be a `MemPlace`.)
75 Local { frame: usize, local: mir::Local },
78 #[derive(Clone, Debug)]
79 pub struct PlaceTy<'tcx, Prov: Provenance = AllocId> {
80 place: Place<Prov>, // Keep this private; it helps enforce invariants.
81 pub layout: TyAndLayout<'tcx>,
82 /// rustc does not have a proper way to represent the type of a field of a `repr(packed)` struct:
83 /// it needs to have a different alignment than the field type would usually have.
84 /// So we represent this here with a separate field that "overwrites" `layout.align`.
85 /// This means `layout.align` should never be used for a `PlaceTy`!
89 impl<'tcx, Prov: Provenance> std::ops::Deref for PlaceTy<'tcx, Prov> {
90 type Target = Place<Prov>;
92 fn deref(&self) -> &Place<Prov> {
97 impl<'tcx, Prov: Provenance> std::ops::Deref for MPlaceTy<'tcx, Prov> {
98 type Target = MemPlace<Prov>;
100 fn deref(&self) -> &MemPlace<Prov> {
105 impl<'tcx, Prov: Provenance> From<MPlaceTy<'tcx, Prov>> for PlaceTy<'tcx, Prov> {
107 fn from(mplace: MPlaceTy<'tcx, Prov>) -> Self {
108 PlaceTy { place: Place::Ptr(*mplace), layout: mplace.layout, align: mplace.align }
112 impl<'tcx, Prov: Provenance> From<&'_ MPlaceTy<'tcx, Prov>> for PlaceTy<'tcx, Prov> {
114 fn from(mplace: &MPlaceTy<'tcx, Prov>) -> Self {
115 PlaceTy { place: Place::Ptr(**mplace), layout: mplace.layout, align: mplace.align }
119 impl<'tcx, Prov: Provenance> From<&'_ mut MPlaceTy<'tcx, Prov>> for PlaceTy<'tcx, Prov> {
121 fn from(mplace: &mut MPlaceTy<'tcx, Prov>) -> Self {
122 PlaceTy { place: Place::Ptr(**mplace), layout: mplace.layout, align: mplace.align }
126 impl<Prov: Provenance> MemPlace<Prov> {
128 pub fn from_ptr(ptr: Pointer<Option<Prov>>) -> Self {
129 MemPlace { ptr, meta: MemPlaceMeta::None }
132 /// Adjust the provenance of the main pointer (metadata is unaffected).
133 pub fn map_provenance(self, f: impl FnOnce(Option<Prov>) -> Option<Prov>) -> Self {
134 MemPlace { ptr: self.ptr.map_provenance(f), ..self }
137 /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
138 /// This is the inverse of `ref_to_mplace`.
140 pub fn to_ref(self, cx: &impl HasDataLayout) -> Immediate<Prov> {
142 MemPlaceMeta::None => Immediate::from(Scalar::from_maybe_pointer(self.ptr, cx)),
143 MemPlaceMeta::Meta(meta) => {
144 Immediate::ScalarPair(Scalar::from_maybe_pointer(self.ptr, cx), meta)
150 pub fn offset_with_meta<'tcx>(
153 meta: MemPlaceMeta<Prov>,
154 cx: &impl HasDataLayout,
155 ) -> InterpResult<'tcx, Self> {
156 Ok(MemPlace { ptr: self.ptr.offset(offset, cx)?, meta })
160 impl<Prov: Provenance> Place<Prov> {
161 /// Asserts that this points to some local variable.
162 /// Returns the frame idx and the variable idx.
164 #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
165 pub fn assert_local(&self) -> (usize, mir::Local) {
167 Place::Local { frame, local } => (*frame, *local),
168 _ => bug!("assert_local: expected Place::Local, got {:?}", self),
173 impl<'tcx, Prov: Provenance> MPlaceTy<'tcx, Prov> {
174 /// Produces a MemPlace that works for ZST but nothing else.
175 /// Conceptually this is a new allocation, but it doesn't actually create an allocation so you
176 /// don't need to worry about memory leaks.
178 pub fn fake_alloc_zst(layout: TyAndLayout<'tcx>) -> Self {
179 assert!(layout.is_zst());
180 let align = layout.align.abi;
181 let ptr = Pointer::from_addr(align.bytes()); // no provenance, absolute address
182 MPlaceTy { mplace: MemPlace { ptr, meta: MemPlaceMeta::None }, layout, align }
186 pub fn offset_with_meta(
189 meta: MemPlaceMeta<Prov>,
190 layout: TyAndLayout<'tcx>,
191 cx: &impl HasDataLayout,
192 ) -> InterpResult<'tcx, Self> {
194 mplace: self.mplace.offset_with_meta(offset, meta, cx)?,
195 align: self.align.restrict_for_offset(offset),
203 layout: TyAndLayout<'tcx>,
204 cx: &impl HasDataLayout,
205 ) -> InterpResult<'tcx, Self> {
206 assert!(layout.is_sized());
207 self.offset_with_meta(offset, MemPlaceMeta::None, layout, cx)
211 pub fn from_aligned_ptr(ptr: Pointer<Option<Prov>>, layout: TyAndLayout<'tcx>) -> Self {
212 MPlaceTy { mplace: MemPlace::from_ptr(ptr), layout, align: layout.align.abi }
216 pub fn from_aligned_ptr_with_meta(
217 ptr: Pointer<Option<Prov>>,
218 layout: TyAndLayout<'tcx>,
219 meta: MemPlaceMeta<Prov>,
221 let mut mplace = MemPlace::from_ptr(ptr);
224 MPlaceTy { mplace, layout, align: layout.align.abi }
228 pub(crate) fn len(&self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
229 if self.layout.is_unsized() {
230 // We need to consult `meta` metadata
231 match self.layout.ty.kind() {
232 ty::Slice(..) | ty::Str => self.mplace.meta.unwrap_meta().to_machine_usize(cx),
233 _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
236 // Go through the layout. There are lots of types that support a length,
237 // e.g., SIMD types. (But not all repr(simd) types even have FieldsShape::Array!)
238 match self.layout.fields {
239 abi::FieldsShape::Array { count, .. } => Ok(count),
240 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
246 pub(super) fn vtable(&self) -> Scalar<Prov> {
247 match self.layout.ty.kind() {
248 ty::Dynamic(..) => self.mplace.meta.unwrap_meta(),
249 _ => bug!("vtable not supported on type {:?}", self.layout.ty),
254 // These are defined here because they produce a place.
255 impl<'tcx, Prov: Provenance> OpTy<'tcx, Prov> {
257 pub fn as_mplace_or_imm(&self) -> Either<MPlaceTy<'tcx, Prov>, ImmTy<'tcx, Prov>> {
259 Operand::Indirect(mplace) => {
260 Left(MPlaceTy { mplace, layout: self.layout, align: self.align.unwrap() })
262 Operand::Immediate(imm) => Right(ImmTy::from_immediate(imm, self.layout)),
267 #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
268 pub fn assert_mem_place(&self) -> MPlaceTy<'tcx, Prov> {
269 self.as_mplace_or_imm().left().unwrap()
273 impl<'tcx, Prov: Provenance> PlaceTy<'tcx, Prov> {
274 /// A place is either an mplace or some local.
276 pub fn as_mplace_or_local(&self) -> Either<MPlaceTy<'tcx, Prov>, (usize, mir::Local)> {
278 Place::Ptr(mplace) => Left(MPlaceTy { mplace, layout: self.layout, align: self.align }),
279 Place::Local { frame, local } => Right((frame, local)),
284 #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
285 pub fn assert_mem_place(&self) -> MPlaceTy<'tcx, Prov> {
286 self.as_mplace_or_local().left().unwrap()
290 // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
291 impl<'mir, 'tcx: 'mir, Prov, M> InterpCx<'mir, 'tcx, M>
293 Prov: Provenance + 'static,
294 M: Machine<'mir, 'tcx, Provenance = Prov>,
296 /// Take a value, which represents a (thin or wide) reference, and make it a place.
297 /// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`.
299 /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
300 /// want to ever use the place for memory access!
301 /// Generally prefer `deref_operand`.
302 pub fn ref_to_mplace(
304 val: &ImmTy<'tcx, M::Provenance>,
305 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
307 val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty;
308 let layout = self.layout_of(pointee_type)?;
309 let (ptr, meta) = match **val {
310 Immediate::Scalar(ptr) => (ptr, MemPlaceMeta::None),
311 Immediate::ScalarPair(ptr, meta) => (ptr, MemPlaceMeta::Meta(meta)),
312 Immediate::Uninit => throw_ub!(InvalidUninitBytes(None)),
315 let mplace = MemPlace { ptr: ptr.to_pointer(self)?, meta };
316 // When deref'ing a pointer, the *static* alignment given by the type is what matters.
317 let align = layout.align.abi;
318 Ok(MPlaceTy { mplace, layout, align })
321 /// Take an operand, representing a pointer, and dereference it to a place.
322 #[instrument(skip(self), level = "debug")]
323 pub fn deref_operand(
325 src: &OpTy<'tcx, M::Provenance>,
326 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
327 let val = self.read_immediate(src)?;
328 trace!("deref to {} on {:?}", val.layout.ty, *val);
330 if val.layout.ty.is_box() {
331 bug!("dereferencing {:?}", val.layout.ty);
334 let mplace = self.ref_to_mplace(&val)?;
335 self.check_mplace(mplace)?;
340 pub(super) fn get_place_alloc(
342 place: &MPlaceTy<'tcx, M::Provenance>,
343 ) -> InterpResult<'tcx, Option<AllocRef<'_, 'tcx, M::Provenance, M::AllocExtra>>> {
344 assert!(place.layout.is_sized());
345 assert!(!place.meta.has_meta());
346 let size = place.layout.size;
347 self.get_ptr_alloc(place.ptr, size, place.align)
351 pub(super) fn get_place_alloc_mut(
353 place: &MPlaceTy<'tcx, M::Provenance>,
354 ) -> InterpResult<'tcx, Option<AllocRefMut<'_, 'tcx, M::Provenance, M::AllocExtra>>> {
355 assert!(place.layout.is_sized());
356 assert!(!place.meta.has_meta());
357 let size = place.layout.size;
358 self.get_ptr_alloc_mut(place.ptr, size, place.align)
361 /// Check if this mplace is dereferenceable and sufficiently aligned.
362 pub fn check_mplace(&self, mplace: MPlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
363 let (size, align) = self
364 .size_and_align_of_mplace(&mplace)?
365 .unwrap_or((mplace.layout.size, mplace.layout.align.abi));
366 assert!(mplace.align <= align, "dynamic alignment less strict than static one?");
367 let align = if M::enforce_alignment(self).should_check() { align } else { Align::ONE };
368 self.check_ptr_access_align(mplace.ptr, size, align, CheckInAllocMsg::DerefTest)?;
372 /// Converts a repr(simd) place into a place where `place_index` accesses the SIMD elements.
373 /// Also returns the number of elements.
374 pub fn mplace_to_simd(
376 mplace: &MPlaceTy<'tcx, M::Provenance>,
377 ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::Provenance>, u64)> {
378 // Basically we just transmute this place into an array following simd_size_and_type.
379 // (Transmuting is okay since this is an in-memory place. We also double-check the size
381 let (len, e_ty) = mplace.layout.ty.simd_size_and_type(*self.tcx);
382 let array = self.tcx.mk_array(e_ty, len);
383 let layout = self.layout_of(array)?;
384 assert_eq!(layout.size, mplace.layout.size);
385 Ok((MPlaceTy { layout, ..*mplace }, len))
388 /// Converts a repr(simd) place into a place where `place_index` accesses the SIMD elements.
389 /// Also returns the number of elements.
390 pub fn place_to_simd(
392 place: &PlaceTy<'tcx, M::Provenance>,
393 ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::Provenance>, u64)> {
394 let mplace = self.force_allocation(place)?;
395 self.mplace_to_simd(&mplace)
398 pub fn local_to_place(
402 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> {
403 let layout = self.layout_of_local(&self.stack()[frame], local, None)?;
404 let place = Place::Local { frame, local };
405 Ok(PlaceTy { place, layout, align: layout.align.abi })
408 /// Computes a place. You should only use this if you intend to write into this
409 /// place; for reading, a more efficient alternative is `eval_place_to_op`.
410 #[instrument(skip(self), level = "debug")]
413 mir_place: mir::Place<'tcx>,
414 ) -> InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> {
415 let mut place = self.local_to_place(self.frame_idx(), mir_place.local)?;
416 // Using `try_fold` turned out to be bad for performance, hence the loop.
417 for elem in mir_place.projection.iter() {
418 place = self.place_projection(&place, elem)?
421 trace!("{:?}", self.dump_place(place.place));
422 // Sanity-check the type we ended up with.
424 mir_assign_valid_types(
427 self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions(
428 mir_place.ty(&self.frame().body.local_decls, *self.tcx).ty
432 "eval_place of a MIR place with type {:?} produced an interpreter place with type {:?}",
433 mir_place.ty(&self.frame().body.local_decls, *self.tcx).ty,
439 /// Write an immediate to a place
441 #[instrument(skip(self), level = "debug")]
442 pub fn write_immediate(
444 src: Immediate<M::Provenance>,
445 dest: &PlaceTy<'tcx, M::Provenance>,
446 ) -> InterpResult<'tcx> {
447 self.write_immediate_no_validate(src, dest)?;
449 if M::enforce_validity(self) {
450 // Data got changed, better make sure it matches the type!
451 self.validate_operand(&self.place_to_op(dest)?)?;
457 /// Write a scalar to a place
461 val: impl Into<Scalar<M::Provenance>>,
462 dest: &PlaceTy<'tcx, M::Provenance>,
463 ) -> InterpResult<'tcx> {
464 self.write_immediate(Immediate::Scalar(val.into()), dest)
467 /// Write a pointer to a place
469 pub fn write_pointer(
471 ptr: impl Into<Pointer<Option<M::Provenance>>>,
472 dest: &PlaceTy<'tcx, M::Provenance>,
473 ) -> InterpResult<'tcx> {
474 self.write_scalar(Scalar::from_maybe_pointer(ptr.into(), self), dest)
477 /// Write an immediate to a place.
478 /// If you use this you are responsible for validating that things got copied at the
480 fn write_immediate_no_validate(
482 src: Immediate<M::Provenance>,
483 dest: &PlaceTy<'tcx, M::Provenance>,
484 ) -> InterpResult<'tcx> {
485 assert!(dest.layout.is_sized(), "Cannot write unsized data");
486 trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
488 // See if we can avoid an allocation. This is the counterpart to `read_immediate_raw`,
489 // but not factored as a separate function.
490 let mplace = match dest.place {
491 Place::Local { frame, local } => {
492 match M::access_local_mut(self, frame, local)? {
493 Operand::Immediate(local) => {
494 // Local can be updated in-place.
498 Operand::Indirect(mplace) => {
499 // The local is in memory, go on below.
504 Place::Ptr(mplace) => mplace, // already referring to memory
507 // This is already in memory, write there.
508 self.write_immediate_to_mplace_no_validate(src, dest.layout, dest.align, mplace)
511 /// Write an immediate to memory.
512 /// If you use this you are responsible for validating that things got copied at the
514 fn write_immediate_to_mplace_no_validate(
516 value: Immediate<M::Provenance>,
517 layout: TyAndLayout<'tcx>,
519 dest: MemPlace<M::Provenance>,
520 ) -> InterpResult<'tcx> {
521 // Note that it is really important that the type here is the right one, and matches the
522 // type things are read at. In case `value` is a `ScalarPair`, we don't do any magic here
523 // to handle padding properly, which is only correct if we never look at this data with the
527 let Some(mut alloc) = self.get_place_alloc_mut(&MPlaceTy { mplace: dest, layout, align })? else {
533 Immediate::Scalar(scalar) => {
534 let Abi::Scalar(s) = layout.abi else { span_bug!(
536 "write_immediate_to_mplace: invalid Scalar layout: {layout:#?}",
539 let size = s.size(&tcx);
540 assert_eq!(size, layout.size, "abi::Scalar size does not match layout size");
541 alloc.write_scalar(alloc_range(Size::ZERO, size), scalar)
543 Immediate::ScalarPair(a_val, b_val) => {
544 // We checked `ptr_align` above, so all fields will have the alignment they need.
545 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
546 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
547 let Abi::ScalarPair(a, b) = layout.abi else { span_bug!(
549 "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
553 let (a_size, b_size) = (a.size(&tcx), b.size(&tcx));
554 let b_offset = a_size.align_to(b.align(&tcx).abi);
555 assert!(b_offset.bytes() > 0); // in `operand_field` we use the offset to tell apart the fields
557 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
558 // but that does not work: We could be a newtype around a pair, then the
559 // fields do not match the `ScalarPair` components.
561 alloc.write_scalar(alloc_range(Size::ZERO, a_size), a_val)?;
562 alloc.write_scalar(alloc_range(b_offset, b_size), b_val)
564 Immediate::Uninit => alloc.write_uninit(),
568 pub fn write_uninit(&mut self, dest: &PlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx> {
569 let mplace = match dest.as_mplace_or_local() {
570 Left(mplace) => mplace,
571 Right((frame, local)) => {
572 match M::access_local_mut(self, frame, local)? {
573 Operand::Immediate(local) => {
574 *local = Immediate::Uninit;
577 Operand::Indirect(mplace) => {
578 // The local is in memory, go on below.
579 MPlaceTy { mplace: *mplace, layout: dest.layout, align: dest.align }
584 let Some(mut alloc) = self.get_place_alloc_mut(&mplace)? else {
588 alloc.write_uninit()?;
592 /// Copies the data from an operand to a place.
593 /// `allow_transmute` indicates whether the layouts may disagree.
595 #[instrument(skip(self), level = "debug")]
598 src: &OpTy<'tcx, M::Provenance>,
599 dest: &PlaceTy<'tcx, M::Provenance>,
600 allow_transmute: bool,
601 ) -> InterpResult<'tcx> {
602 self.copy_op_no_validate(src, dest, allow_transmute)?;
604 if M::enforce_validity(self) {
605 // Data got changed, better make sure it matches the type!
606 self.validate_operand(&self.place_to_op(dest)?)?;
612 /// Copies the data from an operand to a place.
613 /// `allow_transmute` indicates whether the layouts may disagree.
614 /// Also, if you use this you are responsible for validating that things get copied at the
616 #[instrument(skip(self), level = "debug")]
617 fn copy_op_no_validate(
619 src: &OpTy<'tcx, M::Provenance>,
620 dest: &PlaceTy<'tcx, M::Provenance>,
621 allow_transmute: bool,
622 ) -> InterpResult<'tcx> {
623 // We do NOT compare the types for equality, because well-typed code can
624 // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
626 mir_assign_valid_types(*self.tcx, self.param_env, src.layout, dest.layout);
627 if !allow_transmute && !layout_compat {
630 "type mismatch when copying!\nsrc: {:?},\ndest: {:?}",
636 // Let us see if the layout is simple so we take a shortcut,
637 // avoid force_allocation.
638 let src = match self.read_immediate_raw(src)? {
640 // FIXME(const_prop): Const-prop can possibly evaluate an
641 // unsized copy operation when it thinks that the type is
642 // actually sized, due to a trivially false where-clause
643 // predicate like `where Self: Sized` with `Self = dyn Trait`.
644 // See #102553 for an example of such a predicate.
645 if src.layout.is_unsized() {
646 throw_inval!(SizeOfUnsizedType(src.layout.ty));
648 if dest.layout.is_unsized() {
649 throw_inval!(SizeOfUnsizedType(dest.layout.ty));
651 assert_eq!(src.layout.size, dest.layout.size);
652 // Yay, we got a value that we can write directly.
653 return if layout_compat {
654 self.write_immediate_no_validate(*src_val, dest)
656 // This is tricky. The problematic case is `ScalarPair`: the `src_val` was
657 // loaded using the offsets defined by `src.layout`. When we put this back into
658 // the destination, we have to use the same offsets! So (a) we make sure we
659 // write back to memory, and (b) we use `dest` *with the source layout*.
660 let dest_mem = self.force_allocation(dest)?;
661 self.write_immediate_to_mplace_no_validate(
669 Left(mplace) => mplace,
671 // Slow path, this does not fit into an immediate. Just memcpy.
672 trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
674 let dest = self.force_allocation(&dest)?;
675 let Some((dest_size, _)) = self.size_and_align_of_mplace(&dest)? else {
676 span_bug!(self.cur_span(), "copy_op needs (dynamically) sized values")
678 if cfg!(debug_assertions) {
679 let src_size = self.size_and_align_of_mplace(&src)?.unwrap().0;
680 assert_eq!(src_size, dest_size, "Cannot copy differently-sized data");
682 // As a cheap approximation, we compare the fixed parts of the size.
683 assert_eq!(src.layout.size, dest.layout.size);
687 src.ptr, src.align, dest.ptr, dest.align, dest_size, /*nonoverlapping*/ false,
691 /// Ensures that a place is in memory, and returns where it is.
692 /// If the place currently refers to a local that doesn't yet have a matching allocation,
693 /// create such an allocation.
694 /// This is essentially `force_to_memplace`.
695 #[instrument(skip(self), level = "debug")]
696 pub fn force_allocation(
698 place: &PlaceTy<'tcx, M::Provenance>,
699 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
700 let mplace = match place.place {
701 Place::Local { frame, local } => {
702 match M::access_local_mut(self, frame, local)? {
703 &mut Operand::Immediate(local_val) => {
704 // We need to make an allocation.
706 // We need the layout of the local. We can NOT use the layout we got,
707 // that might e.g., be an inner field of a struct with `Scalar` layout,
708 // that has different alignment than the outer field.
710 self.layout_of_local(&self.stack()[frame], local, None)?;
711 if local_layout.is_unsized() {
712 throw_unsup_format!("unsized locals are not supported");
714 let mplace = *self.allocate(local_layout, MemoryKind::Stack)?;
715 if !matches!(local_val, Immediate::Uninit) {
716 // Preserve old value. (As an optimization, we can skip this if it was uninit.)
717 // We don't have to validate as we can assume the local
718 // was already valid for its type.
719 self.write_immediate_to_mplace_no_validate(
722 local_layout.align.abi,
726 // Now we can call `access_mut` again, asserting it goes well,
727 // and actually overwrite things.
728 *M::access_local_mut(self, frame, local).unwrap() =
729 Operand::Indirect(mplace);
732 &mut Operand::Indirect(mplace) => mplace, // this already was an indirect local
735 Place::Ptr(mplace) => mplace,
737 // Return with the original layout, so that the caller can go on
738 Ok(MPlaceTy { mplace, layout: place.layout, align: place.align })
743 layout: TyAndLayout<'tcx>,
744 kind: MemoryKind<M::MemoryKind>,
745 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
746 assert!(layout.is_sized());
747 let ptr = self.allocate_ptr(layout.size, layout.align.abi, kind)?;
748 Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout))
751 /// Returns a wide MPlace of type `&'static [mut] str` to a new 1-aligned allocation.
755 kind: MemoryKind<M::MemoryKind>,
757 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
758 let ptr = self.allocate_bytes_ptr(str.as_bytes(), Align::ONE, kind, mutbl)?;
759 let meta = Scalar::from_machine_usize(u64::try_from(str.len()).unwrap(), self);
760 let mplace = MemPlace { ptr: ptr.into(), meta: MemPlaceMeta::Meta(meta) };
762 let ty = self.tcx.mk_ref(
763 self.tcx.lifetimes.re_static,
764 ty::TypeAndMut { ty: self.tcx.types.str_, mutbl },
766 let layout = self.layout_of(ty).unwrap();
767 Ok(MPlaceTy { mplace, layout, align: layout.align.abi })
770 /// Writes the aggregate to the destination.
771 #[instrument(skip(self), level = "trace")]
772 pub fn write_aggregate(
774 kind: &mir::AggregateKind<'tcx>,
775 operands: &[mir::Operand<'tcx>],
776 dest: &PlaceTy<'tcx, M::Provenance>,
777 ) -> InterpResult<'tcx> {
778 self.write_uninit(&dest)?;
779 let (variant_index, variant_dest, active_field_index) = match *kind {
780 mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
781 let variant_dest = self.place_downcast(&dest, variant_index)?;
782 (variant_index, variant_dest, active_field_index)
784 _ => (VariantIdx::from_u32(0), dest.clone(), None),
786 if active_field_index.is_some() {
787 assert_eq!(operands.len(), 1);
789 for (field_index, operand) in operands.iter().enumerate() {
790 let field_index = active_field_index.unwrap_or(field_index);
791 let field_dest = self.place_field(&variant_dest, field_index)?;
792 let op = self.eval_operand(operand, Some(field_dest.layout))?;
793 self.copy_op(&op, &field_dest, /*allow_transmute*/ false)?;
795 self.write_discriminant(variant_index, &dest)
798 pub fn raw_const_to_mplace(
800 raw: ConstAlloc<'tcx>,
801 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
802 // This must be an allocation in `tcx`
803 let _ = self.tcx.global_alloc(raw.alloc_id);
804 let ptr = self.global_base_pointer(Pointer::from(raw.alloc_id))?;
805 let layout = self.layout_of(raw.ty)?;
806 Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout))
809 /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
810 pub(super) fn unpack_dyn_trait(
812 mplace: &MPlaceTy<'tcx, M::Provenance>,
813 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
814 let vtable = mplace.vtable().to_pointer(self)?; // also sanity checks the type
815 let (ty, _) = self.get_ptr_vtable(vtable)?;
816 let layout = self.layout_of(ty)?;
818 let mplace = MPlaceTy {
819 mplace: MemPlace { meta: MemPlaceMeta::None, ..**mplace },
821 align: layout.align.abi,
827 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
828 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
831 use rustc_data_structures::static_assert_size;
832 // tidy-alphabetical-start
833 static_assert_size!(MemPlace, 40);
834 static_assert_size!(MemPlaceMeta, 24);
835 static_assert_size!(MPlaceTy<'_>, 64);
836 static_assert_size!(Place, 40);
837 static_assert_size!(PlaceTy<'_>, 64);
838 // tidy-alphabetical-end