place.rs 47.4 KB
Newer Older
R
Ralf Jung 已提交
1 2 3 4 5
//! Computations on places -- field projections, going from mir::Place, and writing
//! into a place.
//! All high-level functions to write to memory work on places as destinations.

use std::convert::TryFrom;
6
use std::hash::Hash;
R
Ralf Jung 已提交
7

M
Mazdak Farrokhzad 已提交
8 9
use rustc_macros::HashStable;
use rustc_middle::mir;
10
use rustc_middle::ty::layout::{PrimitiveExt, TyAndLayout};
M
Mazdak Farrokhzad 已提交
11
use rustc_middle::ty::{self, Ty};
12 13
use rustc_target::abi::{Abi, Align, DiscriminantKind, FieldsShape};
use rustc_target::abi::{HasDataLayout, LayoutOf, Size, VariantIdx, Variants};
O
Oliver Schneider 已提交
14

15
use super::{
16 17 18
    mir_assign_valid_types, truncate, AllocId, AllocMap, Allocation, AllocationExtra, ImmTy,
    Immediate, InterpCx, InterpResult, LocalValue, Machine, MemoryKind, OpTy, Operand, Pointer,
    PointerArithmetic, RawConst, Scalar, ScalarMaybeUndef,
R
Ralf Jung 已提交
19 20
};

21
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
O
Oliver Scherer 已提交
22
/// Information required for the sound usage of a `MemPlace`.
23
pub enum MemPlaceMeta<Tag = (), Id = AllocId> {
O
Oliver Scherer 已提交
24
    /// The unsized payload (e.g. length for slices or vtable pointer for trait objects).
O
Oliver Scherer 已提交
25
    Meta(Scalar<Tag, Id>),
26 27 28 29 30 31 32 33 34 35
    /// `Sized` types or unsized `extern type`
    None,
    /// The address of this place may not be taken. This protects the `MemPlace` from coming from
    /// a ZST Operand with a backing allocation and being converted to an integer address. This
    /// should be impossible, because you can't take the address of an operand, but this is a second
    /// protection layer ensuring that we don't mess up.
    Poison,
}

impl<Tag, Id> MemPlaceMeta<Tag, Id> {
O
Oliver Scherer 已提交
36
    pub fn unwrap_meta(self) -> Scalar<Tag, Id> {
37
        match self {
O
Oliver Scherer 已提交
38
            Self::Meta(s) => s,
39 40 41 42 43
            Self::None | Self::Poison => {
                bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)")
            }
        }
    }
O
Oliver Scherer 已提交
44
    fn has_meta(self) -> bool {
45
        match self {
O
Oliver Scherer 已提交
46
            Self::Meta(_) => true,
47 48 49 50 51 52 53 54
            Self::None | Self::Poison => false,
        }
    }
}

impl<Tag> MemPlaceMeta<Tag> {
    pub fn erase_tag(self) -> MemPlaceMeta<()> {
        match self {
O
Oliver Scherer 已提交
55
            Self::Meta(s) => MemPlaceMeta::Meta(s.erase_tag()),
56 57 58 59 60 61
            Self::None => MemPlaceMeta::None,
            Self::Poison => MemPlaceMeta::Poison,
        }
    }
}

62
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
M
Mark Rousskov 已提交
63
pub struct MemPlace<Tag = (), Id = AllocId> {
R
Ralf Jung 已提交
64 65 66
    /// A place may have an integral pointer for ZSTs, and since it might
    /// be turned back into a reference before ever being dereferenced.
    /// However, it may never be undef.
67
    pub ptr: Scalar<Tag, Id>,
68
    pub align: Align,
A
Alexander Regueiro 已提交
69
    /// Metadata for unsized places. Interpretation is up to the type.
R
Ralf Jung 已提交
70
    /// Must not be present for sized types, but can be missing for unsized types
71
    /// (e.g., `extern type`).
72
    pub meta: MemPlaceMeta<Tag, Id>,
R
Ralf Jung 已提交
73
}
O
Oliver Schneider 已提交
74

75
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
M
Mark Rousskov 已提交
76
pub enum Place<Tag = (), Id = AllocId> {
77
    /// A place referring to a value allocated in the `Memory` system.
78
    Ptr(MemPlace<Tag, Id>),
O
Oliver Schneider 已提交
79

R
Ralf Jung 已提交
80 81
    /// To support alloc-free locals, we are able to write directly to a local.
    /// (Without that optimization, we'd just always be a `MemPlace`.)
M
Mark Rousskov 已提交
82
    Local { frame: usize, local: mir::Local },
O
Oliver Schneider 已提交
83 84
}

R
Ralf Jung 已提交
85
#[derive(Copy, Clone, Debug)]
M
Mark Rousskov 已提交
86
pub struct PlaceTy<'tcx, Tag = ()> {
87
    place: Place<Tag>, // Keep this private; it helps enforce invariants.
88
    pub layout: TyAndLayout<'tcx>,
R
Ralf Jung 已提交
89 90
}

91 92
impl<'tcx, Tag> ::std::ops::Deref for PlaceTy<'tcx, Tag> {
    type Target = Place<Tag>;
93
    #[inline(always)]
94
    fn deref(&self) -> &Place<Tag> {
R
Ralf Jung 已提交
95 96 97 98 99
        &self.place
    }
}

/// A MemPlace with its layout. Constructing it is only possible in this module.
100
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
M
Mark Rousskov 已提交
101
pub struct MPlaceTy<'tcx, Tag = ()> {
102
    mplace: MemPlace<Tag>,
103
    pub layout: TyAndLayout<'tcx>,
R
Ralf Jung 已提交
104 105
}

106 107
impl<'tcx, Tag> ::std::ops::Deref for MPlaceTy<'tcx, Tag> {
    type Target = MemPlace<Tag>;
108
    #[inline(always)]
109
    fn deref(&self) -> &MemPlace<Tag> {
R
Ralf Jung 已提交
110
        &self.mplace
O
Oliver Schneider 已提交
111
    }
R
Ralf Jung 已提交
112 113
}

114
impl<'tcx, Tag> From<MPlaceTy<'tcx, Tag>> for PlaceTy<'tcx, Tag> {
115
    #[inline(always)]
116
    fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
M
Mark Rousskov 已提交
117
        PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout }
R
Ralf Jung 已提交
118 119
    }
}
O
Oliver Schneider 已提交
120

121 122
impl<Tag> MemPlace<Tag> {
    /// Replace ptr tag, maintain vtable tag (if any)
123
    #[inline]
124
    pub fn replace_tag(self, new_tag: Tag) -> Self {
M
Mark Rousskov 已提交
125
        MemPlace { ptr: self.ptr.erase_tag().with_tag(new_tag), align: self.align, meta: self.meta }
126 127 128
    }

    #[inline]
129
    pub fn erase_tag(self) -> MemPlace {
130
        MemPlace { ptr: self.ptr.erase_tag(), align: self.align, meta: self.meta.erase_tag() }
131 132
    }

R
Ralf Jung 已提交
133
    #[inline(always)]
134
    fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
135
        MemPlace { ptr, align, meta: MemPlaceMeta::None }
O
Oliver Schneider 已提交
136 137
    }

138 139
    /// Produces a Place that will error if attempted to be read from or written to
    #[inline(always)]
140
    fn null(cx: &impl HasDataLayout) -> Self {
141
        Self::from_scalar_ptr(Scalar::null_ptr(cx), Align::from_bytes(1).unwrap())
142 143
    }

R
Ralf Jung 已提交
144
    #[inline(always)]
145
    pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
R
Ralf Jung 已提交
146 147 148
        Self::from_scalar_ptr(ptr.into(), align)
    }

R
Ralf Jung 已提交
149
    /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
150 151 152 153
    /// This is the inverse of `ref_to_mplace`.
    #[inline(always)]
    pub fn to_ref(self) -> Immediate<Tag> {
        match self.meta {
154
            MemPlaceMeta::None => Immediate::Scalar(self.ptr.into()),
O
Oliver Scherer 已提交
155
            MemPlaceMeta::Meta(meta) => Immediate::ScalarPair(self.ptr.into(), meta.into()),
156 157 158 159
            MemPlaceMeta::Poison => bug!(
                "MPlaceTy::dangling may never be used to produce a \
                place that will have the address of its pointee taken"
            ),
160 161
        }
    }
162 163 164 165

    pub fn offset(
        self,
        offset: Size,
166
        meta: MemPlaceMeta<Tag>,
167
        cx: &impl HasDataLayout,
168
    ) -> InterpResult<'tcx, Self> {
169 170 171 172 173 174
        Ok(MemPlace {
            ptr: self.ptr.ptr_offset(offset, cx)?,
            align: self.align.restrict_for_offset(offset),
            meta,
        })
    }
R
Ralf Jung 已提交
175 176
}

177
impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
R
Ralf Jung 已提交
178 179
    /// Produces a MemPlace that works for ZST but nothing else
    #[inline]
180
    pub fn dangling(layout: TyAndLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
O
Oliver Scherer 已提交
181
        let align = layout.align.abi;
182
        let ptr = Scalar::from_machine_usize(align.bytes(), cx);
183
        // `Poison` this to make sure that the pointer value `ptr` is never observable by the program.
O
Oliver Scherer 已提交
184
        MPlaceTy { mplace: MemPlace { ptr, align, meta: MemPlaceMeta::Poison }, layout }
R
Ralf Jung 已提交
185 186
    }

187
    /// Replace ptr tag, maintain vtable tag (if any)
188
    #[inline]
189
    pub fn replace_tag(self, new_tag: Tag) -> Self {
M
Mark Rousskov 已提交
190
        MPlaceTy { mplace: self.mplace.replace_tag(new_tag), layout: self.layout }
191 192 193
    }

    #[inline]
194 195 196
    pub fn offset(
        self,
        offset: Size,
197
        meta: MemPlaceMeta<Tag>,
198
        layout: TyAndLayout<'tcx>,
199
        cx: &impl HasDataLayout,
200
    ) -> InterpResult<'tcx, Self> {
M
Mark Rousskov 已提交
201
        Ok(MPlaceTy { mplace: self.mplace.offset(offset, meta, cx)?, layout })
202 203
    }

R
Ralf Jung 已提交
204
    #[inline]
205
    fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyAndLayout<'tcx>) -> Self {
206
        MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
R
Ralf Jung 已提交
207 208 209
    }

    #[inline]
210
    pub(super) fn len(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
211
        if self.layout.is_unsized() {
R
Ralf Jung 已提交
212
            // We need to consult `meta` metadata
V
varkor 已提交
213
            match self.layout.ty.kind {
214
                ty::Slice(..) | ty::Str => self.mplace.meta.unwrap_meta().to_machine_usize(cx),
215
                _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
216
            }
217 218
        } else {
            // Go through the layout.  There are lots of types that support a length,
219
            // e.g., SIMD types.
220
            match self.layout.fields {
221
                FieldsShape::Array { count, .. } => Ok(count),
222
                _ => bug!("len not supported on sized type {:?}", self.layout.ty),
223 224 225 226 227
            }
        }
    }

    #[inline]
228
    pub(super) fn vtable(self) -> Scalar<Tag> {
V
varkor 已提交
229
        match self.layout.ty.kind {
O
Oliver Scherer 已提交
230
            ty::Dynamic(..) => self.mplace.meta.unwrap_meta(),
231
            _ => bug!("vtable not supported on type {:?}", self.layout.ty),
R
Ralf Jung 已提交
232 233 234 235
        }
    }
}

236
// These are defined here because they produce a place.
237
impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
238
    #[inline(always)]
239 240
    /// Note: do not call `as_ref` on the resulting place. This function should only be used to
    /// read from the resulting mplace, not to get its address back.
241 242 243 244
    pub fn try_as_mplace(
        self,
        cx: &impl HasDataLayout,
    ) -> Result<MPlaceTy<'tcx, Tag>, ImmTy<'tcx, Tag>> {
245
        match *self {
R
Ralf Jung 已提交
246
            Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
247 248 249
            Operand::Immediate(_) if self.layout.is_zst() => {
                Ok(MPlaceTy::dangling(self.layout, cx))
            }
250
            Operand::Immediate(imm) => Err(ImmTy::from_immediate(imm, self.layout)),
R
Ralf Jung 已提交
251 252 253
        }
    }

254
    #[inline(always)]
255 256
    /// Note: do not call `as_ref` on the resulting place. This function should only be used to
    /// read from the resulting mplace, not to get its address back.
257 258
    pub fn assert_mem_place(self, cx: &impl HasDataLayout) -> MPlaceTy<'tcx, Tag> {
        self.try_as_mplace(cx).unwrap()
R
Ralf Jung 已提交
259 260 261
    }
}

R
Ralf Jung 已提交
262
impl<Tag: ::std::fmt::Debug> Place<Tag> {
R
Ralf Jung 已提交
263
    /// Produces a Place that will error if attempted to be read from or written to
264
    #[inline(always)]
265
    fn null(cx: &impl HasDataLayout) -> Self {
266
        Place::Ptr(MemPlace::null(cx))
R
Ralf Jung 已提交
267 268 269
    }

    #[inline]
270
    pub fn assert_mem_place(self) -> MemPlace<Tag> {
O
Oliver Schneider 已提交
271
        match self {
R
Ralf Jung 已提交
272
            Place::Ptr(mplace) => mplace,
273
            _ => bug!("assert_mem_place: expected Place::Ptr, got {:?}", self),
O
Oliver Schneider 已提交
274 275
        }
    }
R
Ralf Jung 已提交
276
}
O
Oliver Schneider 已提交
277

278
impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
R
Ralf Jung 已提交
279
    #[inline]
280 281
    pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
        MPlaceTy { mplace: self.place.assert_mem_place(), layout: self.layout }
O
Oliver Schneider 已提交
282 283 284
    }
}

285
// separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
R
Ralf Jung 已提交
286
impl<'mir, 'tcx, Tag, M> InterpCx<'mir, 'tcx, M>
287
where
R
Ralf Jung 已提交
288
    // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
289
    Tag: ::std::fmt::Debug + Copy + Eq + Hash + 'static,
290
    M: Machine<'mir, 'tcx, PointerTag = Tag>,
R
Ralf Jung 已提交
291
    // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
292
    M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKind>, Allocation<Tag, M::AllocExtra>)>,
293
    M::AllocExtra: AllocationExtra<Tag>,
294
{
R
Ralf Jung 已提交
295
    /// Take a value, which represents a (thin or wide) reference, and make it a place.
296
    /// Alignment is just based on the type.  This is the inverse of `MemPlace::to_ref()`.
R
Ralf Jung 已提交
297 298 299 300
    ///
    /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not
    /// want to ever use the place for memory access!
    /// Generally prefer `deref_operand`.
R
Ralf Jung 已提交
301
    pub fn ref_to_mplace(
302
        &self,
303
        val: ImmTy<'tcx, M::PointerTag>,
304
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
M
Mark Rousskov 已提交
305 306
        let pointee_type =
            val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty;
307
        let layout = self.layout_of(pointee_type)?;
308
        let (ptr, meta) = match *val {
309 310
            Immediate::Scalar(ptr) => (ptr.not_undef()?, MemPlaceMeta::None),
            Immediate::ScalarPair(ptr, meta) => {
O
Oliver Scherer 已提交
311
                (ptr.not_undef()?, MemPlaceMeta::Meta(meta.not_undef()?))
312
            }
313
        };
314

315
        let mplace = MemPlace {
316
            ptr,
317 318 319 320
            // We could use the run-time alignment here. For now, we do not, because
            // the point of tracking the alignment here is to make sure that the *static*
            // alignment information emitted with the loads is correct. The run-time
            // alignment can only be more restrictive.
321
            align: layout.align.abi,
322
            meta,
323 324
        };
        Ok(MPlaceTy { mplace, layout })
R
Ralf Jung 已提交
325 326
    }

327 328
    /// Take an operand, representing a pointer, and dereference it to a place -- that
    /// will always be a MemPlace.  Lives in `place.rs` because it creates a place.
329 330 331
    pub fn deref_operand(
        &self,
        src: OpTy<'tcx, M::PointerTag>,
332
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
333 334
        let val = self.read_immediate(src)?;
        trace!("deref to {} on {:?}", val.layout.ty, *val);
335 336
        let place = self.ref_to_mplace(val)?;
        self.mplace_access_checked(place)
337 338
    }

339 340 341 342 343 344 345
    /// Check if the given place is good for memory access with the given
    /// size, falling back to the layout's size if `None` (in the latter case,
    /// this must be a statically sized type).
    ///
    /// On success, returns `None` for zero-sized accesses (where nothing else is
    /// left to do) and a `Pointer` to use for the actual access otherwise.
    #[inline]
346
    pub(super) fn check_mplace_access(
347 348 349 350 351 352
        &self,
        place: MPlaceTy<'tcx, M::PointerTag>,
        size: Option<Size>,
    ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
        let size = size.unwrap_or_else(|| {
            assert!(!place.layout.is_unsized());
O
Oliver Scherer 已提交
353
            assert!(!place.meta.has_meta());
354 355 356 357 358
            place.layout.size
        });
        self.memory.check_ptr_access(place.ptr, size, place.align)
    }

359 360 361 362 363 364
    /// Return the "access-checked" version of this `MPlace`, where for non-ZST
    /// this is definitely a `Pointer`.
    pub fn mplace_access_checked(
        &self,
        mut place: MPlaceTy<'tcx, M::PointerTag>,
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
M
Mark Rousskov 已提交
365 366
        let (size, align) = self
            .size_and_align_of_mplace(place)?
367 368 369 370 371 372 373 374 375 376
            .unwrap_or((place.layout.size, place.layout.align.abi));
        assert!(place.mplace.align <= align, "dynamic alignment less strict than static one?");
        place.mplace.align = align; // maximally strict checking
        // When dereferencing a pointer, it must be non-NULL, aligned, and live.
        if let Some(ptr) = self.check_mplace_access(place, Some(size))? {
            place.mplace.ptr = ptr.into();
        }
        Ok(place)
    }

R
Ralf Jung 已提交
377
    /// Force `place.ptr` to a `Pointer`.
378
    /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
379
    pub(super) fn force_mplace_ptr(
380 381 382
        &self,
        mut place: MPlaceTy<'tcx, M::PointerTag>,
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
383
        place.mplace.ptr = self.force_ptr(place.mplace.ptr)?.into();
384 385 386
        Ok(place)
    }

387 388
    /// Offset a pointer to project to a field of a struct/union. Unlike `place_field`, this is
    /// always possible without allocating, so it can take `&self`. Also return the field's layout.
R
Ralf Jung 已提交
389
    /// This supports both struct and array fields.
390 391 392
    ///
    /// This also works for arrays, but then the `usize` index type is restricting.
    /// For indexing into arrays, use `mplace_index`.
R
Ralf Jung 已提交
393 394
    #[inline(always)]
    pub fn mplace_field(
O
Oliver Schneider 已提交
395
        &self,
396
        base: MPlaceTy<'tcx, M::PointerTag>,
397
        field: usize,
398
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
399 400
        let offset = base.layout.fields.offset(field);
        let field_layout = base.layout.field(self, field)?;
R
Ralf Jung 已提交
401

402
        // Offset may need adjustment for unsized fields.
R
Ralf Jung 已提交
403
        let (meta, offset) = if field_layout.is_unsized() {
404 405 406
            // Re-use parent metadata to determine dynamic field layout.
            // With custom DSTS, this *will* execute user-defined code, but the same
            // happens at run-time so that's okay.
407 408
            let align = match self.size_and_align_of(base.meta, field_layout)? {
                Some((_, align)) => align,
R
Ralf Jung 已提交
409 410 411 412 413
                None if offset == Size::ZERO => {
                    // An extern type at offset 0, we fall back to its static alignment.
                    // FIXME: Once we have made decisions for how to handle size and alignment
                    // of `extern type`, this should be adapted.  It is just a temporary hack
                    // to get some code to work that probably ought to work.
M
Mark Rousskov 已提交
414 415 416
                    field_layout.align.abi
                }
                None => bug!("Cannot compute offset for extern type field at non-0 offset"),
417
            };
418
            (base.meta, offset.align_to(align))
R
Ralf Jung 已提交
419
        } else {
R
Ralf Jung 已提交
420
            // base.meta could be present; we might be accessing a sized field of an unsized
421
            // struct.
422
            (MemPlaceMeta::None, offset)
R
Ralf Jung 已提交
423 424
        };

425 426 427
        // We do not look at `base.layout.align` nor `field_layout.align`, unlike
        // codegen -- mostly to see if we can get away with that
        base.offset(offset, meta, field_layout, self)
O
Oliver Schneider 已提交
428 429
    }

430 431 432 433 434 435 436 437 438
    /// Index into an array.
    #[inline(always)]
    pub fn mplace_index(
        &self,
        base: MPlaceTy<'tcx, M::PointerTag>,
        index: u64,
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
        // Not using the layout method because we want to compute on u64
        match base.layout.fields {
439
            FieldsShape::Array { stride, .. } => {
440 441 442 443 444
                let len = base.len(self)?;
                if index >= len {
                    // This can only be reached in ConstProp and non-rustc-MIR.
                    throw_ub!(BoundsCheckFailed { len, index });
                }
R
Ralf Jung 已提交
445
                let offset = stride * index; // `Size` multiplication
446 447 448 449 450 451 452 453 454 455
                // All fields have the same layout.
                let field_layout = base.layout.field(self, 0)?;

                assert!(!field_layout.is_unsized());
                base.offset(offset, MemPlaceMeta::None, field_layout, self)
            }
            _ => bug!("`mplace_index` called on non-array type {:?}", base.layout.ty),
        }
    }

456 457
    // Iterates over all fields of an array. Much more efficient than doing the
    // same by repeatedly calling `mplace_array`.
458
    pub(super) fn mplace_array_fields(
459
        &self,
460
        base: MPlaceTy<'tcx, Tag>,
461
    ) -> InterpResult<'tcx, impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'tcx>
462
    {
463
        let len = base.len(self)?; // also asserts that we have a type where this makes sense
464
        let stride = match base.layout.fields {
465
            FieldsShape::Array { stride, .. } => stride,
466 467 468 469
            _ => bug!("mplace_array_fields: expected an array layout"),
        };
        let layout = base.layout.field(self, 0)?;
        let dl = &self.tcx.data_layout;
R
Ralf Jung 已提交
470 471
        // `Size` multiplication
        Ok((0..len).map(move |i| base.offset(stride * i, MemPlaceMeta::None, layout, dl)))
472 473
    }

474
    fn mplace_subslice(
O
Oliver Schneider 已提交
475
        &self,
476
        base: MPlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
477 478
        from: u64,
        to: u64,
479
        from_end: bool,
480
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
481
        let len = base.len(self)?; // also asserts that we have a type where this makes sense
482
        let actual_to = if from_end {
483
            if from.checked_add(to).map_or(true, |to| to > len) {
484
                // This can only be reached in ConstProp and non-rustc-MIR.
485
                throw_ub!(BoundsCheckFailed { len: len, index: from.saturating_add(to) });
486
            }
487
            len.checked_sub(to).unwrap()
488 489 490
        } else {
            to
        };
R
Ralf Jung 已提交
491 492 493 494

        // Not using layout method because that works with usize, and does not work with slices
        // (that have count 0 in their layout).
        let from_offset = match base.layout.fields {
495
            FieldsShape::Array { stride, .. } => stride * from, // `Size` multiplication is checked
R
Ralf Jung 已提交
496
            _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
O
Oliver Schneider 已提交
497
        };
R
Ralf Jung 已提交
498

R
Ralf Jung 已提交
499
        // Compute meta and new layout
500
        let inner_len = actual_to.checked_sub(from).unwrap();
V
varkor 已提交
501
        let (meta, ty) = match base.layout.ty.kind {
R
Ralf Jung 已提交
502 503
            // It is not nice to match on the type, but that seems to be the only way to
            // implement this.
504
            ty::Array(inner, _) => (MemPlaceMeta::None, self.tcx.mk_array(inner, inner_len)),
505
            ty::Slice(..) => {
506
                let len = Scalar::from_machine_usize(inner_len, self);
O
Oliver Scherer 已提交
507
                (MemPlaceMeta::Meta(len), base.layout.ty)
508
            }
M
Mark Rousskov 已提交
509
            _ => bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
R
Ralf Jung 已提交
510 511
        };
        let layout = self.layout_of(ty)?;
512
        base.offset(from_offset, meta, layout, self)
R
Ralf Jung 已提交
513 514
    }

515
    pub(super) fn mplace_downcast(
R
Ralf Jung 已提交
516
        &self,
517
        base: MPlaceTy<'tcx, M::PointerTag>,
518
        variant: VariantIdx,
519
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
520
        // Downcasts only change the layout
O
Oliver Scherer 已提交
521
        assert!(!base.meta.has_meta());
R
Ralf Jung 已提交
522
        Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
O
Oliver Schneider 已提交
523 524
    }

R
Ralf Jung 已提交
525
    /// Project into an mplace
526
    pub(super) fn mplace_projection(
O
Oliver Schneider 已提交
527
        &self,
528
        base: MPlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
529
        proj_elem: &mir::PlaceElem<'tcx>,
530
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
M
Mazdak Farrokhzad 已提交
531
        use rustc_middle::mir::ProjectionElem::*;
R
Ralf Jung 已提交
532
        Ok(match *proj_elem {
533
            Field(field, _) => self.mplace_field(base, field.index())?,
R
Ralf Jung 已提交
534 535 536 537
            Downcast(_, variant) => self.mplace_downcast(base, variant)?,
            Deref => self.deref_operand(base.into())?,

            Index(local) => {
R
Ralf Jung 已提交
538
                let layout = self.layout_of(self.tcx.types.usize)?;
539 540
                let n = self.access_local(self.frame(), local, Some(layout))?;
                let n = self.read_scalar(n)?;
541 542 543 544 545
                let n = u64::try_from(
                    self.force_bits(n.not_undef()?, self.tcx.data_layout.pointer_size)?,
                )
                .unwrap();
                self.mplace_index(base, n)?
R
Ralf Jung 已提交
546 547
            }

M
Mark Rousskov 已提交
548
            ConstantIndex { offset, min_length, from_end } => {
549
                let n = base.len(self)?;
550
                if n < u64::from(min_length) {
551
                    // This can only be reached in ConstProp and non-rustc-MIR.
552
                    throw_ub!(BoundsCheckFailed { len: min_length.into(), index: n.into() });
553
                }
R
Ralf Jung 已提交
554 555

                let index = if from_end {
556 557
                    assert!(0 < offset && offset <= min_length);
                    n.checked_sub(u64::from(offset)).unwrap()
R
Ralf Jung 已提交
558
                } else {
O
Oliver Scherer 已提交
559
                    assert!(offset < min_length);
R
Ralf Jung 已提交
560 561 562
                    u64::from(offset)
                };

563
                self.mplace_index(base, index)?
R
Ralf Jung 已提交
564 565
            }

M
Mark Rousskov 已提交
566 567 568
            Subslice { from, to, from_end } => {
                self.mplace_subslice(base, u64::from(from), u64::from(to), from_end)?
            }
R
Ralf Jung 已提交
569
        })
O
Oliver Schneider 已提交
570 571
    }

A
Alexander Regueiro 已提交
572
    /// Gets the place of a field inside the place, and also the field's type.
R
Ralf Jung 已提交
573
    /// Just a convenience function, but used quite a bit.
574 575
    /// This is the only projection that might have a side-effect: We cannot project
    /// into the field of a local `ScalarPair`, we have to first allocate it.
R
Ralf Jung 已提交
576
    pub fn place_field(
O
Oliver Schneider 已提交
577
        &mut self,
578
        base: PlaceTy<'tcx, M::PointerTag>,
579
        field: usize,
580
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
581 582 583 584
        // FIXME: We could try to be smarter and avoid allocation for fields that span the
        // entire place.
        let mplace = self.force_allocation(base)?;
        Ok(self.mplace_field(mplace, field)?.into())
O
Oliver Schneider 已提交
585 586
    }

587 588 589 590 591 592 593 594 595
    pub fn place_index(
        &mut self,
        base: PlaceTy<'tcx, M::PointerTag>,
        index: u64,
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
        let mplace = self.force_allocation(base)?;
        Ok(self.mplace_index(mplace, index)?.into())
    }

R
Ralf Jung 已提交
596
    pub fn place_downcast(
597
        &self,
598
        base: PlaceTy<'tcx, M::PointerTag>,
599
        variant: VariantIdx,
600
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
601 602
        // Downcast just changes the layout
        Ok(match base.place {
M
Mark Rousskov 已提交
603 604 605
            Place::Ptr(mplace) => {
                self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into()
            }
R
Ralf Jung 已提交
606
            Place::Local { .. } => {
607
                let layout = base.layout.for_variant(self, variant);
R
Ralf Jung 已提交
608
                PlaceTy { layout, ..base }
O
Oliver Schneider 已提交
609
            }
R
Ralf Jung 已提交
610
        })
O
Oliver Schneider 已提交
611 612
    }

A
Alexander Regueiro 已提交
613
    /// Projects into a place.
R
Ralf Jung 已提交
614 615
    pub fn place_projection(
        &mut self,
616
        base: PlaceTy<'tcx, M::PointerTag>,
617
        proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
618
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
M
Mazdak Farrokhzad 已提交
619
        use rustc_middle::mir::ProjectionElem::*;
R
Ralf Jung 已提交
620
        Ok(match *proj_elem {
621
            Field(field, _) => self.place_field(base, field.index())?,
R
Ralf Jung 已提交
622 623 624 625 626 627 628 629 630 631 632
            Downcast(_, variant) => self.place_downcast(base, variant)?,
            Deref => self.deref_operand(self.place_to_op(base)?)?.into(),
            // For the other variants, we have to force an allocation.
            // This matches `operand_projection`.
            Subslice { .. } | ConstantIndex { .. } | Index(_) => {
                let mplace = self.force_allocation(base)?;
                self.mplace_projection(mplace, proj_elem)?.into()
            }
        })
    }

A
Alexander Regueiro 已提交
633
    /// Computes a place. You should only use this if you intend to write into this
634
    /// place; for reading, a more efficient alternative is `eval_place_for_read`.
R
Ralf Jung 已提交
635 636
    pub fn eval_place(
        &mut self,
637
        place: mir::Place<'tcx>,
638
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
639 640
        let mut place_ty = match place.local {
            mir::RETURN_PLACE => {
641 642 643 644 645 646
                // `return_place` has the *caller* layout, but we want to use our
                // `layout to verify our assumption. The caller will validate
                // their layout on return.
                PlaceTy {
                    place: match self.frame().return_place {
                        Some(p) => *p,
R
comment  
Ralf Jung 已提交
647 648 649 650 651 652 653
                        // Even if we don't have a return place, we sometimes need to
                        // create this place, but any attempt to read from / write to it
                        // (even a ZST read/write) needs to error, so let us make this
                        // a NULL place.
                        //
                        // FIXME: Ideally we'd make sure that the place projections also
                        // bail out.
654 655
                        None => Place::null(&*self),
                    },
656 657 658 659 660
                    layout: self.layout_of(
                        self.subst_from_current_frame_and_normalize_erasing_regions(
                            self.frame().body.return_ty(),
                        ),
                    )?,
661
                }
M
Mark Rousskov 已提交
662
            }
663
            local => PlaceTy {
664
                // This works even for dead/uninitialized locals; we check further when writing
665
                place: Place::Local { frame: self.cur_frame(), local },
666
                layout: self.layout_of_local(self.frame(), local, None)?,
667 668
            },
        };
669

670 671 672
        for elem in place.projection.iter() {
            place_ty = self.place_projection(place_ty, elem)?
        }
O
Oliver Schneider 已提交
673

674 675
        self.dump_place(place_ty.place);
        Ok(place_ty)
O
Oliver Schneider 已提交
676 677
    }

R
Ralf Jung 已提交
678
    /// Write a scalar to a place
679
    #[inline(always)]
R
Ralf Jung 已提交
680
    pub fn write_scalar(
O
Oliver Schneider 已提交
681
        &mut self,
682 683
        val: impl Into<ScalarMaybeUndef<M::PointerTag>>,
        dest: PlaceTy<'tcx, M::PointerTag>,
684
    ) -> InterpResult<'tcx> {
685
        self.write_immediate(Immediate::Scalar(val.into()), dest)
R
Ralf Jung 已提交
686
    }
O
Oliver Schneider 已提交
687

688
    /// Write an immediate to a place
689
    #[inline(always)]
690
    pub fn write_immediate(
R
Ralf Jung 已提交
691
        &mut self,
692
        src: Immediate<M::PointerTag>,
693
        dest: PlaceTy<'tcx, M::PointerTag>,
694
    ) -> InterpResult<'tcx> {
695
        self.write_immediate_no_validate(src, dest)?;
696

R
Ralf Jung 已提交
697
        if M::enforce_validity(self) {
698
            // Data got changed, better make sure it matches the type!
699
            self.validate_operand(self.place_to_op(dest)?)?;
700 701
        }

702 703 704
        Ok(())
    }

W
Wesley Wiser 已提交
705 706 707 708 709 710
    /// Write an `Immediate` to memory.
    #[inline(always)]
    pub fn write_immediate_to_mplace(
        &mut self,
        src: Immediate<M::PointerTag>,
        dest: MPlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
711
    ) -> InterpResult<'tcx> {
W
Wesley Wiser 已提交
712 713 714 715
        self.write_immediate_to_mplace_no_validate(src, dest)?;

        if M::enforce_validity(self) {
            // Data got changed, better make sure it matches the type!
716
            self.validate_operand(dest.into())?;
W
Wesley Wiser 已提交
717 718 719 720 721
        }

        Ok(())
    }

722
    /// Write an immediate to a place.
723 724
    /// If you use this you are responsible for validating that things got copied at the
    /// right type.
725
    fn write_immediate_no_validate(
726
        &mut self,
727
        src: Immediate<M::PointerTag>,
728
        dest: PlaceTy<'tcx, M::PointerTag>,
729
    ) -> InterpResult<'tcx> {
730 731 732
        if cfg!(debug_assertions) {
            // This is a very common path, avoid some checks in release mode
            assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
733
            match src {
M
Mark Rousskov 已提交
734 735 736 737 738 739 740
                Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Ptr(_))) => assert_eq!(
                    self.pointer_size(),
                    dest.layout.size,
                    "Size mismatch when writing pointer"
                ),
                Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Raw { size, .. })) => {
                    assert_eq!(
741
                        Size::from_bytes(size),
M
Mark Rousskov 已提交
742 743 744 745 746
                        dest.layout.size,
                        "Size mismatch when writing bits"
                    )
                }
                Immediate::Scalar(ScalarMaybeUndef::Undef) => {} // undef can have any size
747
                Immediate::ScalarPair(_, _) => {
748 749 750 751
                    // FIXME: Can we check anything here?
                }
            }
        }
752
        trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
753

754
        // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
R
Ralf Jung 已提交
755
        // but not factored as a separate function.
R
Ralf Jung 已提交
756
        let mplace = match dest.place {
O
Oliver Schneider 已提交
757
            Place::Local { frame, local } => {
758 759 760 761
                match self.stack[frame].locals[local].access_mut()? {
                    Ok(local) => {
                        // Local can be updated in-place.
                        *local = LocalValue::Live(Operand::Immediate(src));
R
Ralf Jung 已提交
762
                        return Ok(());
763 764 765 766 767
                    }
                    Err(mplace) => {
                        // The local is in memory, go on below.
                        mplace
                    }
O
Oliver Schneider 已提交
768
                }
M
Mark Rousskov 已提交
769
            }
770
            Place::Ptr(mplace) => mplace, // already referring to memory
O
Oliver Schneider 已提交
771
        };
772
        let dest = MPlaceTy { mplace, layout: dest.layout };
O
Oliver Schneider 已提交
773

R
Ralf Jung 已提交
774
        // This is already in memory, write there.
775
        self.write_immediate_to_mplace_no_validate(src, dest)
O
Oliver Schneider 已提交
776 777
    }

778
    /// Write an immediate to memory.
779
    /// If you use this you are responsible for validating that things got copied at the
780
    /// right type.
781
    fn write_immediate_to_mplace_no_validate(
R
Ralf Jung 已提交
782
        &mut self,
783
        value: Immediate<M::PointerTag>,
784
        dest: MPlaceTy<'tcx, M::PointerTag>,
785
    ) -> InterpResult<'tcx> {
B
Bernardo Meurer 已提交
786 787 788 789
        // Note that it is really important that the type here is the right one, and matches the
        // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
        // to handle padding properly, which is only correct if we never look at this data with the
        // wrong type.
790

791
        // Invalid places are a thing: the return place of a diverging function
M
Mark Rousskov 已提交
792
        let ptr = match self.check_mplace_access(dest, None)? {
793 794 795
            Some(ptr) => ptr,
            None => return Ok(()), // zero-sized access
        };
796

797
        let tcx = &*self.tcx;
798 799 800
        // FIXME: We should check that there are dest.layout.size many bytes available in
        // memory.  The code below is not sufficient, with enough padding it might not
        // cover all the bytes!
R
Ralf Jung 已提交
801
        match value {
802
            Immediate::Scalar(scalar) => {
803
                match dest.layout.abi {
804
                    Abi::Scalar(_) => {} // fine
M
Mark Rousskov 已提交
805 806 807
                    _ => {
                        bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}", dest.layout)
                    }
808
                }
809
                self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(
M
Mark Rousskov 已提交
810 811 812 813
                    tcx,
                    ptr,
                    scalar,
                    dest.layout.size,
R
Ralf Jung 已提交
814
                )
O
Oliver Schneider 已提交
815
            }
816
            Immediate::ScalarPair(a_val, b_val) => {
817 818 819
                // We checked `ptr_align` above, so all fields will have the alignment they need.
                // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
                // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
R
Ralf Jung 已提交
820
                let (a, b) = match dest.layout.abi {
821
                    Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
M
Mark Rousskov 已提交
822 823 824 825
                    _ => bug!(
                        "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
                        dest.layout
                    ),
R
Ralf Jung 已提交
826
                };
827
                let (a_size, b_size) = (a.size(self), b.size(self));
828
                let b_offset = a_size.align_to(b.align(self).abi);
829
                let b_ptr = ptr.offset(b_offset, self)?;
830

831 832 833 834
                // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
                // but that does not work: We could be a newtype around a pair, then the
                // fields do not match the `ScalarPair` components.

M
Mark Rousskov 已提交
835 836
                self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(tcx, ptr, a_val, a_size)?;
                self.memory.get_raw_mut(b_ptr.alloc_id)?.write_scalar(tcx, b_ptr, b_val, b_size)
O
Oliver Schneider 已提交
837
            }
R
Ralf Jung 已提交
838
        }
O
Oliver Schneider 已提交
839 840
    }

A
Alexander Regueiro 已提交
841
    /// Copies the data from an operand to a place. This does not support transmuting!
842 843
    /// Use `copy_op_transmute` if the layouts could disagree.
    #[inline(always)]
R
Ralf Jung 已提交
844
    pub fn copy_op(
O
Oliver Schneider 已提交
845
        &mut self,
846 847
        src: OpTy<'tcx, M::PointerTag>,
        dest: PlaceTy<'tcx, M::PointerTag>,
848
    ) -> InterpResult<'tcx> {
849 850
        self.copy_op_no_validate(src, dest)?;

R
Ralf Jung 已提交
851
        if M::enforce_validity(self) {
852
            // Data got changed, better make sure it matches the type!
853
            self.validate_operand(self.place_to_op(dest)?)?;
854 855 856 857 858
        }

        Ok(())
    }

A
Alexander Regueiro 已提交
859
    /// Copies the data from an operand to a place. This does not support transmuting!
860
    /// Use `copy_op_transmute` if the layouts could disagree.
861
    /// Also, if you use this you are responsible for validating that things get copied at the
862 863 864 865 866
    /// right type.
    fn copy_op_no_validate(
        &mut self,
        src: OpTy<'tcx, M::PointerTag>,
        dest: PlaceTy<'tcx, M::PointerTag>,
867
    ) -> InterpResult<'tcx> {
868 869
        // We do NOT compare the types for equality, because well-typed code can
        // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
870 871 872 873 874 875 876 877
        if !mir_assign_valid_types(self.tcx.tcx, src.layout, dest.layout) {
            span_bug!(
                self.tcx.span,
                "type mismatch when copying!\nsrc: {:?},\ndest: {:?}",
                src.layout.ty,
                dest.layout.ty,
            );
        }
R
Ralf Jung 已提交
878 879

        // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
880
        let src = match self.try_read_immediate(src)? {
881
            Ok(src_val) => {
882
                assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
883
                // Yay, we got a value that we can write directly.
884 885
                // FIXME: Add a check to make sure that if `src` is indirect,
                // it does not overlap with `dest`.
886
                return self.write_immediate_no_validate(*src_val, dest);
887 888
            }
            Err(mplace) => mplace,
R
Ralf Jung 已提交
889 890
        };
        // Slow path, this does not fit into an immediate. Just memcpy.
891 892
        trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);

893 894 895 896
        // This interprets `src.meta` with the `dest` local's layout, if an unsized local
        // is being initialized!
        let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?;
        let size = size.unwrap_or_else(|| {
M
Mark Rousskov 已提交
897 898 899 900
            assert!(
                !dest.layout.is_unsized(),
                "Cannot copy into already initialized unsized place"
            );
901 902 903
            dest.layout.size
        });
        assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
904

M
Mark Rousskov 已提交
905 906
        let src = self
            .check_mplace_access(src, Some(size))
907
            .expect("places should be checked on creation");
M
Mark Rousskov 已提交
908 909
        let dest = self
            .check_mplace_access(dest, Some(size))
910
            .expect("places should be checked on creation");
911 912 913 914 915 916
        let (src_ptr, dest_ptr) = match (src, dest) {
            (Some(src_ptr), Some(dest_ptr)) => (src_ptr, dest_ptr),
            (None, None) => return Ok(()), // zero-sized copy
            _ => bug!("The pointers should both be Some or both None"),
        };

M
Mark Rousskov 已提交
917
        self.memory.copy(src_ptr, dest_ptr, size, /*nonoverlapping*/ true)
918 919
    }

A
Alexander Regueiro 已提交
920
    /// Copies the data from an operand to a place. The layouts may disagree, but they must
921 922 923 924 925
    /// have the same size.
    pub fn copy_op_transmute(
        &mut self,
        src: OpTy<'tcx, M::PointerTag>,
        dest: PlaceTy<'tcx, M::PointerTag>,
926
    ) -> InterpResult<'tcx> {
927
        if mir_assign_valid_types(self.tcx.tcx, src.layout, dest.layout) {
928 929 930
            // Fast path: Just use normal `copy_op`
            return self.copy_op(src, dest);
        }
931
        // We still require the sizes to match.
932
        if src.layout.size != dest.layout.size {
933 934 935 936
            // FIXME: This should be an assert instead of an error, but if we transmute within an
            // array length computation, `typeck` may not have yet been run and errored out. In fact
            // most likey we *are* running `typeck` right now. Investigate whether we can bail out
            // on `typeck_tables().has_errors` at all const eval entry points.
937
            debug!("Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
938 939 940 941
            self.tcx.sess.delay_span_bug(
                self.tcx.span,
                "size-changing transmute, should have been caught by transmute checking",
            );
942
            throw_inval!(TransmuteSizeDiff(src.layout.ty, dest.layout.ty));
943
        }
944 945
        // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
        // to avoid that here.
M
Mark Rousskov 已提交
946 947 948 949
        assert!(
            !src.layout.is_unsized() && !dest.layout.is_unsized(),
            "Cannot transmute unsized data"
        );
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964

        // The hard case is `ScalarPair`.  `src` is already read from memory in this case,
        // using `src.layout` to figure out which bytes to use for the 1st and 2nd field.
        // We have to write them to `dest` at the offsets they were *read at*, which is
        // not necessarily the same as the offsets in `dest.layout`!
        // Hence we do the copy with the source layout on both sides.  We also make sure to write
        // into memory, because if `dest` is a local we would not even have a way to write
        // at the `src` offsets; the fact that we came from a different layout would
        // just be lost.
        let dest = self.force_allocation(dest)?;
        self.copy_op_no_validate(
            src,
            PlaceTy::from(MPlaceTy { mplace: *dest, layout: src.layout }),
        )?;

R
Ralf Jung 已提交
965
        if M::enforce_validity(self) {
966
            // Data got changed, better make sure it matches the type!
967
            self.validate_operand(dest.into())?;
968
        }
969

970
        Ok(())
O
Oliver Schneider 已提交
971 972
    }

A
Alexander Regueiro 已提交
973
    /// Ensures that a place is in memory, and returns where it is.
974 975
    /// If the place currently refers to a local that doesn't yet have a matching allocation,
    /// create such an allocation.
R
Ralf Jung 已提交
976
    /// This is essentially `force_to_memplace`.
977
    ///
R
Ralf Jung 已提交
978
    /// This supports unsized types and returns the computed size to avoid some
979 980 981
    /// redundant computation when copying; use `force_allocation` for a simpler, sized-only
    /// version.
    pub fn force_allocation_maybe_sized(
O
Oliver Schneider 已提交
982
        &mut self,
983
        place: PlaceTy<'tcx, M::PointerTag>,
984
        meta: MemPlaceMeta<M::PointerTag>,
985
    ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
986
        let (mplace, size) = match place.place {
R
Ralf Jung 已提交
987
            Place::Local { frame, local } => {
988
                match self.stack[frame].locals[local].access_mut()? {
989
                    Ok(&mut local_val) => {
990
                        // We need to make an allocation.
991

992
                        // We need the layout of the local.  We can NOT use the layout we got,
993
                        // that might e.g., be an inner field of a struct with `Scalar` layout,
R
Ralf Jung 已提交
994
                        // that has different alignment than the outer field.
995
                        let local_layout = self.layout_of_local(&self.stack[frame], local, None)?;
996
                        // We also need to support unsized types, and hence cannot use `allocate`.
M
Mark Rousskov 已提交
997 998
                        let (size, align) = self
                            .size_and_align_of(meta, local_layout)?
999 1000 1001
                            .expect("Cannot allocate for non-dyn-sized type");
                        let ptr = self.memory.allocate(size, align, MemoryKind::Stack);
                        let mplace = MemPlace { ptr: ptr.into(), align, meta };
1002
                        if let LocalValue::Live(Operand::Immediate(value)) = local_val {
1003 1004 1005
                            // Preserve old value.
                            // We don't have to validate as we can assume the local
                            // was already valid for its type.
1006 1007
                            let mplace = MPlaceTy { mplace, layout: local_layout };
                            self.write_immediate_to_mplace_no_validate(value, mplace)?;
1008 1009 1010 1011 1012
                        }
                        // Now we can call `access_mut` again, asserting it goes well,
                        // and actually overwrite things.
                        *self.stack[frame].locals[local].access_mut().unwrap().unwrap() =
                            LocalValue::Live(Operand::Indirect(mplace));
1013
                        (mplace, Some(size))
1014
                    }
1015
                    Err(mplace) => (mplace, None), // this already was an indirect local
1016
                }
R
Ralf Jung 已提交
1017
            }
M
Mark Rousskov 已提交
1018
            Place::Ptr(mplace) => (mplace, None),
R
Ralf Jung 已提交
1019 1020
        };
        // Return with the original layout, so that the caller can go on
1021 1022 1023 1024 1025 1026 1027
        Ok((MPlaceTy { mplace, layout: place.layout }, size))
    }

    #[inline(always)]
    pub fn force_allocation(
        &mut self,
        place: PlaceTy<'tcx, M::PointerTag>,
1028
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1029
        Ok(self.force_allocation_maybe_sized(place, MemPlaceMeta::None)?.0)
O
Oliver Schneider 已提交
1030 1031
    }

R
Ralf Jung 已提交
1032
    pub fn allocate(
O
Oliver Schneider 已提交
1033
        &mut self,
1034
        layout: TyAndLayout<'tcx>,
1035
        kind: MemoryKind<M::MemoryKind>,
R
Ralf Jung 已提交
1036
    ) -> MPlaceTy<'tcx, M::PointerTag> {
1037 1038
        let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
        MPlaceTy::from_aligned_ptr(ptr, layout)
R
Ralf Jung 已提交
1039
    }
O
Oliver Schneider 已提交
1040

R
Ralf Jung 已提交
1041
    /// Returns a wide MPlace.
1042 1043 1044
    pub fn allocate_str(
        &mut self,
        str: &str,
1045
        kind: MemoryKind<M::MemoryKind>,
1046
    ) -> MPlaceTy<'tcx, M::PointerTag> {
1047
        let ptr = self.memory.allocate_bytes(str.as_bytes(), kind);
1048
        let meta = Scalar::from_machine_usize(u64::try_from(str.len()).unwrap(), self);
1049 1050 1051
        let mplace = MemPlace {
            ptr: ptr.into(),
            align: Align::from_bytes(1).unwrap(),
O
Oliver Scherer 已提交
1052
            meta: MemPlaceMeta::Meta(meta),
1053
        };
1054 1055 1056 1057 1058

        let layout = self.layout_of(self.tcx.mk_static_str()).unwrap();
        MPlaceTy { mplace, layout }
    }

1059
    pub fn write_discriminant_index(
R
Ralf Jung 已提交
1060
        &mut self,
1061
        variant_index: VariantIdx,
1062
        dest: PlaceTy<'tcx, M::PointerTag>,
1063
    ) -> InterpResult<'tcx> {
1064 1065 1066 1067 1068
        // Layout computation excludes uninhabited variants from consideration
        // therefore there's no way to represent those variants in the given layout.
        if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() {
            throw_ub!(Unreachable);
        }
1069

R
Ralf Jung 已提交
1070
        match dest.layout.variants {
1071
            Variants::Single { index } => {
1072
                assert_eq!(index, variant_index);
O
Oliver Schneider 已提交
1073
            }
1074 1075
            Variants::Multiple {
                discr_kind: DiscriminantKind::Tag,
1076
                discr: ref discr_layout,
1077
                discr_index,
1078 1079
                ..
            } => {
1080
                // No need to validate that the discriminant here because the
1081
                // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
1082

1083 1084
                let discr_val =
                    dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
R
Ralf Jung 已提交
1085 1086 1087 1088

                // raw discriminants for enums are isize or bigger during
                // their computation, but the in-memory tag is the smallest possible
                // representation
1089
                let size = discr_layout.value.size(self);
1090
                let discr_val = truncate(discr_val, size);
R
Ralf Jung 已提交
1091

1092
                let discr_dest = self.place_field(dest, discr_index)?;
1093
                self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
O
Oliver Schneider 已提交
1094
            }
1095
            Variants::Multiple {
M
Mark Rousskov 已提交
1096
                discr_kind:
1097
                    DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start },
1098
                discr: ref discr_layout,
1099
                discr_index,
R
Ralf Jung 已提交
1100
                ..
O
Oliver Schneider 已提交
1101
            } => {
1102
                // No need to validate that the discriminant here because the
1103
                // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
1104

R
Ralf Jung 已提交
1105
                if variant_index != dataful_variant {
1106
                    let variants_start = niche_variants.start().as_u32();
M
Mark Rousskov 已提交
1107 1108
                    let variant_index_relative = variant_index
                        .as_u32()
1109 1110
                        .checked_sub(variants_start)
                        .expect("overflow computing relative variant idx");
1111 1112
                    // We need to use machine arithmetic when taking into account `niche_start`:
                    // discr_val = variant_index_relative + niche_start_val
1113
                    let discr_layout = self.layout_of(discr_layout.value.to_int_ty(*self.tcx))?;
1114
                    let niche_start_val = ImmTy::from_uint(niche_start, discr_layout);
1115 1116
                    let variant_index_relative_val =
                        ImmTy::from_uint(variant_index_relative, discr_layout);
1117
                    let discr_val = self.binary_op(
1118
                        mir::BinOp::Add,
1119
                        variant_index_relative_val,
1120
                        niche_start_val,
1121
                    )?;
1122
                    // Write result.
1123
                    let niche_dest = self.place_field(dest, discr_index)?;
1124
                    self.write_immediate(*discr_val, niche_dest)?;
R
Ralf Jung 已提交
1125
                }
O
Oliver Schneider 已提交
1126
            }
1127
        }
R
Ralf Jung 已提交
1128 1129

        Ok(())
O
Oliver Schneider 已提交
1130 1131
    }

1132 1133 1134
    pub fn raw_const_to_mplace(
        &self,
        raw: RawConst<'tcx>,
1135
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1136 1137
        // This must be an allocation in `tcx`
        assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1138
        let ptr = self.tag_global_base_pointer(Pointer::from(raw.alloc_id));
1139
        let layout = self.layout_of(raw.ty)?;
1140
        Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
1141 1142
    }

1143 1144
    /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
    /// Also return some more information so drop doesn't have to run the same code twice.
M
Mark Rousskov 已提交
1145 1146 1147 1148
    pub(super) fn unpack_dyn_trait(
        &self,
        mplace: MPlaceTy<'tcx, M::PointerTag>,
    ) -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1149
        let vtable = mplace.vtable(); // also sanity checks the type
1150 1151 1152 1153
        let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
        let layout = self.layout_of(ty)?;

        // More sanity checks
1154 1155 1156
        if cfg!(debug_assertions) {
            let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
            assert_eq!(size, layout.size);
1157
            // only ABI alignment is preserved
1158
            assert_eq!(align, layout.align.abi);
1159
        }
1160

1161
        let mplace = MPlaceTy { mplace: MemPlace { meta: MemPlaceMeta::None, ..*mplace }, layout };
1162
        Ok((instance, mplace))
1163
    }
O
Oliver Schneider 已提交
1164
}