1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Computations on places -- field projections, going from mir::Place, and writing
13 //! All high-level functions to write to memory work on places as destinations.
15 use std::convert::TryFrom;
20 use rustc::ty::{self, Ty};
21 use rustc::ty::layout::{self, Size, Align, LayoutOf, TyLayout, HasDataLayout, VariantIdx};
24 GlobalId, AllocId, Allocation, Scalar, EvalResult, Pointer, PointerArithmetic,
25 EvalContext, Machine, AllocMap, AllocationExtra,
26 RawConst, Immediate, ImmTy, ScalarMaybeUndef, Operand, OpTy, MemoryKind
29 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
30 pub struct MemPlace<Tag=(), Id=AllocId> {
31 /// A place may have an integral pointer for ZSTs, and since it might
32 /// be turned back into a reference before ever being dereferenced.
33 /// However, it may never be undef.
34 pub ptr: Scalar<Tag, Id>,
36 /// Metadata for unsized places. Interpretation is up to the type.
37 /// Must not be present for sized types, but can be missing for unsized types
38 /// (e.g. `extern type`).
39 pub meta: Option<Scalar<Tag, Id>>,
42 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
43 pub enum Place<Tag=(), Id=AllocId> {
44 /// A place referring to a value allocated in the `Memory` system.
45 Ptr(MemPlace<Tag, Id>),
47 /// To support alloc-free locals, we are able to write directly to a local.
48 /// (Without that optimization, we'd just always be a `MemPlace`.)
55 #[derive(Copy, Clone, Debug)]
56 pub struct PlaceTy<'tcx, Tag=()> {
58 pub layout: TyLayout<'tcx>,
61 impl<'tcx, Tag> ::std::ops::Deref for PlaceTy<'tcx, Tag> {
62 type Target = Place<Tag>;
64 fn deref(&self) -> &Place<Tag> {
69 /// A MemPlace with its layout. Constructing it is only possible in this module.
70 #[derive(Copy, Clone, Debug)]
71 pub struct MPlaceTy<'tcx, Tag=()> {
72 mplace: MemPlace<Tag>,
73 pub layout: TyLayout<'tcx>,
76 impl<'tcx, Tag> ::std::ops::Deref for MPlaceTy<'tcx, Tag> {
77 type Target = MemPlace<Tag>;
79 fn deref(&self) -> &MemPlace<Tag> {
84 impl<'tcx, Tag> From<MPlaceTy<'tcx, Tag>> for PlaceTy<'tcx, Tag> {
86 fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
88 place: Place::Ptr(mplace.mplace),
96 pub fn with_default_tag<Tag>(self) -> MemPlace<Tag>
100 ptr: self.ptr.with_default_tag(),
102 meta: self.meta.map(Scalar::with_default_tag),
107 impl<Tag> MemPlace<Tag> {
109 pub fn erase_tag(self) -> MemPlace
112 ptr: self.ptr.erase_tag(),
114 meta: self.meta.map(Scalar::erase_tag),
119 pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
127 /// Produces a Place that will error if attempted to be read from or written to
129 pub fn null(cx: &impl HasDataLayout) -> Self {
130 Self::from_scalar_ptr(Scalar::ptr_null(cx), Align::from_bytes(1).unwrap())
134 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
135 Self::from_scalar_ptr(ptr.into(), align)
139 pub fn to_scalar_ptr_align(self) -> (Scalar<Tag>, Align) {
140 assert!(self.meta.is_none());
141 (self.ptr, self.align)
144 /// metact the ptr part of the mplace
146 pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
147 // At this point, we forget about the alignment information --
148 // the place has been turned into a reference, and no matter where it came from,
149 // it now must be aligned.
150 self.to_scalar_ptr_align().0.to_ptr()
153 /// Turn a mplace into a (thin or fat) pointer, as a reference, pointing to the same space.
154 /// This is the inverse of `ref_to_mplace`.
156 pub fn to_ref(self) -> Immediate<Tag> {
158 None => Immediate::Scalar(self.ptr.into()),
159 Some(meta) => Immediate::ScalarPair(self.ptr.into(), meta.into()),
166 meta: Option<Scalar<Tag>>,
167 cx: &impl HasDataLayout,
168 ) -> EvalResult<'tcx, Self> {
170 ptr: self.ptr.ptr_offset(offset, cx)?,
171 align: self.align.restrict_for_offset(offset),
177 impl<'tcx, Tag> MPlaceTy<'tcx, Tag> {
178 /// Produces a MemPlace that works for ZST but nothing else
180 pub fn dangling(layout: TyLayout<'tcx>, cx: &impl HasDataLayout) -> Self {
182 mplace: MemPlace::from_scalar_ptr(
183 Scalar::from_uint(layout.align.abi.bytes(), cx.pointer_size()),
193 meta: Option<Scalar<Tag>>,
194 layout: TyLayout<'tcx>,
195 cx: &impl HasDataLayout,
196 ) -> EvalResult<'tcx, Self> {
198 mplace: self.mplace.offset(offset, meta, cx)?,
204 fn from_aligned_ptr(ptr: Pointer<Tag>, layout: TyLayout<'tcx>) -> Self {
205 MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout }
209 pub(super) fn len(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, u64> {
210 if self.layout.is_unsized() {
211 // We need to consult `meta` metadata
212 match self.layout.ty.sty {
213 ty::Slice(..) | ty::Str =>
214 return self.mplace.meta.unwrap().to_usize(cx),
215 _ => bug!("len not supported on unsized type {:?}", self.layout.ty),
218 // Go through the layout. There are lots of types that support a length,
220 match self.layout.fields {
221 layout::FieldPlacement::Array { count, .. } => Ok(count),
222 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
228 pub(super) fn vtable(self) -> EvalResult<'tcx, Pointer<Tag>> {
229 match self.layout.ty.sty {
230 ty::Dynamic(..) => self.mplace.meta.unwrap().to_ptr(),
231 _ => bug!("vtable not supported on type {:?}", self.layout.ty),
236 impl<'tcx, Tag: ::std::fmt::Debug> OpTy<'tcx, Tag> {
238 pub fn try_as_mplace(self) -> Result<MPlaceTy<'tcx, Tag>, Immediate<Tag>> {
240 Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }),
241 Operand::Immediate(imm) => Err(imm),
246 pub fn to_mem_place(self) -> MPlaceTy<'tcx, Tag> {
247 self.try_as_mplace().unwrap()
251 impl<'tcx, Tag: ::std::fmt::Debug> Place<Tag> {
252 /// Produces a Place that will error if attempted to be read from or written to
254 pub fn null(cx: &impl HasDataLayout) -> Self {
255 Place::Ptr(MemPlace::null(cx))
259 pub fn from_scalar_ptr(ptr: Scalar<Tag>, align: Align) -> Self {
260 Place::Ptr(MemPlace::from_scalar_ptr(ptr, align))
264 pub fn from_ptr(ptr: Pointer<Tag>, align: Align) -> Self {
265 Place::Ptr(MemPlace::from_ptr(ptr, align))
269 pub fn to_mem_place(self) -> MemPlace<Tag> {
271 Place::Ptr(mplace) => mplace,
272 _ => bug!("to_mem_place: expected Place::Ptr, got {:?}", self),
278 pub fn to_scalar_ptr_align(self) -> (Scalar<Tag>, Align) {
279 self.to_mem_place().to_scalar_ptr_align()
283 pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
284 self.to_mem_place().to_ptr()
288 impl<'tcx, Tag: ::std::fmt::Debug> PlaceTy<'tcx, Tag> {
290 pub fn to_mem_place(self) -> MPlaceTy<'tcx, Tag> {
291 MPlaceTy { mplace: self.place.to_mem_place(), layout: self.layout }
295 // separating the pointer tag for `impl Trait`, see https://github.com/rust-lang/rust/issues/54385
296 impl<'a, 'mir, 'tcx, Tag, M> EvalContext<'a, 'mir, 'tcx, M>
298 // FIXME: Working around https://github.com/rust-lang/rust/issues/54385
299 Tag: ::std::fmt::Debug+Default+Copy+Eq+Hash+'static,
300 M: Machine<'a, 'mir, 'tcx, PointerTag=Tag>,
301 // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
302 M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation<Tag, M::AllocExtra>)>,
303 M::AllocExtra: AllocationExtra<Tag, M::MemoryExtra>,
305 /// Take a value, which represents a (thin or fat) reference, and make it a place.
306 /// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`.
307 /// This does NOT call the "deref" machine hook, so it does NOT count as a
308 /// deref as far as Stacked Borrows is concerned. Use `deref_operand` for that!
309 pub fn ref_to_mplace(
311 val: ImmTy<'tcx, M::PointerTag>,
312 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
313 let pointee_type = val.layout.ty.builtin_deref(true).unwrap().ty;
314 let layout = self.layout_of(pointee_type)?;
316 let mplace = MemPlace {
317 ptr: val.to_scalar_ptr()?,
318 align: layout.align.abi,
319 meta: val.to_meta()?,
321 Ok(MPlaceTy { mplace, layout })
324 // Take an operand, representing a pointer, and dereference it to a place -- that
325 // will always be a MemPlace. Lives in `place.rs` because it creates a place.
326 // This calls the "deref" machine hook, and counts as a deref as far as
327 // Stacked Borrows is concerned.
328 pub fn deref_operand(
330 src: OpTy<'tcx, M::PointerTag>,
331 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
332 let val = self.read_immediate(src)?;
333 trace!("deref to {} on {:?}", val.layout.ty, *val);
334 let mut place = self.ref_to_mplace(val)?;
335 // Pointer tag tracking might want to adjust the tag.
336 let mutbl = match val.layout.ty.sty {
337 // `builtin_deref` considers boxes immutable, that's useless for our purposes
338 ty::Ref(_, _, mutbl) => Some(mutbl),
339 ty::Adt(def, _) if def.is_box() => Some(hir::MutMutable),
340 ty::RawPtr(_) => None,
341 _ => bug!("Unexpected pointer type {}", val.layout.ty.sty),
343 place.mplace.ptr = M::tag_dereference(self, place, mutbl)?;
347 /// Offset a pointer to project to a field. Unlike place_field, this is always
348 /// possible without allocating, so it can take &self. Also return the field's layout.
349 /// This supports both struct and array fields.
353 base: MPlaceTy<'tcx, M::PointerTag>,
355 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
356 // Not using the layout method because we want to compute on u64
357 let offset = match base.layout.fields {
358 layout::FieldPlacement::Arbitrary { ref offsets, .. } =>
359 offsets[usize::try_from(field).unwrap()],
360 layout::FieldPlacement::Array { stride, .. } => {
361 let len = base.len(self)?;
362 assert!(field < len, "Tried to access element {} of array/slice with length {}",
366 layout::FieldPlacement::Union(count) => {
367 assert!(field < count as u64,
368 "Tried to access field {} of union with {} fields", field, count);
369 // Offset is always 0
373 // the only way conversion can fail if is this is an array (otherwise we already panicked
374 // above). In that case, all fields are equal.
375 let field_layout = base.layout.field(self, usize::try_from(field).unwrap_or(0))?;
377 // Offset may need adjustment for unsized fields
378 let (meta, offset) = if field_layout.is_unsized() {
379 // re-use parent metadata to determine dynamic field layout
380 let align = match self.size_and_align_of(base.meta, field_layout)? {
381 Some((_, align)) => align,
382 None if offset == Size::ZERO =>
383 // An extern type at offset 0, we fall back to its static alignment.
384 // FIXME: Once we have made decisions for how to handle size and alignment
385 // of `extern type`, this should be adapted. It is just a temporary hack
386 // to get some code to work that probably ought to work.
387 field_layout.align.abi,
389 bug!("Cannot compute offset for extern type field at non-0 offset"),
391 (base.meta, offset.align_to(align))
393 // base.meta could be present; we might be accessing a sized field of an unsized
398 // We do not look at `base.layout.align` nor `field_layout.align`, unlike
399 // codegen -- mostly to see if we can get away with that
400 base.offset(offset, meta, field_layout, self)
403 // Iterates over all fields of an array. Much more efficient than doing the
404 // same by repeatedly calling `mplace_array`.
405 pub fn mplace_array_fields(
407 base: MPlaceTy<'tcx, Tag>,
409 EvalResult<'tcx, impl Iterator<Item=EvalResult<'tcx, MPlaceTy<'tcx, Tag>>> + 'a>
411 let len = base.len(self)?; // also asserts that we have a type where this makes sense
412 let stride = match base.layout.fields {
413 layout::FieldPlacement::Array { stride, .. } => stride,
414 _ => bug!("mplace_array_fields: expected an array layout"),
416 let layout = base.layout.field(self, 0)?;
417 let dl = &self.tcx.data_layout;
418 Ok((0..len).map(move |i| base.offset(i * stride, None, layout, dl)))
421 pub fn mplace_subslice(
423 base: MPlaceTy<'tcx, M::PointerTag>,
426 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
427 let len = base.len(self)?; // also asserts that we have a type where this makes sense
428 assert!(from <= len - to);
430 // Not using layout method because that works with usize, and does not work with slices
431 // (that have count 0 in their layout).
432 let from_offset = match base.layout.fields {
433 layout::FieldPlacement::Array { stride, .. } =>
435 _ => bug!("Unexpected layout of index access: {:#?}", base.layout),
438 // Compute meta and new layout
439 let inner_len = len - to - from;
440 let (meta, ty) = match base.layout.ty.sty {
441 // It is not nice to match on the type, but that seems to be the only way to
443 ty::Array(inner, _) =>
444 (None, self.tcx.mk_array(inner, inner_len)),
446 let len = Scalar::from_uint(inner_len, self.pointer_size());
447 (Some(len), base.layout.ty)
450 bug!("cannot subslice non-array type: `{:?}`", base.layout.ty),
452 let layout = self.layout_of(ty)?;
453 base.offset(from_offset, meta, layout, self)
456 pub fn mplace_downcast(
458 base: MPlaceTy<'tcx, M::PointerTag>,
460 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
461 // Downcasts only change the layout
462 assert!(base.meta.is_none());
463 Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..base })
466 /// Project into an mplace
467 pub fn mplace_projection(
469 base: MPlaceTy<'tcx, M::PointerTag>,
470 proj_elem: &mir::PlaceElem<'tcx>,
471 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
472 use rustc::mir::ProjectionElem::*;
473 Ok(match *proj_elem {
474 Field(field, _) => self.mplace_field(base, field.index() as u64)?,
475 Downcast(_, variant) => self.mplace_downcast(base, variant)?,
476 Deref => self.deref_operand(base.into())?,
479 let n = *self.frame().locals[local].access()?;
480 let n_layout = self.layout_of(self.tcx.types.usize)?;
481 let n = self.read_scalar(OpTy { op: n, layout: n_layout })?;
482 let n = n.to_bits(self.tcx.data_layout.pointer_size)?;
483 self.mplace_field(base, u64::try_from(n).unwrap())?
491 let n = base.len(self)?;
492 assert!(n >= min_length as u64);
494 let index = if from_end {
495 n - u64::from(offset)
500 self.mplace_field(base, index)?
503 Subslice { from, to } =>
504 self.mplace_subslice(base, u64::from(from), u64::from(to))?,
508 /// Get the place of a field inside the place, and also the field's type.
509 /// Just a convenience function, but used quite a bit.
510 /// This is the only projection that might have a side-effect: We cannot project
511 /// into the field of a local `ScalarPair`, we have to first allocate it.
514 base: PlaceTy<'tcx, M::PointerTag>,
516 ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
517 // FIXME: We could try to be smarter and avoid allocation for fields that span the
519 let mplace = self.force_allocation(base)?;
520 Ok(self.mplace_field(mplace, field)?.into())
523 pub fn place_downcast(
525 base: PlaceTy<'tcx, M::PointerTag>,
527 ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
528 // Downcast just changes the layout
529 Ok(match base.place {
530 Place::Ptr(mplace) =>
531 self.mplace_downcast(MPlaceTy { mplace, layout: base.layout }, variant)?.into(),
532 Place::Local { .. } => {
533 let layout = base.layout.for_variant(self, variant);
534 PlaceTy { layout, ..base }
539 /// Project into a place
540 pub fn place_projection(
542 base: PlaceTy<'tcx, M::PointerTag>,
543 proj_elem: &mir::ProjectionElem<'tcx, mir::Local, Ty<'tcx>>,
544 ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
545 use rustc::mir::ProjectionElem::*;
546 Ok(match *proj_elem {
547 Field(field, _) => self.place_field(base, field.index() as u64)?,
548 Downcast(_, variant) => self.place_downcast(base, variant)?,
549 Deref => self.deref_operand(self.place_to_op(base)?)?.into(),
550 // For the other variants, we have to force an allocation.
551 // This matches `operand_projection`.
552 Subslice { .. } | ConstantIndex { .. } | Index(_) => {
553 let mplace = self.force_allocation(base)?;
554 self.mplace_projection(mplace, proj_elem)?.into()
559 /// Evaluate statics and promoteds to an `MPlace`. Used to share some code between
560 /// `eval_place` and `eval_place_to_op`.
561 pub(super) fn eval_place_to_mplace(
563 mir_place: &mir::Place<'tcx>
564 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
565 use rustc::mir::Place::*;
566 Ok(match *mir_place {
567 Promoted(ref promoted) => {
568 let instance = self.frame().instance;
569 self.const_eval_raw(GlobalId {
571 promoted: Some(promoted.0),
575 Static(ref static_) => {
576 let ty = self.monomorphize(static_.ty, self.substs());
577 let layout = self.layout_of(ty)?;
578 let instance = ty::Instance::mono(*self.tcx, static_.def_id);
583 // Just create a lazy reference, so we can support recursive statics.
584 // tcx takes are of assigning every static one and only one unique AllocId.
585 // When the data here is ever actually used, memory will notice,
586 // and it knows how to deal with alloc_id that are present in the
587 // global table but not in its local memory: It calls back into tcx through
588 // a query, triggering the CTFE machinery to actually turn this lazy reference
589 // into a bunch of bytes. IOW, statics are evaluated with CTFE even when
590 // this EvalContext uses another Machine (e.g., in miri). This is what we
591 // want! This way, computing statics works concistently between codegen
592 // and miri: They use the same query to eventually obtain a `ty::Const`
593 // and use that for further computation.
594 let alloc = self.tcx.alloc_map.lock().intern_static(cid.instance.def_id());
595 MPlaceTy::from_aligned_ptr(Pointer::from(alloc).with_default_tag(), layout)
598 _ => bug!("eval_place_to_mplace called on {:?}", mir_place),
602 /// Compute a place. You should only use this if you intend to write into this
603 /// place; for reading, a more efficient alternative is `eval_place_for_read`.
606 mir_place: &mir::Place<'tcx>
607 ) -> EvalResult<'tcx, PlaceTy<'tcx, M::PointerTag>> {
608 use rustc::mir::Place::*;
609 let place = match *mir_place {
610 Local(mir::RETURN_PLACE) => match self.frame().return_place {
611 Some(return_place) =>
612 // We use our layout to verify our assumption; caller will validate
613 // their layout on return.
615 place: *return_place,
616 layout: self.layout_of_local(self.frame(), mir::RETURN_PLACE)?,
618 None => return err!(InvalidNullPointerUsage),
620 Local(local) => PlaceTy {
621 place: Place::Local {
622 frame: self.cur_frame(),
625 layout: self.layout_of_local(self.frame(), local)?,
628 Projection(ref proj) => {
629 let place = self.eval_place(&proj.base)?;
630 self.place_projection(place, &proj.elem)?
633 _ => self.eval_place_to_mplace(mir_place)?.into(),
636 self.dump_place(place.place);
640 /// Write a scalar to a place
643 val: impl Into<ScalarMaybeUndef<M::PointerTag>>,
644 dest: PlaceTy<'tcx, M::PointerTag>,
645 ) -> EvalResult<'tcx> {
646 self.write_immediate(Immediate::Scalar(val.into()), dest)
649 /// Write an immediate to a place
651 pub fn write_immediate(
653 src: Immediate<M::PointerTag>,
654 dest: PlaceTy<'tcx, M::PointerTag>,
655 ) -> EvalResult<'tcx> {
656 self.write_immediate_no_validate(src, dest)?;
658 if M::enforce_validity(self) {
659 // Data got changed, better make sure it matches the type!
660 self.validate_operand(self.place_to_op(dest)?, vec![], None, /*const_mode*/false)?;
666 /// Write an immediate to a place.
667 /// If you use this you are responsible for validating that things got copied at the
669 fn write_immediate_no_validate(
671 src: Immediate<M::PointerTag>,
672 dest: PlaceTy<'tcx, M::PointerTag>,
673 ) -> EvalResult<'tcx> {
674 if cfg!(debug_assertions) {
675 // This is a very common path, avoid some checks in release mode
676 assert!(!dest.layout.is_unsized(), "Cannot write unsized data");
678 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Ptr(_))) =>
679 assert_eq!(self.pointer_size(), dest.layout.size,
680 "Size mismatch when writing pointer"),
681 Immediate::Scalar(ScalarMaybeUndef::Scalar(Scalar::Bits { size, .. })) =>
682 assert_eq!(Size::from_bytes(size.into()), dest.layout.size,
683 "Size mismatch when writing bits"),
684 Immediate::Scalar(ScalarMaybeUndef::Undef) => {}, // undef can have any size
685 Immediate::ScalarPair(_, _) => {
686 // FIXME: Can we check anything here?
690 trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
692 // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`,
693 // but not factored as a separate function.
694 let mplace = match dest.place {
695 Place::Local { frame, local } => {
696 match *self.stack[frame].locals[local].access_mut()? {
697 Operand::Immediate(ref mut dest_val) => {
698 // Yay, we can just change the local directly.
702 Operand::Indirect(mplace) => mplace, // already in memory
705 Place::Ptr(mplace) => mplace, // already in memory
707 let dest = MPlaceTy { mplace, layout: dest.layout };
709 // This is already in memory, write there.
710 self.write_immediate_to_mplace_no_validate(src, dest)
713 /// Write an immediate to memory.
714 /// If you use this you are responsible for validating that things git copied at the
716 fn write_immediate_to_mplace_no_validate(
718 value: Immediate<M::PointerTag>,
719 dest: MPlaceTy<'tcx, M::PointerTag>,
720 ) -> EvalResult<'tcx> {
721 let (ptr, ptr_align) = dest.to_scalar_ptr_align();
722 // Note that it is really important that the type here is the right one, and matches the
723 // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here
724 // to handle padding properly, which is only correct if we never look at this data with the
727 // Nothing to do for ZSTs, other than checking alignment
728 if dest.layout.is_zst() {
729 return self.memory.check_align(ptr, ptr_align);
732 // check for integer pointers before alignment to report better errors
733 let ptr = ptr.to_ptr()?;
734 self.memory.check_align(ptr.into(), ptr_align)?;
735 let tcx = &*self.tcx;
736 // FIXME: We should check that there are dest.layout.size many bytes available in
737 // memory. The code below is not sufficient, with enough padding it might not
738 // cover all the bytes!
740 Immediate::Scalar(scalar) => {
741 match dest.layout.abi {
742 layout::Abi::Scalar(_) => {}, // fine
743 _ => bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}",
746 self.memory.get_mut(ptr.alloc_id)?.write_scalar(
747 tcx, ptr, scalar, dest.layout.size
750 Immediate::ScalarPair(a_val, b_val) => {
751 let (a, b) = match dest.layout.abi {
752 layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
753 _ => bug!("write_immediate_to_mplace: invalid ScalarPair layout: {:#?}",
756 let (a_size, b_size) = (a.size(self), b.size(self));
757 let b_offset = a_size.align_to(b.align(self).abi);
758 let b_align = ptr_align.restrict_for_offset(b_offset);
759 let b_ptr = ptr.offset(b_offset, self)?;
761 self.memory.check_align(b_ptr.into(), b_align)?;
763 // It is tempting to verify `b_offset` against `layout.fields.offset(1)`,
764 // but that does not work: We could be a newtype around a pair, then the
765 // fields do not match the `ScalarPair` components.
768 .get_mut(ptr.alloc_id)?
769 .write_scalar(tcx, ptr, a_val, a_size)?;
771 .get_mut(b_ptr.alloc_id)?
772 .write_scalar(tcx, b_ptr, b_val, b_size)
777 /// Copy the data from an operand to a place. This does not support transmuting!
778 /// Use `copy_op_transmute` if the layouts could disagree.
782 src: OpTy<'tcx, M::PointerTag>,
783 dest: PlaceTy<'tcx, M::PointerTag>,
784 ) -> EvalResult<'tcx> {
785 self.copy_op_no_validate(src, dest)?;
787 if M::enforce_validity(self) {
788 // Data got changed, better make sure it matches the type!
789 self.validate_operand(self.place_to_op(dest)?, vec![], None, /*const_mode*/false)?;
795 /// Copy the data from an operand to a place. This does not support transmuting!
796 /// Use `copy_op_transmute` if the layouts could disagree.
797 /// Also, if you use this you are responsible for validating that things git copied at the
799 fn copy_op_no_validate(
801 src: OpTy<'tcx, M::PointerTag>,
802 dest: PlaceTy<'tcx, M::PointerTag>,
803 ) -> EvalResult<'tcx> {
804 debug_assert!(!src.layout.is_unsized() && !dest.layout.is_unsized(),
805 "Cannot copy unsized data");
806 // We do NOT compare the types for equality, because well-typed code can
807 // actually "transmute" `&mut T` to `&T` in an assignment without a cast.
808 assert!(src.layout.details == dest.layout.details,
809 "Layout mismatch when copying!\nsrc: {:#?}\ndest: {:#?}", src, dest);
811 // Let us see if the layout is simple so we take a shortcut, avoid force_allocation.
812 let src = match self.try_read_immediate(src)? {
814 // Yay, we got a value that we can write directly.
815 return self.write_immediate_no_validate(src_val, dest);
817 Err(mplace) => mplace,
819 // Slow path, this does not fit into an immediate. Just memcpy.
820 trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty);
822 let dest = self.force_allocation(dest)?;
823 let (src_ptr, src_align) = src.to_scalar_ptr_align();
824 let (dest_ptr, dest_align) = dest.to_scalar_ptr_align();
827 dest_ptr, dest_align,
828 dest.layout.size, false
834 /// Copy the data from an operand to a place. The layouts may disagree, but they must
835 /// have the same size.
836 pub fn copy_op_transmute(
838 src: OpTy<'tcx, M::PointerTag>,
839 dest: PlaceTy<'tcx, M::PointerTag>,
840 ) -> EvalResult<'tcx> {
841 if src.layout.details == dest.layout.details {
842 // Fast path: Just use normal `copy_op`
843 return self.copy_op(src, dest);
845 // We still require the sizes to match
846 debug_assert!(!src.layout.is_unsized() && !dest.layout.is_unsized(),
847 "Cannot copy unsized data");
848 assert!(src.layout.size == dest.layout.size,
849 "Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest);
851 // The hard case is `ScalarPair`. `src` is already read from memory in this case,
852 // using `src.layout` to figure out which bytes to use for the 1st and 2nd field.
853 // We have to write them to `dest` at the offsets they were *read at*, which is
854 // not necessarily the same as the offsets in `dest.layout`!
855 // Hence we do the copy with the source layout on both sides. We also make sure to write
856 // into memory, because if `dest` is a local we would not even have a way to write
857 // at the `src` offsets; the fact that we came from a different layout would
859 let dest = self.force_allocation(dest)?;
860 self.copy_op_no_validate(
862 PlaceTy::from(MPlaceTy { mplace: *dest, layout: src.layout }),
865 if M::enforce_validity(self) {
866 // Data got changed, better make sure it matches the type!
867 self.validate_operand(dest.into(), vec![], None, /*const_mode*/false)?;
873 /// Make sure that a place is in memory, and return where it is.
874 /// If the place currently refers to a local that doesn't yet have a matching allocation,
875 /// create such an allocation.
876 /// This is essentially `force_to_memplace`.
877 pub fn force_allocation(
879 place: PlaceTy<'tcx, M::PointerTag>,
880 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
881 let mplace = match place.place {
882 Place::Local { frame, local } => {
883 match *self.stack[frame].locals[local].access()? {
884 Operand::Indirect(mplace) => mplace,
885 Operand::Immediate(value) => {
886 // We need to make an allocation.
887 // FIXME: Consider not doing anything for a ZST, and just returning
888 // a fake pointer? Are we even called for ZST?
890 // We need the layout of the local. We can NOT use the layout we got,
891 // that might e.g. be an inner field of a struct with `Scalar` layout,
892 // that has different alignment than the outer field.
893 let local_layout = self.layout_of_local(&self.stack[frame], local)?;
894 let ptr = self.allocate(local_layout, MemoryKind::Stack)?;
895 // We don't have to validate as we can assume the local
896 // was already valid for its type.
897 self.write_immediate_to_mplace_no_validate(value, ptr)?;
898 let mplace = ptr.mplace;
900 *self.stack[frame].locals[local].access_mut()? =
901 Operand::Indirect(mplace);
906 Place::Ptr(mplace) => mplace
908 // Return with the original layout, so that the caller can go on
909 Ok(MPlaceTy { mplace, layout: place.layout })
914 layout: TyLayout<'tcx>,
915 kind: MemoryKind<M::MemoryKinds>,
916 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
917 if layout.is_unsized() {
918 assert!(self.tcx.features().unsized_locals, "cannot alloc memory for unsized type");
919 // FIXME: What should we do here? We should definitely also tag!
920 Ok(MPlaceTy::dangling(layout, self))
922 let ptr = self.memory.allocate(layout.size, layout.align.abi, kind)?;
923 let ptr = M::tag_new_allocation(self, ptr, kind)?;
924 Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
928 pub fn write_discriminant_index(
930 variant_index: VariantIdx,
931 dest: PlaceTy<'tcx, M::PointerTag>,
932 ) -> EvalResult<'tcx> {
933 match dest.layout.variants {
934 layout::Variants::Single { index } => {
935 assert_eq!(index, variant_index);
937 layout::Variants::Tagged { ref tag, .. } => {
938 let adt_def = dest.layout.ty.ty_adt_def().unwrap();
939 assert!(variant_index.as_usize() < adt_def.variants.len());
940 let discr_val = adt_def
941 .discriminant_for_variant(*self.tcx, variant_index)
944 // raw discriminants for enums are isize or bigger during
945 // their computation, but the in-memory tag is the smallest possible
947 let size = tag.value.size(self);
948 let shift = 128 - size.bits();
949 let discr_val = (discr_val << shift) >> shift;
951 let discr_dest = self.place_field(dest, 0)?;
952 self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?;
954 layout::Variants::NicheFilling {
961 variant_index.as_usize() < dest.layout.ty.ty_adt_def().unwrap().variants.len(),
963 if variant_index != dataful_variant {
965 self.place_field(dest, 0)?;
966 let niche_value = variant_index.as_u32() - niche_variants.start().as_u32();
967 let niche_value = (niche_value as u128)
968 .wrapping_add(niche_start);
970 Scalar::from_uint(niche_value, niche_dest.layout.size),
980 /// Every place can be read from, so we can turm them into an operand
984 place: PlaceTy<'tcx, M::PointerTag>
985 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
986 let op = match place.place {
987 Place::Ptr(mplace) => {
988 Operand::Indirect(mplace)
990 Place::Local { frame, local } =>
991 *self.stack[frame].locals[local].access()?
993 Ok(OpTy { op, layout: place.layout })
996 pub fn raw_const_to_mplace(
999 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
1000 // This must be an allocation in `tcx`
1001 assert!(self.tcx.alloc_map.lock().get(raw.alloc_id).is_some());
1002 let layout = self.layout_of(raw.ty)?;
1003 Ok(MPlaceTy::from_aligned_ptr(
1004 Pointer::new(raw.alloc_id, Size::ZERO).with_default_tag(),
1009 /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.
1010 /// Also return some more information so drop doesn't have to run the same code twice.
1011 pub(super) fn unpack_dyn_trait(&self, mplace: MPlaceTy<'tcx, M::PointerTag>)
1012 -> EvalResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> {
1013 let vtable = mplace.vtable()?; // also sanity checks the type
1014 let (instance, ty) = self.read_drop_type_from_vtable(vtable)?;
1015 let layout = self.layout_of(ty)?;
1017 // More sanity checks
1018 if cfg!(debug_assertions) {
1019 let (size, align) = self.read_size_and_align_from_vtable(vtable)?;
1020 assert_eq!(size, layout.size);
1021 // only ABI alignment is preserved
1022 assert_eq!(align, layout.align.abi);
1025 let mplace = MPlaceTy {
1026 mplace: MemPlace { meta: None, ..*mplace },
1029 Ok((instance, mplace))