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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

R
Ralf Jung 已提交
136
    #[inline(always)]
137
    pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
R
Ralf Jung 已提交
138 139 140
        Self::from_scalar_ptr(ptr.into(), align)
    }

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

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

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

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

    #[inline]
186 187 188
    pub fn offset(
        self,
        offset: Size,
189
        meta: MemPlaceMeta<Tag>,
190
        layout: TyAndLayout<'tcx>,
191
        cx: &impl HasDataLayout,
192
    ) -> InterpResult<'tcx, Self> {
M
Mark Rousskov 已提交
193
        Ok(MPlaceTy { mplace: self.mplace.offset(offset, meta, cx)?, layout })
194 195
    }

R
Ralf Jung 已提交
196
    #[inline]
197
    fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyAndLayout<'tcx>) -> Self {
198
        MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
R
Ralf Jung 已提交
199 200 201
    }

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

    #[inline]
220
    pub(super) fn vtable(self) -> Scalar<Tag> {
V
varkor 已提交
221
        match self.layout.ty.kind {
O
Oliver Scherer 已提交
222
            ty::Dynamic(..) => self.mplace.meta.unwrap_meta(),
223
            _ => bug!("vtable not supported on type {:?}", self.layout.ty),
R
Ralf Jung 已提交
224 225 226 227
        }
    }
}

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

246
    #[inline(always)]
247 248
    /// Note: do not call `as_ref` on the resulting place. This function should only be used to
    /// read from the resulting mplace, not to get its address back.
249 250
    pub fn assert_mem_place(self, cx: &impl HasDataLayout) -> MPlaceTy<'tcx, Tag> {
        self.try_as_mplace(cx).unwrap()
R
Ralf Jung 已提交
251 252 253
    }
}

R
Ralf Jung 已提交
254
impl<Tag: ::std::fmt::Debug> Place<Tag> {
R
Ralf Jung 已提交
255
    #[inline]
256
    pub fn assert_mem_place(self) -> MemPlace<Tag> {
O
Oliver Schneider 已提交
257
        match self {
R
Ralf Jung 已提交
258
            Place::Ptr(mplace) => mplace,
259
            _ => bug!("assert_mem_place: expected Place::Ptr, got {:?}", self),
O
Oliver Schneider 已提交
260 261
        }
    }
R
Ralf Jung 已提交
262
}
O
Oliver Schneider 已提交
263

264
impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
R
Ralf Jung 已提交
265
    #[inline]
266 267
    pub fn assert_mem_place(self) -> MPlaceTy<'tcx, Tag> {
        MPlaceTy { mplace: self.place.assert_mem_place(), layout: self.layout }
O
Oliver Schneider 已提交
268 269 270
    }
}

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

301
        let mplace = MemPlace {
302
            ptr,
303 304 305 306
            // 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.
307
            align: layout.align.abi,
308
            meta,
309 310
        };
        Ok(MPlaceTy { mplace, layout })
R
Ralf Jung 已提交
311 312
    }

313 314
    /// 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.
315 316 317
    pub fn deref_operand(
        &self,
        src: OpTy<'tcx, M::PointerTag>,
318
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
319 320
        let val = self.read_immediate(src)?;
        trace!("deref to {} on {:?}", val.layout.ty, *val);
321
        let place = self.ref_to_mplace(val)?;
322
        self.mplace_access_checked(place, None)
323 324
    }

325 326 327 328 329 330 331
    /// Check if the given place is good for memory access with the given
    /// size, falling back to the layout's size if `None` (in the latter case,
    /// this must be a statically sized type).
    ///
    /// On success, returns `None` for zero-sized accesses (where nothing else is
    /// left to do) and a `Pointer` to use for the actual access otherwise.
    #[inline]
332
    pub(super) fn check_mplace_access(
333 334 335 336 337 338
        &self,
        place: MPlaceTy<'tcx, M::PointerTag>,
        size: Option<Size>,
    ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
        let size = size.unwrap_or_else(|| {
            assert!(!place.layout.is_unsized());
O
Oliver Scherer 已提交
339
            assert!(!place.meta.has_meta());
340 341 342 343 344
            place.layout.size
        });
        self.memory.check_ptr_access(place.ptr, size, place.align)
    }

345 346
    /// Return the "access-checked" version of this `MPlace`, where for non-ZST
    /// this is definitely a `Pointer`.
R
Ralf Jung 已提交
347 348 349
    ///
    /// `force_align` must only be used when correct alignment does not matter,
    /// like in Stacked Borrows.
350 351 352
    pub fn mplace_access_checked(
        &self,
        mut place: MPlaceTy<'tcx, M::PointerTag>,
353
        force_align: Option<Align>,
354
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
M
Mark Rousskov 已提交
355 356
        let (size, align) = self
            .size_and_align_of_mplace(place)?
357 358
            .unwrap_or((place.layout.size, place.layout.align.abi));
        assert!(place.mplace.align <= align, "dynamic alignment less strict than static one?");
359 360
        // Check (stricter) dynamic alignment, unless forced otherwise.
        place.mplace.align = force_align.unwrap_or(align);
361 362 363 364 365 366 367
        // When dereferencing a pointer, it must be non-NULL, aligned, and live.
        if let Some(ptr) = self.check_mplace_access(place, Some(size))? {
            place.mplace.ptr = ptr.into();
        }
        Ok(place)
    }

R
Ralf Jung 已提交
368
    /// Force `place.ptr` to a `Pointer`.
369
    /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
370
    pub(super) fn force_mplace_ptr(
371 372 373
        &self,
        mut place: MPlaceTy<'tcx, M::PointerTag>,
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
374
        place.mplace.ptr = self.force_ptr(place.mplace.ptr)?.into();
375 376 377
        Ok(place)
    }

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

393
        // Offset may need adjustment for unsized fields.
R
Ralf Jung 已提交
394
        let (meta, offset) = if field_layout.is_unsized() {
395 396 397
            // 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.
398 399
            let align = match self.size_and_align_of(base.meta, field_layout)? {
                Some((_, align)) => align,
R
Ralf Jung 已提交
400 401 402 403 404
                None if offset == Size::ZERO => {
                    // An extern type at offset 0, we fall back to its static alignment.
                    // FIXME: Once we have made decisions for how to handle size and alignment
                    // of `extern type`, this should be adapted.  It is just a temporary hack
                    // to get some code to work that probably ought to work.
M
Mark Rousskov 已提交
405 406 407
                    field_layout.align.abi
                }
                None => bug!("Cannot compute offset for extern type field at non-0 offset"),
408
            };
409
            (base.meta, offset.align_to(align))
R
Ralf Jung 已提交
410
        } else {
R
Ralf Jung 已提交
411
            // base.meta could be present; we might be accessing a sized field of an unsized
412
            // struct.
413
            (MemPlaceMeta::None, offset)
R
Ralf Jung 已提交
414 415
        };

416 417 418
        // 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 已提交
419 420
    }

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

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

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

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

        // 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 {
486
            FieldsShape::Array { stride, .. } => stride * from, // `Size` multiplication is checked
R
Ralf Jung 已提交
487
            _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
O
Oliver Schneider 已提交
488
        };
R
Ralf Jung 已提交
489

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

506
    pub(super) fn mplace_downcast(
R
Ralf Jung 已提交
507
        &self,
508
        base: MPlaceTy<'tcx, M::PointerTag>,
509
        variant: VariantIdx,
510
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
511
        // Downcasts only change the layout
O
Oliver Scherer 已提交
512
        assert!(!base.meta.has_meta());
R
Ralf Jung 已提交
513
        Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
O
Oliver Schneider 已提交
514 515
    }

R
Ralf Jung 已提交
516
    /// Project into an mplace
517
    pub(super) fn mplace_projection(
O
Oliver Schneider 已提交
518
        &self,
519
        base: MPlaceTy<'tcx, M::PointerTag>,
R
Ralf Jung 已提交
520
        proj_elem: &mir::PlaceElem<'tcx>,
521
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
M
Mazdak Farrokhzad 已提交
522
        use rustc_middle::mir::ProjectionElem::*;
R
Ralf Jung 已提交
523
        Ok(match *proj_elem {
524
            Field(field, _) => self.mplace_field(base, field.index())?,
R
Ralf Jung 已提交
525 526 527 528
            Downcast(_, variant) => self.mplace_downcast(base, variant)?,
            Deref => self.deref_operand(base.into())?,

            Index(local) => {
R
Ralf Jung 已提交
529
                let layout = self.layout_of(self.tcx.types.usize)?;
530 531
                let n = self.access_local(self.frame(), local, Some(layout))?;
                let n = self.read_scalar(n)?;
532 533 534 535 536
                let n = u64::try_from(
                    self.force_bits(n.not_undef()?, self.tcx.data_layout.pointer_size)?,
                )
                .unwrap();
                self.mplace_index(base, n)?
R
Ralf Jung 已提交
537 538
            }

M
Mark Rousskov 已提交
539
            ConstantIndex { offset, min_length, from_end } => {
540
                let n = base.len(self)?;
541
                if n < u64::from(min_length) {
542
                    // This can only be reached in ConstProp and non-rustc-MIR.
M
Matthias Krüger 已提交
543
                    throw_ub!(BoundsCheckFailed { len: min_length.into(), index: n });
544
                }
R
Ralf Jung 已提交
545 546

                let index = if from_end {
547 548
                    assert!(0 < offset && offset <= min_length);
                    n.checked_sub(u64::from(offset)).unwrap()
R
Ralf Jung 已提交
549
                } else {
O
Oliver Scherer 已提交
550
                    assert!(offset < min_length);
R
Ralf Jung 已提交
551 552 553
                    u64::from(offset)
                };

554
                self.mplace_index(base, index)?
R
Ralf Jung 已提交
555 556
            }

M
Mark Rousskov 已提交
557 558 559
            Subslice { from, to, from_end } => {
                self.mplace_subslice(base, u64::from(from), u64::from(to), from_end)?
            }
R
Ralf Jung 已提交
560
        })
O
Oliver Schneider 已提交
561 562
    }

A
Alexander Regueiro 已提交
563
    /// Gets the place of a field inside the place, and also the field's type.
R
Ralf Jung 已提交
564
    /// Just a convenience function, but used quite a bit.
565 566
    /// 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 已提交
567
    pub fn place_field(
O
Oliver Schneider 已提交
568
        &mut self,
569
        base: PlaceTy<'tcx, M::PointerTag>,
570
        field: usize,
571
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
R
Ralf Jung 已提交
572 573 574 575
        // 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 已提交
576 577
    }

578 579 580 581 582 583 584 585 586
    pub fn place_index(
        &mut self,
        base: PlaceTy<'tcx, M::PointerTag>,
        index: u64,
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
        let mplace = self.force_allocation(base)?;
        Ok(self.mplace_index(mplace, index)?.into())
    }

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

A
Alexander Regueiro 已提交
604
    /// Projects into a place.
R
Ralf Jung 已提交
605 606
    pub fn place_projection(
        &mut self,
607
        base: PlaceTy<'tcx, M::PointerTag>,
608
        proj_elem: &mir::ProjectionElem<mir::Local, Ty<'tcx>>,
609
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
M
Mazdak Farrokhzad 已提交
610
        use rustc_middle::mir::ProjectionElem::*;
R
Ralf Jung 已提交
611
        Ok(match *proj_elem {
612
            Field(field, _) => self.place_field(base, field.index())?,
R
Ralf Jung 已提交
613 614 615 616 617 618 619 620 621 622 623
            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 已提交
624
    /// Computes a place. You should only use this if you intend to write into this
625
    /// place; for reading, a more efficient alternative is `eval_place_for_read`.
R
Ralf Jung 已提交
626 627
    pub fn eval_place(
        &mut self,
628
        place: mir::Place<'tcx>,
629
    ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
630 631 632 633
        let mut place_ty = PlaceTy {
            // This works even for dead/uninitialized locals; we check further when writing
            place: Place::Local { frame: self.frame_idx(), local: place.local },
            layout: self.layout_of_local(self.frame(), place.local, None)?,
634
        };
635

636 637 638
        for elem in place.projection.iter() {
            place_ty = self.place_projection(place_ty, elem)?
        }
O
Oliver Schneider 已提交
639

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

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

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

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

668 669 670
        Ok(())
    }

W
Wesley Wiser 已提交
671 672 673 674 675 676
    /// 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 已提交
677
    ) -> InterpResult<'tcx> {
W
Wesley Wiser 已提交
678 679 680 681
        self.write_immediate_to_mplace_no_validate(src, dest)?;

        if M::enforce_validity(self) {
            // Data got changed, better make sure it matches the type!
682
            self.validate_operand(dest.into())?;
W
Wesley Wiser 已提交
683 684 685 686 687
        }

        Ok(())
    }

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

720
        // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
R
Ralf Jung 已提交
721
        // but not factored as a separate function.
R
Ralf Jung 已提交
722
        let mplace = match dest.place {
O
Oliver Schneider 已提交
723
            Place::Local { frame, local } => {
724
                match self.stack_mut()[frame].locals[local].access_mut()? {
725 726 727
                    Ok(local) => {
                        // Local can be updated in-place.
                        *local = LocalValue::Live(Operand::Immediate(src));
R
Ralf Jung 已提交
728
                        return Ok(());
729 730 731 732 733
                    }
                    Err(mplace) => {
                        // The local is in memory, go on below.
                        mplace
                    }
O
Oliver Schneider 已提交
734
                }
M
Mark Rousskov 已提交
735
            }
736
            Place::Ptr(mplace) => mplace, // already referring to memory
O
Oliver Schneider 已提交
737
        };
738
        let dest = MPlaceTy { mplace, layout: dest.layout };
O
Oliver Schneider 已提交
739

R
Ralf Jung 已提交
740
        // This is already in memory, write there.
741
        self.write_immediate_to_mplace_no_validate(src, dest)
O
Oliver Schneider 已提交
742 743
    }

744
    /// Write an immediate to memory.
745
    /// If you use this you are responsible for validating that things got copied at the
746
    /// right type.
747
    fn write_immediate_to_mplace_no_validate(
R
Ralf Jung 已提交
748
        &mut self,
749
        value: Immediate<M::PointerTag>,
750
        dest: MPlaceTy<'tcx, M::PointerTag>,
751
    ) -> InterpResult<'tcx> {
B
Bernardo Meurer 已提交
752 753 754 755
        // 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.
756

757
        // Invalid places are a thing: the return place of a diverging function
M
Mark Rousskov 已提交
758
        let ptr = match self.check_mplace_access(dest, None)? {
759 760 761
            Some(ptr) => ptr,
            None => return Ok(()), // zero-sized access
        };
762

763
        let tcx = &*self.tcx;
764 765 766
        // 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 已提交
767
        match value {
768
            Immediate::Scalar(scalar) => {
769
                match dest.layout.abi {
770
                    Abi::Scalar(_) => {} // fine
M
Mark Rousskov 已提交
771 772 773
                    _ => {
                        bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}", dest.layout)
                    }
774
                }
775
                self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(
M
Mark Rousskov 已提交
776 777 778 779
                    tcx,
                    ptr,
                    scalar,
                    dest.layout.size,
R
Ralf Jung 已提交
780
                )
O
Oliver Schneider 已提交
781
            }
782
            Immediate::ScalarPair(a_val, b_val) => {
783 784 785
                // 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 已提交
786
                let (a, b) = match dest.layout.abi {
787
                    Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
M
Mark Rousskov 已提交
788 789 790 791
                    _ => bug!(
                        "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
                        dest.layout
                    ),
R
Ralf Jung 已提交
792
                };
793
                let (a_size, b_size) = (a.size(self), b.size(self));
794
                let b_offset = a_size.align_to(b.align(self).abi);
795
                let b_ptr = ptr.offset(b_offset, self)?;
796

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

M
Mark Rousskov 已提交
801 802
                self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(tcx, ptr, a_val, a_size)?;
                self.memory.get_raw_mut(b_ptr.alloc_id)?.write_scalar(tcx, b_ptr, b_val, b_size)
O
Oliver Schneider 已提交
803
            }
R
Ralf Jung 已提交
804
        }
O
Oliver Schneider 已提交
805 806
    }

A
Alexander Regueiro 已提交
807
    /// Copies the data from an operand to a place. This does not support transmuting!
808 809
    /// Use `copy_op_transmute` if the layouts could disagree.
    #[inline(always)]
R
Ralf Jung 已提交
810
    pub fn copy_op(
O
Oliver Schneider 已提交
811
        &mut self,
812 813
        src: OpTy<'tcx, M::PointerTag>,
        dest: PlaceTy<'tcx, M::PointerTag>,
814
    ) -> InterpResult<'tcx> {
815 816
        self.copy_op_no_validate(src, dest)?;

R
Ralf Jung 已提交
817
        if M::enforce_validity(self) {
818
            // Data got changed, better make sure it matches the type!
819
            self.validate_operand(self.place_to_op(dest)?)?;
820 821 822 823 824
        }

        Ok(())
    }

A
Alexander Regueiro 已提交
825
    /// Copies the data from an operand to a place. This does not support transmuting!
826
    /// Use `copy_op_transmute` if the layouts could disagree.
827
    /// Also, if you use this you are responsible for validating that things get copied at the
828 829 830 831 832
    /// right type.
    fn copy_op_no_validate(
        &mut self,
        src: OpTy<'tcx, M::PointerTag>,
        dest: PlaceTy<'tcx, M::PointerTag>,
833
    ) -> InterpResult<'tcx> {
834 835
        // 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.
836 837 838 839 840 841 842 843
        if !mir_assign_valid_types(self.tcx.tcx, src.layout, dest.layout) {
            span_bug!(
                self.tcx.span,
                "type mismatch when copying!\nsrc: {:?},\ndest: {:?}",
                src.layout.ty,
                dest.layout.ty,
            );
        }
R
Ralf Jung 已提交
844 845

        // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
846
        let src = match self.try_read_immediate(src)? {
847
            Ok(src_val) => {
848
                assert!(!src.layout.is_unsized(), "cannot have unsized immediates");
849
                // Yay, we got a value that we can write directly.
850 851
                // FIXME: Add a check to make sure that if `src` is indirect,
                // it does not overlap with `dest`.
852
                return self.write_immediate_no_validate(*src_val, dest);
853 854
            }
            Err(mplace) => mplace,
R
Ralf Jung 已提交
855 856
        };
        // Slow path, this does not fit into an immediate. Just memcpy.
857 858
        trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);

859 860 861 862
        // This interprets `src.meta` with the `dest` local's layout, if an unsized local
        // is being initialized!
        let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?;
        let size = size.unwrap_or_else(|| {
M
Mark Rousskov 已提交
863 864 865 866
            assert!(
                !dest.layout.is_unsized(),
                "Cannot copy into already initialized unsized place"
            );
867 868 869
            dest.layout.size
        });
        assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances");
870

M
Mark Rousskov 已提交
871 872
        let src = self
            .check_mplace_access(src, Some(size))
873
            .expect("places should be checked on creation");
M
Mark Rousskov 已提交
874 875
        let dest = self
            .check_mplace_access(dest, Some(size))
876
            .expect("places should be checked on creation");
877 878 879 880 881 882
        let (src_ptr, dest_ptr) = match (src, dest) {
            (Some(src_ptr), Some(dest_ptr)) => (src_ptr, dest_ptr),
            (None, None) => return Ok(()), // zero-sized copy
            _ => bug!("The pointers should both be Some or both None"),
        };

M
Mark Rousskov 已提交
883
        self.memory.copy(src_ptr, dest_ptr, size, /*nonoverlapping*/ true)
884 885
    }

A
Alexander Regueiro 已提交
886
    /// Copies the data from an operand to a place. The layouts may disagree, but they must
887 888 889 890 891
    /// have the same size.
    pub fn copy_op_transmute(
        &mut self,
        src: OpTy<'tcx, M::PointerTag>,
        dest: PlaceTy<'tcx, M::PointerTag>,
892
    ) -> InterpResult<'tcx> {
893
        if mir_assign_valid_types(self.tcx.tcx, src.layout, dest.layout) {
894 895 896
            // Fast path: Just use normal `copy_op`
            return self.copy_op(src, dest);
        }
897
        // We still require the sizes to match.
898
        if src.layout.size != dest.layout.size {
899 900 901 902
            // FIXME: This should be an assert instead of an error, but if we transmute within an
            // array length computation, `typeck` may not have yet been run and errored out. In fact
            // most likey we *are* running `typeck` right now. Investigate whether we can bail out
            // on `typeck_tables().has_errors` at all const eval entry points.
903
            debug!("Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
904 905 906 907
            self.tcx.sess.delay_span_bug(
                self.tcx.span,
                "size-changing transmute, should have been caught by transmute checking",
            );
908
            throw_inval!(TransmuteSizeDiff(src.layout.ty, dest.layout.ty));
909
        }
910 911
        // Unsized copies rely on interpreting `src.meta` with `dest.layout`, we want
        // to avoid that here.
M
Mark Rousskov 已提交
912 913 914 915
        assert!(
            !src.layout.is_unsized() && !dest.layout.is_unsized(),
            "Cannot transmute unsized data"
        );
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930

        // 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 已提交
931
        if M::enforce_validity(self) {
932
            // Data got changed, better make sure it matches the type!
933
            self.validate_operand(dest.into())?;
934
        }
935

936
        Ok(())
O
Oliver Schneider 已提交
937 938
    }

A
Alexander Regueiro 已提交
939
    /// Ensures that a place is in memory, and returns where it is.
940 941
    /// If the place currently refers to a local that doesn't yet have a matching allocation,
    /// create such an allocation.
R
Ralf Jung 已提交
942
    /// This is essentially `force_to_memplace`.
943
    ///
R
Ralf Jung 已提交
944
    /// This supports unsized types and returns the computed size to avoid some
945 946 947
    /// redundant computation when copying; use `force_allocation` for a simpler, sized-only
    /// version.
    pub fn force_allocation_maybe_sized(
O
Oliver Schneider 已提交
948
        &mut self,
949
        place: PlaceTy<'tcx, M::PointerTag>,
950
        meta: MemPlaceMeta<M::PointerTag>,
951
    ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option<Size>)> {
952
        let (mplace, size) = match place.place {
R
Ralf Jung 已提交
953
            Place::Local { frame, local } => {
954
                match self.stack_mut()[frame].locals[local].access_mut()? {
955
                    Ok(&mut local_val) => {
956
                        // We need to make an allocation.
957

958
                        // We need the layout of the local.  We can NOT use the layout we got,
959
                        // that might e.g., be an inner field of a struct with `Scalar` layout,
R
Ralf Jung 已提交
960
                        // that has different alignment than the outer field.
961 962
                        let local_layout =
                            self.layout_of_local(&self.stack()[frame], local, None)?;
963
                        // We also need to support unsized types, and hence cannot use `allocate`.
M
Mark Rousskov 已提交
964 965
                        let (size, align) = self
                            .size_and_align_of(meta, local_layout)?
966 967 968
                            .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 };
969
                        if let LocalValue::Live(Operand::Immediate(value)) = local_val {
970 971 972
                            // Preserve old value.
                            // We don't have to validate as we can assume the local
                            // was already valid for its type.
973 974
                            let mplace = MPlaceTy { mplace, layout: local_layout };
                            self.write_immediate_to_mplace_no_validate(value, mplace)?;
975 976 977
                        }
                        // Now we can call `access_mut` again, asserting it goes well,
                        // and actually overwrite things.
978
                        *self.stack_mut()[frame].locals[local].access_mut().unwrap().unwrap() =
979
                            LocalValue::Live(Operand::Indirect(mplace));
980
                        (mplace, Some(size))
981
                    }
982
                    Err(mplace) => (mplace, None), // this already was an indirect local
983
                }
R
Ralf Jung 已提交
984
            }
M
Mark Rousskov 已提交
985
            Place::Ptr(mplace) => (mplace, None),
R
Ralf Jung 已提交
986 987
        };
        // Return with the original layout, so that the caller can go on
988 989 990 991 992 993 994
        Ok((MPlaceTy { mplace, layout: place.layout }, size))
    }

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

R
Ralf Jung 已提交
999
    pub fn allocate(
O
Oliver Schneider 已提交
1000
        &mut self,
1001
        layout: TyAndLayout<'tcx>,
1002
        kind: MemoryKind<M::MemoryKind>,
R
Ralf Jung 已提交
1003
    ) -> MPlaceTy<'tcx, M::PointerTag> {
1004 1005
        let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
        MPlaceTy::from_aligned_ptr(ptr, layout)
R
Ralf Jung 已提交
1006
    }
O
Oliver Schneider 已提交
1007

R
Ralf Jung 已提交
1008
    /// Returns a wide MPlace.
1009 1010 1011
    pub fn allocate_str(
        &mut self,
        str: &str,
1012
        kind: MemoryKind<M::MemoryKind>,
1013
    ) -> MPlaceTy<'tcx, M::PointerTag> {
1014
        let ptr = self.memory.allocate_bytes(str.as_bytes(), kind);
1015
        let meta = Scalar::from_machine_usize(u64::try_from(str.len()).unwrap(), self);
1016 1017 1018
        let mplace = MemPlace {
            ptr: ptr.into(),
            align: Align::from_bytes(1).unwrap(),
O
Oliver Scherer 已提交
1019
            meta: MemPlaceMeta::Meta(meta),
1020
        };
1021 1022 1023 1024 1025

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

1026
    pub fn write_discriminant_index(
R
Ralf Jung 已提交
1027
        &mut self,
1028
        variant_index: VariantIdx,
1029
        dest: PlaceTy<'tcx, M::PointerTag>,
1030
    ) -> InterpResult<'tcx> {
1031 1032 1033 1034 1035
        // Layout computation excludes uninhabited variants from consideration
        // therefore there's no way to represent those variants in the given layout.
        if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() {
            throw_ub!(Unreachable);
        }
1036

R
Ralf Jung 已提交
1037
        match dest.layout.variants {
1038
            Variants::Single { index } => {
1039
                assert_eq!(index, variant_index);
O
Oliver Schneider 已提交
1040
            }
1041 1042
            Variants::Multiple {
                discr_kind: DiscriminantKind::Tag,
1043
                discr: ref discr_layout,
1044
                discr_index,
1045 1046
                ..
            } => {
1047
                // No need to validate that the discriminant here because the
1048
                // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
1049

1050 1051
                let discr_val =
                    dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;
R
Ralf Jung 已提交
1052 1053 1054 1055

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

1059
                let discr_dest = self.place_field(dest, discr_index)?;
1060
                self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
O
Oliver Schneider 已提交
1061
            }
1062
            Variants::Multiple {
M
Mark Rousskov 已提交
1063
                discr_kind:
1064
                    DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start },
1065
                discr: ref discr_layout,
1066
                discr_index,
R
Ralf Jung 已提交
1067
                ..
O
Oliver Schneider 已提交
1068
            } => {
1069
                // No need to validate that the discriminant here because the
1070
                // `TyAndLayout::for_variant()` call earlier already checks the variant is valid.
1071

R
Ralf Jung 已提交
1072
                if variant_index != dataful_variant {
1073
                    let variants_start = niche_variants.start().as_u32();
M
Mark Rousskov 已提交
1074 1075
                    let variant_index_relative = variant_index
                        .as_u32()
1076 1077
                        .checked_sub(variants_start)
                        .expect("overflow computing relative variant idx");
1078 1079
                    // We need to use machine arithmetic when taking into account `niche_start`:
                    // discr_val = variant_index_relative + niche_start_val
1080
                    let discr_layout = self.layout_of(discr_layout.value.to_int_ty(*self.tcx))?;
1081
                    let niche_start_val = ImmTy::from_uint(niche_start, discr_layout);
1082 1083
                    let variant_index_relative_val =
                        ImmTy::from_uint(variant_index_relative, discr_layout);
1084
                    let discr_val = self.binary_op(
1085
                        mir::BinOp::Add,
1086
                        variant_index_relative_val,
1087
                        niche_start_val,
1088
                    )?;
1089
                    // Write result.
1090
                    let niche_dest = self.place_field(dest, discr_index)?;
1091
                    self.write_immediate(*discr_val, niche_dest)?;
R
Ralf Jung 已提交
1092
                }
O
Oliver Schneider 已提交
1093
            }
1094
        }
R
Ralf Jung 已提交
1095 1096

        Ok(())
O
Oliver Schneider 已提交
1097 1098
    }

1099 1100 1101
    pub fn raw_const_to_mplace(
        &self,
        raw: RawConst<'tcx>,
1102
    ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1103 1104
        // This must be an allocation in `tcx`
        assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1105
        let ptr = self.tag_global_base_pointer(Pointer::from(raw.alloc_id));
1106
        let layout = self.layout_of(raw.ty)?;
1107
        Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
1108 1109
    }

1110 1111
    /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
    /// Also return some more information so drop doesn't have to run the same code twice.
M
Mark Rousskov 已提交
1112 1113 1114 1115
    pub(super) fn unpack_dyn_trait(
        &self,
        mplace: MPlaceTy<'tcx, M::PointerTag>,
    ) -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1116
        let vtable = mplace.vtable(); // also sanity checks the type
1117 1118 1119 1120
        let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
        let layout = self.layout_of(ty)?;

        // More sanity checks
1121 1122 1123
        if cfg!(debug_assertions) {
            let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
            assert_eq!(size, layout.size);
1124
            // only ABI alignment is preserved
1125
            assert_eq!(align, layout.align.abi);
1126
        }
1127

1128
        let mplace = MPlaceTy { mplace: MemPlace { meta: MemPlaceMeta::None, ..*mplace }, layout };
1129
        Ok((instance, mplace))
1130
    }
O
Oliver Schneider 已提交
1131
}