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 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=()> {
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>
193 pub fn from_scalar(val: Scalar<Tag>, layout: TyLayout<'tcx>) -> Self {
194 ImmTy { imm: val.into(), layout }
198 pub fn to_bits(self) -> InterpResult<'tcx, u128> {
199 self.to_scalar()?.to_bits(self.layout.size)
203 // Use the existing layout if given (but sanity check in debug mode),
204 // or compute the layout.
206 pub(super) fn from_known_layout<'tcx>(
207 layout: Option<TyLayout<'tcx>>,
208 compute: impl FnOnce() -> InterpResult<'tcx, TyLayout<'tcx>>
209 ) -> InterpResult<'tcx, TyLayout<'tcx>> {
213 if cfg!(debug_assertions) {
214 let layout2 = compute()?;
215 assert_eq!(layout.details, layout2.details,
216 "Mismatch in layout of supposedly equal-layout types {:?} and {:?}",
217 layout.ty, layout2.ty);
224 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
225 /// Normalice `place.ptr` to a `Pointer` if this is a place and not a ZST.
226 /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot.
230 op: OpTy<'tcx, M::PointerTag>,
231 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
232 match op.try_as_mplace() {
233 Ok(mplace) => Ok(self.force_mplace_ptr(mplace)?.into()),
234 Err(imm) => Ok(imm.into()), // Nothing to cast/force
238 /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`.
239 /// Returns `None` if the layout does not permit loading this as a value.
240 fn try_read_immediate_from_mplace(
242 mplace: MPlaceTy<'tcx, M::PointerTag>,
243 ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::PointerTag>>> {
244 if mplace.layout.is_unsized() {
245 // Don't touch unsized
249 let ptr = match self.check_mplace_access(mplace, None)? {
251 None => return Ok(Some(ImmTy { // zero-sized type
252 imm: Scalar::zst().into(),
253 layout: mplace.layout,
257 match mplace.layout.abi {
258 layout::Abi::Scalar(..) => {
259 let scalar = self.memory
261 .read_scalar(self, ptr, mplace.layout.size)?;
264 layout: mplace.layout,
267 layout::Abi::ScalarPair(ref a, ref b) => {
268 // We checked `ptr_align` above, so all fields will have the alignment they need.
269 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
270 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
271 let (a, b) = (&a.value, &b.value);
272 let (a_size, b_size) = (a.size(self), b.size(self));
274 let b_offset = a_size.align_to(b.align(self).abi);
275 assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields
276 let b_ptr = ptr.offset(b_offset, self)?;
277 let a_val = self.memory
279 .read_scalar(self, a_ptr, a_size)?;
280 let b_val = self.memory
282 .read_scalar(self, b_ptr, b_size)?;
284 imm: Immediate::ScalarPair(a_val, b_val),
285 layout: mplace.layout,
292 /// Try returning an immediate for the operand.
293 /// If the layout does not permit loading this as an immediate, return where in memory
294 /// we can find the data.
295 /// Note that for a given layout, this operation will either always fail or always
296 /// succeed! Whether it succeeds depends on whether the layout can be represented
297 /// in a `Immediate`, not on which data is stored there currently.
298 pub(crate) fn try_read_immediate(
300 src: OpTy<'tcx, M::PointerTag>,
301 ) -> InterpResult<'tcx, Result<ImmTy<'tcx, M::PointerTag>, MPlaceTy<'tcx, M::PointerTag>>> {
302 Ok(match src.try_as_mplace() {
304 if let Some(val) = self.try_read_immediate_from_mplace(mplace)? {
314 /// Read an immediate from a place, asserting that that is possible with the given layout.
316 pub fn read_immediate(
318 op: OpTy<'tcx, M::PointerTag>
319 ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
320 if let Ok(imm) = self.try_read_immediate(op)? {
323 bug!("primitive read failed for type: {:?}", op.layout.ty);
327 /// Read a scalar from a place
330 op: OpTy<'tcx, M::PointerTag>
331 ) -> InterpResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
332 Ok(self.read_immediate(op)?.to_scalar_or_undef())
335 // Turn the MPlace into a string (must already be dereferenced!)
338 mplace: MPlaceTy<'tcx, M::PointerTag>,
339 ) -> InterpResult<'tcx, &str> {
340 let len = mplace.len(self)?;
341 let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?;
342 let str = ::std::str::from_utf8(bytes).map_err(|err| {
343 err_unsup!(ValidationFailure(err.to_string()))
348 /// Projection functions
349 pub fn operand_field(
351 op: OpTy<'tcx, M::PointerTag>,
353 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
354 let base = match op.try_as_mplace() {
357 let field = self.mplace_field(mplace, field)?;
358 return Ok(field.into());
363 let field = field.try_into().unwrap();
364 let field_layout = op.layout.field(self, field)?;
365 if field_layout.is_zst() {
366 let immediate = Scalar::zst().into();
367 return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout });
369 let offset = op.layout.fields.offset(field);
370 let immediate = match *base {
371 // the field covers the entire type
372 _ if offset.bytes() == 0 && field_layout.size == op.layout.size => *base,
373 // extract fields from types with `ScalarPair` ABI
374 Immediate::ScalarPair(a, b) => {
375 let val = if offset.bytes() == 0 { a } else { b };
378 Immediate::Scalar(val) =>
379 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
381 Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout })
384 pub fn operand_downcast(
386 op: OpTy<'tcx, M::PointerTag>,
388 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
389 // Downcasts only change the layout
390 Ok(match op.try_as_mplace() {
392 self.mplace_downcast(mplace, variant)?.into()
395 let layout = op.layout.for_variant(self, variant);
396 OpTy { layout, ..op }
401 pub fn operand_projection(
403 base: OpTy<'tcx, M::PointerTag>,
404 proj_elem: &mir::PlaceElem<'tcx>,
405 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
406 use rustc::mir::ProjectionElem::*;
407 Ok(match *proj_elem {
408 Field(field, _) => self.operand_field(base, field.index() as u64)?,
409 Downcast(_, variant) => self.operand_downcast(base, variant)?,
410 Deref => self.deref_operand(base)?.into(),
411 Subslice { .. } | ConstantIndex { .. } | Index(_) => if base.layout.is_zst() {
413 op: Operand::Immediate(Scalar::zst().into()),
414 // the actual index doesn't matter, so we just pick a convenient one like 0
415 layout: base.layout.field(self, 0)?,
418 // The rest should only occur as mplace, we do not use Immediates for types
419 // allowing such operations. This matches place_projection forcing an allocation.
420 let mplace = base.assert_mem_place();
421 self.mplace_projection(mplace, proj_elem)?.into()
426 /// This is used by [priroda](https://github.com/oli-obk/priroda) to get an OpTy from a local
429 frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
431 layout: Option<TyLayout<'tcx>>,
432 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
433 assert_ne!(local, mir::RETURN_PLACE);
434 let layout = self.layout_of_local(frame, local, layout)?;
435 let op = if layout.is_zst() {
436 // Do not read from ZST, they might not be initialized
437 Operand::Immediate(Scalar::zst().into())
439 frame.locals[local].access()?
441 Ok(OpTy { op, layout })
444 /// Every place can be read from, so we can turn them into an operand
448 place: PlaceTy<'tcx, M::PointerTag>
449 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
450 let op = match *place {
451 Place::Ptr(mplace) => {
452 Operand::Indirect(mplace)
454 Place::Local { frame, local } =>
455 *self.access_local(&self.stack[frame], local, None)?
457 Ok(OpTy { op, layout: place.layout })
460 // Evaluate a place with the goal of reading from it. This lets us sometimes
461 // avoid allocations.
462 pub(super) fn eval_place_to_op(
464 mir_place: &mir::Place<'tcx>,
465 layout: Option<TyLayout<'tcx>>,
466 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
467 use rustc::mir::PlaceBase;
469 mir_place.iterate(|place_base, place_projection| {
470 let mut op = match place_base {
471 PlaceBase::Local(mir::RETURN_PLACE) =>
472 throw_unsup!(ReadFromReturnPointer),
473 PlaceBase::Local(local) => {
474 // Do not use the layout passed in as argument if the base we are looking at
475 // here is not the entire place.
476 // FIXME use place_projection.is_empty() when is available
477 let layout = if mir_place.projection.is_none() {
483 self.access_local(self.frame(), *local, layout)?
485 PlaceBase::Static(place_static) => {
486 self.eval_static_to_mplace(place_static)?.into()
490 for proj in place_projection {
491 op = self.operand_projection(op, &proj.elem)?
494 trace!("eval_place_to_op: got {:?}", *op);
499 /// Evaluate the operand, returning a place where you can then find the data.
500 /// If you already know the layout, you can save two table lookups
501 /// by passing it in here.
504 mir_op: &mir::Operand<'tcx>,
505 layout: Option<TyLayout<'tcx>>,
506 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
507 use rustc::mir::Operand::*;
508 let op = match *mir_op {
509 // FIXME: do some more logic on `move` to invalidate the old location
512 self.eval_place_to_op(place, layout)?,
514 Constant(ref constant) => self.eval_const_to_op(constant.literal, layout)?,
516 trace!("{:?}: {:?}", mir_op, *op);
520 /// Evaluate a bunch of operands at once
521 pub(super) fn eval_operands(
523 ops: &[mir::Operand<'tcx>],
524 ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
526 .map(|op| self.eval_operand(op, None))
530 // Used when the miri-engine runs into a constant and for extracting information from constants
531 // in patterns via the `const_eval` module
532 crate fn eval_const_to_op(
534 val: &'tcx ty::Const<'tcx>,
535 layout: Option<TyLayout<'tcx>>,
536 ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
537 let tag_scalar = |scalar| match scalar {
538 Scalar::Ptr(ptr) => Scalar::Ptr(self.tag_static_base_pointer(ptr)),
539 Scalar::Raw { data, size } => Scalar::Raw { data, size },
541 // Early-return cases.
543 ConstValue::Param(_) =>
544 // FIXME(oli-obk): try to monomorphize
545 throw_inval!(TooGeneric),
546 ConstValue::Unevaluated(def_id, substs) => {
547 let instance = self.resolve(def_id, substs)?;
548 return Ok(OpTy::from(self.const_eval_raw(GlobalId {
555 // Other cases need layout.
556 let layout = from_known_layout(layout, || {
557 self.layout_of(self.monomorphize(val.ty)?)
559 let op = match val.val {
560 ConstValue::ByRef { offset, align, alloc } => {
561 let id = self.tcx.alloc_map.lock().create_memory_alloc(alloc);
562 // We rely on mutability being set correctly in that allocation to prevent writes
563 // where none should happen.
564 let ptr = self.tag_static_base_pointer(Pointer::new(id, offset));
565 Operand::Indirect(MemPlace::from_ptr(ptr, align))
567 ConstValue::Scalar(x) =>
568 Operand::Immediate(tag_scalar(x).into()),
569 ConstValue::Slice { data, start, end } => {
570 // We rely on mutability being set correctly in `data` to prevent writes
571 // where none should happen.
572 let ptr = Pointer::new(
573 self.tcx.alloc_map.lock().create_memory_alloc(data),
574 Size::from_bytes(start as u64), // offset: `start`
576 Operand::Immediate(Immediate::new_slice(
577 self.tag_static_base_pointer(ptr).into(),
578 (end - start) as u64, // len: `end - start`
582 ConstValue::Param(..) |
583 ConstValue::Infer(..) |
584 ConstValue::Placeholder(..) |
585 ConstValue::Unevaluated(..) =>
586 bug!("eval_const_to_op: Unexpected ConstValue {:?}", val),
588 Ok(OpTy { op, layout })
591 /// Read discriminant, return the runtime value as well as the variant index.
592 pub fn read_discriminant(
594 rval: OpTy<'tcx, M::PointerTag>,
595 ) -> InterpResult<'tcx, (u128, VariantIdx)> {
596 trace!("read_discriminant_value {:#?}", rval.layout);
598 let (discr_kind, discr_index) = match rval.layout.variants {
599 layout::Variants::Single { index } => {
600 let discr_val = rval.layout.ty.discriminant_for_variant(*self.tcx, index).map_or(
601 index.as_u32() as u128,
603 return Ok((discr_val, index));
605 layout::Variants::Multiple { ref discr_kind, discr_index, .. } =>
606 (discr_kind, discr_index),
609 // read raw discriminant value
610 let discr_op = self.operand_field(rval, discr_index as u64)?;
611 let discr_val = self.read_immediate(discr_op)?;
612 let raw_discr = discr_val.to_scalar_or_undef();
613 trace!("discr value: {:?}", raw_discr);
615 Ok(match *discr_kind {
616 layout::DiscriminantKind::Tag => {
617 let bits_discr = match raw_discr.to_bits(discr_val.layout.size) {
618 Ok(raw_discr) => raw_discr,
620 throw_unsup!(InvalidDiscriminant(raw_discr.erase_tag())),
622 let real_discr = if discr_val.layout.ty.is_signed() {
623 // going from layout tag type to typeck discriminant type
624 // requires first sign extending with the layout discriminant
625 let sexted = sign_extend(bits_discr, discr_val.layout.size) as i128;
626 // and then zeroing with the typeck discriminant type
627 let discr_ty = rval.layout.ty
628 .ty_adt_def().expect("tagged layout corresponds to adt")
631 let size = layout::Integer::from_attr(self, discr_ty).size();
632 let truncatee = sexted as u128;
633 truncate(truncatee, size)
637 // Make sure we catch invalid discriminants
638 let index = match &rval.layout.ty.sty {
639 ty::Adt(adt, _) => adt
640 .discriminants(self.tcx.tcx)
641 .find(|(_, var)| var.val == real_discr),
642 ty::Generator(def_id, substs, _) => substs
643 .discriminants(*def_id, self.tcx.tcx)
644 .find(|(_, var)| var.val == real_discr),
645 _ => bug!("tagged layout for non-adt non-generator"),
647 || err_unsup!(InvalidDiscriminant(raw_discr.erase_tag()))
649 (real_discr, index.0)
651 layout::DiscriminantKind::Niche {
656 let variants_start = niche_variants.start().as_u32() as u128;
657 let variants_end = niche_variants.end().as_u32() as u128;
658 let raw_discr = raw_discr.not_undef().map_err(|_| {
659 err_unsup!(InvalidDiscriminant(ScalarMaybeUndef::Undef))
661 match raw_discr.to_bits_or_ptr(discr_val.layout.size, self) {
663 // The niche must be just 0 (which an inbounds pointer value never is)
664 let ptr_valid = niche_start == 0 && variants_start == variants_end &&
665 !self.memory.ptr_may_be_null(ptr);
667 throw_unsup!(InvalidDiscriminant(raw_discr.erase_tag().into()))
669 (dataful_variant.as_u32() as u128, dataful_variant)
672 let adjusted_discr = raw_discr.wrapping_sub(niche_start)
673 .wrapping_add(variants_start);
674 if variants_start <= adjusted_discr && adjusted_discr <= variants_end {
675 let index = adjusted_discr as usize;
676 assert_eq!(index as u128, adjusted_discr);
677 assert!(index < rval.layout.ty
679 .expect("tagged layout for non adt")
681 (adjusted_discr, VariantIdx::from_usize(index))
683 (dataful_variant.as_u32() as u128, dataful_variant)