1 //! Functions concerning immediate values and operands, and reading from operands.
2 //! All high-level functions to read from memory work on operands as sources.
4 use std::convert::TryInto;
7 use rustc::ty::layout::{
8 self, Size, LayoutOf, TyLayout, HasDataLayout, IntegerExt, VariantIdx,
11 use rustc::mir::interpret::{
13 ConstValue, Pointer, Scalar,
14 InterpResult, sign_extend, truncate,
18 MemPlace, MPlaceTy, PlaceTy, Place,
20 pub use rustc::mir::interpret::ScalarMaybeUndef;
22 /// A `Value` represents a single immediate self-contained Rust value.
24 /// For optimization of a few very common cases, there is also a representation for a pair of
25 /// primitive values (`ScalarPair`). It allows Miri to avoid making allocations for checked binary
26 /// operations and fat pointers. This idea was taken from rustc's codegen.
27 /// In particular, thanks to `ScalarPair`, arithmetic operations and casts can be entirely
28 /// defined on `Immediate`, and do not have to work with a `Place`.
29 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
30 pub enum Immediate<Tag=(), Id=AllocId> {
31 Scalar(ScalarMaybeUndef<Tag, Id>),
32 ScalarPair(ScalarMaybeUndef<Tag, Id>, ScalarMaybeUndef<Tag, Id>),
35 impl<Tag> From<ScalarMaybeUndef<Tag>> for Immediate<Tag> {
37 fn from(val: ScalarMaybeUndef<Tag>) -> Self {
38 Immediate::Scalar(val)
42 impl<Tag> From<Scalar<Tag>> for Immediate<Tag> {
44 fn from(val: Scalar<Tag>) -> Self {
45 Immediate::Scalar(val.into())
49 impl<'tcx, Tag> Immediate<Tag> {
53 cx: &impl HasDataLayout
55 Immediate::ScalarPair(
57 Scalar::from_uint(len, cx.data_layout().pointer_size).into(),
61 pub fn new_dyn_trait(val: Scalar<Tag>, vtable: Pointer<Tag>) -> Self {
62 Immediate::ScalarPair(val.into(), Scalar::Ptr(vtable).into())
66 pub fn to_scalar_or_undef(self) -> ScalarMaybeUndef<Tag> {
68 Immediate::Scalar(val) => val,
69 Immediate::ScalarPair(..) => bug!("Got a fat pointer where a scalar was expected"),
74 pub fn to_scalar(self) -> InterpResult<'tcx, Scalar<Tag>> {
75 self.to_scalar_or_undef().not_undef()
79 pub fn to_scalar_pair(self) -> InterpResult<'tcx, (Scalar<Tag>, Scalar<Tag>)> {
81 Immediate::Scalar(..) => bug!("Got a thin pointer where a scalar pair was expected"),
82 Immediate::ScalarPair(a, b) => Ok((a.not_undef()?, b.not_undef()?))
86 /// Converts the immediate into a pointer (or a pointer-sized integer).
87 /// Throws away the second half of a ScalarPair!
89 pub fn to_scalar_ptr(self) -> InterpResult<'tcx, Scalar<Tag>> {
91 Immediate::Scalar(ptr) |
92 Immediate::ScalarPair(ptr, _) => ptr.not_undef(),
96 /// Converts the value into its metadata.
97 /// Throws away the first half of a ScalarPair!
99 pub fn to_meta(self) -> InterpResult<'tcx, Option<Scalar<Tag>>> {
101 Immediate::Scalar(_) => None,
102 Immediate::ScalarPair(_, meta) => Some(meta.not_undef()?),
107 // ScalarPair needs a type to interpret, so we often have an immediate and a type together
108 // as input for binary and cast operations.
109 #[derive(Copy, Clone, Debug)]
110 pub struct ImmTy<'tcx, Tag=()> {
111 pub(crate) imm: Immediate<Tag>,
112 pub layout: TyLayout<'tcx>,
115 impl<'tcx, Tag> ::std::ops::Deref for ImmTy<'tcx, Tag> {
116 type Target = Immediate<Tag>;
118 fn deref(&self) -> &Immediate<Tag> {
123 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
124 /// or still in memory. The latter is an optimization, to delay reading that chunk of
125 /// memory and to avoid having to store arbitrary-sized data here.
126 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
127 pub enum Operand<Tag=(), Id=AllocId> {
128 Immediate(Immediate<Tag, Id>),
129 Indirect(MemPlace<Tag, Id>),
132 impl<Tag> Operand<Tag> {
134 pub fn assert_mem_place(self) -> MemPlace<Tag>
135 where Tag: ::std::fmt::Debug
138 Operand::Indirect(mplace) => mplace,
139 _ => bug!("assert_mem_place: expected Operand::Indirect, got {:?}", self),
145 pub fn assert_immediate(self) -> Immediate<Tag>
146 where Tag: ::std::fmt::Debug
149 Operand::Immediate(imm) => imm,
150 _ => bug!("assert_immediate: expected Operand::Immediate, got {:?}", self),
156 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
157 pub struct OpTy<'tcx, Tag=()> {
158 op: Operand<Tag>, // Keep this private, it helps enforce invariants
159 pub layout: TyLayout<'tcx>,
162 impl<'tcx, Tag> ::std::ops::Deref for OpTy<'tcx, Tag> {
163 type Target = Operand<Tag>;
165 fn deref(&self) -> &Operand<Tag> {
170 impl<'tcx, Tag: Copy> From<MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
172 fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
174 op: Operand::Indirect(*mplace),
175 layout: mplace.layout
180 impl<'tcx, Tag> From<ImmTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
182 fn from(val: ImmTy<'tcx, Tag>) -> Self {
184 op: Operand::Immediate(val.imm),
190 impl<'tcx, Tag: Copy> ImmTy<'tcx, Tag> {
192 pub fn from_scalar(val: Scalar<Tag>, layout: TyLayout<'tcx>) -> Self {
193 ImmTy { imm: val.into(), layout }
197 pub fn from_uint(i: impl Into<u128>, layout: TyLayout<'tcx>) -> Self {
198 Self::from_scalar(Scalar::from_uint(i, layout.size), layout)
202 pub fn from_int(i: impl Into<i128>, layout: TyLayout<'tcx>) -> Self {
203 Self::from_scalar(Scalar::from_int(i, layout.size), layout)
207 pub fn to_bits(self) -> InterpResult<'tcx, u128> {
208 self.to_scalar()?.to_bits(self.layout.size)
212 // Use the existing layout if given (but sanity check in debug mode),
213 // or compute the layout.
215 pub(super) fn from_known_layout<'tcx>(
216 layout: Option<TyLayout<'tcx>>,
217 compute: impl FnOnce() -> InterpResult<'tcx, TyLayout<'tcx>>
218 ) -> InterpResult<'tcx, TyLayout<'tcx>> {
222 if cfg!(debug_assertions) {
223 let layout2 = compute()?;
224 assert_eq!(layout.details, layout2.details,
225 "Mismatch in layout of supposedly equal-layout types {:?} and {:?}",
226 layout.ty, layout2.ty);
233 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
234 /// Normalice `place.ptr` to a `Pointer` if this is a place and not a ZST.
235 /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
239 op: OpTy<'tcx, M::PointerTag>,
240 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
241 match op.try_as_mplace() {
242 Ok(mplace) => Ok(self.force_mplace_ptr(mplace)?.into()),
243 Err(imm) => Ok(imm.into()), // Nothing to cast/force
247 /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`.
248 /// Returns `None` if the layout does not permit loading this as a value.
249 fn try_read_immediate_from_mplace(
251 mplace: MPlaceTy<'tcx, M::PointerTag>,
252 ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::PointerTag>>> {
253 if mplace.layout.is_unsized() {
254 // Don't touch unsized
258 let ptr = match self.check_mplace_access(mplace, None)
259 .expect("places should be checked on creation")
262 None => return Ok(Some(ImmTy { // zero-sized type
263 imm: Scalar::zst().into(),
264 layout: mplace.layout,
268 match mplace.layout.abi {
269 layout::Abi::Scalar(..) => {
270 let scalar = self.memory
272 .read_scalar(self, ptr, mplace.layout.size)?;
275 layout: mplace.layout,
278 layout::Abi::ScalarPair(ref a, ref b) => {
279 // We checked `ptr_align` above, so all fields will have the alignment they need.
280 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
281 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
282 let (a, b) = (&a.value, &b.value);
283 let (a_size, b_size) = (a.size(self), b.size(self));
285 let b_offset = a_size.align_to(b.align(self).abi);
286 assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields
287 let b_ptr = ptr.offset(b_offset, self)?;
288 let a_val = self.memory
290 .read_scalar(self, a_ptr, a_size)?;
291 let b_val = self.memory
293 .read_scalar(self, b_ptr, b_size)?;
295 imm: Immediate::ScalarPair(a_val, b_val),
296 layout: mplace.layout,
303 /// Try returning an immediate for the operand.
304 /// If the layout does not permit loading this as an immediate, return where in memory
305 /// we can find the data.
306 /// Note that for a given layout, this operation will either always fail or always
307 /// succeed! Whether it succeeds depends on whether the layout can be represented
308 /// in a `Immediate`, not on which data is stored there currently.
309 pub(crate) fn try_read_immediate(
311 src: OpTy<'tcx, M::PointerTag>,
312 ) -> InterpResult<'tcx, Result<ImmTy<'tcx, M::PointerTag>, MPlaceTy<'tcx, M::PointerTag>>> {
313 Ok(match src.try_as_mplace() {
315 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
325 /// Read an immediate from a place, asserting that that is possible with the given layout.
327 pub fn read_immediate(
329 op: OpTy<'tcx, M::PointerTag>
330 ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
331 if let Ok(imm) = self.try_read_immediate(op)? {
334 bug!("primitive read failed for type: {:?}", op.layout.ty);
338 /// Read a scalar from a place
341 op: OpTy<'tcx, M::PointerTag>
342 ) -> InterpResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
343 Ok(self.read_immediate(op)?.to_scalar_or_undef())
346 // Turn the MPlace into a string (must already be dereferenced!)
349 mplace: MPlaceTy<'tcx, M::PointerTag>,
350 ) -> InterpResult<'tcx, &str> {
351 let len = mplace.len(self)?;
352 let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?;
353 let str = ::std::str::from_utf8(bytes).map_err(|err| {
354 err_unsup!(ValidationFailure(err.to_string()))
359 /// Projection functions
360 pub fn operand_field(
362 op: OpTy<'tcx, M::PointerTag>,
364 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
365 let base = match op.try_as_mplace() {
368 let field = self.mplace_field(mplace, field)?;
369 return Ok(field.into());
374 let field = field.try_into().unwrap();
375 let field_layout = op.layout.field(self, field)?;
376 if field_layout.is_zst() {
377 let immediate = Scalar::zst().into();
378 return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
380 let offset = op.layout.fields.offset(field);
381 let immediate = match *base {
382 // the field covers the entire type
383 _ if offset.bytes() == 0 && field_layout.size == op.layout.size => *base,
384 // extract fields from types with `ScalarPair` ABI
385 Immediate::ScalarPair(a, b) => {
386 let val = if offset.bytes() == 0 { a } else { b };
389 Immediate::Scalar(val) =>
390 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
392 Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
395 pub fn operand_downcast(
397 op: OpTy<'tcx, M::PointerTag>,
399 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
400 // Downcasts only change the layout
401 Ok(match op.try_as_mplace() {
403 self.mplace_downcast(mplace, variant)?.into()
406 let layout = op.layout.for_variant(self, variant);
407 OpTy { layout, ..op }
412 pub fn operand_projection(
414 base: OpTy<'tcx, M::PointerTag>,
415 proj_elem: &mir::PlaceElem<'tcx>,
416 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
417 use rustc::mir::ProjectionElem::*;
418 Ok(match *proj_elem {
419 Field(field, _) => self.operand_field(base, field.index() as u64)?,
420 Downcast(_, variant) => self.operand_downcast(base, variant)?,
421 Deref => self.deref_operand(base)?.into(),
422 Subslice { .. } | ConstantIndex { .. } | Index(_) => if base.layout.is_zst() {
424 op: Operand::Immediate(Scalar::zst().into()),
425 // the actual index doesn't matter, so we just pick a convenient one like 0
426 layout: base.layout.field(self, 0)?,
429 // The rest should only occur as mplace, we do not use Immediates for types
430 // allowing such operations. This matches place_projection forcing an allocation.
431 let mplace = base.assert_mem_place();
432 self.mplace_projection(mplace, proj_elem)?.into()
437 /// This is used by [priroda](https://github.com/oli-obk/priroda) to get an OpTy from a local
440 frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
442 layout: Option<TyLayout<'tcx>>,
443 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
444 assert_ne!(local, mir::RETURN_PLACE);
445 let layout = self.layout_of_local(frame, local, layout)?;
446 let op = if layout.is_zst() {
447 // Do not read from ZST, they might not be initialized
448 Operand::Immediate(Scalar::zst().into())
450 frame.locals[local].access()?
452 Ok(OpTy { op, layout })
455 /// Every place can be read from, so we can turn them into an operand
459 place: PlaceTy<'tcx, M::PointerTag>
460 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
461 let op = match *place {
462 Place::Ptr(mplace) => {
463 Operand::Indirect(mplace)
465 Place::Local { frame, local } =>
466 *self.access_local(&self.stack[frame], local, None)?
468 Ok(OpTy { op, layout: place.layout })
471 // Evaluate a place with the goal of reading from it. This lets us sometimes
472 // avoid allocations.
473 pub(super) fn eval_place_to_op(
475 mir_place: &mir::Place<'tcx>,
476 layout: Option<TyLayout<'tcx>>,
477 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
478 use rustc::mir::PlaceBase;
480 mir_place.iterate(|place_base, place_projection| {
481 let mut op = match place_base {
482 PlaceBase::Local(mir::RETURN_PLACE) =>
483 throw_unsup!(ReadFromReturnPointer),
484 PlaceBase::Local(local) => {
485 // Do not use the layout passed in as argument if the base we are looking at
486 // here is not the entire place.
487 // FIXME use place_projection.is_empty() when is available
488 let layout = if mir_place.projection.is_none() {
494 self.access_local(self.frame(), *local, layout)?
496 PlaceBase::Static(place_static) => {
497 self.eval_static_to_mplace(place_static)?.into()
501 for proj in place_projection {
502 op = self.operand_projection(op, &proj.elem)?
505 trace!("eval_place_to_op: got {:?}", *op);
510 /// Evaluate the operand, returning a place where you can then find the data.
511 /// If you already know the layout, you can save two table lookups
512 /// by passing it in here.
515 mir_op: &mir::Operand<'tcx>,
516 layout: Option<TyLayout<'tcx>>,
517 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
518 use rustc::mir::Operand::*;
519 let op = match *mir_op {
520 // FIXME: do some more logic on `move` to invalidate the old location
523 self.eval_place_to_op(place, layout)?,
525 Constant(ref constant) => self.eval_const_to_op(constant.literal, layout)?,
527 trace!("{:?}: {:?}", mir_op, *op);
531 /// Evaluate a bunch of operands at once
532 pub(super) fn eval_operands(
534 ops: &[mir::Operand<'tcx>],
535 ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
537 .map(|op| self.eval_operand(op, None))
541 // Used when the miri-engine runs into a constant and for extracting information from constants
542 // in patterns via the `const_eval` module
543 crate fn eval_const_to_op(
545 val: &'tcx ty::Const<'tcx>,
546 layout: Option<TyLayout<'tcx>>,
547 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
548 let tag_scalar = |scalar| match scalar {
549 Scalar::Ptr(ptr) => Scalar::Ptr(self.tag_static_base_pointer(ptr)),
550 Scalar::Raw { data, size } => Scalar::Raw { data, size },
552 // Early-return cases.
554 ConstValue::Param(_) =>
555 // FIXME(oli-obk): try to monomorphize
556 throw_inval!(TooGeneric),
557 ConstValue::Unevaluated(def_id, substs) => {
558 let instance = self.resolve(def_id, substs)?;
559 return Ok(OpTy::from(self.const_eval_raw(GlobalId {
566 // Other cases need layout.
567 let layout = from_known_layout(layout, || {
568 self.layout_of(self.monomorphize(val.ty)?)
570 let op = match val.val {
571 ConstValue::ByRef { alloc, offset } => {
572 let id = self.tcx.alloc_map.lock().create_memory_alloc(alloc);
573 // We rely on mutability being set correctly in that allocation to prevent writes
574 // where none should happen.
575 let ptr = self.tag_static_base_pointer(Pointer::new(id, offset));
576 Operand::Indirect(MemPlace::from_ptr(ptr, layout.align.abi))
578 ConstValue::Scalar(x) =>
579 Operand::Immediate(tag_scalar(x).into()),
580 ConstValue::Slice { data, start, end } => {
581 // We rely on mutability being set correctly in `data` to prevent writes
582 // where none should happen.
583 let ptr = Pointer::new(
584 self.tcx.alloc_map.lock().create_memory_alloc(data),
585 Size::from_bytes(start as u64), // offset: `start`
587 Operand::Immediate(Immediate::new_slice(
588 self.tag_static_base_pointer(ptr).into(),
589 (end - start) as u64, // len: `end - start`
593 ConstValue::Param(..) |
594 ConstValue::Infer(..) |
595 ConstValue::Placeholder(..) |
596 ConstValue::Unevaluated(..) =>
597 bug!("eval_const_to_op: Unexpected ConstValue {:?}", val),
599 Ok(OpTy { op, layout })
602 /// Read discriminant, return the runtime value as well as the variant index.
603 pub fn read_discriminant(
605 rval: OpTy<'tcx, M::PointerTag>,
606 ) -> InterpResult<'tcx, (u128, VariantIdx)> {
607 trace!("read_discriminant_value {:#?}", rval.layout);
609 let (discr_kind, discr_index) = match rval.layout.variants {
610 layout::Variants::Single { index } => {
611 let discr_val = rval.layout.ty.discriminant_for_variant(*self.tcx, index).map_or(
612 index.as_u32() as u128,
614 return Ok((discr_val, index));
616 layout::Variants::Multiple { ref discr_kind, discr_index, .. } =>
617 (discr_kind, discr_index),
620 // read raw discriminant value
621 let discr_op = self.operand_field(rval, discr_index as u64)?;
622 let discr_val = self.read_immediate(discr_op)?;
623 let raw_discr = discr_val.to_scalar_or_undef();
624 trace!("discr value: {:?}", raw_discr);
626 Ok(match *discr_kind {
627 layout::DiscriminantKind::Tag => {
628 let bits_discr = match raw_discr.to_bits(discr_val.layout.size) {
629 Ok(raw_discr) => raw_discr,
631 throw_unsup!(InvalidDiscriminant(raw_discr.erase_tag())),
633 let real_discr = if discr_val.layout.ty.is_signed() {
634 // going from layout tag type to typeck discriminant type
635 // requires first sign extending with the layout discriminant
636 let sexted = sign_extend(bits_discr, discr_val.layout.size) as i128;
637 // and then zeroing with the typeck discriminant type
638 let discr_ty = rval.layout.ty
639 .ty_adt_def().expect("tagged layout corresponds to adt")
642 let size = layout::Integer::from_attr(self, discr_ty).size();
643 let truncatee = sexted as u128;
644 truncate(truncatee, size)
648 // Make sure we catch invalid discriminants
649 let index = match &rval.layout.ty.sty {
650 ty::Adt(adt, _) => adt
651 .discriminants(self.tcx.tcx)
652 .find(|(_, var)| var.val == real_discr),
653 ty::Generator(def_id, substs, _) => substs
654 .discriminants(*def_id, self.tcx.tcx)
655 .find(|(_, var)| var.val == real_discr),
656 _ => bug!("tagged layout for non-adt non-generator"),
658 || err_unsup!(InvalidDiscriminant(raw_discr.erase_tag()))
660 (real_discr, index.0)
662 layout::DiscriminantKind::Niche {
667 let variants_start = niche_variants.start().as_u32() as u128;
668 let variants_end = niche_variants.end().as_u32() as u128;
669 let raw_discr = raw_discr.not_undef().map_err(|_| {
670 err_unsup!(InvalidDiscriminant(ScalarMaybeUndef::Undef))
672 match raw_discr.to_bits_or_ptr(discr_val.layout.size, self) {
674 // The niche must be just 0 (which an inbounds pointer value never is)
675 let ptr_valid = niche_start == 0 && variants_start == variants_end &&
676 !self.memory.ptr_may_be_null(ptr);
678 throw_unsup!(InvalidDiscriminant(raw_discr.erase_tag().into()))
680 (dataful_variant.as_u32() as u128, dataful_variant)
683 let adjusted_discr = raw_discr.wrapping_sub(niche_start)
684 .wrapping_add(variants_start);
685 if variants_start <= adjusted_discr && adjusted_discr <= variants_end {
686 let index = adjusted_discr as usize;
687 assert_eq!(index as u128, adjusted_discr);
688 assert!(index < rval.layout.ty
690 .expect("tagged layout for non adt")
692 (adjusted_discr, VariantIdx::from_usize(index))
694 (dataful_variant.as_u32() as u128, dataful_variant)