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

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

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

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

R
Ralf Jung 已提交
39 40 41 42 43 44
    /// 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 已提交
45 46
}

R
Ralf Jung 已提交
47
#[derive(Copy, Clone, Debug)]
48 49
pub struct PlaceTy<'tcx, Tag=()> {
    place: Place<Tag>,
R
Ralf Jung 已提交
50 51 52
    pub layout: TyLayout<'tcx>,
}

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

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

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

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

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

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

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

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

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

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

R
Ralf Jung 已提交
132
    /// metact the ptr part of the mplace
R
Ralf Jung 已提交
133
    #[inline(always)]
134
    pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
B
Bernardo Meurer 已提交
135 136 137
        // 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 已提交
138 139
        self.to_scalar_ptr_align().0.to_ptr()
    }
140 141 142 143 144 145 146 147 148 149

    /// 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()),
        }
    }
150 151 152 153 154 155 156 157 158 159 160 161 162

    pub fn offset(
        self,
        offset: Size,
        meta: Option<Scalar<Tag>>,
        cx: &impl HasDataLayout,
    ) -> EvalResult<'tcx, Self> {
        Ok(MemPlace {
            ptr: self.ptr.ptr_offset(offset, cx)?,
            align: self.align.restrict_for_offset(offset),
            meta,
        })
    }
R
Ralf Jung 已提交
163 164
}

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

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

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

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

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

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

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

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

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

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

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

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

        }
    }

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

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

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

293
// separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
K
kenta7777 已提交
294
impl<'a, 'mir, 'tcx, Tag, M> InterpretCx<'a, 'mir, 'tcx, M>
295
where
R
Ralf Jung 已提交
296
    // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
297 298
    Tag: ::std::fmt::Debug+Default+Copy+Eq+Hash+'static,
    M: Machine<'a, 'mir, 'tcx, PointerTag=Tag>,
R
Ralf Jung 已提交
299
    // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
300
    M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation<Tag, M::AllocExtra>)>,
301
    M::AllocExtra: AllocationExtra<Tag>,
302
{
R
Ralf Jung 已提交
303
    /// Take a value, which represents a (thin or fat) reference, and make it a place.
304
    /// Alignment is just based on the type.  This is the inverse of `MemPlace::to_ref()`.
305 306
    /// 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 已提交
307
    pub fn ref_to_mplace(
308
        &self,
309
        val: ImmTy<'tcx, M::PointerTag>,
310
    ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
311 312 313
        let pointee_type = val.layout.ty.builtin_deref(true).unwrap().ty;
        let layout = self.layout_of(pointee_type)?;

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

326 327 328 329 330 331 332 333 334 335 336
    // 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.
    // This calls the "deref" machine hook, and counts as a deref as far as
    // Stacked Borrows is concerned.
    pub fn deref_operand(
        &self,
        src: OpTy<'tcx, M::PointerTag>,
    ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
        let val = self.read_immediate(src)?;
        trace!("deref to {} on {:?}", val.layout.ty, *val);
        let mut place = self.ref_to_mplace(val)?;
337
        // Pointer tag tracking might want to adjust the tag.
338 339 340 341 342
        let mutbl = match val.layout.ty.sty {
            // `builtin_deref` considers boxes immutable, that's useless for our purposes
            ty::Ref(_, _, mutbl) => Some(mutbl),
            ty::Adt(def, _) if def.is_box() => Some(hir::MutMutable),
            ty::RawPtr(_) => None,
343
            _ => bug!("Unexpected pointer type {}", val.layout.ty),
344
        };
345 346
        place.mplace.ptr = M::tag_dereference(self, place, mutbl)?;
        Ok(place)
347 348
    }

R
Ralf Jung 已提交
349 350 351 352 353
    /// 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.
    /// 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
    ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
358 359 360 361 362
        // 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, .. } => {
363 364 365
                let len = base.len(self)?;
                assert!(field < len, "Tried to access element {} of array/slice with length {}",
                    field, len);
R
Ralf Jung 已提交
366 367
                stride * field
            }
368
            layout::FieldPlacement::Union(count) => {
B
Bernardo Meurer 已提交
369 370
                assert!(field < count as u64,
                        "Tried to access field {} of union with {} fields", field, count);
371 372 373
                // Offset is always 0
                Size::from_bytes(0)
            }
R
Ralf Jung 已提交
374 375 376
        };
        // 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 已提交
377
        let field_layout = base.layout.field(self, usize::try_from(field).unwrap_or(0))?;
R
Ralf Jung 已提交
378

379
        // Offset may need adjustment for unsized fields.
R
Ralf Jung 已提交
380
        let (meta, offset) = if field_layout.is_unsized() {
381 382 383
            // 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.
384 385 386 387 388 389 390
            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.
391
                    field_layout.align.abi,
392 393 394
                None =>
                    bug!("Cannot compute offset for extern type field at non-0 offset"),
            };
395
            (base.meta, offset.align_to(align))
R
Ralf Jung 已提交
396
        } else {
R
Ralf Jung 已提交
397
            // base.meta could be present; we might be accessing a sized field of an unsized
398 399
            // struct.
            (None, offset)
R
Ralf Jung 已提交
400 401
        };

402 403 404
        // 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 已提交
405 406
    }

407 408 409 410
    // 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,
411 412 413 414
        base: MPlaceTy<'tcx, Tag>,
    ) ->
        EvalResult<'tcx, impl Iterator<Item=EvalResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'a>
    {
415
        let len = base.len(self)?; // also asserts that we have a type where this makes sense
416 417 418 419 420 421
        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;
422
        Ok((0..len).map(move |i| base.offset(i * stride, None, layout, dl)))
423 424
    }

R
Ralf Jung 已提交
425
    pub fn mplace_subslice(
O
Oliver Schneider 已提交
426
        &self,
427
        base: MPlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
428 429
        from: u64,
        to: u64,
430
    ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
431
        let len = base.len(self)?; // also asserts that we have a type where this makes sense
R
Ralf Jung 已提交
432 433 434 435 436 437 438 439
        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 已提交
440
        };
R
Ralf Jung 已提交
441

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

    pub fn mplace_downcast(
        &self,
462
        base: MPlaceTy<'tcx, M::PointerTag>,
463
        variant: VariantIdx,
464
    ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
465
        // Downcasts only change the layout
R
Ralf Jung 已提交
466
        assert!(base.meta.is_none());
R
Ralf Jung 已提交
467
        Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
O
Oliver Schneider 已提交
468 469
    }

R
Ralf Jung 已提交
470 471
    /// Project into an mplace
    pub fn mplace_projection(
O
Oliver Schneider 已提交
472
        &self,
473
        base: MPlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
474
        proj_elem: &mir::PlaceElem<'tcx>,
475
    ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
476
        use rustc::mir::ProjectionElem::*;
R
Ralf Jung 已提交
477 478 479 480 481 482
        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 已提交
483
                let layout = self.layout_of(self.tcx.types.usize)?;
484 485
                let n = self.access_local(self.frame(), local, Some(layout))?;
                let n = self.read_scalar(n)?;
R
Ralf Jung 已提交
486 487 488 489 490 491 492 493 494
                let n = n.to_bits(self.tcx.data_layout.pointer_size)?;
                self.mplace_field(base, u64::try_from(n).unwrap())?
            }

            ConstantIndex {
                offset,
                min_length,
                from_end,
            } => {
495
                let n = base.len(self)?;
R
Ralf Jung 已提交
496 497 498 499 500 501 502 503 504 505 506 507 508 509
                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 已提交
510 511
    }

A
Alexander Regueiro 已提交
512
    /// Gets the place of a field inside the place, and also the field's type.
R
Ralf Jung 已提交
513
    /// Just a convenience function, but used quite a bit.
514 515
    /// 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 已提交
516
    pub fn place_field(
O
Oliver Schneider 已提交
517
        &mut self,
518
        base: PlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
519
        field: u64,
520
    ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
521 522 523 524
        // 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 已提交
525 526
    }

R
Ralf Jung 已提交
527
    pub fn place_downcast(
528
        &self,
529
        base: PlaceTy<'tcx, M::PointerTag>,
530
        variant: VariantIdx,
531
    ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
532 533 534 535 536
        // Downcast just changes the layout
        Ok(match base.place {
            Place::Ptr(mplace) =>
                self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into(),
            Place::Local { .. } => {
537
                let layout = base.layout.for_variant(self, variant);
R
Ralf Jung 已提交
538
                PlaceTy { layout, ..base }
O
Oliver Schneider 已提交
539
            }
R
Ralf Jung 已提交
540
        })
O
Oliver Schneider 已提交
541 542
    }

A
Alexander Regueiro 已提交
543
    /// Projects into a place.
R
Ralf Jung 已提交
544 545
    pub fn place_projection(
        &mut self,
546
        base: PlaceTy<'tcx, M::PointerTag>,
547
        proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
548
    ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
549 550 551 552 553 554 555 556 557 558 559 560 561 562
        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 已提交
563
    /// Evaluate statics and promoteds to an `MPlace`. Used to share some code between
564
    /// `eval_place` and `eval_place_to_op`.
565
    pub(super) fn eval_static_to_mplace(
566
        &self,
567
        place_static: &mir::Static<'tcx>
568
    ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
569 570 571 572
        use rustc::mir::StaticKind;

        Ok(match place_static.kind {
            StaticKind::Promoted(promoted) => {
S
Saleem Jaffer 已提交
573 574 575 576 577 578 579
                let instance = self.frame().instance;
                self.const_eval_raw(GlobalId {
                    instance,
                    promoted: Some(promoted),
                })?
            }

580 581
            StaticKind::Static(def_id) => {
                let ty = place_static.ty;
S
Saleem Jaffer 已提交
582 583 584 585 586 587 588 589 590 591 592 593 594 595
                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.
                // tcx takes are of assigning every static one and only one unique AllocId.
                // 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
K
kenta7777 已提交
596
                // this InterpretCx uses another Machine (e.g., in miri).  This is what we
S
Saleem Jaffer 已提交
597 598 599 600 601
                // want!  This way, computing statics works concistently between codegen
                // and miri: They use the same query to eventually obtain a `ty::Const`
                // and use that for further computation.
                let alloc = self.tcx.alloc_map.lock().intern_static(cid.instance.def_id());
                MPlaceTy::from_aligned_ptr(Pointer::from(alloc).with_default_tag(), layout)
O
Oliver Schneider 已提交
602
            }
603 604 605
        })
    }

A
Alexander Regueiro 已提交
606
    /// Computes a place. You should only use this if you intend to write into this
607
    /// place; for reading, a more efficient alternative is `eval_place_for_read`.
R
Ralf Jung 已提交
608 609
    pub fn eval_place(
        &mut self,
610
        mir_place: &mir::Place<'tcx>,
R
Ralf Jung 已提交
611
    ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
612
        use rustc::mir::PlaceBase;
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632

        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
                                .layout_of(self.monomorphize(self.frame().mir.return_ty())?)?,
                        }
                    }
                    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 已提交
633
                    },
634
                    layout: self.layout_of_local(self.frame(), *local, None)?,
635
                },
636 637
                PlaceBase::Static(place_static) => self.eval_static_to_mplace(place_static)?.into(),
            };
638

639 640
            for proj in place_projection {
                place = self.place_projection(place, &proj.elem)?
641
            }
O
Oliver Schneider 已提交
642

643 644 645
            self.dump_place(place.place);
            Ok(place)
        })
O
Oliver Schneider 已提交
646 647
    }

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

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

R
Ralf Jung 已提交
666
        if M::enforce_validity(self) {
667
            // Data got changed, better make sure it matches the type!
668
            self.validate_operand(self.place_to_op(dest)?, vec![], None, /*const_mode*/false)?;
669 670
        }

671 672 673
        Ok(())
    }

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

700
        // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
R
Ralf Jung 已提交
701
        // but not factored as a separate function.
R
Ralf Jung 已提交
702
        let mplace = match dest.place {
O
Oliver Schneider 已提交
703
            Place::Local { frame, local } => {
704 705 706 707
                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 已提交
708
                        return Ok(());
709 710 711 712 713
                    }
                    Err(mplace) => {
                        // The local is in memory, go on below.
                        mplace
                    }
O
Oliver Schneider 已提交
714
                }
R
Ralf Jung 已提交
715
            },
716
            Place::Ptr(mplace) => mplace, // already referring to memory
O
Oliver Schneider 已提交
717
        };
718
        let dest = MPlaceTy { mplace, layout: dest.layout };
O
Oliver Schneider 已提交
719

R
Ralf Jung 已提交
720
        // This is already in memory, write there.
721
        self.write_immediate_to_mplace_no_validate(src, dest)
O
Oliver Schneider 已提交
722 723
    }

724
    /// Write an immediate to memory.
725 726
    /// If you use this you are responsible for validating that things git copied at the
    /// right type.
727
    fn write_immediate_to_mplace_no_validate(
R
Ralf Jung 已提交
728
        &mut self,
729
        value: Immediate<M::PointerTag>,
730
        dest: MPlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
731
    ) -> EvalResult<'tcx> {
732
        let (ptr, ptr_align) = dest.to_scalar_ptr_align();
B
Bernardo Meurer 已提交
733 734 735 736
        // 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.
737 738

        // Nothing to do for ZSTs, other than checking alignment
739
        if dest.layout.is_zst() {
740
            return self.memory.check_align(ptr, ptr_align);
741 742
        }

743
        // check for integer pointers before alignment to report better errors
744
        let ptr = ptr.to_ptr()?;
745
        self.memory.check_align(ptr.into(), ptr_align)?;
746
        let tcx = &*self.tcx;
747 748 749
        // 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 已提交
750
        match value {
751
            Immediate::Scalar(scalar) => {
752 753
                match dest.layout.abi {
                    layout::Abi::Scalar(_) => {}, // fine
754
                    _ => bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}",
755 756
                            dest.layout)
                }
757
                self.memory.get_mut(ptr.alloc_id)?.write_scalar(
758
                    tcx, ptr, scalar, dest.layout.size
R
Ralf Jung 已提交
759
                )
O
Oliver Schneider 已提交
760
            }
761
            Immediate::ScalarPair(a_val, b_val) => {
R
Ralf Jung 已提交
762 763
                let (a, b) = match dest.layout.abi {
                    layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
764
                    _ => bug!("write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
B
Bernardo Meurer 已提交
765
                              dest.layout)
R
Ralf Jung 已提交
766
                };
767
                let (a_size, b_size) = (a.size(self), b.size(self));
768 769
                let b_offset = a_size.align_to(b.align(self).abi);
                let b_align = ptr_align.restrict_for_offset(b_offset);
770
                let b_ptr = ptr.offset(b_offset, self)?;
771

772
                self.memory.check_align(b_ptr.into(), b_align)?;
773

774 775 776 777
                // 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.

778 779
                self.memory
                    .get_mut(ptr.alloc_id)?
780
                    .write_scalar(tcx, ptr, a_val, a_size)?;
781 782
                self.memory
                    .get_mut(b_ptr.alloc_id)?
783
                    .write_scalar(tcx, b_ptr, b_val, b_size)
O
Oliver Schneider 已提交
784
            }
R
Ralf Jung 已提交
785
        }
O
Oliver Schneider 已提交
786 787
    }

A
Alexander Regueiro 已提交
788
    /// Copies the data from an operand to a place. This does not support transmuting!
789 790
    /// Use `copy_op_transmute` if the layouts could disagree.
    #[inline(always)]
R
Ralf Jung 已提交
791
    pub fn copy_op(
O
Oliver Schneider 已提交
792
        &mut self,
793 794
        src: OpTy<'tcx, M::PointerTag>,
        dest: PlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
795
    ) -> EvalResult<'tcx> {
796 797
        self.copy_op_no_validate(src, dest)?;

R
Ralf Jung 已提交
798
        if M::enforce_validity(self) {
799
            // Data got changed, better make sure it matches the type!
800
            self.validate_operand(self.place_to_op(dest)?, vec![], None, /*const_mode*/false)?;
801 802 803 804 805
        }

        Ok(())
    }

A
Alexander Regueiro 已提交
806
    /// Copies the data from an operand to a place. This does not support transmuting!
807 808 809 810 811 812 813 814 815 816 817 818
    /// Use `copy_op_transmute` if the layouts could disagree.
    /// Also, if you use this you are responsible for validating that things git copied at the
    /// right type.
    fn copy_op_no_validate(
        &mut self,
        src: OpTy<'tcx, M::PointerTag>,
        dest: PlaceTy<'tcx, M::PointerTag>,
    ) -> EvalResult<'tcx> {
        // 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 已提交
819 820

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

834 835 836 837 838 839 840 841 842
        // 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 已提交
843
        self.memory.copy(
844 845 846
            src.ptr, src.align,
            dest.ptr, dest.align,
            size,
847
            /*nonoverlapping*/ true,
848
        )?;
849 850 851 852

        Ok(())
    }

A
Alexander Regueiro 已提交
853
    /// Copies the data from an operand to a place. The layouts may disagree, but they must
854 855 856 857 858 859 860 861 862 863
    /// have the same size.
    pub fn copy_op_transmute(
        &mut self,
        src: OpTy<'tcx, M::PointerTag>,
        dest: PlaceTy<'tcx, M::PointerTag>,
    ) -> EvalResult<'tcx> {
        if src.layout.details == dest.layout.details {
            // Fast path: Just use normal `copy_op`
            return self.copy_op(src, dest);
        }
864
        // We still require the sizes to match.
865 866
        assert!(src.layout.size == dest.layout.size,
            "Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
867 868 869 870
        // 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");
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885

        // 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 已提交
886
        if M::enforce_validity(self) {
887
            // Data got changed, better make sure it matches the type!
888
            self.validate_operand(dest.into(), vec![], None, /*const_mode*/false)?;
889
        }
890

891
        Ok(())
O
Oliver Schneider 已提交
892 893
    }

A
Alexander Regueiro 已提交
894
    /// Ensures that a place is in memory, and returns where it is.
895 896
    /// If the place currently refers to a local that doesn't yet have a matching allocation,
    /// create such an allocation.
R
Ralf Jung 已提交
897
    /// This is essentially `force_to_memplace`.
898
    ///
R
Ralf Jung 已提交
899
    /// This supports unsized types and returns the computed size to avoid some
900 901 902
    /// redundant computation when copying; use `force_allocation` for a simpler, sized-only
    /// version.
    pub fn force_allocation_maybe_sized(
O
Oliver Schneider 已提交
903
        &mut self,
904
        place: PlaceTy<'tcx, M::PointerTag>,
905 906 907
        meta: Option<Scalar<M::PointerTag>>,
    ) -> EvalResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
        let (mplace, size) = match place.place {
R
Ralf Jung 已提交
908
            Place::Local { frame, local } => {
909 910
                match self.stack[frame].locals[local].access_mut()? {
                    Ok(local_val) => {
911 912 913 914
                        // 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?

915 916 917 918 919 920 921 922 923
                        // 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
                            };

924
                        // We need the layout of the local.  We can NOT use the layout we got,
925
                        // that might e.g., be an inner field of a struct with `Scalar` layout,
R
Ralf Jung 已提交
926
                        // that has different alignment than the outer field.
927
                        // We also need to support unsized types, and hence cannot use `allocate`.
928
                        let local_layout = self.layout_of_local(&self.stack[frame], local, None)?;
929 930 931 932
                        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 };
933 934 935 936
                        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.
937 938
                            let mplace = MPlaceTy { mplace, layout: local_layout };
                            self.write_immediate_to_mplace_no_validate(value, mplace)?;
939 940 941 942 943
                        }
                        // 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));
944
                        (mplace, Some(size))
945
                    }
946
                    Err(mplace) => (mplace, None), // this already was an indirect local
947
                }
R
Ralf Jung 已提交
948
            }
949
            Place::Ptr(mplace) => (mplace, None)
R
Ralf Jung 已提交
950 951
        };
        // Return with the original layout, so that the caller can go on
952 953 954 955 956 957 958 959 960
        Ok((MPlaceTy { mplace, layout: place.layout }, size))
    }

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

R
Ralf Jung 已提交
963
    pub fn allocate(
O
Oliver Schneider 已提交
964
        &mut self,
R
Ralf Jung 已提交
965 966
        layout: TyLayout<'tcx>,
        kind: MemoryKind<M::MemoryKinds>,
R
Ralf Jung 已提交
967
    ) -> MPlaceTy<'tcx, M::PointerTag> {
968 969
        let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
        MPlaceTy::from_aligned_ptr(ptr, layout)
R
Ralf Jung 已提交
970
    }
O
Oliver Schneider 已提交
971

972
    pub fn write_discriminant_index(
R
Ralf Jung 已提交
973
        &mut self,
974
        variant_index: VariantIdx,
975
        dest: PlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
976 977 978
    ) -> EvalResult<'tcx> {
        match dest.layout.variants {
            layout::Variants::Single { index } => {
R
Ralf Jung 已提交
979
                assert_eq!(index, variant_index);
O
Oliver Schneider 已提交
980
            }
981 982 983
            layout::Variants::Multiple {
                discr_kind: layout::DiscriminantKind::Tag,
                ref discr,
984
                discr_index,
985 986
                ..
            } => {
987 988 989
                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 已提交
990 991 992 993

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

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

        Ok(())
O
Oliver Schneider 已提交
1027 1028
    }

1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
    pub fn raw_const_to_mplace(
        &self,
        raw: RawConst<'tcx>,
    ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
        // This must be an allocation in `tcx`
        assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
        let layout = self.layout_of(raw.ty)?;
        Ok(MPlaceTy::from_aligned_ptr(
            Pointer::new(raw.alloc_id, Size::ZERO).with_default_tag(),
            layout,
        ))
    }

1042 1043
    /// 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.
1044 1045
    pub(super) fn unpack_dyn_trait(&self, mplace: MPlaceTy<'tcx, M::PointerTag>)
    -> EvalResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1046 1047 1048 1049 1050
        let vtable = mplace.vtable()?; // also sanity checks the type
        let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
        let layout = self.layout_of(ty)?;

        // More sanity checks
1051 1052 1053
        if cfg!(debug_assertions) {
            let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
            assert_eq!(size, layout.size);
1054
            // only ABI alignment is preserved
1055
            assert_eq!(align, layout.align.abi);
1056
        }
1057 1058

        let mplace = MPlaceTy {
R
Ralf Jung 已提交
1059
            mplace: MemPlace { meta: None, ..*mplace },
1060
            layout
1061 1062
        };
        Ok((instance, mplace))
1063
    }
O
Oliver Schneider 已提交
1064
}