place.rs 42.6 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;
R
Ralf Jung 已提交
10
use rustc::ty::{self, Ty};
11
use rustc::ty::layout::{self, Size, Align, LayoutOf, TyLayout, HasDataLayout, VariantIdx};
12
use rustc::ty::TypeFoldable;
O
Oliver Schneider 已提交
13

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

#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
21
pub struct MemPlace<Tag=(), Id=AllocId> {
R
Ralf Jung 已提交
22 23 24
    /// 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.
25
    pub ptr: Scalar<Tag, Id>,
26
    pub align: Align,
A
Alexander Regueiro 已提交
27
    /// Metadata for unsized places. Interpretation is up to the type.
R
Ralf Jung 已提交
28
    /// Must not be present for sized types, but can be missing for unsized types
29
    /// (e.g., `extern type`).
R
Ralf Jung 已提交
30
    pub meta: Option<Scalar<Tag, Id>>,
R
Ralf Jung 已提交
31
}
O
Oliver Schneider 已提交
32

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

R
Ralf Jung 已提交
38 39 40 41 42 43
    /// To support alloc-free locals, we are able to write directly to a local.
    /// (Without that optimization, we'd just always be a `MemPlace`.)
    Local {
        frame: usize,
        local: mir::Local,
    },
O
Oliver Schneider 已提交
44 45
}

R
Ralf Jung 已提交
46
#[derive(Copy, Clone, Debug)]
47 48
pub struct PlaceTy<'tcx, Tag=()> {
    place: Place<Tag>,
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)]
62 63
pub struct MPlaceTy<'tcx, Tag=()> {
    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 {
R
Ralf Jung 已提交
78 79 80 81 82 83
        PlaceTy {
            place: Place::Ptr(mplace.mplace),
            layout: mplace.layout
        }
    }
}
O
Oliver Schneider 已提交
84

85 86
impl<Tag> MemPlace<Tag> {
    /// Replace ptr tag, maintain vtable tag (if any)
87
    #[inline]
88
    pub fn replace_tag(self, new_tag: Tag) -> Self {
89
        MemPlace {
90
            ptr: self.ptr.erase_tag().with_tag(new_tag),
91
            align: self.align,
92
            meta: self.meta,
93 94 95 96
        }
    }

    #[inline]
97
    pub fn erase_tag(self) -> MemPlace {
98 99 100
        MemPlace {
            ptr: self.ptr.erase_tag(),
            align: self.align,
R
Ralf Jung 已提交
101
            meta: self.meta.map(Scalar::erase_tag),
102 103 104
        }
    }

R
Ralf Jung 已提交
105
    #[inline(always)]
106
    pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
R
Ralf Jung 已提交
107
        MemPlace {
108 109
            ptr,
            align,
R
Ralf Jung 已提交
110
            meta: None,
O
Oliver Schneider 已提交
111 112 113
        }
    }

114 115
    /// Produces a Place that will error if attempted to be read from or written to
    #[inline(always)]
116
    pub fn null(cx: &impl HasDataLayout) -> Self {
117
        Self::from_scalar_ptr(Scalar::ptr_null(cx), Align::from_bytes(1).unwrap())
118 119
    }

R
Ralf Jung 已提交
120
    #[inline(always)]
121
    pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
R
Ralf Jung 已提交
122 123 124 125
        Self::from_scalar_ptr(ptr.into(), align)
    }

    #[inline(always)]
126
    pub fn to_scalar_ptr_align(self) -> (Scalar<Tag>, Align) {
R
Ralf Jung 已提交
127
        assert!(self.meta.is_none());
R
Ralf Jung 已提交
128 129 130
        (self.ptr, self.align)
    }

R
Ralf Jung 已提交
131
    /// metact the ptr part of the mplace
R
Ralf Jung 已提交
132
    #[inline(always)]
133
    pub fn to_ptr(self) -> InterpResult<'tcx, Pointer<Tag>> {
B
Bernardo Meurer 已提交
134 135 136
        // At this point, we forget about the alignment information --
        // the place has been turned into a reference, and no matter where it came from,
        // it now must be aligned.
R
Ralf Jung 已提交
137 138
        self.to_scalar_ptr_align().0.to_ptr()
    }
139 140 141 142 143 144 145 146 147 148

    /// Turn a mplace into a (thin or fat) pointer, as a reference, pointing to the same space.
    /// 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()),
        }
    }
149 150 151 152 153 154

    pub fn offset(
        self,
        offset: Size,
        meta: Option<Scalar<Tag>>,
        cx: &impl HasDataLayout,
155
    ) -> InterpResult<'tcx, Self> {
156 157 158 159 160 161
        Ok(MemPlace {
            ptr: self.ptr.ptr_offset(offset, cx)?,
            align: self.align.restrict_for_offset(offset),
            meta,
        })
    }
R
Ralf Jung 已提交
162 163
}

164
impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
R
Ralf Jung 已提交
165 166
    /// Produces a MemPlace that works for ZST but nothing else
    #[inline]
167
    pub fn dangling(layout: TyLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
R
Ralf Jung 已提交
168 169
        MPlaceTy {
            mplace: MemPlace::from_scalar_ptr(
170
                Scalar::from_uint(layout.align.abi.bytes(), cx.pointer_size()),
171
                layout.align.abi
R
Ralf Jung 已提交
172 173 174 175 176
            ),
            layout
        }
    }

177
    /// Replace ptr tag, maintain vtable tag (if any)
178
    #[inline]
179
    pub fn replace_tag(self, new_tag: Tag) -> Self {
180
        MPlaceTy {
181
            mplace: self.mplace.replace_tag(new_tag),
182 183 184 185 186
            layout: self.layout,
        }
    }

    #[inline]
187 188 189 190 191 192
    pub fn offset(
        self,
        offset: Size,
        meta: Option<Scalar<Tag>>,
        layout: TyLayout<'tcx>,
        cx: &impl HasDataLayout,
193
    ) -> InterpResult<'tcx, Self> {
194 195 196 197 198 199
        Ok(MPlaceTy {
            mplace: self.mplace.offset(offset, meta, cx)?,
            layout,
        })
    }

R
Ralf Jung 已提交
200
    #[inline]
201
    fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyLayout<'tcx>) -> Self {
202
        MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
R
Ralf Jung 已提交
203 204 205
    }

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

    #[inline]
225
    pub(super) fn vtable(self) -> Scalar<Tag> {
226
        match self.layout.ty.sty {
227
            ty::Dynamic(..) => self.mplace.meta.unwrap(),
228
            _ => bug!("vtable not supported on type {:?}", self.layout.ty),
R
Ralf Jung 已提交
229 230 231 232
        }
    }
}

233
impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> {
234
    #[inline(always)]
235
    pub fn try_as_mplace(self) -> Result<MPlaceTy<'tcx, Tag>, ImmTy<'tcx, Tag>> {
236
        match *self {
R
Ralf Jung 已提交
237
            Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
238
            Operand::Immediate(imm) => Err(ImmTy { imm, layout: self.layout }),
R
Ralf Jung 已提交
239 240 241
        }
    }

242
    #[inline(always)]
243
    pub fn to_mem_place(self) -> MPlaceTy<'tcx, Tag> {
R
Ralf Jung 已提交
244 245 246 247
        self.try_as_mplace().unwrap()
    }
}

248
impl<'tcx, Tag: ::std::fmt::Debug> Place<Tag> {
R
Ralf Jung 已提交
249
    /// Produces a Place that will error if attempted to be read from or written to
250
    #[inline(always)]
251
    pub fn null(cx: &impl HasDataLayout) -> Self {
252
        Place::Ptr(MemPlace::null(cx))
R
Ralf Jung 已提交
253 254
    }

255
    #[inline(always)]
256
    pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
R
Ralf Jung 已提交
257 258 259
        Place::Ptr(MemPlace::from_scalar_ptr(ptr, align))
    }

260
    #[inline(always)]
261
    pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
R
Ralf Jung 已提交
262
        Place::Ptr(MemPlace::from_ptr(ptr, align))
O
Oliver Schneider 已提交
263 264
    }

R
Ralf Jung 已提交
265
    #[inline]
266
    pub fn to_mem_place(self) -> MemPlace<Tag> {
O
Oliver Schneider 已提交
267
        match self {
R
Ralf Jung 已提交
268 269
            Place::Ptr(mplace) => mplace,
            _ => bug!("to_mem_place: expected Place::Ptr, got {:?}", self),
O
Oliver Schneider 已提交
270 271 272 273

        }
    }

R
Ralf Jung 已提交
274
    #[inline]
275
    pub fn to_scalar_ptr_align(self) -> (Scalar<Tag>, Align) {
R
Ralf Jung 已提交
276
        self.to_mem_place().to_scalar_ptr_align()
277
    }
278

R
Ralf Jung 已提交
279
    #[inline]
280
    pub fn to_ptr(self) -> InterpResult<'tcx, Pointer<Tag>> {
R
Ralf Jung 已提交
281 282 283
        self.to_mem_place().to_ptr()
    }
}
O
Oliver Schneider 已提交
284

285
impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
R
Ralf Jung 已提交
286
    #[inline]
287
    pub fn to_mem_place(self) -> MPlaceTy<'tcx, Tag> {
R
Ralf Jung 已提交
288
        MPlaceTy { mplace: self.place.to_mem_place(), layout: self.layout }
O
Oliver Schneider 已提交
289 290 291
    }
}

292
// separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
R
Ralf Jung 已提交
293
impl<'mir, 'tcx, Tag, M> InterpCx<'mir, 'tcx, M>
294
where
R
Ralf Jung 已提交
295
    // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
296
    Tag: ::std::fmt::Debug + Copy + Eq + Hash + 'static,
297
    M: Machine<'mir, 'tcx, PointerTag = Tag>,
R
Ralf Jung 已提交
298
    // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
299
    M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation<Tag, M::AllocExtra>)>,
300
    M::AllocExtra: AllocationExtra<Tag>,
301
{
R
Ralf Jung 已提交
302
    /// Take a value, which represents a (thin or fat) reference, and make it a place.
303
    /// Alignment is just based on the type.  This is the inverse of `MemPlace::to_ref()`.
304 305
    /// This does NOT call the "deref" machine hook, so it does NOT count as a
    /// deref as far as Stacked Borrows is concerned.  Use `deref_operand` for that!
R
Ralf Jung 已提交
306
    pub fn ref_to_mplace(
307
        &self,
308
        val: ImmTy<'tcx, M::PointerTag>,
309
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
310 311 312
        let pointee_type = val.layout.ty.builtin_deref(true).unwrap().ty;
        let layout = self.layout_of(pointee_type)?;

313 314
        let mplace = MemPlace {
            ptr: val.to_scalar_ptr()?,
315 316 317 318
            // 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.
319
            align: layout.align.abi,
320 321 322
            meta: val.to_meta()?,
        };
        Ok(MPlaceTy { mplace, layout })
R
Ralf Jung 已提交
323 324
    }

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

336 337
    /// 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 已提交
338 339 340
    /// This supports both struct and array fields.
    #[inline(always)]
    pub fn mplace_field(
O
Oliver Schneider 已提交
341
        &self,
342
        base: MPlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
343
        field: u64,
344
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
345 346 347 348 349
        // Not using the layout method because we want to compute on u64
        let offset = match base.layout.fields {
            layout::FieldPlacement::Arbitrary { ref offsets, .. } =>
                offsets[usize::try_from(field).unwrap()],
            layout::FieldPlacement::Array { stride, .. } => {
350
                let len = base.len(self)?;
351 352 353 354 355 356
                if field >= len {
                    // This can be violated because this runs during promotion on code where the
                    // type system has not yet ensured that such things don't happen.
                    debug!("Tried to access element {} of array/slice with length {}", field, len);
                    return err!(BoundsCheck { len, index: field });
                }
R
Ralf Jung 已提交
357 358
                stride * field
            }
359
            layout::FieldPlacement::Union(count) => {
B
Bernardo Meurer 已提交
360 361
                assert!(field < count as u64,
                        "Tried to access field {} of union with {} fields", field, count);
362 363 364
                // Offset is always 0
                Size::from_bytes(0)
            }
R
Ralf Jung 已提交
365 366 367
        };
        // 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 已提交
368
        let field_layout = base.layout.field(self, usize::try_from(field).unwrap_or(0))?;
R
Ralf Jung 已提交
369

370
        // Offset may need adjustment for unsized fields.
R
Ralf Jung 已提交
371
        let (meta, offset) = if field_layout.is_unsized() {
372 373 374
            // 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.
375 376 377 378 379 380 381
            let align = match self.size_and_align_of(base.meta, field_layout)? {
                Some((_, align)) => align,
                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.
382
                    field_layout.align.abi,
383 384 385
                None =>
                    bug!("Cannot compute offset for extern type field at non-0 offset"),
            };
386
            (base.meta, offset.align_to(align))
R
Ralf Jung 已提交
387
        } else {
R
Ralf Jung 已提交
388
            // base.meta could be present; we might be accessing a sized field of an unsized
389 390
            // struct.
            (None, offset)
R
Ralf Jung 已提交
391 392
        };

393 394 395
        // 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 已提交
396 397
    }

398 399 400 401
    // 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,
402
        base: MPlaceTy<'tcx, Tag>,
403
    ) -> InterpResult<'tcx, impl Iterator<Item = InterpResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'tcx>
404
    {
405
        let len = base.len(self)?; // also asserts that we have a type where this makes sense
406 407 408 409 410 411
        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;
412
        Ok((0..len).map(move |i| base.offset(i * stride, None, layout, dl)))
413 414
    }

R
Ralf Jung 已提交
415
    pub fn mplace_subslice(
O
Oliver Schneider 已提交
416
        &self,
417
        base: MPlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
418 419
        from: u64,
        to: u64,
420
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
421
        let len = base.len(self)?; // also asserts that we have a type where this makes sense
R
Ralf Jung 已提交
422 423 424 425 426 427 428 429
        assert!(from <= len - to);

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

R
Ralf Jung 已提交
432
        // Compute meta and new layout
R
Ralf Jung 已提交
433
        let inner_len = len - to - from;
R
Ralf Jung 已提交
434
        let (meta, ty) = match base.layout.ty.sty {
R
Ralf Jung 已提交
435 436
            // It is not nice to match on the type, but that seems to be the only way to
            // implement this.
V
varkor 已提交
437
            ty::Array(inner, _) =>
438 439
                (None, self.tcx.mk_array(inner, inner_len)),
            ty::Slice(..) => {
440
                let len = Scalar::from_uint(inner_len, self.pointer_size());
441 442
                (Some(len), base.layout.ty)
            }
R
Ralf Jung 已提交
443 444 445 446
            _ =>
                bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
        };
        let layout = self.layout_of(ty)?;
447
        base.offset(from_offset, meta, layout, self)
R
Ralf Jung 已提交
448 449 450 451
    }

    pub fn mplace_downcast(
        &self,
452
        base: MPlaceTy<'tcx, M::PointerTag>,
453
        variant: VariantIdx,
454
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
455
        // Downcasts only change the layout
R
Ralf Jung 已提交
456
        assert!(base.meta.is_none());
R
Ralf Jung 已提交
457
        Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
O
Oliver Schneider 已提交
458 459
    }

R
Ralf Jung 已提交
460 461
    /// Project into an mplace
    pub fn mplace_projection(
O
Oliver Schneider 已提交
462
        &self,
463
        base: MPlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
464
        proj_elem: &mir::PlaceElem<'tcx>,
465
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
466
        use rustc::mir::ProjectionElem::*;
R
Ralf Jung 已提交
467 468 469 470 471 472
        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 已提交
473
                let layout = self.layout_of(self.tcx.types.usize)?;
474 475
                let n = self.access_local(self.frame(), local, Some(layout))?;
                let n = self.read_scalar(n)?;
476
                let n = self.force_bits(n.not_undef()?, self.tcx.data_layout.pointer_size)?;
R
Ralf Jung 已提交
477 478 479 480 481 482 483 484
                self.mplace_field(base, u64::try_from(n).unwrap())?
            }

            ConstantIndex {
                offset,
                min_length,
                from_end,
            } => {
485
                let n = base.len(self)?;
R
Ralf Jung 已提交
486 487 488 489 490 491 492 493 494 495 496 497 498 499
                assert!(n >= min_length as u64);

                let index = if from_end {
                    n - u64::from(offset)
                } else {
                    u64::from(offset)
                };

                self.mplace_field(base, index)?
            }

            Subslice { from, to } =>
                self.mplace_subslice(base, u64::from(from), u64::from(to))?,
        })
O
Oliver Schneider 已提交
500 501
    }

A
Alexander Regueiro 已提交
502
    /// Gets the place of a field inside the place, and also the field's type.
R
Ralf Jung 已提交
503
    /// Just a convenience function, but used quite a bit.
504 505
    /// 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 已提交
506
    pub fn place_field(
O
Oliver Schneider 已提交
507
        &mut self,
508
        base: PlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
509
        field: u64,
510
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
511 512 513 514
        // 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 已提交
515 516
    }

R
Ralf Jung 已提交
517
    pub fn place_downcast(
518
        &self,
519
        base: PlaceTy<'tcx, M::PointerTag>,
520
        variant: VariantIdx,
521
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
522 523 524 525 526
        // Downcast just changes the layout
        Ok(match base.place {
            Place::Ptr(mplace) =>
                self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into(),
            Place::Local { .. } => {
527
                let layout = base.layout.for_variant(self, variant);
R
Ralf Jung 已提交
528
                PlaceTy { layout, ..base }
O
Oliver Schneider 已提交
529
            }
R
Ralf Jung 已提交
530
        })
O
Oliver Schneider 已提交
531 532
    }

A
Alexander Regueiro 已提交
533
    /// Projects into a place.
R
Ralf Jung 已提交
534 535
    pub fn place_projection(
        &mut self,
536
        base: PlaceTy<'tcx, M::PointerTag>,
537
        proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
538
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
539 540 541 542 543 544 545 546 547 548 549 550 551 552
        use rustc::mir::ProjectionElem::*;
        Ok(match *proj_elem {
            Field(field, _) =>  self.place_field(base, field.index() as u64)?,
            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 已提交
553
    /// Evaluate statics and promoteds to an `MPlace`. Used to share some code between
554
    /// `eval_place` and `eval_place_to_op`.
555
    pub(super) fn eval_static_to_mplace(
556
        &self,
557
        place_static: &mir::Static<'tcx>
558
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
559 560 561 562
        use rustc::mir::StaticKind;

        Ok(match place_static.kind {
            StaticKind::Promoted(promoted) => {
S
Saleem Jaffer 已提交
563 564 565 566 567 568 569
                let instance = self.frame().instance;
                self.const_eval_raw(GlobalId {
                    instance,
                    promoted: Some(promoted),
                })?
            }

570 571
            StaticKind::Static(def_id) => {
                let ty = place_static.ty;
S
Saleem Jaffer 已提交
572 573 574 575 576 577 578 579
                assert!(!ty.needs_subst());
                let layout = self.layout_of(ty)?;
                let instance = ty::Instance::mono(*self.tcx, def_id);
                let cid = GlobalId {
                    instance,
                    promoted: None
                };
                // Just create a lazy reference, so we can support recursive statics.
580
                // tcx takes care of assigning every static one and only one unique AllocId.
S
Saleem Jaffer 已提交
581 582 583 584 585
                // 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 已提交
586
                // this InterpCx uses another Machine (e.g., in miri).  This is what we
587
                // want!  This way, computing statics works consistently between codegen
S
Saleem Jaffer 已提交
588 589
                // and miri: They use the same query to eventually obtain a `ty::Const`
                // and use that for further computation.
590 591 592 593 594 595 596
                //
                // 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`.
                let alloc_id = self.tcx.alloc_map.lock().create_static_alloc(cid.instance.def_id());
                let ptr = self.tag_static_base_pointer(Pointer::from(alloc_id));
                MPlaceTy::from_aligned_ptr(ptr, layout)
O
Oliver Schneider 已提交
597
            }
598 599 600
        })
    }

A
Alexander Regueiro 已提交
601
    /// Computes a place. You should only use this if you intend to write into this
602
    /// place; for reading, a more efficient alternative is `eval_place_for_read`.
R
Ralf Jung 已提交
603 604
    pub fn eval_place(
        &mut self,
605
        mir_place: &mir::Place<'tcx>,
606
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
607
        use rustc::mir::PlaceBase;
608 609 610 611 612 613 614 615 616 617

        mir_place.iterate(|place_base, place_projection| {
            let mut place = match place_base {
                PlaceBase::Local(mir::RETURN_PLACE) => match self.frame().return_place {
                    Some(return_place) => {
                        // We use our layout to verify our assumption; caller will validate
                        // their layout on return.
                        PlaceTy {
                            place: *return_place,
                            layout: self
618
                                .layout_of(self.monomorphize(self.frame().body.return_ty())?)?,
619 620 621 622 623 624 625 626 627
                        }
                    }
                    None => return err!(InvalidNullPointerUsage),
                },
                PlaceBase::Local(local) => PlaceTy {
                    // This works even for dead/uninitialized locals; we check further when writing
                    place: Place::Local {
                        frame: self.cur_frame(),
                        local: *local,
R
Ralf Jung 已提交
628
                    },
629
                    layout: self.layout_of_local(self.frame(), *local, None)?,
630
                },
631 632
                PlaceBase::Static(place_static) => self.eval_static_to_mplace(place_static)?.into(),
            };
633

634 635
            for proj in place_projection {
                place = self.place_projection(place, &proj.elem)?
636
            }
O
Oliver Schneider 已提交
637

638 639 640
            self.dump_place(place.place);
            Ok(place)
        })
O
Oliver Schneider 已提交
641 642
    }

R
Ralf Jung 已提交
643 644
    /// Write a scalar to a place
    pub fn write_scalar(
O
Oliver Schneider 已提交
645
        &mut self,
646 647
        val: impl Into<ScalarMaybeUndef<M::PointerTag>>,
        dest: PlaceTy<'tcx, M::PointerTag>,
648
    ) -> InterpResult<'tcx> {
649
        self.write_immediate(Immediate::Scalar(val.into()), dest)
R
Ralf Jung 已提交
650
    }
O
Oliver Schneider 已提交
651

652
    /// Write an immediate to a place
653
    #[inline(always)]
654
    pub fn write_immediate(
R
Ralf Jung 已提交
655
        &mut self,
656
        src: Immediate<M::PointerTag>,
657
        dest: PlaceTy<'tcx, M::PointerTag>,
658
    ) -> InterpResult<'tcx> {
659
        self.write_immediate_no_validate(src, dest)?;
660

R
Ralf Jung 已提交
661
        if M::enforce_validity(self) {
662
            // Data got changed, better make sure it matches the type!
663
            self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
664 665
        }

666 667 668
        Ok(())
    }

W
Wesley Wiser 已提交
669 670 671 672 673 674
    /// 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 已提交
675
    ) -> InterpResult<'tcx> {
W
Wesley Wiser 已提交
676 677 678 679
        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 已提交
680
            self.validate_operand(dest.into(), vec![], None)?;
W
Wesley Wiser 已提交
681 682 683 684 685
        }

        Ok(())
    }

686
    /// Write an immediate to a place.
687 688
    /// If you use this you are responsible for validating that things got copied at the
    /// right type.
689
    fn write_immediate_no_validate(
690
        &mut self,
691
        src: Immediate<M::PointerTag>,
692
        dest: PlaceTy<'tcx, M::PointerTag>,
693
    ) -> InterpResult<'tcx> {
694 695 696
        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");
697 698
            match src {
                Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Ptr(_))) =>
699 700
                    assert_eq!(self.pointer_size(), dest.layout.size,
                        "Size mismatch when writing pointer"),
701
                Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Raw { size, .. })) =>
702 703
                    assert_eq!(Size::from_bytes(size.into()), dest.layout.size,
                        "Size mismatch when writing bits"),
704 705
                Immediate::Scalar(ScalarMaybeUndef::Undef) => {}, // undef can have any size
                Immediate::ScalarPair(_, _) => {
706 707 708 709
                    // FIXME: Can we check anything here?
                }
            }
        }
710
        trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
711

712
        // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
R
Ralf Jung 已提交
713
        // but not factored as a separate function.
R
Ralf Jung 已提交
714
        let mplace = match dest.place {
O
Oliver Schneider 已提交
715
            Place::Local { frame, local } => {
716 717 718 719
                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 已提交
720
                        return Ok(());
721 722 723 724 725
                    }
                    Err(mplace) => {
                        // The local is in memory, go on below.
                        mplace
                    }
O
Oliver Schneider 已提交
726
                }
R
Ralf Jung 已提交
727
            },
728
            Place::Ptr(mplace) => mplace, // already referring to memory
O
Oliver Schneider 已提交
729
        };
730
        let dest = MPlaceTy { mplace, layout: dest.layout };
O
Oliver Schneider 已提交
731

R
Ralf Jung 已提交
732
        // This is already in memory, write there.
733
        self.write_immediate_to_mplace_no_validate(src, dest)
O
Oliver Schneider 已提交
734 735
    }

736
    /// Write an immediate to memory.
737
    /// If you use this you are responsible for validating that things got copied at the
738
    /// right type.
739
    fn write_immediate_to_mplace_no_validate(
R
Ralf Jung 已提交
740
        &mut self,
741
        value: Immediate<M::PointerTag>,
742
        dest: MPlaceTy<'tcx, M::PointerTag>,
743
    ) -> InterpResult<'tcx> {
744
        let (ptr, ptr_align) = dest.to_scalar_ptr_align();
B
Bernardo Meurer 已提交
745 746 747 748
        // 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.
749
        assert!(!dest.layout.is_unsized());
750

751 752 753 754
        let ptr = match self.memory.check_ptr_access(ptr, dest.layout.size, ptr_align)? {
            Some(ptr) => ptr,
            None => return Ok(()), // zero-sized access
        };
755

756
        let tcx = &*self.tcx;
757 758 759
        // 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 已提交
760
        match value {
761
            Immediate::Scalar(scalar) => {
762 763
                match dest.layout.abi {
                    layout::Abi::Scalar(_) => {}, // fine
764
                    _ => bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}",
765 766
                            dest.layout)
                }
767
                self.memory.get_mut(ptr.alloc_id)?.write_scalar(
768
                    tcx, ptr, scalar, dest.layout.size
R
Ralf Jung 已提交
769
                )
O
Oliver Schneider 已提交
770
            }
771
            Immediate::ScalarPair(a_val, b_val) => {
772 773 774
                // 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 已提交
775 776
                let (a, b) = match dest.layout.abi {
                    layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
777
                    _ => bug!("write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
B
Bernardo Meurer 已提交
778
                              dest.layout)
R
Ralf Jung 已提交
779
                };
780
                let (a_size, b_size) = (a.size(self), b.size(self));
781
                let b_offset = a_size.align_to(b.align(self).abi);
782
                let b_ptr = ptr.offset(b_offset, self)?;
783

784 785 786 787
                // 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.

788 789
                self.memory
                    .get_mut(ptr.alloc_id)?
790
                    .write_scalar(tcx, ptr, a_val, a_size)?;
791 792
                self.memory
                    .get_mut(b_ptr.alloc_id)?
793
                    .write_scalar(tcx, b_ptr, b_val, b_size)
O
Oliver Schneider 已提交
794
            }
R
Ralf Jung 已提交
795
        }
O
Oliver Schneider 已提交
796 797
    }

A
Alexander Regueiro 已提交
798
    /// Copies the data from an operand to a place. This does not support transmuting!
799 800
    /// Use `copy_op_transmute` if the layouts could disagree.
    #[inline(always)]
R
Ralf Jung 已提交
801
    pub fn copy_op(
O
Oliver Schneider 已提交
802
        &mut self,
803 804
        src: OpTy<'tcx, M::PointerTag>,
        dest: PlaceTy<'tcx, M::PointerTag>,
805
    ) -> InterpResult<'tcx> {
806 807
        self.copy_op_no_validate(src, dest)?;

R
Ralf Jung 已提交
808
        if M::enforce_validity(self) {
809
            // Data got changed, better make sure it matches the type!
810
            self.validate_operand(self.place_to_op(dest)?, vec![], None)?;
811 812 813 814 815
        }

        Ok(())
    }

A
Alexander Regueiro 已提交
816
    /// Copies the data from an operand to a place. This does not support transmuting!
817
    /// Use `copy_op_transmute` if the layouts could disagree.
818
    /// Also, if you use this you are responsible for validating that things get copied at the
819 820 821 822 823
    /// right type.
    fn copy_op_no_validate(
        &mut self,
        src: OpTy<'tcx, M::PointerTag>,
        dest: PlaceTy<'tcx, M::PointerTag>,
824
    ) -> InterpResult<'tcx> {
825 826 827 828
        // 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.
        assert!(src.layout.details == dest.layout.details,
            "Layout mismatch when copying!\nsrc: {:#?}\ndest: {:#?}", src, dest);
R
Ralf Jung 已提交
829 830

        // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
831
        let src = match self.try_read_immediate(src)? {
832
            Ok(src_val) => {
833
                assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
834
                // Yay, we got a value that we can write directly.
835 836
                // FIXME: Add a check to make sure that if `src` is indirect,
                // it does not overlap with `dest`.
837
                return self.write_immediate_no_validate(*src_val, dest);
838 839
            }
            Err(mplace) => mplace,
R
Ralf Jung 已提交
840 841
        };
        // Slow path, this does not fit into an immediate. Just memcpy.
842 843
        trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);

844 845 846 847 848 849 850 851 852
        // 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(|| {
            assert!(!dest.layout.is_unsized(),
                "Cannot copy into already initialized unsized place");
            dest.layout.size
        });
        assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
R
Ralf Jung 已提交
853
        self.memory.copy(
854 855 856
            src.ptr, src.align,
            dest.ptr, dest.align,
            size,
857
            /*nonoverlapping*/ true,
858
        )?;
859 860 861 862

        Ok(())
    }

A
Alexander Regueiro 已提交
863
    /// Copies the data from an operand to a place. The layouts may disagree, but they must
864 865 866 867 868
    /// have the same size.
    pub fn copy_op_transmute(
        &mut self,
        src: OpTy<'tcx, M::PointerTag>,
        dest: PlaceTy<'tcx, M::PointerTag>,
869
    ) -> InterpResult<'tcx> {
870 871 872 873
        if src.layout.details == dest.layout.details {
            // Fast path: Just use normal `copy_op`
            return self.copy_op(src, dest);
        }
874
        // We still require the sizes to match.
875 876
        assert!(src.layout.size == dest.layout.size,
            "Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
877 878 879 880
        // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
        // to avoid that here.
        assert!(!src.layout.is_unsized() && !dest.layout.is_unsized(),
            "Cannot transmute unsized data");
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895

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

901
        Ok(())
O
Oliver Schneider 已提交
902 903
    }

A
Alexander Regueiro 已提交
904
    /// Ensures that a place is in memory, and returns where it is.
905 906
    /// If the place currently refers to a local that doesn't yet have a matching allocation,
    /// create such an allocation.
R
Ralf Jung 已提交
907
    /// This is essentially `force_to_memplace`.
908
    ///
R
Ralf Jung 已提交
909
    /// This supports unsized types and returns the computed size to avoid some
910 911 912
    /// redundant computation when copying; use `force_allocation` for a simpler, sized-only
    /// version.
    pub fn force_allocation_maybe_sized(
O
Oliver Schneider 已提交
913
        &mut self,
914
        place: PlaceTy<'tcx, M::PointerTag>,
915
        meta: Option<Scalar<M::PointerTag>>,
916
    ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
917
        let (mplace, size) = match place.place {
R
Ralf Jung 已提交
918
            Place::Local { frame, local } => {
919 920
                match self.stack[frame].locals[local].access_mut()? {
                    Ok(local_val) => {
921 922 923 924
                        // We need to make an allocation.
                        // FIXME: Consider not doing anything for a ZST, and just returning
                        // a fake pointer?  Are we even called for ZST?

925 926 927 928 929 930 931 932 933
                        // We cannot hold on to the reference `local_val` while allocating,
                        // but we can hold on to the value in there.
                        let old_val =
                            if let LocalValue::Live(Operand::Immediate(value)) = *local_val {
                                Some(value)
                            } else {
                                None
                            };

934
                        // We need the layout of the local.  We can NOT use the layout we got,
935
                        // that might e.g., be an inner field of a struct with `Scalar` layout,
R
Ralf Jung 已提交
936
                        // that has different alignment than the outer field.
937
                        // We also need to support unsized types, and hence cannot use `allocate`.
938
                        let local_layout = self.layout_of_local(&self.stack[frame], local, None)?;
939 940 941 942
                        let (size, align) = self.size_and_align_of(meta, local_layout)?
                            .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 };
943 944 945 946
                        if let Some(value) = old_val {
                            // Preserve old value.
                            // We don't have to validate as we can assume the local
                            // was already valid for its type.
947 948
                            let mplace = MPlaceTy { mplace, layout: local_layout };
                            self.write_immediate_to_mplace_no_validate(value, mplace)?;
949 950 951 952 953
                        }
                        // 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));
954
                        (mplace, Some(size))
955
                    }
956
                    Err(mplace) => (mplace, None), // this already was an indirect local
957
                }
R
Ralf Jung 已提交
958
            }
959
            Place::Ptr(mplace) => (mplace, None)
R
Ralf Jung 已提交
960 961
        };
        // Return with the original layout, so that the caller can go on
962 963 964 965 966 967 968
        Ok((MPlaceTy { mplace, layout: place.layout }, size))
    }

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

R
Ralf Jung 已提交
973
    pub fn allocate(
O
Oliver Schneider 已提交
974
        &mut self,
R
Ralf Jung 已提交
975 976
        layout: TyLayout<'tcx>,
        kind: MemoryKind<M::MemoryKinds>,
R
Ralf Jung 已提交
977
    ) -> MPlaceTy<'tcx, M::PointerTag> {
978 979
        let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
        MPlaceTy::from_aligned_ptr(ptr, layout)
R
Ralf Jung 已提交
980
    }
O
Oliver Schneider 已提交
981

982
    pub fn write_discriminant_index(
R
Ralf Jung 已提交
983
        &mut self,
984
        variant_index: VariantIdx,
985
        dest: PlaceTy<'tcx, M::PointerTag>,
986
    ) -> InterpResult<'tcx> {
R
Ralf Jung 已提交
987 988
        match dest.layout.variants {
            layout::Variants::Single { index } => {
R
Ralf Jung 已提交
989
                assert_eq!(index, variant_index);
O
Oliver Schneider 已提交
990
            }
991 992 993
            layout::Variants::Multiple {
                discr_kind: layout::DiscriminantKind::Tag,
                ref discr,
994
                discr_index,
995 996
                ..
            } => {
997 998 999
                assert!(dest.layout.ty.variant_range(*self.tcx).unwrap().contains(&variant_index));
                let discr_val =
                    dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
R
Ralf Jung 已提交
1000 1001 1002 1003

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

1007
                let discr_dest = self.place_field(dest, discr_index as u64)?;
1008
                self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
O
Oliver Schneider 已提交
1009
            }
1010 1011 1012 1013 1014 1015
            layout::Variants::Multiple {
                discr_kind: layout::DiscriminantKind::Niche {
                    dataful_variant,
                    ref niche_variants,
                    niche_start,
                },
1016
                discr_index,
R
Ralf Jung 已提交
1017
                ..
O
Oliver Schneider 已提交
1018
            } => {
1019 1020 1021
                assert!(
                    variant_index.as_usize() < dest.layout.ty.ty_adt_def().unwrap().variants.len(),
                );
R
Ralf Jung 已提交
1022 1023
                if variant_index != dataful_variant {
                    let niche_dest =
1024
                        self.place_field(dest, discr_index as u64)?;
1025 1026
                    let niche_value = variant_index.as_u32() - niche_variants.start().as_u32();
                    let niche_value = (niche_value as u128)
R
Ralf Jung 已提交
1027
                        .wrapping_add(niche_start);
1028 1029 1030 1031
                    self.write_scalar(
                        Scalar::from_uint(niche_value, niche_dest.layout.size),
                        niche_dest
                    )?;
R
Ralf Jung 已提交
1032
                }
O
Oliver Schneider 已提交
1033
            }
1034
        }
R
Ralf Jung 已提交
1035 1036

        Ok(())
O
Oliver Schneider 已提交
1037 1038
    }

1039 1040 1041
    pub fn raw_const_to_mplace(
        &self,
        raw: RawConst<'tcx>,
1042
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1043 1044
        // This must be an allocation in `tcx`
        assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1045
        let ptr = self.tag_static_base_pointer(Pointer::from(raw.alloc_id));
1046
        let layout = self.layout_of(raw.ty)?;
1047
        Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
1048 1049
    }

1050 1051
    /// 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.
1052
    pub(super) fn unpack_dyn_trait(&self, mplace: MPlaceTy<'tcx, M::PointerTag>)
1053
    -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1054
        let vtable = mplace.vtable(); // also sanity checks the type
1055 1056 1057 1058
        let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
        let layout = self.layout_of(ty)?;

        // More sanity checks
1059 1060 1061
        if cfg!(debug_assertions) {
            let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
            assert_eq!(size, layout.size);
1062
            // only ABI alignment is preserved
1063
            assert_eq!(align, layout.align.abi);
1064
        }
1065 1066

        let mplace = MPlaceTy {
R
Ralf Jung 已提交
1067
            mplace: MemPlace { meta: None, ..*mplace },
1068
            layout
1069 1070
        };
        Ok((instance, mplace))
1071
    }
O
Oliver Schneider 已提交
1072
}