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
::assert_matches
::assert_matches
;
7 use either
::{Either, Left, Right}
;
9 use rustc_ast
::Mutability
;
10 use rustc_index
::IndexSlice
;
11 use rustc_middle
::mir
;
13 use rustc_middle
::ty
::layout
::{LayoutOf, TyAndLayout}
;
14 use rustc_middle
::ty
::Ty
;
15 use rustc_target
::abi
::{Abi, Align, FieldIdx, HasDataLayout, Size, FIRST_VARIANT}
;
18 alloc_range
, mir_assign_valid_types
, AllocId
, AllocRef
, AllocRefMut
, CheckInAllocMsg
, ImmTy
,
19 Immediate
, InterpCx
, InterpResult
, Machine
, MemoryKind
, OpTy
, Operand
, Pointer
,
20 PointerArithmetic
, Projectable
, Provenance
, Readable
, Scalar
,
23 #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
24 /// Information required for the sound usage of a `MemPlace`.
25 pub enum MemPlaceMeta
<Prov
: Provenance
= AllocId
> {
26 /// The unsized payload (e.g. length for slices or vtable pointer for trait objects).
28 /// `Sized` types or unsized `extern type`
32 impl<Prov
: Provenance
> MemPlaceMeta
<Prov
> {
33 #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
34 pub fn unwrap_meta(self) -> Scalar
<Prov
> {
38 bug
!("expected wide pointer extra data (e.g. slice length or trait object vtable)")
44 pub fn has_meta(self) -> bool
{
46 Self::Meta(_
) => true,
52 #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
53 pub(super) struct MemPlace
<Prov
: Provenance
= AllocId
> {
54 /// The pointer can be a pure integer, with the `None` provenance.
55 pub ptr
: Pointer
<Option
<Prov
>>,
56 /// Metadata for unsized places. Interpretation is up to the type.
57 /// Must not be present for sized types, but can be missing for unsized types
58 /// (e.g., `extern type`).
59 pub meta
: MemPlaceMeta
<Prov
>,
62 impl<Prov
: Provenance
> MemPlace
<Prov
> {
64 pub fn from_ptr(ptr
: Pointer
<Option
<Prov
>>) -> Self {
65 MemPlace { ptr, meta: MemPlaceMeta::None }
69 pub fn from_ptr_with_meta(ptr
: Pointer
<Option
<Prov
>>, meta
: MemPlaceMeta
<Prov
>) -> Self {
70 MemPlace { ptr, meta }
73 /// Adjust the provenance of the main pointer (metadata is unaffected).
74 pub fn map_provenance(self, f
: impl FnOnce(Option
<Prov
>) -> Option
<Prov
>) -> Self {
75 MemPlace { ptr: self.ptr.map_provenance(f), ..self }
78 /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
80 pub fn to_ref(self, cx
: &impl HasDataLayout
) -> Immediate
<Prov
> {
82 MemPlaceMeta
::None
=> Immediate
::from(Scalar
::from_maybe_pointer(self.ptr
, cx
)),
83 MemPlaceMeta
::Meta(meta
) => {
84 Immediate
::ScalarPair(Scalar
::from_maybe_pointer(self.ptr
, cx
), meta
)
90 // Not called `offset_with_meta` to avoid confusion with the trait method.
91 fn offset_with_meta_
<'tcx
>(
94 meta
: MemPlaceMeta
<Prov
>,
95 cx
: &impl HasDataLayout
,
96 ) -> InterpResult
<'tcx
, Self> {
98 !meta
.has_meta() || self.meta
.has_meta(),
99 "cannot use `offset_with_meta` to add metadata to a place"
101 Ok(MemPlace { ptr: self.ptr.offset(offset, cx)?, meta }
)
105 /// A MemPlace with its layout. Constructing it is only possible in this module.
106 #[derive(Clone, Hash, Eq, PartialEq)]
107 pub struct MPlaceTy
<'tcx
, Prov
: Provenance
= AllocId
> {
108 mplace
: MemPlace
<Prov
>,
109 pub layout
: TyAndLayout
<'tcx
>,
110 /// rustc does not have a proper way to represent the type of a field of a `repr(packed)` struct:
111 /// it needs to have a different alignment than the field type would usually have.
112 /// So we represent this here with a separate field that "overwrites" `layout.align`.
113 /// This means `layout.align` should never be used for a `MPlaceTy`!
117 impl<Prov
: Provenance
> std
::fmt
::Debug
for MPlaceTy
<'_
, Prov
> {
118 fn fmt(&self, f
: &mut std
::fmt
::Formatter
<'_
>) -> std
::fmt
::Result
{
119 // Printing `layout` results in too much noise; just print a nice version of the type.
120 f
.debug_struct("MPlaceTy")
121 .field("mplace", &self.mplace
)
122 .field("ty", &format_args
!("{}", self.layout
.ty
))
127 impl<'tcx
, Prov
: Provenance
> MPlaceTy
<'tcx
, Prov
> {
128 /// Produces a MemPlace that works for ZST but nothing else.
129 /// Conceptually this is a new allocation, but it doesn't actually create an allocation so you
130 /// don't need to worry about memory leaks.
132 pub fn fake_alloc_zst(layout
: TyAndLayout
<'tcx
>) -> Self {
133 assert
!(layout
.is_zst());
134 let align
= layout
.align
.abi
;
135 let ptr
= Pointer
::from_addr_invalid(align
.bytes()); // no provenance, absolute address
136 MPlaceTy { mplace: MemPlace { ptr, meta: MemPlaceMeta::None }
, layout
, align
}
140 pub fn from_aligned_ptr(ptr
: Pointer
<Option
<Prov
>>, layout
: TyAndLayout
<'tcx
>) -> Self {
141 MPlaceTy { mplace: MemPlace::from_ptr(ptr), layout, align: layout.align.abi }
145 pub fn from_aligned_ptr_with_meta(
146 ptr
: Pointer
<Option
<Prov
>>,
147 layout
: TyAndLayout
<'tcx
>,
148 meta
: MemPlaceMeta
<Prov
>,
151 mplace
: MemPlace
::from_ptr_with_meta(ptr
, meta
),
153 align
: layout
.align
.abi
,
157 /// Adjust the provenance of the main pointer (metadata is unaffected).
158 pub fn map_provenance(self, f
: impl FnOnce(Option
<Prov
>) -> Option
<Prov
>) -> Self {
159 MPlaceTy { mplace: self.mplace.map_provenance(f), ..self }
163 pub(super) fn mplace(&self) -> &MemPlace
<Prov
> {
168 pub fn ptr(&self) -> Pointer
<Option
<Prov
>> {
173 pub fn to_ref(&self, cx
: &impl HasDataLayout
) -> Immediate
<Prov
> {
174 self.mplace
.to_ref(cx
)
178 impl<'tcx
, Prov
: Provenance
> Projectable
<'tcx
, Prov
> for MPlaceTy
<'tcx
, Prov
> {
180 fn layout(&self) -> TyAndLayout
<'tcx
> {
185 fn meta(&self) -> MemPlaceMeta
<Prov
> {
189 fn offset_with_meta
<'mir
, M
: Machine
<'mir
, 'tcx
, Provenance
= Prov
>>(
192 meta
: MemPlaceMeta
<Prov
>,
193 layout
: TyAndLayout
<'tcx
>,
194 ecx
: &InterpCx
<'mir
, 'tcx
, M
>,
195 ) -> InterpResult
<'tcx
, Self> {
197 mplace
: self.mplace
.offset_with_meta_(offset
, meta
, ecx
)?
,
198 align
: self.align
.restrict_for_offset(offset
),
203 fn to_op
<'mir
, M
: Machine
<'mir
, 'tcx
, Provenance
= Prov
>>(
205 _ecx
: &InterpCx
<'mir
, 'tcx
, M
>,
206 ) -> InterpResult
<'tcx
, OpTy
<'tcx
, M
::Provenance
>> {
207 Ok(self.clone().into())
211 #[derive(Copy, Clone, Debug)]
212 pub(super) enum Place
<Prov
: Provenance
= AllocId
> {
213 /// A place referring to a value allocated in the `Memory` system.
216 /// To support alloc-free locals, we are able to write directly to a local. The offset indicates
217 /// where in the local this place is located; if it is `None`, no projection has been applied.
218 /// Such projections are meaningful even if the offset is 0, since they can change layouts.
219 /// (Without that optimization, we'd just always be a `MemPlace`.)
220 /// Note that this only stores the frame index, not the thread this frame belongs to -- that is
221 /// implicit. This means a `Place` must never be moved across interpreter thread boundaries!
223 /// This variant shall not be used for unsized types -- those must always live in memory.
224 Local { frame: usize, local: mir::Local, offset: Option<Size> }
,
228 pub struct PlaceTy
<'tcx
, Prov
: Provenance
= AllocId
> {
229 place
: Place
<Prov
>, // Keep this private; it helps enforce invariants.
230 pub layout
: TyAndLayout
<'tcx
>,
231 /// rustc does not have a proper way to represent the type of a field of a `repr(packed)` struct:
232 /// it needs to have a different alignment than the field type would usually have.
233 /// So we represent this here with a separate field that "overwrites" `layout.align`.
234 /// This means `layout.align` should never be used for a `PlaceTy`!
238 impl<Prov
: Provenance
> std
::fmt
::Debug
for PlaceTy
<'_
, Prov
> {
239 fn fmt(&self, f
: &mut std
::fmt
::Formatter
<'_
>) -> std
::fmt
::Result
{
240 // Printing `layout` results in too much noise; just print a nice version of the type.
241 f
.debug_struct("PlaceTy")
242 .field("place", &self.place
)
243 .field("ty", &format_args
!("{}", self.layout
.ty
))
248 impl<'tcx
, Prov
: Provenance
> From
<MPlaceTy
<'tcx
, Prov
>> for PlaceTy
<'tcx
, Prov
> {
250 fn from(mplace
: MPlaceTy
<'tcx
, Prov
>) -> Self {
251 PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout, align: mplace.align }
255 impl<'tcx
, Prov
: Provenance
> PlaceTy
<'tcx
, Prov
> {
257 pub(super) fn place(&self) -> &Place
<Prov
> {
261 /// A place is either an mplace or some local.
263 pub fn as_mplace_or_local(
265 ) -> Either
<MPlaceTy
<'tcx
, Prov
>, (usize, mir
::Local
, Option
<Size
>)> {
267 Place
::Ptr(mplace
) => Left(MPlaceTy { mplace, layout: self.layout, align: self.align }
),
268 Place
::Local { frame, local, offset }
=> Right((frame
, local
, offset
)),
273 #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
274 pub fn assert_mem_place(&self) -> MPlaceTy
<'tcx
, Prov
> {
275 self.as_mplace_or_local().left().unwrap_or_else(|| {
277 "PlaceTy of type {} was a local when it was expected to be an MPlace",
284 impl<'tcx
, Prov
: Provenance
> Projectable
<'tcx
, Prov
> for PlaceTy
<'tcx
, Prov
> {
286 fn layout(&self) -> TyAndLayout
<'tcx
> {
291 fn meta(&self) -> MemPlaceMeta
<Prov
> {
292 match self.as_mplace_or_local() {
293 Left(mplace
) => mplace
.meta(),
295 debug_assert
!(self.layout
.is_sized(), "unsized locals should live in memory");
301 fn offset_with_meta
<'mir
, M
: Machine
<'mir
, 'tcx
, Provenance
= Prov
>>(
304 meta
: MemPlaceMeta
<Prov
>,
305 layout
: TyAndLayout
<'tcx
>,
306 ecx
: &InterpCx
<'mir
, 'tcx
, M
>,
307 ) -> InterpResult
<'tcx
, Self> {
308 Ok(match self.as_mplace_or_local() {
309 Left(mplace
) => mplace
.offset_with_meta(offset
, meta
, layout
, ecx
)?
.into(),
310 Right((frame
, local
, old_offset
)) => {
311 debug_assert
!(layout
.is_sized(), "unsized locals should live in memory");
312 assert_matches
!(meta
, MemPlaceMeta
::None
); // we couldn't store it anyway...
315 .offset(old_offset
.unwrap_or(Size
::ZERO
).bytes(), offset
.bytes())?
;
317 place
: Place
::Local
{
320 offset
: Some(Size
::from_bytes(new_offset
)),
322 align
: self.align
.restrict_for_offset(offset
),
329 fn to_op
<'mir
, M
: Machine
<'mir
, 'tcx
, Provenance
= Prov
>>(
331 ecx
: &InterpCx
<'mir
, 'tcx
, M
>,
332 ) -> InterpResult
<'tcx
, OpTy
<'tcx
, M
::Provenance
>> {
333 ecx
.place_to_op(self)
337 // These are defined here because they produce a place.
338 impl<'tcx
, Prov
: Provenance
> OpTy
<'tcx
, Prov
> {
340 pub fn as_mplace_or_imm(&self) -> Either
<MPlaceTy
<'tcx
, Prov
>, ImmTy
<'tcx
, Prov
>> {
342 Operand
::Indirect(mplace
) => {
343 Left(MPlaceTy { mplace: *mplace, layout: self.layout, align: self.align.unwrap() }
)
345 Operand
::Immediate(imm
) => Right(ImmTy
::from_immediate(*imm
, self.layout
)),
350 #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
351 pub fn assert_mem_place(&self) -> MPlaceTy
<'tcx
, Prov
> {
352 self.as_mplace_or_imm().left().unwrap_or_else(|| {
354 "OpTy of type {} was immediate when it was expected to be an MPlace",
361 /// The `Weiteable` trait describes interpreter values that can be written to.
362 pub trait Writeable
<'tcx
, Prov
: Provenance
>: Projectable
<'tcx
, Prov
> {
363 fn as_mplace_or_local(
365 ) -> Either
<MPlaceTy
<'tcx
, Prov
>, (usize, mir
::Local
, Option
<Size
>, Align
, TyAndLayout
<'tcx
>)>;
367 fn force_mplace
<'mir
, M
: Machine
<'mir
, 'tcx
, Provenance
= Prov
>>(
369 ecx
: &mut InterpCx
<'mir
, 'tcx
, M
>,
370 ) -> InterpResult
<'tcx
, MPlaceTy
<'tcx
, Prov
>>;
373 impl<'tcx
, Prov
: Provenance
> Writeable
<'tcx
, Prov
> for PlaceTy
<'tcx
, Prov
> {
375 fn as_mplace_or_local(
377 ) -> Either
<MPlaceTy
<'tcx
, Prov
>, (usize, mir
::Local
, Option
<Size
>, Align
, TyAndLayout
<'tcx
>)>
379 self.as_mplace_or_local()
380 .map_right(|(frame
, local
, offset
)| (frame
, local
, offset
, self.align
, self.layout
))
384 fn force_mplace
<'mir
, M
: Machine
<'mir
, 'tcx
, Provenance
= Prov
>>(
386 ecx
: &mut InterpCx
<'mir
, 'tcx
, M
>,
387 ) -> InterpResult
<'tcx
, MPlaceTy
<'tcx
, Prov
>> {
388 ecx
.force_allocation(self)
392 impl<'tcx
, Prov
: Provenance
> Writeable
<'tcx
, Prov
> for MPlaceTy
<'tcx
, Prov
> {
394 fn as_mplace_or_local(
396 ) -> Either
<MPlaceTy
<'tcx
, Prov
>, (usize, mir
::Local
, Option
<Size
>, Align
, TyAndLayout
<'tcx
>)>
402 fn force_mplace
<'mir
, M
: Machine
<'mir
, 'tcx
, Provenance
= Prov
>>(
404 _ecx
: &mut InterpCx
<'mir
, 'tcx
, M
>,
405 ) -> InterpResult
<'tcx
, MPlaceTy
<'tcx
, Prov
>> {
410 // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
411 impl<'mir
, 'tcx
: 'mir
, Prov
, M
> InterpCx
<'mir
, 'tcx
, M
>
414 M
: Machine
<'mir
, 'tcx
, Provenance
= Prov
>,
416 /// Take a value, which represents a (thin or wide) reference, and make it a place.
417 /// Alignment is just based on the type. This is the inverse of `mplace_to_ref()`.
419 /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
420 /// want to ever use the place for memory access!
421 /// Generally prefer `deref_pointer`.
422 pub fn ref_to_mplace(
424 val
: &ImmTy
<'tcx
, M
::Provenance
>,
425 ) -> InterpResult
<'tcx
, MPlaceTy
<'tcx
, M
::Provenance
>> {
427 val
.layout
.ty
.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty
;
428 let layout
= self.layout_of(pointee_type
)?
;
429 let (ptr
, meta
) = match **val
{
430 Immediate
::Scalar(ptr
) => (ptr
, MemPlaceMeta
::None
),
431 Immediate
::ScalarPair(ptr
, meta
) => (ptr
, MemPlaceMeta
::Meta(meta
)),
432 Immediate
::Uninit
=> throw_ub
!(InvalidUninitBytes(None
)),
435 // `ref_to_mplace` is called on raw pointers even if they don't actually get dereferenced;
436 // we hence can't call `size_and_align_of` since that asserts more validity than we want.
437 Ok(MPlaceTy
::from_aligned_ptr_with_meta(ptr
.to_pointer(self)?
, layout
, meta
))
440 /// Turn a mplace into a (thin or wide) mutable raw pointer, pointing to the same space.
441 /// `align` information is lost!
442 /// This is the inverse of `ref_to_mplace`.
443 pub fn mplace_to_ref(
445 mplace
: &MPlaceTy
<'tcx
, M
::Provenance
>,
446 ) -> InterpResult
<'tcx
, ImmTy
<'tcx
, M
::Provenance
>> {
447 let imm
= mplace
.mplace
.to_ref(self);
448 let layout
= self.layout_of(Ty
::new_mut_ptr(self.tcx
.tcx
, mplace
.layout
.ty
))?
;
449 Ok(ImmTy
::from_immediate(imm
, layout
))
452 /// Take an operand, representing a pointer, and dereference it to a place.
453 /// Corresponds to the `*` operator in Rust.
454 #[instrument(skip(self), level = "debug")]
455 pub fn deref_pointer(
457 src
: &impl Readable
<'tcx
, M
::Provenance
>,
458 ) -> InterpResult
<'tcx
, MPlaceTy
<'tcx
, M
::Provenance
>> {
459 let val
= self.read_immediate(src
)?
;
460 trace
!("deref to {} on {:?}", val
.layout
.ty
, *val
);
462 if val
.layout
.ty
.is_box() {
463 bug
!("dereferencing {}", val
.layout
.ty
);
466 let mplace
= self.ref_to_mplace(&val
)?
;
467 self.check_mplace(&mplace
)?
;
472 pub(super) fn get_place_alloc(
474 mplace
: &MPlaceTy
<'tcx
, M
::Provenance
>,
475 ) -> InterpResult
<'tcx
, Option
<AllocRef
<'_
, 'tcx
, M
::Provenance
, M
::AllocExtra
, M
::Bytes
>>>
477 let (size
, _align
) = self
478 .size_and_align_of_mplace(&mplace
)?
479 .unwrap_or((mplace
.layout
.size
, mplace
.layout
.align
.abi
));
480 // Due to packed places, only `mplace.align` matters.
481 self.get_ptr_alloc(mplace
.ptr(), size
, mplace
.align
)
485 pub(super) fn get_place_alloc_mut(
487 mplace
: &MPlaceTy
<'tcx
, M
::Provenance
>,
488 ) -> InterpResult
<'tcx
, Option
<AllocRefMut
<'_
, 'tcx
, M
::Provenance
, M
::AllocExtra
, M
::Bytes
>>>
490 let (size
, _align
) = self
491 .size_and_align_of_mplace(&mplace
)?
492 .unwrap_or((mplace
.layout
.size
, mplace
.layout
.align
.abi
));
493 // Due to packed places, only `mplace.align` matters.
494 self.get_ptr_alloc_mut(mplace
.ptr(), size
, mplace
.align
)
497 /// Check if this mplace is dereferenceable and sufficiently aligned.
498 pub fn check_mplace(&self, mplace
: &MPlaceTy
<'tcx
, M
::Provenance
>) -> InterpResult
<'tcx
> {
499 let (size
, _align
) = self
500 .size_and_align_of_mplace(&mplace
)?
501 .unwrap_or((mplace
.layout
.size
, mplace
.layout
.align
.abi
));
502 // Due to packed places, only `mplace.align` matters.
504 if M
::enforce_alignment(self).should_check() { mplace.align }
else { Align::ONE }
;
505 self.check_ptr_access_align(mplace
.ptr(), size
, align
, CheckInAllocMsg
::DerefTest
)?
;
509 /// Converts a repr(simd) place into a place where `place_index` accesses the SIMD elements.
510 /// Also returns the number of elements.
511 pub fn mplace_to_simd(
513 mplace
: &MPlaceTy
<'tcx
, M
::Provenance
>,
514 ) -> InterpResult
<'tcx
, (MPlaceTy
<'tcx
, M
::Provenance
>, u64)> {
515 // Basically we just transmute this place into an array following simd_size_and_type.
516 // (Transmuting is okay since this is an in-memory place. We also double-check the size
518 let (len
, e_ty
) = mplace
.layout
.ty
.simd_size_and_type(*self.tcx
);
519 let array
= Ty
::new_array(self.tcx
.tcx
, e_ty
, len
);
520 let layout
= self.layout_of(array
)?
;
521 assert_eq
!(layout
.size
, mplace
.layout
.size
);
522 Ok((MPlaceTy { layout, ..*mplace }
, len
))
525 /// Converts a repr(simd) place into a place where `place_index` accesses the SIMD elements.
526 /// Also returns the number of elements.
527 pub fn place_to_simd(
529 place
: &PlaceTy
<'tcx
, M
::Provenance
>,
530 ) -> InterpResult
<'tcx
, (MPlaceTy
<'tcx
, M
::Provenance
>, u64)> {
531 let mplace
= self.force_allocation(place
)?
;
532 self.mplace_to_simd(&mplace
)
535 pub fn local_to_place(
539 ) -> InterpResult
<'tcx
, PlaceTy
<'tcx
, M
::Provenance
>> {
540 // Other parts of the system rely on `Place::Local` never being unsized.
541 // So we eagerly check here if this local has an MPlace, and if yes we use it.
542 let frame_ref
= &self.stack()[frame
];
543 let layout
= self.layout_of_local(frame_ref
, local
, None
)?
;
544 let place
= if layout
.is_sized() {
545 // We can just always use the `Local` for sized values.
546 Place
::Local { frame, local, offset: None }
548 // Unsized `Local` isn't okay (we cannot store the metadata).
549 match frame_ref
.locals
[local
].access()?
{
550 Operand
::Immediate(_
) => {
551 // ConstProp marks *all* locals as `Immediate::Uninit` since it cannot
552 // efficiently check whether they are sized. We have to catch that case here.
553 throw_inval
!(ConstPropNonsense
);
555 Operand
::Indirect(mplace
) => Place
::Ptr(*mplace
),
558 Ok(PlaceTy { place, layout, align: layout.align.abi }
)
561 /// Computes a place. You should only use this if you intend to write into this
562 /// place; for reading, a more efficient alternative is `eval_place_to_op`.
563 #[instrument(skip(self), level = "debug")]
566 mir_place
: mir
::Place
<'tcx
>,
567 ) -> InterpResult
<'tcx
, PlaceTy
<'tcx
, M
::Provenance
>> {
568 let mut place
= self.local_to_place(self.frame_idx(), mir_place
.local
)?
;
569 // Using `try_fold` turned out to be bad for performance, hence the loop.
570 for elem
in mir_place
.projection
.iter() {
571 place
= self.project(&place
, elem
)?
574 trace
!("{:?}", self.dump_place(&place
));
575 // Sanity-check the type we ended up with.
577 mir_assign_valid_types(
580 self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions(
581 mir_place
.ty(&self.frame().body
.local_decls
, *self.tcx
).ty
585 "eval_place of a MIR place with type {:?} produced an interpreter place with type {}",
586 mir_place
.ty(&self.frame().body
.local_decls
, *self.tcx
).ty
,
592 /// Write an immediate to a place
594 #[instrument(skip(self), level = "debug")]
595 pub fn write_immediate(
597 src
: Immediate
<M
::Provenance
>,
598 dest
: &impl Writeable
<'tcx
, M
::Provenance
>,
599 ) -> InterpResult
<'tcx
> {
600 self.write_immediate_no_validate(src
, dest
)?
;
602 if M
::enforce_validity(self, dest
.layout()) {
603 // Data got changed, better make sure it matches the type!
604 self.validate_operand(&dest
.to_op(self)?
)?
;
610 /// Write a scalar to a place
614 val
: impl Into
<Scalar
<M
::Provenance
>>,
615 dest
: &impl Writeable
<'tcx
, M
::Provenance
>,
616 ) -> InterpResult
<'tcx
> {
617 self.write_immediate(Immediate
::Scalar(val
.into()), dest
)
620 /// Write a pointer to a place
622 pub fn write_pointer(
624 ptr
: impl Into
<Pointer
<Option
<M
::Provenance
>>>,
625 dest
: &impl Writeable
<'tcx
, M
::Provenance
>,
626 ) -> InterpResult
<'tcx
> {
627 self.write_scalar(Scalar
::from_maybe_pointer(ptr
.into(), self), dest
)
630 /// Write an immediate to a place.
631 /// If you use this you are responsible for validating that things got copied at the
633 fn write_immediate_no_validate(
635 src
: Immediate
<M
::Provenance
>,
636 dest
: &impl Writeable
<'tcx
, M
::Provenance
>,
637 ) -> InterpResult
<'tcx
> {
638 assert
!(dest
.layout().is_sized(), "Cannot write unsized immediate data");
640 // See if we can avoid an allocation. This is the counterpart to `read_immediate_raw`,
641 // but not factored as a separate function.
642 let mplace
= match dest
.as_mplace_or_local() {
643 Right((frame
, local
, offset
, align
, layout
)) => {
644 if offset
.is_some() {
645 // This has been projected to a part of this local. We could have complicated
646 // logic to still keep this local as an `Operand`... but it's much easier to
647 // just fall back to the indirect path.
648 dest
.force_mplace(self)?
650 M
::before_access_local_mut(self, frame
, local
)?
;
651 match self.stack_mut()[frame
].locals
[local
].access_mut()?
{
652 Operand
::Immediate(local_val
) => {
653 // Local can be updated in-place.
655 // Double-check that the value we are storing and the local fit to each other.
656 // (*After* doing the update for borrow checker reasons.)
657 if cfg
!(debug_assertions
) {
659 self.layout_of_local(&self.stack()[frame
], local
, None
)?
;
660 match (src
, local_layout
.abi
) {
661 (Immediate
::Scalar(scalar
), Abi
::Scalar(s
)) => {
662 assert_eq
!(scalar
.size(), s
.size(self))
665 Immediate
::ScalarPair(a_val
, b_val
),
666 Abi
::ScalarPair(a
, b
),
668 assert_eq
!(a_val
.size(), a
.size(self));
669 assert_eq
!(b_val
.size(), b
.size(self));
671 (Immediate
::Uninit
, _
) => {}
674 "value {src:?} cannot be written into local with type {} (ABI {abi:?})",
682 Operand
::Indirect(mplace
) => {
683 // The local is in memory, go on below.
684 MPlaceTy { mplace: *mplace, align, layout }
689 Left(mplace
) => mplace
, // already referring to memory
692 // This is already in memory, write there.
693 self.write_immediate_to_mplace_no_validate(src
, mplace
.layout
, mplace
.align
, mplace
.mplace
)
696 /// Write an immediate to memory.
697 /// If you use this you are responsible for validating that things got copied at the
699 fn write_immediate_to_mplace_no_validate(
701 value
: Immediate
<M
::Provenance
>,
702 layout
: TyAndLayout
<'tcx
>,
704 dest
: MemPlace
<M
::Provenance
>,
705 ) -> InterpResult
<'tcx
> {
706 // Note that it is really important that the type here is the right one, and matches the
707 // type things are read at. In case `value` is a `ScalarPair`, we don't do any magic here
708 // to handle padding properly, which is only correct if we never look at this data with the
712 let Some(mut alloc
) =
713 self.get_place_alloc_mut(&MPlaceTy { mplace: dest, layout, align }
)?
720 Immediate
::Scalar(scalar
) => {
721 let Abi
::Scalar(s
) = layout
.abi
else {
724 "write_immediate_to_mplace: invalid Scalar layout: {layout:#?}",
727 let size
= s
.size(&tcx
);
728 assert_eq
!(size
, layout
.size
, "abi::Scalar size does not match layout size");
729 alloc
.write_scalar(alloc_range(Size
::ZERO
, size
), scalar
)
731 Immediate
::ScalarPair(a_val
, b_val
) => {
732 // We checked `ptr_align` above, so all fields will have the alignment they need.
733 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
734 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
735 let Abi
::ScalarPair(a
, b
) = layout
.abi
else {
738 "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
742 let (a_size
, b_size
) = (a
.size(&tcx
), b
.size(&tcx
));
743 let b_offset
= a_size
.align_to(b
.align(&tcx
).abi
);
744 assert
!(b_offset
.bytes() > 0); // in `operand_field` we use the offset to tell apart the fields
746 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
747 // but that does not work: We could be a newtype around a pair, then the
748 // fields do not match the `ScalarPair` components.
750 alloc
.write_scalar(alloc_range(Size
::ZERO
, a_size
), a_val
)?
;
751 alloc
.write_scalar(alloc_range(b_offset
, b_size
), b_val
)
753 Immediate
::Uninit
=> alloc
.write_uninit(),
759 dest
: &impl Writeable
<'tcx
, M
::Provenance
>,
760 ) -> InterpResult
<'tcx
> {
761 let mplace
= match dest
.as_mplace_or_local() {
762 Left(mplace
) => mplace
,
763 Right((frame
, local
, offset
, align
, layout
)) => {
764 if offset
.is_some() {
765 // This has been projected to a part of this local. We could have complicated
766 // logic to still keep this local as an `Operand`... but it's much easier to
767 // just fall back to the indirect path.
768 // FIXME: share the logic with `write_immediate_no_validate`.
769 dest
.force_mplace(self)?
771 M
::before_access_local_mut(self, frame
, local
)?
;
772 match self.stack_mut()[frame
].locals
[local
].access_mut()?
{
773 Operand
::Immediate(local
) => {
774 *local
= Immediate
::Uninit
;
777 Operand
::Indirect(mplace
) => {
778 // The local is in memory, go on below.
779 MPlaceTy { mplace: *mplace, layout, align }
785 let Some(mut alloc
) = self.get_place_alloc_mut(&mplace
)?
else {
789 alloc
.write_uninit()?
;
793 /// Copies the data from an operand to a place.
794 /// `allow_transmute` indicates whether the layouts may disagree.
796 #[instrument(skip(self), level = "debug")]
799 src
: &impl Readable
<'tcx
, M
::Provenance
>,
800 dest
: &impl Writeable
<'tcx
, M
::Provenance
>,
801 allow_transmute
: bool
,
802 ) -> InterpResult
<'tcx
> {
803 // Generally for transmutation, data must be valid both at the old and new type.
804 // But if the types are the same, the 2nd validation below suffices.
805 if src
.layout().ty
!= dest
.layout().ty
&& M
::enforce_validity(self, src
.layout()) {
806 self.validate_operand(&src
.to_op(self)?
)?
;
809 // Do the actual copy.
810 self.copy_op_no_validate(src
, dest
, allow_transmute
)?
;
812 if M
::enforce_validity(self, dest
.layout()) {
813 // Data got changed, better make sure it matches the type!
814 self.validate_operand(&dest
.to_op(self)?
)?
;
820 /// Copies the data from an operand to a place.
821 /// `allow_transmute` indicates whether the layouts may disagree.
822 /// Also, if you use this you are responsible for validating that things get copied at the
824 #[instrument(skip(self), level = "debug")]
825 fn copy_op_no_validate(
827 src
: &impl Readable
<'tcx
, M
::Provenance
>,
828 dest
: &impl Writeable
<'tcx
, M
::Provenance
>,
829 allow_transmute
: bool
,
830 ) -> InterpResult
<'tcx
> {
831 // We do NOT compare the types for equality, because well-typed code can
832 // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
834 mir_assign_valid_types(*self.tcx
, self.param_env
, src
.layout(), dest
.layout());
835 if !allow_transmute
&& !layout_compat
{
838 "type mismatch when copying!\nsrc: {},\ndest: {}",
844 // Let us see if the layout is simple so we take a shortcut,
845 // avoid force_allocation.
846 let src
= match self.read_immediate_raw(src
)?
{
848 // FIXME(const_prop): Const-prop can possibly evaluate an
849 // unsized copy operation when it thinks that the type is
850 // actually sized, due to a trivially false where-clause
851 // predicate like `where Self: Sized` with `Self = dyn Trait`.
852 // See #102553 for an example of such a predicate.
853 if src
.layout().is_unsized() {
854 throw_inval
!(ConstPropNonsense
);
856 if dest
.layout().is_unsized() {
857 throw_inval
!(ConstPropNonsense
);
859 assert_eq
!(src
.layout().size
, dest
.layout().size
);
860 // Yay, we got a value that we can write directly.
861 return if layout_compat
{
862 self.write_immediate_no_validate(*src_val
, dest
)
864 // This is tricky. The problematic case is `ScalarPair`: the `src_val` was
865 // loaded using the offsets defined by `src.layout`. When we put this back into
866 // the destination, we have to use the same offsets! So (a) we make sure we
867 // write back to memory, and (b) we use `dest` *with the source layout*.
868 let dest_mem
= dest
.force_mplace(self)?
;
869 self.write_immediate_to_mplace_no_validate(
877 Left(mplace
) => mplace
,
879 // Slow path, this does not fit into an immediate. Just memcpy.
880 trace
!("copy_op: {:?} <- {:?}: {}", *dest
, src
, dest
.layout().ty
);
882 let dest
= dest
.force_mplace(self)?
;
883 let Some((dest_size
, _
)) = self.size_and_align_of_mplace(&dest
)?
else {
884 span_bug
!(self.cur_span(), "copy_op needs (dynamically) sized values")
886 if cfg
!(debug_assertions
) {
887 let src_size
= self.size_and_align_of_mplace(&src
)?
.unwrap().0;
888 assert_eq
!(src_size
, dest_size
, "Cannot copy differently-sized data");
890 // As a cheap approximation, we compare the fixed parts of the size.
891 assert_eq
!(src
.layout
.size
, dest
.layout
.size
);
894 // Setting `nonoverlapping` here only has an effect when we don't hit the fast-path above,
895 // but that should at least match what LLVM does where `memcpy` is also only used when the
896 // type does not have Scalar/ScalarPair layout.
897 // (Or as the `Assign` docs put it, assignments "not producing primitives" must be
905 /*nonoverlapping*/ true,
909 /// Ensures that a place is in memory, and returns where it is.
910 /// If the place currently refers to a local that doesn't yet have a matching allocation,
911 /// create such an allocation.
912 /// This is essentially `force_to_memplace`.
913 #[instrument(skip(self), level = "debug")]
914 pub fn force_allocation(
916 place
: &PlaceTy
<'tcx
, M
::Provenance
>,
917 ) -> InterpResult
<'tcx
, MPlaceTy
<'tcx
, M
::Provenance
>> {
918 let mplace
= match place
.place
{
919 Place
::Local { frame, local, offset }
=> {
920 M
::before_access_local_mut(self, frame
, local
)?
;
921 let whole_local
= match self.stack_mut()[frame
].locals
[local
].access_mut()?
{
922 &mut Operand
::Immediate(local_val
) => {
923 // We need to make an allocation.
925 // We need the layout of the local. We can NOT use the layout we got,
926 // that might e.g., be an inner field of a struct with `Scalar` layout,
927 // that has different alignment than the outer field.
929 self.layout_of_local(&self.stack()[frame
], local
, None
)?
;
930 assert
!(local_layout
.is_sized(), "unsized locals cannot be immediate");
931 let mplace
= self.allocate(local_layout
, MemoryKind
::Stack
)?
;
932 // Preserve old value. (As an optimization, we can skip this if it was uninit.)
933 if !matches
!(local_val
, Immediate
::Uninit
) {
934 // We don't have to validate as we can assume the local was already
935 // valid for its type. We must not use any part of `place` here, that
936 // could be a projection to a part of the local!
937 self.write_immediate_to_mplace_no_validate(
940 local_layout
.align
.abi
,
944 M
::after_local_allocated(self, frame
, local
, &mplace
)?
;
945 // Now we can call `access_mut` again, asserting it goes well, and actually
946 // overwrite things. This points to the entire allocation, not just the part
947 // the place refers to, i.e. we do this before we apply `offset`.
948 *self.stack_mut()[frame
].locals
[local
].access_mut().unwrap() =
949 Operand
::Indirect(mplace
.mplace
);
952 &mut Operand
::Indirect(mplace
) => mplace
, // this already was an indirect local
954 if let Some(offset
) = offset
{
955 whole_local
.offset_with_meta_(offset
, MemPlaceMeta
::None
, self)?
957 // Preserve wide place metadata, do not call `offset`.
961 Place
::Ptr(mplace
) => mplace
,
963 // Return with the original layout and align, so that the caller can go on
964 Ok(MPlaceTy { mplace, layout: place.layout, align: place.align }
)
969 layout
: TyAndLayout
<'tcx
>,
970 kind
: MemoryKind
<M
::MemoryKind
>,
971 meta
: MemPlaceMeta
<M
::Provenance
>,
972 ) -> InterpResult
<'tcx
, MPlaceTy
<'tcx
, M
::Provenance
>> {
973 let Some((size
, align
)) = self.size_and_align_of(&meta
, &layout
)?
else {
974 span_bug
!(self.cur_span(), "cannot allocate space for `extern` type, size is not known")
976 let ptr
= self.allocate_ptr(size
, align
, kind
)?
;
977 Ok(MPlaceTy
::from_aligned_ptr_with_meta(ptr
.into(), layout
, meta
))
982 layout
: TyAndLayout
<'tcx
>,
983 kind
: MemoryKind
<M
::MemoryKind
>,
984 ) -> InterpResult
<'tcx
, MPlaceTy
<'tcx
, M
::Provenance
>> {
985 assert
!(layout
.is_sized());
986 self.allocate_dyn(layout
, kind
, MemPlaceMeta
::None
)
989 /// Returns a wide MPlace of type `&'static [mut] str` to a new 1-aligned allocation.
993 kind
: MemoryKind
<M
::MemoryKind
>,
995 ) -> InterpResult
<'tcx
, MPlaceTy
<'tcx
, M
::Provenance
>> {
996 let ptr
= self.allocate_bytes_ptr(str.as_bytes(), Align
::ONE
, kind
, mutbl
)?
;
997 let meta
= Scalar
::from_target_usize(u64::try_from(str.len()).unwrap(), self);
998 let mplace
= MemPlace { ptr: ptr.into(), meta: MemPlaceMeta::Meta(meta) }
;
1000 let ty
= Ty
::new_ref(
1002 self.tcx
.lifetimes
.re_static
,
1003 ty
::TypeAndMut { ty: self.tcx.types.str_, mutbl }
,
1005 let layout
= self.layout_of(ty
).unwrap();
1006 Ok(MPlaceTy { mplace, layout, align: layout.align.abi }
)
1009 /// Writes the aggregate to the destination.
1010 #[instrument(skip(self), level = "trace")]
1011 pub fn write_aggregate(
1013 kind
: &mir
::AggregateKind
<'tcx
>,
1014 operands
: &IndexSlice
<FieldIdx
, mir
::Operand
<'tcx
>>,
1015 dest
: &PlaceTy
<'tcx
, M
::Provenance
>,
1016 ) -> InterpResult
<'tcx
> {
1017 self.write_uninit(dest
)?
;
1018 let (variant_index
, variant_dest
, active_field_index
) = match *kind
{
1019 mir
::AggregateKind
::Adt(_
, variant_index
, _
, _
, active_field_index
) => {
1020 let variant_dest
= self.project_downcast(dest
, variant_index
)?
;
1021 (variant_index
, variant_dest
, active_field_index
)
1023 _
=> (FIRST_VARIANT
, dest
.clone(), None
),
1025 if active_field_index
.is_some() {
1026 assert_eq
!(operands
.len(), 1);
1028 for (field_index
, operand
) in operands
.iter_enumerated() {
1029 let field_index
= active_field_index
.unwrap_or(field_index
);
1030 let field_dest
= self.project_field(&variant_dest
, field_index
.as_usize())?
;
1031 let op
= self.eval_operand(operand
, Some(field_dest
.layout
))?
;
1032 self.copy_op(&op
, &field_dest
, /*allow_transmute*/ false)?
;
1034 self.write_discriminant(variant_index
, dest
)
1037 pub fn raw_const_to_mplace(
1039 raw
: mir
::ConstAlloc
<'tcx
>,
1040 ) -> InterpResult
<'tcx
, MPlaceTy
<'tcx
, M
::Provenance
>> {
1041 // This must be an allocation in `tcx`
1042 let _
= self.tcx
.global_alloc(raw
.alloc_id
);
1043 let ptr
= self.global_base_pointer(Pointer
::from(raw
.alloc_id
))?
;
1044 let layout
= self.layout_of(raw
.ty
)?
;
1045 Ok(MPlaceTy
::from_aligned_ptr(ptr
.into(), layout
))
1048 /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
1049 /// Aso returns the vtable.
1050 pub(super) fn unpack_dyn_trait(
1052 mplace
: &MPlaceTy
<'tcx
, M
::Provenance
>,
1053 ) -> InterpResult
<'tcx
, (MPlaceTy
<'tcx
, M
::Provenance
>, Pointer
<Option
<M
::Provenance
>>)> {
1055 matches
!(mplace
.layout
.ty
.kind(), ty
::Dynamic(_
, _
, ty
::Dyn
)),
1056 "`unpack_dyn_trait` only makes sense on `dyn*` types"
1058 let vtable
= mplace
.meta().unwrap_meta().to_pointer(self)?
;
1059 let (ty
, _
) = self.get_ptr_vtable(vtable
)?
;
1060 let layout
= self.layout_of(ty
)?
;
1062 let mplace
= MPlaceTy
{
1063 mplace
: MemPlace { meta: MemPlaceMeta::None, ..mplace.mplace }
,
1065 align
: layout
.align
.abi
,
1067 Ok((mplace
, vtable
))
1070 /// Turn a `dyn* Trait` type into an value with the actual dynamic type.
1071 /// Also returns the vtable.
1072 pub(super) fn unpack_dyn_star
<P
: Projectable
<'tcx
, M
::Provenance
>>(
1075 ) -> InterpResult
<'tcx
, (P
, Pointer
<Option
<M
::Provenance
>>)> {
1077 matches
!(val
.layout().ty
.kind(), ty
::Dynamic(_
, _
, ty
::DynStar
)),
1078 "`unpack_dyn_star` only makes sense on `dyn*` types"
1080 let data
= self.project_field(val
, 0)?
;
1081 let vtable
= self.project_field(val
, 1)?
;
1082 let vtable
= self.read_pointer(&vtable
.to_op(self)?
)?
;
1083 let (ty
, _
) = self.get_ptr_vtable(vtable
)?
;
1084 let layout
= self.layout_of(ty
)?
;
1085 // `data` is already the right thing but has the wrong type. So we transmute it, by
1086 // projecting with offset 0.
1087 let data
= data
.transmute(layout
, self)?
;
1092 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
1093 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
1096 use rustc_data_structures
::static_assert_size
;
1097 // tidy-alphabetical-start
1098 static_assert_size
!(MemPlace
, 40);
1099 static_assert_size
!(MemPlaceMeta
, 24);
1100 static_assert_size
!(MPlaceTy
<'_
>, 64);
1101 static_assert_size
!(Place
, 40);
1102 static_assert_size
!(PlaceTy
<'_
>, 64);
1103 // tidy-alphabetical-end