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 //! Functions concerning immediate values and operands, and reading from operands.
12 //! All high-level functions to read from memory work on operands as sources.
14 use std::convert::TryInto;
17 use rustc::ty::layout::{self, Size, LayoutOf, TyLayout, HasDataLayout, IntegerExt, VariantIdx};
19 use rustc::mir::interpret::{
21 ConstValue, Pointer, Scalar,
22 EvalResult, EvalErrorKind, InboundsCheck,
24 use super::{EvalContext, Machine, MemPlace, MPlaceTy, MemoryKind};
25 pub use rustc::mir::interpret::ScalarMaybeUndef;
27 /// A `Value` represents a single immediate self-contained Rust value.
29 /// For optimization of a few very common cases, there is also a representation for a pair of
30 /// primitive values (`ScalarPair`). It allows Miri to avoid making allocations for checked binary
31 /// operations and fat pointers. This idea was taken from rustc's codegen.
32 /// In particular, thanks to `ScalarPair`, arithmetic operations and casts can be entirely
33 /// defined on `Immediate`, and do not have to work with a `Place`.
34 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
35 pub enum Immediate<Tag=(), Id=AllocId> {
36 Scalar(ScalarMaybeUndef<Tag, Id>),
37 ScalarPair(ScalarMaybeUndef<Tag, Id>, ScalarMaybeUndef<Tag, Id>),
42 pub fn with_default_tag<Tag>(self) -> Immediate<Tag>
46 Immediate::Scalar(x) => Immediate::Scalar(x.with_default_tag()),
47 Immediate::ScalarPair(x, y) =>
48 Immediate::ScalarPair(x.with_default_tag(), y.with_default_tag()),
53 impl<'tcx, Tag> Immediate<Tag> {
55 pub fn erase_tag(self) -> Immediate
58 Immediate::Scalar(x) => Immediate::Scalar(x.erase_tag()),
59 Immediate::ScalarPair(x, y) =>
60 Immediate::ScalarPair(x.erase_tag(), y.erase_tag()),
67 cx: &impl HasDataLayout
69 Immediate::ScalarPair(
71 Scalar::from_uint(len, cx.data_layout().pointer_size).into(),
75 pub fn new_dyn_trait(val: Scalar<Tag>, vtable: Pointer<Tag>) -> Self {
76 Immediate::ScalarPair(val.into(), Scalar::Ptr(vtable).into())
80 pub fn to_scalar_or_undef(self) -> ScalarMaybeUndef<Tag> {
82 Immediate::Scalar(val) => val,
83 Immediate::ScalarPair(..) => bug!("Got a fat pointer where a scalar was expected"),
88 pub fn to_scalar(self) -> EvalResult<'tcx, Scalar<Tag>> {
89 self.to_scalar_or_undef().not_undef()
93 pub fn to_scalar_pair(self) -> EvalResult<'tcx, (Scalar<Tag>, Scalar<Tag>)> {
95 Immediate::Scalar(..) => bug!("Got a thin pointer where a scalar pair was expected"),
96 Immediate::ScalarPair(a, b) => Ok((a.not_undef()?, b.not_undef()?))
100 /// Convert the immediate into a pointer (or a pointer-sized integer).
101 /// Throws away the second half of a ScalarPair!
103 pub fn to_scalar_ptr(self) -> EvalResult<'tcx, Scalar<Tag>> {
105 Immediate::Scalar(ptr) |
106 Immediate::ScalarPair(ptr, _) => ptr.not_undef(),
110 /// Convert the value into its metadata.
111 /// Throws away the first half of a ScalarPair!
113 pub fn to_meta(self) -> EvalResult<'tcx, Option<Scalar<Tag>>> {
115 Immediate::Scalar(_) => None,
116 Immediate::ScalarPair(_, meta) => Some(meta.not_undef()?),
121 // ScalarPair needs a type to interpret, so we often have an immediate and a type together
122 // as input for binary and cast operations.
123 #[derive(Copy, Clone, Debug)]
124 pub struct ImmTy<'tcx, Tag=()> {
125 immediate: Immediate<Tag>,
126 pub layout: TyLayout<'tcx>,
129 impl<'tcx, Tag> ::std::ops::Deref for ImmTy<'tcx, Tag> {
130 type Target = Immediate<Tag>;
132 fn deref(&self) -> &Immediate<Tag> {
137 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
138 /// or still in memory. The latter is an optimization, to delay reading that chunk of
139 /// memory and to avoid having to store arbitrary-sized data here.
140 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
141 pub enum Operand<Tag=(), Id=AllocId> {
142 Immediate(Immediate<Tag, Id>),
143 Indirect(MemPlace<Tag, Id>),
148 pub fn with_default_tag<Tag>(self) -> Operand<Tag>
152 Operand::Immediate(x) => Operand::Immediate(x.with_default_tag()),
153 Operand::Indirect(x) => Operand::Indirect(x.with_default_tag()),
158 impl<Tag> Operand<Tag> {
160 pub fn erase_tag(self) -> Operand
163 Operand::Immediate(x) => Operand::Immediate(x.erase_tag()),
164 Operand::Indirect(x) => Operand::Indirect(x.erase_tag()),
169 pub fn to_mem_place(self) -> MemPlace<Tag>
170 where Tag: ::std::fmt::Debug
173 Operand::Indirect(mplace) => mplace,
174 _ => bug!("to_mem_place: expected Operand::Indirect, got {:?}", self),
180 pub fn to_immediate(self) -> Immediate<Tag>
181 where Tag: ::std::fmt::Debug
184 Operand::Immediate(imm) => imm,
185 _ => bug!("to_immediate: expected Operand::Immediate, got {:?}", self),
191 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
192 pub struct OpTy<'tcx, Tag=()> {
193 crate op: Operand<Tag>, // ideally we'd make this private, but const_prop needs this
194 pub layout: TyLayout<'tcx>,
197 impl<'tcx, Tag> ::std::ops::Deref for OpTy<'tcx, Tag> {
198 type Target = Operand<Tag>;
200 fn deref(&self) -> &Operand<Tag> {
205 impl<'tcx, Tag: Copy> From<MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
207 fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self {
209 op: Operand::Indirect(*mplace),
210 layout: mplace.layout
215 impl<'tcx, Tag> From<ImmTy<'tcx, Tag>> for OpTy<'tcx, Tag> {
217 fn from(val: ImmTy<'tcx, Tag>) -> Self {
219 op: Operand::Immediate(val.immediate),
225 impl<'tcx, Tag> OpTy<'tcx, Tag>
228 pub fn erase_tag(self) -> OpTy<'tcx>
231 op: self.op.erase_tag(),
237 // Use the existing layout if given (but sanity check in debug mode),
238 // or compute the layout.
240 fn from_known_layout<'tcx>(
241 layout: Option<TyLayout<'tcx>>,
242 compute: impl FnOnce() -> EvalResult<'tcx, TyLayout<'tcx>>
243 ) -> EvalResult<'tcx, TyLayout<'tcx>> {
247 if cfg!(debug_assertions) {
248 let layout2 = compute()?;
249 assert_eq!(layout.details, layout2.details,
250 "Mismatch in layout of supposedly equal-layout types {:?} and {:?}",
251 layout.ty, layout2.ty);
258 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
259 /// Try reading an immediate in memory; this is interesting particularly for ScalarPair.
260 /// Return None if the layout does not permit loading this as a value.
261 pub(super) fn try_read_immediate_from_mplace(
263 mplace: MPlaceTy<'tcx, M::PointerTag>,
264 ) -> EvalResult<'tcx, Option<Immediate<M::PointerTag>>> {
265 if mplace.layout.is_unsized() {
266 // Don't touch unsized
269 let (ptr, ptr_align) = mplace.to_scalar_ptr_align();
271 if mplace.layout.is_zst() {
272 // Not all ZSTs have a layout we would handle below, so just short-circuit them
274 self.memory.check_align(ptr, ptr_align)?;
275 return Ok(Some(Immediate::Scalar(Scalar::zst().into())));
278 let ptr = ptr.to_ptr()?;
279 match mplace.layout.abi {
280 layout::Abi::Scalar(..) => {
281 let scalar = self.memory.read_scalar(ptr, ptr_align, mplace.layout.size)?;
282 Ok(Some(Immediate::Scalar(scalar)))
284 layout::Abi::ScalarPair(ref a, ref b) => {
285 let (a, b) = (&a.value, &b.value);
286 let (a_size, b_size) = (a.size(self), b.size(self));
288 let b_offset = a_size.abi_align(b.align(self));
289 assert!(b_offset.bytes() > 0); // we later use the offset to test which field to use
290 let b_ptr = ptr.offset(b_offset, self)?.into();
291 let a_val = self.memory.read_scalar(a_ptr, ptr_align, a_size)?;
292 let b_val = self.memory.read_scalar(b_ptr, ptr_align, b_size)?;
293 Ok(Some(Immediate::ScalarPair(a_val, b_val)))
299 /// Try returning an immediate for the operand.
300 /// If the layout does not permit loading this as an immediate, return where in memory
301 /// we can find the data.
302 /// Note that for a given layout, this operation will either always fail or always
303 /// succeed! Whether it succeeds depends on whether the layout can be represented
304 /// in a `Immediate`, not on which data is stored there currently.
305 pub(crate) fn try_read_immediate(
307 src: OpTy<'tcx, M::PointerTag>,
308 ) -> EvalResult<'tcx, Result<Immediate<M::PointerTag>, MemPlace<M::PointerTag>>> {
309 Ok(match src.try_as_mplace() {
311 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
321 /// Read an immediate from a place, asserting that that is possible with the given layout.
323 pub fn read_immediate(
325 op: OpTy<'tcx, M::PointerTag>
326 ) -> EvalResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
327 if let Ok(immediate) = self.try_read_immediate(op)? {
328 Ok(ImmTy { immediate, layout: op.layout })
330 bug!("primitive read failed for type: {:?}", op.layout.ty);
334 /// Read a scalar from a place
337 op: OpTy<'tcx, M::PointerTag>
338 ) -> EvalResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
339 Ok(self.read_immediate(op)?.to_scalar_or_undef())
342 // Turn the MPlace into a string (must already be dereferenced!)
345 mplace: MPlaceTy<'tcx, M::PointerTag>,
346 ) -> EvalResult<'tcx, &str> {
347 let len = mplace.len(self)?;
348 let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?;
349 let str = ::std::str::from_utf8(bytes)
350 .map_err(|err| EvalErrorKind::ValidationFailure(err.to_string()))?;
354 pub fn uninit_operand(
356 layout: TyLayout<'tcx>
357 ) -> EvalResult<'tcx, Operand<M::PointerTag>> {
358 // This decides which types we will use the Immediate optimization for, and hence should
359 // match what `try_read_immediate` and `eval_place_to_op` support.
361 return Ok(Operand::Immediate(Immediate::Scalar(Scalar::zst().into())));
364 Ok(match layout.abi {
365 layout::Abi::Scalar(..) =>
366 Operand::Immediate(Immediate::Scalar(ScalarMaybeUndef::Undef)),
367 layout::Abi::ScalarPair(..) =>
368 Operand::Immediate(Immediate::ScalarPair(
369 ScalarMaybeUndef::Undef,
370 ScalarMaybeUndef::Undef,
373 trace!("Forcing allocation for local of type {:?}", layout.ty);
375 *self.allocate(layout, MemoryKind::Stack)?
381 /// Projection functions
382 pub fn operand_field(
384 op: OpTy<'tcx, M::PointerTag>,
386 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
387 let base = match op.try_as_mplace() {
390 let field = self.mplace_field(mplace, field)?;
391 return Ok(field.into());
396 let field = field.try_into().unwrap();
397 let field_layout = op.layout.field(self, field)?;
398 if field_layout.is_zst() {
399 let immediate = Immediate::Scalar(Scalar::zst().into());
400 return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
402 let offset = op.layout.fields.offset(field);
403 let immediate = match base {
404 // the field covers the entire type
405 _ if offset.bytes() == 0 && field_layout.size == op.layout.size => base,
406 // extract fields from types with `ScalarPair` ABI
407 Immediate::ScalarPair(a, b) => {
408 let val = if offset.bytes() == 0 { a } else { b };
409 Immediate::Scalar(val)
411 Immediate::Scalar(val) =>
412 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
414 Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
417 pub fn operand_downcast(
419 op: OpTy<'tcx, M::PointerTag>,
421 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
422 // Downcasts only change the layout
423 Ok(match op.try_as_mplace() {
425 self.mplace_downcast(mplace, variant)?.into()
428 let layout = op.layout.for_variant(self, variant);
429 OpTy { layout, ..op }
434 pub fn operand_projection(
436 base: OpTy<'tcx, M::PointerTag>,
437 proj_elem: &mir::PlaceElem<'tcx>,
438 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
439 use rustc::mir::ProjectionElem::*;
440 Ok(match *proj_elem {
441 Field(field, _) => self.operand_field(base, field.index() as u64)?,
442 Downcast(_, variant) => self.operand_downcast(base, variant)?,
443 Deref => self.deref_operand(base)?.into(),
444 Subslice { .. } | ConstantIndex { .. } | Index(_) => if base.layout.is_zst() {
446 op: Operand::Immediate(Immediate::Scalar(Scalar::zst().into())),
447 // the actual index doesn't matter, so we just pick a convenient one like 0
448 layout: base.layout.field(self, 0)?,
451 // The rest should only occur as mplace, we do not use Immediates for types
452 // allowing such operations. This matches place_projection forcing an allocation.
453 let mplace = base.to_mem_place();
454 self.mplace_projection(mplace, proj_elem)?.into()
459 /// This is used by [priroda](https://github.com/oli-obk/priroda) to get an OpTy from a local
461 /// When you know the layout of the local in advance, you can pass it as last argument
464 frame: &super::Frame<'mir, 'tcx, M::PointerTag>,
466 layout: Option<TyLayout<'tcx>>,
467 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
468 assert_ne!(local, mir::RETURN_PLACE);
469 let op = *frame.locals[local].access()?;
470 let layout = from_known_layout(layout,
471 || self.layout_of_local(frame, local))?;
472 Ok(OpTy { op, layout })
475 // Evaluate a place with the goal of reading from it. This lets us sometimes
476 // avoid allocations. If you already know the layout, you can pass it in
477 // to avoid looking it up again.
480 mir_place: &mir::Place<'tcx>,
481 layout: Option<TyLayout<'tcx>>,
482 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
483 use rustc::mir::Place::*;
484 let op = match *mir_place {
485 Local(mir::RETURN_PLACE) => return err!(ReadFromReturnPointer),
486 Local(local) => self.access_local(self.frame(), local, layout)?,
488 Projection(ref proj) => {
489 let op = self.eval_place_to_op(&proj.base, None)?;
490 self.operand_projection(op, &proj.elem)?
493 _ => self.eval_place_to_mplace(mir_place)?.into(),
496 trace!("eval_place_to_op: got {:?}", *op);
500 /// Evaluate the operand, returning a place where you can then find the data.
501 /// if you already know the layout, you can save two some table lookups
502 /// by passing it in here.
505 mir_op: &mir::Operand<'tcx>,
506 layout: Option<TyLayout<'tcx>>,
507 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
508 use rustc::mir::Operand::*;
509 let op = match *mir_op {
510 // FIXME: do some more logic on `move` to invalidate the old location
513 self.eval_place_to_op(place, layout)?,
515 Constant(ref constant) => {
516 let layout = from_known_layout(layout, || {
517 let ty = self.monomorphize(mir_op.ty(self.mir(), *self.tcx), self.substs());
520 let op = self.const_value_to_op(constant.literal.val)?;
524 trace!("{:?}: {:?}", mir_op, *op);
528 /// Evaluate a bunch of operands at once
529 pub(super) fn eval_operands(
531 ops: &[mir::Operand<'tcx>],
532 ) -> EvalResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
534 .map(|op| self.eval_operand(op, None))
538 // Also used e.g. when miri runs into a constant.
539 pub(super) fn const_value_to_op(
541 val: ConstValue<'tcx>,
542 ) -> EvalResult<'tcx, Operand<M::PointerTag>> {
543 trace!("const_value_to_op: {:?}", val);
545 ConstValue::Unevaluated(def_id, substs) => {
546 let instance = self.resolve(def_id, substs)?;
547 self.global_to_op(GlobalId {
552 ConstValue::ByRef(id, alloc, offset) => {
553 // We rely on mutability being set correctly in that allocation to prevent writes
554 // where none should happen -- and for `static mut`, we copy on demand anyway.
555 Ok(Operand::Indirect(
556 MemPlace::from_ptr(Pointer::new(id, offset), alloc.align)
557 ).with_default_tag())
559 ConstValue::ScalarPair(a, b) =>
560 Ok(Operand::Immediate(Immediate::ScalarPair(
563 )).with_default_tag()),
564 ConstValue::Scalar(x) =>
565 Ok(Operand::Immediate(Immediate::Scalar(x.into())).with_default_tag()),
570 cnst: &ty::Const<'tcx>,
571 ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>> {
572 let op = self.const_value_to_op(cnst.val)?;
573 Ok(OpTy { op, layout: self.layout_of(cnst.ty)? })
576 pub(super) fn global_to_op(
579 ) -> EvalResult<'tcx, Operand<M::PointerTag>> {
580 let cv = self.const_eval(gid)?;
581 self.const_value_to_op(cv.val)
584 /// Read discriminant, return the runtime value as well as the variant index.
585 pub fn read_discriminant(
587 rval: OpTy<'tcx, M::PointerTag>,
588 ) -> EvalResult<'tcx, (u128, VariantIdx)> {
589 trace!("read_discriminant_value {:#?}", rval.layout);
591 match rval.layout.variants {
592 layout::Variants::Single { index } => {
593 let discr_val = rval.layout.ty.ty_adt_def().map_or(
594 index.as_u32() as u128,
595 |def| def.discriminant_for_variant(*self.tcx, index).val);
596 return Ok((discr_val, index));
598 layout::Variants::Tagged { .. } |
599 layout::Variants::NicheFilling { .. } => {},
601 // read raw discriminant value
602 let discr_op = self.operand_field(rval, 0)?;
603 let discr_val = self.read_immediate(discr_op)?;
604 let raw_discr = discr_val.to_scalar_or_undef();
605 trace!("discr value: {:?}", raw_discr);
607 Ok(match rval.layout.variants {
608 layout::Variants::Single { .. } => bug!(),
609 layout::Variants::Tagged { .. } => {
610 let bits_discr = match raw_discr.to_bits(discr_val.layout.size) {
611 Ok(raw_discr) => raw_discr,
612 Err(_) => return err!(InvalidDiscriminant(raw_discr.erase_tag())),
614 let real_discr = if discr_val.layout.ty.is_signed() {
615 let i = bits_discr as i128;
616 // going from layout tag type to typeck discriminant type
617 // requires first sign extending with the layout discriminant
618 let shift = 128 - discr_val.layout.size.bits();
619 let sexted = (i << shift) >> shift;
620 // and then zeroing with the typeck discriminant type
621 let discr_ty = rval.layout.ty
622 .ty_adt_def().expect("tagged layout corresponds to adt")
625 let discr_ty = layout::Integer::from_attr(self, discr_ty);
626 let shift = 128 - discr_ty.size().bits();
627 let truncatee = sexted as u128;
628 (truncatee << shift) >> shift
632 // Make sure we catch invalid discriminants
633 let index = rval.layout.ty
635 .expect("tagged layout for non adt")
636 .discriminants(self.tcx.tcx)
637 .find(|(_, var)| var.val == real_discr)
638 .ok_or_else(|| EvalErrorKind::InvalidDiscriminant(raw_discr.erase_tag()))?;
639 (real_discr, index.0)
641 layout::Variants::NicheFilling {
647 let variants_start = niche_variants.start().as_u32() as u128;
648 let variants_end = niche_variants.end().as_u32() as u128;
650 ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) => {
651 // The niche must be just 0 (which an inbounds pointer value never is)
652 let ptr_valid = niche_start == 0 && variants_start == variants_end &&
653 self.memory.check_bounds_ptr(ptr, InboundsCheck::MaybeDead).is_ok();
655 return err!(InvalidDiscriminant(raw_discr.erase_tag()));
657 (dataful_variant.as_u32() as u128, dataful_variant)
659 ScalarMaybeUndef::Scalar(Scalar::Bits { bits: raw_discr, size }) => {
660 assert_eq!(size as u64, discr_val.layout.size.bytes());
661 let adjusted_discr = raw_discr.wrapping_sub(niche_start)
662 .wrapping_add(variants_start);
663 if variants_start <= adjusted_discr && adjusted_discr <= variants_end {
664 let index = adjusted_discr as usize;
665 assert_eq!(index as u128, adjusted_discr);
666 assert!(index < rval.layout.ty
668 .expect("tagged layout for non adt")
670 (adjusted_discr, VariantIdx::from_usize(index))
672 (dataful_variant.as_u32() as u128, dataful_variant)
675 ScalarMaybeUndef::Undef =>
676 return err!(InvalidDiscriminant(ScalarMaybeUndef::Undef)),