place.rs 47.3 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;
7
use std::ops::Mul;
R
Ralf Jung 已提交
8

9
use rustc::mir;
10
use rustc::mir::interpret::truncate;
11
use rustc::ty::layout::{
M
Mark Rousskov 已提交
12
    self, Align, HasDataLayout, LayoutOf, PrimitiveExt, Size, TyLayout, VariantIdx,
13
};
M
Mark Rousskov 已提交
14
use rustc::ty::{self, Ty};
15
use rustc_macros::HashStable;
O
Oliver Schneider 已提交
16

17
use super::{
S
Santiago Pastorino 已提交
18 19 20
    AllocId, AllocMap, Allocation, AllocationExtra, ImmTy, Immediate, InterpCx, InterpResult,
    LocalValue, Machine, MemoryKind, OpTy, Operand, Pointer, PointerArithmetic, RawConst, Scalar,
    ScalarMaybeUndef,
R
Ralf Jung 已提交
21 22
};

23
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
O
Oliver Scherer 已提交
24
/// Information required for the sound usage of a `MemPlace`.
25
pub enum MemPlaceMeta<Tag = (), Id = AllocId> {
O
Oliver Scherer 已提交
26
    /// The unsized payload (e.g. length for slices or vtable pointer for trait objects).
O
Oliver Scherer 已提交
27
    Meta(Scalar<Tag, Id>),
28 29 30 31 32 33 34 35 36 37
    /// `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 已提交
38
    pub fn unwrap_meta(self) -> Scalar<Tag, Id> {
39
        match self {
O
Oliver Scherer 已提交
40
            Self::Meta(s) => s,
41 42 43 44 45
            Self::None | Self::Poison => {
                bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)")
            }
        }
    }
O
Oliver Scherer 已提交
46
    fn has_meta(self) -> bool {
47
        match self {
O
Oliver Scherer 已提交
48
            Self::Meta(_) => true,
49 50 51 52 53 54 55 56
            Self::None | Self::Poison => false,
        }
    }
}

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

64
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable)]
M
Mark Rousskov 已提交
65
pub struct MemPlace<Tag = (), Id = AllocId> {
R
Ralf Jung 已提交
66 67 68
    /// 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.
69
    pub ptr: Scalar<Tag, Id>,
70
    pub align: Align,
A
Alexander Regueiro 已提交
71
    /// Metadata for unsized places. Interpretation is up to the type.
R
Ralf Jung 已提交
72
    /// Must not be present for sized types, but can be missing for unsized types
73
    /// (e.g., `extern type`).
74
    pub meta: MemPlaceMeta<Tag, Id>,
R
Ralf Jung 已提交
75
}
O
Oliver Schneider 已提交
76

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

R
Ralf Jung 已提交
82 83
    /// 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 已提交
84
    Local { frame: usize, local: mir::Local },
O
Oliver Schneider 已提交
85 86
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

238
// These are defined here because they produce a place.
239
impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
240
    #[inline(always)]
241 242
    /// 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.
243 244 245 246
    pub fn try_as_mplace(
        self,
        cx: &impl HasDataLayout,
    ) -> Result<MPlaceTy<'tcx, Tag>, ImmTy<'tcx, Tag>> {
247
        match *self {
R
Ralf Jung 已提交
248
            Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
249 250 251
            Operand::Immediate(_) if self.layout.is_zst() => {
                Ok(MPlaceTy::dangling(self.layout, cx))
            }
252
            Operand::Immediate(imm) => Err(ImmTy { imm, layout: self.layout }),
R
Ralf Jung 已提交
253 254 255
        }
    }

256
    #[inline(always)]
257 258
    /// 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.
259 260
    pub fn assert_mem_place(self, cx: &impl HasDataLayout) -> MPlaceTy<'tcx, Tag> {
        self.try_as_mplace(cx).unwrap()
R
Ralf Jung 已提交
261 262 263
    }
}

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

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

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

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

317
        let mplace = MemPlace {
318
            ptr,
319 320 321 322
            // 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.
323
            align: layout.align.abi,
324
            meta,
325 326
        };
        Ok(MPlaceTy { mplace, layout })
R
Ralf Jung 已提交
327 328
    }

329 330
    /// 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.
331 332 333
    pub fn deref_operand(
        &self,
        src: OpTy<'tcx, M::PointerTag>,
334
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
335 336
        let val = self.read_immediate(src)?;
        trace!("deref to {} on {:?}", val.layout.ty, *val);
337 338
        let place = self.ref_to_mplace(val)?;
        self.mplace_access_checked(place)
339 340
    }

341 342 343 344 345 346 347
    /// 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]
348
    pub(super) fn check_mplace_access(
349 350 351 352 353 354
        &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 已提交
355
            assert!(!place.meta.has_meta());
356 357 358 359 360
            place.layout.size
        });
        self.memory.check_ptr_access(place.ptr, size, place.align)
    }

361 362 363 364 365 366
    /// 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 已提交
367 368
        let (size, align) = self
            .size_and_align_of_mplace(place)?
369 370 371 372 373 374 375 376 377 378
            .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 已提交
379
    /// Force `place.ptr` to a `Pointer`.
380
    /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
381
    pub(super) fn force_mplace_ptr(
382 383 384
        &self,
        mut place: MPlaceTy<'tcx, M::PointerTag>,
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
385
        place.mplace.ptr = self.force_ptr(place.mplace.ptr)?.into();
386 387 388
        Ok(place)
    }

389 390
    /// 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 已提交
391
    /// This supports both struct and array fields.
392 393 394
    ///
    /// This also works for arrays, but then the `usize` index type is restricting.
    /// For indexing into arrays, use `mplace_index`.
R
Ralf Jung 已提交
395 396
    #[inline(always)]
    pub fn mplace_field(
O
Oliver Schneider 已提交
397
        &self,
398
        base: MPlaceTy<'tcx, M::PointerTag>,
399
        field: usize,
400
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
401 402
        let offset = base.layout.fields.offset(field);
        let field_layout = base.layout.field(self, field)?;
R
Ralf Jung 已提交
403

404
        // Offset may need adjustment for unsized fields.
R
Ralf Jung 已提交
405
        let (meta, offset) = if field_layout.is_unsized() {
406 407 408
            // 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.
409 410
            let align = match self.size_and_align_of(base.meta, field_layout)? {
                Some((_, align)) => align,
R
Ralf Jung 已提交
411 412 413 414 415
                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 已提交
416 417 418
                    field_layout.align.abi
                }
                None => bug!("Cannot compute offset for extern type field at non-0 offset"),
419
            };
420
            (base.meta, offset.align_to(align))
R
Ralf Jung 已提交
421
        } else {
R
Ralf Jung 已提交
422
            // base.meta could be present; we might be accessing a sized field of an unsized
423
            // struct.
424
            (MemPlaceMeta::None, offset)
R
Ralf Jung 已提交
425 426
        };

427 428 429
        // 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 已提交
430 431
    }

432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    /// 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 {
            layout::FieldPlacement::Array { stride, .. } => {
                let len = base.len(self)?;
                if index >= len {
                    // This can only be reached in ConstProp and non-rustc-MIR.
                    throw_ub!(BoundsCheckFailed { len, index });
                }
                let offset = Size::mul(stride, index);
                // 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),
        }
    }

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

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

        // 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 {
496
            layout::FieldPlacement::Array { stride, .. } => Size::mul(stride, from), // `Size` multiplication is checked
R
Ralf Jung 已提交
497
            _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
O
Oliver Schneider 已提交
498
        };
R
Ralf Jung 已提交
499

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

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

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

            Index(local) => {
R
Ralf Jung 已提交
539
                let layout = self.layout_of(self.tcx.types.usize)?;
540 541
                let n = self.access_local(self.frame(), local, Some(layout))?;
                let n = self.read_scalar(n)?;
542 543 544 545 546
                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 已提交
547 548
            }

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

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

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

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

A
Alexander Regueiro 已提交
573
    /// Gets the place of a field inside the place, and also the field's type.
R
Ralf Jung 已提交
574
    /// Just a convenience function, but used quite a bit.
575 576
    /// 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 已提交
577
    pub fn place_field(
O
Oliver Schneider 已提交
578
        &mut self,
579
        base: PlaceTy<'tcx, M::PointerTag>,
580
        field: usize,
581
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
582 583 584 585
        // 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 已提交
586 587
    }

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

A
Alexander Regueiro 已提交
614
    /// Projects into a place.
R
Ralf Jung 已提交
615 616
    pub fn place_projection(
        &mut self,
617
        base: PlaceTy<'tcx, M::PointerTag>,
618
        proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
619
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
620 621
        use rustc::mir::ProjectionElem::*;
        Ok(match *proj_elem {
622
            Field(field, _) => self.place_field(base, field.index())?,
R
Ralf Jung 已提交
623 624 625 626 627 628 629 630 631 632 633
            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 已提交
634
    /// Computes a place. You should only use this if you intend to write into this
635
    /// place; for reading, a more efficient alternative is `eval_place_for_read`.
R
Ralf Jung 已提交
636 637
    pub fn eval_place(
        &mut self,
638
        place: &mir::Place<'tcx>,
639
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
640 641
        let mut place_ty = match place.local {
            mir::RETURN_PLACE => {
642 643 644 645 646 647
                // `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 已提交
648 649 650 651 652 653 654
                        // 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.
655 656
                        None => Place::null(&*self),
                    },
657 658 659 660 661
                    layout: self.layout_of(
                        self.subst_from_current_frame_and_normalize_erasing_regions(
                            self.frame().body.return_ty(),
                        ),
                    )?,
662
                }
M
Mark Rousskov 已提交
663
            }
664
            local => PlaceTy {
665
                // This works even for dead/uninitialized locals; we check further when writing
666
                place: Place::Local { frame: self.cur_frame(), local },
667
                layout: self.layout_of_local(self.frame(), local, None)?,
668 669
            },
        };
670

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

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

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

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

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

703 704 705
        Ok(())
    }

W
Wesley Wiser 已提交
706 707 708 709 710 711
    /// 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 已提交
712
    ) -> InterpResult<'tcx> {
W
Wesley Wiser 已提交
713 714 715 716
        self.write_immediate_to_mplace_no_validate(src, dest)?;

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

        Ok(())
    }

723
    /// Write an immediate to a place.
724 725
    /// If you use this you are responsible for validating that things got copied at the
    /// right type.
726
    fn write_immediate_no_validate(
727
        &mut self,
728
        src: Immediate<M::PointerTag>,
729
        dest: PlaceTy<'tcx, M::PointerTag>,
730
    ) -> InterpResult<'tcx> {
731 732 733
        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");
734
            match src {
M
Mark Rousskov 已提交
735 736 737 738 739 740 741 742 743 744 745 746 747
                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!(
                        Size::from_bytes(size.into()),
                        dest.layout.size,
                        "Size mismatch when writing bits"
                    )
                }
                Immediate::Scalar(ScalarMaybeUndef::Undef) => {} // undef can have any size
748
                Immediate::ScalarPair(_, _) => {
749 750 751 752
                    // FIXME: Can we check anything here?
                }
            }
        }
753
        trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
754

755
        // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
R
Ralf Jung 已提交
756
        // but not factored as a separate function.
R
Ralf Jung 已提交
757
        let mplace = match dest.place {
O
Oliver Schneider 已提交
758
            Place::Local { frame, local } => {
759 760 761 762
                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 已提交
763
                        return Ok(());
764 765 766 767 768
                    }
                    Err(mplace) => {
                        // The local is in memory, go on below.
                        mplace
                    }
O
Oliver Schneider 已提交
769
                }
M
Mark Rousskov 已提交
770
            }
771
            Place::Ptr(mplace) => mplace, // already referring to memory
O
Oliver Schneider 已提交
772
        };
773
        let dest = MPlaceTy { mplace, layout: dest.layout };
O
Oliver Schneider 已提交
774

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

779
    /// Write an immediate to memory.
780
    /// If you use this you are responsible for validating that things got copied at the
781
    /// right type.
782
    fn write_immediate_to_mplace_no_validate(
R
Ralf Jung 已提交
783
        &mut self,
784
        value: Immediate<M::PointerTag>,
785
        dest: MPlaceTy<'tcx, M::PointerTag>,
786
    ) -> InterpResult<'tcx> {
B
Bernardo Meurer 已提交
787 788 789 790
        // 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.
791

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

798
        let tcx = &*self.tcx;
799 800 801
        // 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 已提交
802
        match value {
803
            Immediate::Scalar(scalar) => {
804
                match dest.layout.abi {
M
Mark Rousskov 已提交
805 806 807 808
                    layout::Abi::Scalar(_) => {} // fine
                    _ => {
                        bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}", dest.layout)
                    }
809
                }
810
                self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(
M
Mark Rousskov 已提交
811 812 813 814
                    tcx,
                    ptr,
                    scalar,
                    dest.layout.size,
R
Ralf Jung 已提交
815
                )
O
Oliver Schneider 已提交
816
            }
817
            Immediate::ScalarPair(a_val, b_val) => {
818 819 820
                // 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 已提交
821 822
                let (a, b) = match dest.layout.abi {
                    layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
M
Mark Rousskov 已提交
823 824 825 826
                    _ => bug!(
                        "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
                        dest.layout
                    ),
R
Ralf Jung 已提交
827
                };
828
                let (a_size, b_size) = (a.size(self), b.size(self));
829
                let b_offset = a_size.align_to(b.align(self).abi);
830
                let b_ptr = ptr.offset(b_offset, self)?;
831

832 833 834 835
                // 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 已提交
836 837
                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 已提交
838
            }
R
Ralf Jung 已提交
839
        }
O
Oliver Schneider 已提交
840 841
    }

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

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

        Ok(())
    }

A
Alexander Regueiro 已提交
860
    /// Copies the data from an operand to a place. This does not support transmuting!
861
    /// Use `copy_op_transmute` if the layouts could disagree.
862
    /// Also, if you use this you are responsible for validating that things get copied at the
863 864 865 866 867
    /// right type.
    fn copy_op_no_validate(
        &mut self,
        src: OpTy<'tcx, M::PointerTag>,
        dest: PlaceTy<'tcx, M::PointerTag>,
868
    ) -> InterpResult<'tcx> {
869 870
        // 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.
M
Mark Rousskov 已提交
871 872 873 874 875 876
        assert!(
            src.layout.details == dest.layout.details,
            "Layout mismatch when copying!\nsrc: {:#?}\ndest: {:#?}",
            src,
            dest
        );
R
Ralf Jung 已提交
877 878

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

892 893 894 895
        // 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 已提交
896 897 898 899
            assert!(
                !dest.layout.is_unsized(),
                "Cannot copy into already initialized unsized place"
            );
900 901 902
            dest.layout.size
        });
        assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
903

M
Mark Rousskov 已提交
904 905
        let src = self
            .check_mplace_access(src, Some(size))
906
            .expect("places should be checked on creation");
M
Mark Rousskov 已提交
907 908
        let dest = self
            .check_mplace_access(dest, Some(size))
909
            .expect("places should be checked on creation");
910 911 912 913 914 915
        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 已提交
916
        self.memory.copy(src_ptr, dest_ptr, size, /*nonoverlapping*/ true)
917 918
    }

A
Alexander Regueiro 已提交
919
    /// Copies the data from an operand to a place. The layouts may disagree, but they must
920 921 922 923 924
    /// have the same size.
    pub fn copy_op_transmute(
        &mut self,
        src: OpTy<'tcx, M::PointerTag>,
        dest: PlaceTy<'tcx, M::PointerTag>,
925
    ) -> InterpResult<'tcx> {
926 927 928 929
        if src.layout.details == dest.layout.details {
            // Fast path: Just use normal `copy_op`
            return self.copy_op(src, dest);
        }
930
        // We still require the sizes to match.
931
        if src.layout.size != dest.layout.size {
932 933 934 935
            // 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.
936
            debug!("Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
937 938 939 940
            self.tcx.sess.delay_span_bug(
                self.tcx.span,
                "size-changing transmute, should have been caught by transmute checking",
            );
941
            throw_inval!(TransmuteSizeDiff(src.layout.ty, dest.layout.ty));
942
        }
943 944
        // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
        // to avoid that here.
M
Mark Rousskov 已提交
945 946 947 948
        assert!(
            !src.layout.is_unsized() && !dest.layout.is_unsized(),
            "Cannot transmute unsized data"
        );
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963

        // 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 已提交
964
        if M::enforce_validity(self) {
965
            // Data got changed, better make sure it matches the type!
966
            self.validate_operand(dest.into())?;
967
        }
968

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

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

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

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

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

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

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

1058
    pub fn write_discriminant_index(
R
Ralf Jung 已提交
1059
        &mut self,
1060
        variant_index: VariantIdx,
1061
        dest: PlaceTy<'tcx, M::PointerTag>,
1062
    ) -> InterpResult<'tcx> {
1063 1064 1065 1066 1067
        // 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);
        }
1068

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

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

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

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

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

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

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

1142 1143
    /// 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 已提交
1144 1145 1146 1147
    pub(super) fn unpack_dyn_trait(
        &self,
        mplace: MPlaceTy<'tcx, M::PointerTag>,
    ) -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1148
        let vtable = mplace.vtable(); // also sanity checks the type
1149 1150 1151 1152
        let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
        let layout = self.layout_of(ty)?;

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

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