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;
R
Ralf Jung 已提交
7

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

17
use super::{
M
Mark Rousskov 已提交
18 19 20
    AllocId, AllocMap, Allocation, AllocationExtra, GlobalId, 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)]
M
Mark Rousskov 已提交
24
pub struct MemPlace<Tag = (), Id = AllocId> {
R
Ralf Jung 已提交
25 26 27
    /// 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.
28
    pub ptr: Scalar<Tag, Id>,
29
    pub align: Align,
A
Alexander Regueiro 已提交
30
    /// Metadata for unsized places. Interpretation is up to the type.
R
Ralf Jung 已提交
31
    /// Must not be present for sized types, but can be missing for unsized types
32
    /// (e.g., `extern type`).
R
Ralf Jung 已提交
33
    pub meta: Option<Scalar<Tag, Id>>,
R
Ralf Jung 已提交
34
}
O
Oliver Schneider 已提交
35

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

R
Ralf Jung 已提交
41 42
    /// 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 已提交
43
    Local { frame: usize, local: mir::Local },
O
Oliver Schneider 已提交
44 45
}

R
Ralf Jung 已提交
46
#[derive(Copy, Clone, Debug)]
M
Mark Rousskov 已提交
47
pub struct PlaceTy<'tcx, Tag = ()> {
48
    place: Place<Tag>, // Keep this private; it helps enforce invariants.
R
Ralf Jung 已提交
49 50 51
    pub layout: TyLayout<'tcx>,
}

52 53
impl<'tcx, Tag> ::std::ops::Deref for PlaceTy<'tcx, Tag> {
    type Target = Place<Tag>;
54
    #[inline(always)]
55
    fn deref(&self) -> &Place<Tag> {
R
Ralf Jung 已提交
56 57 58 59 60
        &self.place
    }
}

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

67 68
impl<'tcx, Tag> ::std::ops::Deref for MPlaceTy<'tcx, Tag> {
    type Target = MemPlace<Tag>;
69
    #[inline(always)]
70
    fn deref(&self) -> &MemPlace<Tag> {
R
Ralf Jung 已提交
71
        &self.mplace
O
Oliver Schneider 已提交
72
    }
R
Ralf Jung 已提交
73 74
}

75
impl<'tcx, Tag> From<MPlaceTy<'tcx, Tag>> for PlaceTy<'tcx, Tag> {
76
    #[inline(always)]
77
    fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
M
Mark Rousskov 已提交
78
        PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout }
R
Ralf Jung 已提交
79 80
    }
}
O
Oliver Schneider 已提交
81

82 83
impl<Tag> MemPlace<Tag> {
    /// Replace ptr tag, maintain vtable tag (if any)
84
    #[inline]
85
    pub fn replace_tag(self, new_tag: Tag) -> Self {
M
Mark Rousskov 已提交
86
        MemPlace { ptr: self.ptr.erase_tag().with_tag(new_tag), align: self.align, meta: self.meta }
87 88 89
    }

    #[inline]
90
    pub fn erase_tag(self) -> MemPlace {
91 92 93
        MemPlace {
            ptr: self.ptr.erase_tag(),
            align: self.align,
R
Ralf Jung 已提交
94
            meta: self.meta.map(Scalar::erase_tag),
95 96 97
        }
    }

R
Ralf Jung 已提交
98
    #[inline(always)]
99
    pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
M
Mark Rousskov 已提交
100
        MemPlace { ptr, align, meta: None }
O
Oliver Schneider 已提交
101 102
    }

103 104
    /// Produces a Place that will error if attempted to be read from or written to
    #[inline(always)]
105
    pub fn null(cx: &impl HasDataLayout) -> Self {
106
        Self::from_scalar_ptr(Scalar::ptr_null(cx), Align::from_bytes(1).unwrap())
107 108
    }

R
Ralf Jung 已提交
109
    #[inline(always)]
110
    pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
R
Ralf Jung 已提交
111 112 113
        Self::from_scalar_ptr(ptr.into(), align)
    }

R
Ralf Jung 已提交
114
    /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space.
115 116 117 118 119 120 121 122
    /// This is the inverse of `ref_to_mplace`.
    #[inline(always)]
    pub fn to_ref(self) -> Immediate<Tag> {
        match self.meta {
            None => Immediate::Scalar(self.ptr.into()),
            Some(meta) => Immediate::ScalarPair(self.ptr.into(), meta.into()),
        }
    }
123 124 125 126 127 128

    pub fn offset(
        self,
        offset: Size,
        meta: Option<Scalar<Tag>>,
        cx: &impl HasDataLayout,
129
    ) -> InterpResult<'tcx, Self> {
130 131 132 133 134 135
        Ok(MemPlace {
            ptr: self.ptr.ptr_offset(offset, cx)?,
            align: self.align.restrict_for_offset(offset),
            meta,
        })
    }
R
Ralf Jung 已提交
136 137
}

138
impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
R
Ralf Jung 已提交
139 140
    /// Produces a MemPlace that works for ZST but nothing else
    #[inline]
141
    pub fn dangling(layout: TyLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
R
Ralf Jung 已提交
142 143
        MPlaceTy {
            mplace: MemPlace::from_scalar_ptr(
144
                Scalar::from_uint(layout.align.abi.bytes(), cx.pointer_size()),
M
Mark Rousskov 已提交
145
                layout.align.abi,
R
Ralf Jung 已提交
146
            ),
M
Mark Rousskov 已提交
147
            layout,
R
Ralf Jung 已提交
148 149 150
        }
    }

151
    /// Replace ptr tag, maintain vtable tag (if any)
152
    #[inline]
153
    pub fn replace_tag(self, new_tag: Tag) -> Self {
M
Mark Rousskov 已提交
154
        MPlaceTy { mplace: self.mplace.replace_tag(new_tag), layout: self.layout }
155 156 157
    }

    #[inline]
158 159 160 161 162 163
    pub fn offset(
        self,
        offset: Size,
        meta: Option<Scalar<Tag>>,
        layout: TyLayout<'tcx>,
        cx: &impl HasDataLayout,
164
    ) -> InterpResult<'tcx, Self> {
M
Mark Rousskov 已提交
165
        Ok(MPlaceTy { mplace: self.mplace.offset(offset, meta, cx)?, layout })
166 167
    }

R
Ralf Jung 已提交
168
    #[inline]
169
    fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyLayout<'tcx>) -> Self {
170
        MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
R
Ralf Jung 已提交
171 172 173
    }

    #[inline]
174
    pub(super) fn len(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
175
        if self.layout.is_unsized() {
R
Ralf Jung 已提交
176
            // We need to consult `meta` metadata
V
varkor 已提交
177
            match self.layout.ty.kind {
M
Mark Rousskov 已提交
178
                ty::Slice(..) | ty::Str => return self.mplace.meta.unwrap().to_machine_usize(cx),
179
                _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
180
            }
181 182
        } else {
            // Go through the layout.  There are lots of types that support a length,
183
            // e.g., SIMD types.
184 185 186
            match self.layout.fields {
                layout::FieldPlacement::Array { count, .. } => Ok(count),
                _ => bug!("len not supported on sized type {:?}", self.layout.ty),
187 188 189 190 191
            }
        }
    }

    #[inline]
192
    pub(super) fn vtable(self) -> Scalar<Tag> {
V
varkor 已提交
193
        match self.layout.ty.kind {
194
            ty::Dynamic(..) => self.mplace.meta.unwrap(),
195
            _ => bug!("vtable not supported on type {:?}", self.layout.ty),
R
Ralf Jung 已提交
196 197 198 199
        }
    }
}

200
// These are defined here because they produce a place.
201
impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
202
    #[inline(always)]
203
    pub fn try_as_mplace(self) -> Result<MPlaceTy<'tcx, Tag>, ImmTy<'tcx, Tag>> {
204
        match *self {
R
Ralf Jung 已提交
205
            Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
206
            Operand::Immediate(imm) => Err(ImmTy { imm, layout: self.layout }),
R
Ralf Jung 已提交
207 208 209
        }
    }

210
    #[inline(always)]
211
    pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
R
Ralf Jung 已提交
212 213 214 215
        self.try_as_mplace().unwrap()
    }
}

R
Ralf Jung 已提交
216
impl<Tag: ::std::fmt::Debug> Place<Tag> {
R
Ralf Jung 已提交
217
    /// Produces a Place that will error if attempted to be read from or written to
218
    #[inline(always)]
219
    pub fn null(cx: &impl HasDataLayout) -> Self {
220
        Place::Ptr(MemPlace::null(cx))
R
Ralf Jung 已提交
221 222
    }

223
    #[inline(always)]
224
    pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
R
Ralf Jung 已提交
225 226 227
        Place::Ptr(MemPlace::from_scalar_ptr(ptr, align))
    }

228
    #[inline(always)]
229
    pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
R
Ralf Jung 已提交
230
        Place::Ptr(MemPlace::from_ptr(ptr, align))
O
Oliver Schneider 已提交
231 232
    }

R
Ralf Jung 已提交
233
    #[inline]
234
    pub fn assert_mem_place(self) -> MemPlace<Tag> {
O
Oliver Schneider 已提交
235
        match self {
R
Ralf Jung 已提交
236
            Place::Ptr(mplace) => mplace,
237
            _ => bug!("assert_mem_place: expected Place::Ptr, got {:?}", self),
O
Oliver Schneider 已提交
238 239
        }
    }
R
Ralf Jung 已提交
240
}
O
Oliver Schneider 已提交
241

242
impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
R
Ralf Jung 已提交
243
    #[inline]
244 245
    pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
        MPlaceTy { mplace: self.place.assert_mem_place(), layout: self.layout }
O
Oliver Schneider 已提交
246 247 248
    }
}

249
// separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
R
Ralf Jung 已提交
250
impl<'mir, 'tcx, Tag, M> InterpCx<'mir, 'tcx, M>
251
where
R
Ralf Jung 已提交
252
    // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
253
    Tag: ::std::fmt::Debug + Copy + Eq + Hash + 'static,
254
    M: Machine<'mir, 'tcx, PointerTag = Tag>,
R
Ralf Jung 已提交
255
    // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
256
    M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation<Tag, M::AllocExtra>)>,
257
    M::AllocExtra: AllocationExtra<Tag>,
258
{
R
Ralf Jung 已提交
259
    /// Take a value, which represents a (thin or wide) reference, and make it a place.
260
    /// Alignment is just based on the type.  This is the inverse of `MemPlace::to_ref()`.
R
Ralf Jung 已提交
261 262 263 264
    ///
    /// 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 已提交
265
    pub fn ref_to_mplace(
266
        &self,
267
        val: ImmTy<'tcx, M::PointerTag>,
268
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
M
Mark Rousskov 已提交
269 270
        let pointee_type =
            val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty;
271
        let layout = self.layout_of(pointee_type)?;
272 273 274 275
        let (ptr, meta) = match *val {
            Immediate::Scalar(ptr) => (ptr.not_undef()?, None),
            Immediate::ScalarPair(ptr, meta) => (ptr.not_undef()?, Some(meta.not_undef()?)),
        };
276

277
        let mplace = MemPlace {
278
            ptr,
279 280 281 282
            // 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.
283
            align: layout.align.abi,
284
            meta,
285 286
        };
        Ok(MPlaceTy { mplace, layout })
R
Ralf Jung 已提交
287 288
    }

289 290
    /// 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.
291 292 293
    pub fn deref_operand(
        &self,
        src: OpTy<'tcx, M::PointerTag>,
294
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
295 296
        let val = self.read_immediate(src)?;
        trace!("deref to {} on {:?}", val.layout.ty, *val);
297 298
        let place = self.ref_to_mplace(val)?;
        self.mplace_access_checked(place)
299 300
    }

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    /// 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]
    pub fn check_mplace_access(
        &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());
            assert!(place.meta.is_none());
            place.layout.size
        });
        self.memory.check_ptr_access(place.ptr, size, place.align)
    }

321 322 323 324 325 326
    /// 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 已提交
327 328
        let (size, align) = self
            .size_and_align_of_mplace(place)?
329 330 331 332 333 334 335 336 337 338
            .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 已提交
339
    /// Force `place.ptr` to a `Pointer`.
340
    /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
R
Ralf Jung 已提交
341
    pub fn force_mplace_ptr(
342 343 344
        &self,
        mut place: MPlaceTy<'tcx, M::PointerTag>,
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
345
        place.mplace.ptr = self.force_ptr(place.mplace.ptr)?.into();
346 347 348
        Ok(place)
    }

349 350
    /// Offset a pointer to project to a field. Unlike `place_field`, this is always
    /// possible without allocating, so it can take `&self`. Also return the field's layout.
R
Ralf Jung 已提交
351 352 353
    /// This supports both struct and array fields.
    #[inline(always)]
    pub fn mplace_field(
O
Oliver Schneider 已提交
354
        &self,
355
        base: MPlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
356
        field: u64,
357
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
358 359
        // Not using the layout method because we want to compute on u64
        let offset = match base.layout.fields {
M
Mark Rousskov 已提交
360 361 362
            layout::FieldPlacement::Arbitrary { ref offsets, .. } => {
                offsets[usize::try_from(field).unwrap()]
            }
R
Ralf Jung 已提交
363
            layout::FieldPlacement::Array { stride, .. } => {
364
                let len = base.len(self)?;
365
                if field >= len {
366 367
                    // This can only be reached in ConstProp and non-rustc-MIR.
                    throw_ub!(BoundsCheckFailed { len, index: field });
368
                }
R
Ralf Jung 已提交
369 370
                stride * field
            }
371
            layout::FieldPlacement::Union(count) => {
M
Mark Rousskov 已提交
372 373 374 375 376 377 378
                assert!(
                    field < count as u64,
                    "Tried to access field {} of union {:#?} with {} fields",
                    field,
                    base.layout,
                    count
                );
379 380 381
                // Offset is always 0
                Size::from_bytes(0)
            }
R
Ralf Jung 已提交
382 383 384
        };
        // the only way conversion can fail if is this is an array (otherwise we already panicked
        // above). In that case, all fields are equal.
R
Ralf Jung 已提交
385
        let field_layout = base.layout.field(self, usize::try_from(field).unwrap_or(0))?;
R
Ralf Jung 已提交
386

387
        // Offset may need adjustment for unsized fields.
R
Ralf Jung 已提交
388
        let (meta, offset) = if field_layout.is_unsized() {
389 390 391
            // 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.
392 393 394
            let align = match self.size_and_align_of(base.meta, field_layout)? {
                Some((_, align)) => align,
                None if offset == Size::ZERO =>
M
Mark Rousskov 已提交
395 396 397 398 399 400 401 402
                // 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.
                {
                    field_layout.align.abi
                }
                None => bug!("Cannot compute offset for extern type field at non-0 offset"),
403
            };
404
            (base.meta, offset.align_to(align))
R
Ralf Jung 已提交
405
        } else {
R
Ralf Jung 已提交
406
            // base.meta could be present; we might be accessing a sized field of an unsized
407 408
            // struct.
            (None, offset)
R
Ralf Jung 已提交
409 410
        };

411 412 413
        // 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 已提交
414 415
    }

416 417 418 419
    // Iterates over all fields of an array. Much more efficient than doing the
    // same by repeatedly calling `mplace_array`.
    pub fn mplace_array_fields(
        &self,
420
        base: MPlaceTy<'tcx, Tag>,
421
    ) -> InterpResult<'tcx, impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'tcx>
422
    {
423
        let len = base.len(self)?; // also asserts that we have a type where this makes sense
424 425 426 427 428 429
        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;
430
        Ok((0..len).map(move |i| base.offset(i * stride, None, layout, dl)))
431 432
    }

R
Ralf Jung 已提交
433
    pub fn mplace_subslice(
O
Oliver Schneider 已提交
434
        &self,
435
        base: MPlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
436 437
        from: u64,
        to: u64,
438
        from_end: bool,
439
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
440
        let len = base.len(self)?; // also asserts that we have a type where this makes sense
441
        let actual_to = if from_end {
442 443 444 445
            if from + to > len {
                // This can only be reached in ConstProp and non-rustc-MIR.
                throw_ub!(BoundsCheckFailed { len: len as u64, index: from as u64 + to as u64 });
            }
446 447 448 449
            len - to
        } else {
            to
        };
R
Ralf Jung 已提交
450 451 452 453

        // 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 {
M
Mark Rousskov 已提交
454
            layout::FieldPlacement::Array { stride, .. } => stride * from,
R
Ralf Jung 已提交
455
            _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
O
Oliver Schneider 已提交
456
        };
R
Ralf Jung 已提交
457

R
Ralf Jung 已提交
458
        // Compute meta and new layout
459
        let inner_len = actual_to - from;
V
varkor 已提交
460
        let (meta, ty) = match base.layout.ty.kind {
R
Ralf Jung 已提交
461 462
            // It is not nice to match on the type, but that seems to be the only way to
            // implement this.
M
Mark Rousskov 已提交
463
            ty::Array(inner, _) => (None, self.tcx.mk_array(inner, inner_len)),
464
            ty::Slice(..) => {
465
                let len = Scalar::from_uint(inner_len, self.pointer_size());
466 467
                (Some(len), base.layout.ty)
            }
M
Mark Rousskov 已提交
468
            _ => bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
R
Ralf Jung 已提交
469 470
        };
        let layout = self.layout_of(ty)?;
471
        base.offset(from_offset, meta, layout, self)
R
Ralf Jung 已提交
472 473 474 475
    }

    pub fn mplace_downcast(
        &self,
476
        base: MPlaceTy<'tcx, M::PointerTag>,
477
        variant: VariantIdx,
478
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
479
        // Downcasts only change the layout
R
Ralf Jung 已提交
480
        assert!(base.meta.is_none());
R
Ralf Jung 已提交
481
        Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
O
Oliver Schneider 已提交
482 483
    }

R
Ralf Jung 已提交
484 485
    /// Project into an mplace
    pub fn mplace_projection(
O
Oliver Schneider 已提交
486
        &self,
487
        base: MPlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
488
        proj_elem: &mir::PlaceElem<'tcx>,
489
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
490
        use rustc::mir::ProjectionElem::*;
R
Ralf Jung 已提交
491 492 493 494 495 496
        Ok(match *proj_elem {
            Field(field, _) => self.mplace_field(base, field.index() as u64)?,
            Downcast(_, variant) => self.mplace_downcast(base, variant)?,
            Deref => self.deref_operand(base.into())?,

            Index(local) => {
R
Ralf Jung 已提交
497
                let layout = self.layout_of(self.tcx.types.usize)?;
498 499
                let n = self.access_local(self.frame(), local, Some(layout))?;
                let n = self.read_scalar(n)?;
500
                let n = self.force_bits(n.not_undef()?, self.tcx.data_layout.pointer_size)?;
R
Ralf Jung 已提交
501 502 503
                self.mplace_field(base, u64::try_from(n).unwrap())?
            }

M
Mark Rousskov 已提交
504
            ConstantIndex { offset, min_length, from_end } => {
505
                let n = base.len(self)?;
506 507 508 509
                if n < min_length as u64 {
                    // This can only be reached in ConstProp and non-rustc-MIR.
                    throw_ub!(BoundsCheckFailed { len: min_length as u64, index: n as u64 });
                }
R
Ralf Jung 已提交
510 511

                let index = if from_end {
512
                    assert!(0 < offset && offset - 1 < min_length);
R
Ralf Jung 已提交
513 514
                    n - u64::from(offset)
                } else {
O
Oliver Scherer 已提交
515
                    assert!(offset < min_length);
R
Ralf Jung 已提交
516 517 518 519 520 521
                    u64::from(offset)
                };

                self.mplace_field(base, index)?
            }

M
Mark Rousskov 已提交
522 523 524
            Subslice { from, to, from_end } => {
                self.mplace_subslice(base, u64::from(from), u64::from(to), from_end)?
            }
R
Ralf Jung 已提交
525
        })
O
Oliver Schneider 已提交
526 527
    }

A
Alexander Regueiro 已提交
528
    /// Gets the place of a field inside the place, and also the field's type.
R
Ralf Jung 已提交
529
    /// Just a convenience function, but used quite a bit.
530 531
    /// 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 已提交
532
    pub fn place_field(
O
Oliver Schneider 已提交
533
        &mut self,
534
        base: PlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
535
        field: u64,
536
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
537 538 539 540
        // 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 已提交
541 542
    }

R
Ralf Jung 已提交
543
    pub fn place_downcast(
544
        &self,
545
        base: PlaceTy<'tcx, M::PointerTag>,
546
        variant: VariantIdx,
547
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
548 549
        // Downcast just changes the layout
        Ok(match base.place {
M
Mark Rousskov 已提交
550 551 552
            Place::Ptr(mplace) => {
                self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into()
            }
R
Ralf Jung 已提交
553
            Place::Local { .. } => {
554
                let layout = base.layout.for_variant(self, variant);
R
Ralf Jung 已提交
555
                PlaceTy { layout, ..base }
O
Oliver Schneider 已提交
556
            }
R
Ralf Jung 已提交
557
        })
O
Oliver Schneider 已提交
558 559
    }

A
Alexander Regueiro 已提交
560
    /// Projects into a place.
R
Ralf Jung 已提交
561 562
    pub fn place_projection(
        &mut self,
563
        base: PlaceTy<'tcx, M::PointerTag>,
564
        proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
565
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
566 567
        use rustc::mir::ProjectionElem::*;
        Ok(match *proj_elem {
M
Mark Rousskov 已提交
568
            Field(field, _) => self.place_field(base, field.index() as u64)?,
R
Ralf Jung 已提交
569 570 571 572 573 574 575 576 577 578 579
            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 已提交
580
    /// Evaluate statics and promoteds to an `MPlace`. Used to share some code between
581
    /// `eval_place` and `eval_place_to_op`.
582
    pub(super) fn eval_static_to_mplace(
583
        &self,
M
Mark Rousskov 已提交
584
        place_static: &mir::Static<'tcx>,
585
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
586 587 588
        use rustc::mir::StaticKind;

        Ok(match place_static.kind {
589 590 591
            StaticKind::Promoted(promoted, promoted_substs) => {
                let substs = self.subst_from_frame_and_normalize_erasing_regions(promoted_substs);
                let instance = ty::Instance::new(place_static.def_id, substs);
592 593 594 595 596 597 598

                // Even after getting `substs` from the frame, this instance may still be
                // polymorphic because `ConstProp` will try to promote polymorphic MIR.
                if instance.needs_subst() {
                    throw_inval!(TooGeneric);
                }

M
Mark Rousskov 已提交
599
                self.const_eval_raw(GlobalId { instance, promoted: Some(promoted) })?
S
Saleem Jaffer 已提交
600 601
            }

W
Wesley Wiser 已提交
602
            StaticKind::Static => {
603
                let ty = place_static.ty;
S
Saleem Jaffer 已提交
604 605 606
                assert!(!ty.needs_subst());
                let layout = self.layout_of(ty)?;
                // Just create a lazy reference, so we can support recursive statics.
607
                // tcx takes care of assigning every static one and only one unique AllocId.
S
Saleem Jaffer 已提交
608 609 610 611 612
                // When the data here is ever actually used, memory will notice,
                // and it knows how to deal with alloc_id that are present in the
                // global table but not in its local memory: It calls back into tcx through
                // a query, triggering the CTFE machinery to actually turn this lazy reference
                // into a bunch of bytes.  IOW, statics are evaluated with CTFE even when
R
Ralf Jung 已提交
613
                // this InterpCx uses another Machine (e.g., in miri).  This is what we
614
                // want!  This way, computing statics works consistently between codegen
S
Saleem Jaffer 已提交
615 616
                // and miri: They use the same query to eventually obtain a `ty::Const`
                // and use that for further computation.
617 618 619 620
                //
                // Notice that statics have *two* AllocIds: the lazy one, and the resolved
                // one.  Here we make sure that the interpreted program never sees the
                // resolved ID.  Also see the doc comment of `Memory::get_static_alloc`.
621
                let alloc_id = self.tcx.alloc_map.lock().create_static_alloc(place_static.def_id);
622 623
                let ptr = self.tag_static_base_pointer(Pointer::from(alloc_id));
                MPlaceTy::from_aligned_ptr(ptr, layout)
O
Oliver Schneider 已提交
624
            }
625 626 627
        })
    }

A
Alexander Regueiro 已提交
628
    /// Computes a place. You should only use this if you intend to write into this
629
    /// place; for reading, a more efficient alternative is `eval_place_for_read`.
R
Ralf Jung 已提交
630 631
    pub fn eval_place(
        &mut self,
632
        place: &mir::Place<'tcx>,
633
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
634
        use rustc::mir::PlaceBase;
635

636
        let mut place_ty = match &place.base {
637 638 639 640 641 642 643
            PlaceBase::Local(mir::RETURN_PLACE) => {
                // `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 已提交
644 645 646 647 648 649 650
                        // 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.
651 652
                        None => Place::null(&*self),
                    },
M
Mark Rousskov 已提交
653 654 655
                    layout: self.layout_of(self.subst_from_frame_and_normalize_erasing_regions(
                        self.frame().body.return_ty(),
                    ))?,
656
                }
M
Mark Rousskov 已提交
657
            }
658 659
            PlaceBase::Local(local) => PlaceTy {
                // This works even for dead/uninitialized locals; we check further when writing
M
Mark Rousskov 已提交
660
                place: Place::Local { frame: self.cur_frame(), local: *local },
661 662 663 664
                layout: self.layout_of_local(self.frame(), *local, None)?,
            },
            PlaceBase::Static(place_static) => self.eval_static_to_mplace(&place_static)?.into(),
        };
665

666 667 668
        for elem in place.projection.iter() {
            place_ty = self.place_projection(place_ty, elem)?
        }
O
Oliver Schneider 已提交
669

670 671
        self.dump_place(place_ty.place);
        Ok(place_ty)
O
Oliver Schneider 已提交
672 673
    }

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

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

R
Ralf Jung 已提交
693
        if M::enforce_validity(self) {
694
            // Data got changed, better make sure it matches the type!
695
            self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
696 697
        }

698 699 700
        Ok(())
    }

W
Wesley Wiser 已提交
701 702 703 704 705 706
    /// 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 已提交
707
    ) -> InterpResult<'tcx> {
W
Wesley Wiser 已提交
708 709 710 711
        self.write_immediate_to_mplace_no_validate(src, dest)?;

        if M::enforce_validity(self) {
            // Data got changed, better make sure it matches the type!
O
Oliver Scherer 已提交
712
            self.validate_operand(dest.into(), vec![], None)?;
W
Wesley Wiser 已提交
713 714 715 716 717
        }

        Ok(())
    }

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

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

R
Ralf Jung 已提交
770
        // This is already in memory, write there.
771
        self.write_immediate_to_mplace_no_validate(src, dest)
O
Oliver Schneider 已提交
772 773
    }

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

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

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

827 828 829 830
                // 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 已提交
831 832
                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 已提交
833
            }
R
Ralf Jung 已提交
834
        }
O
Oliver Schneider 已提交
835 836
    }

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

R
Ralf Jung 已提交
847
        if M::enforce_validity(self) {
848
            // Data got changed, better make sure it matches the type!
849
            self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
850 851 852 853 854
        }

        Ok(())
    }

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

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

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

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

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

        // 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 已提交
955
        if M::enforce_validity(self) {
956
            // Data got changed, better make sure it matches the type!
957
            self.validate_operand(dest.into(), vec![], None)?;
958
        }
959

960
        Ok(())
O
Oliver Schneider 已提交
961 962
    }

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

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

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

R
Ralf Jung 已提交
1022
    pub fn allocate(
O
Oliver Schneider 已提交
1023
        &mut self,
R
Ralf Jung 已提交
1024 1025
        layout: TyLayout<'tcx>,
        kind: MemoryKind<M::MemoryKinds>,
R
Ralf Jung 已提交
1026
    ) -> MPlaceTy<'tcx, M::PointerTag> {
1027 1028
        let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
        MPlaceTy::from_aligned_ptr(ptr, layout)
R
Ralf Jung 已提交
1029
    }
O
Oliver Schneider 已提交
1030

R
Ralf Jung 已提交
1031
    /// Returns a wide MPlace.
1032 1033 1034 1035 1036 1037 1038
    pub fn allocate_str(
        &mut self,
        str: &str,
        kind: MemoryKind<M::MemoryKinds>,
    ) -> MPlaceTy<'tcx, M::PointerTag> {
        let ptr = self.memory.allocate_static_bytes(str.as_bytes(), kind);
        let meta = Scalar::from_uint(str.len() as u128, self.pointer_size());
M
Mark Rousskov 已提交
1039 1040
        let mplace =
            MemPlace { ptr: ptr.into(), align: Align::from_bytes(1).unwrap(), meta: Some(meta) };
1041 1042 1043 1044 1045

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

1046
    pub fn write_discriminant_index(
R
Ralf Jung 已提交
1047
        &mut self,
1048
        variant_index: VariantIdx,
1049
        dest: PlaceTy<'tcx, M::PointerTag>,
1050
    ) -> InterpResult<'tcx> {
1051 1052 1053 1054 1055
        // 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);
        }
1056

R
Ralf Jung 已提交
1057 1058
        match dest.layout.variants {
            layout::Variants::Single { index } => {
1059
                assert_eq!(index, variant_index);
O
Oliver Schneider 已提交
1060
            }
1061 1062
            layout::Variants::Multiple {
                discr_kind: layout::DiscriminantKind::Tag,
1063
                discr: ref discr_layout,
1064
                discr_index,
1065 1066
                ..
            } => {
1067 1068 1069
                // No need to validate that the discriminant here because the
                // `TyLayout::for_variant()` call earlier already checks the variant is valid.

1070 1071
                let discr_val =
                    dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
R
Ralf Jung 已提交
1072 1073 1074 1075

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

1079
                let discr_dest = self.place_field(dest, discr_index as u64)?;
1080
                self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
O
Oliver Schneider 已提交
1081
            }
1082
            layout::Variants::Multiple {
M
Mark Rousskov 已提交
1083 1084
                discr_kind:
                    layout::DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start },
1085
                discr: ref discr_layout,
1086
                discr_index,
R
Ralf Jung 已提交
1087
                ..
O
Oliver Schneider 已提交
1088
            } => {
1089 1090 1091
                // No need to validate that the discriminant here because the
                // `TyLayout::for_variant()` call earlier already checks the variant is valid.

R
Ralf Jung 已提交
1092
                if variant_index != dataful_variant {
1093
                    let variants_start = niche_variants.start().as_u32();
M
Mark Rousskov 已提交
1094 1095
                    let variant_index_relative = variant_index
                        .as_u32()
1096 1097
                        .checked_sub(variants_start)
                        .expect("overflow computing relative variant idx");
1098 1099
                    // We need to use machine arithmetic when taking into account `niche_start`:
                    // discr_val = variant_index_relative + niche_start_val
1100
                    let discr_layout = self.layout_of(discr_layout.value.to_int_ty(*self.tcx))?;
1101
                    let niche_start_val = ImmTy::from_uint(niche_start, discr_layout);
1102 1103
                    let variant_index_relative_val =
                        ImmTy::from_uint(variant_index_relative, discr_layout);
1104
                    let discr_val = self.binary_op(
1105
                        mir::BinOp::Add,
1106
                        variant_index_relative_val,
1107
                        niche_start_val,
1108
                    )?;
1109 1110
                    // Write result.
                    let niche_dest = self.place_field(dest, discr_index as u64)?;
1111
                    self.write_immediate(*discr_val, niche_dest)?;
R
Ralf Jung 已提交
1112
                }
O
Oliver Schneider 已提交
1113
            }
1114
        }
R
Ralf Jung 已提交
1115 1116

        Ok(())
O
Oliver Schneider 已提交
1117 1118
    }

1119 1120 1121
    pub fn raw_const_to_mplace(
        &self,
        raw: RawConst<'tcx>,
1122
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1123 1124
        // This must be an allocation in `tcx`
        assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1125
        let ptr = self.tag_static_base_pointer(Pointer::from(raw.alloc_id));
1126
        let layout = self.layout_of(raw.ty)?;
1127
        Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
1128 1129
    }

1130 1131
    /// 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 已提交
1132 1133 1134 1135
    pub(super) fn unpack_dyn_trait(
        &self,
        mplace: MPlaceTy<'tcx, M::PointerTag>,
    ) -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1136
        let vtable = mplace.vtable(); // also sanity checks the type
1137 1138 1139 1140
        let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
        let layout = self.layout_of(ty)?;

        // More sanity checks
1141 1142 1143
        if cfg!(debug_assertions) {
            let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
            assert_eq!(size, layout.size);
1144
            // only ABI alignment is preserved
1145
            assert_eq!(align, layout.align.abi);
1146
        }
1147

M
Mark Rousskov 已提交
1148
        let mplace = MPlaceTy { mplace: MemPlace { meta: None, ..*mplace }, layout };
1149
        Ok((instance, mplace))
1150
    }
O
Oliver Schneider 已提交
1151
}