]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/operand.rs
Auto merge of #54265 - arielb1:civilize-proc-macros, r=alexcrichton
[rust.git] / src / librustc_mir / interpret / operand.rs
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.
4 //
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.
10
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.
13
14 use std::hash::{Hash, Hasher};
15 use std::convert::TryInto;
16
17 use rustc::{mir, ty};
18 use rustc::ty::layout::{self, Size, LayoutOf, TyLayout, HasDataLayout, IntegerExt};
19
20 use rustc::mir::interpret::{
21     GlobalId, AllocId,
22     ConstValue, Pointer, Scalar, ScalarMaybeUndef,
23     EvalResult, EvalErrorKind
24 };
25 use super::{EvalContext, Machine, MemPlace, MPlaceTy, MemoryKind};
26
27 /// A `Value` represents a single immediate self-contained Rust value.
28 ///
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 `Value`, and do not have to work with a `Place`.
34 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
35 pub enum Value<Id=AllocId> {
36     Scalar(ScalarMaybeUndef<Id>),
37     ScalarPair(ScalarMaybeUndef<Id>, ScalarMaybeUndef<Id>),
38 }
39
40 impl<'tcx> Value {
41     pub fn new_slice(
42         val: Scalar,
43         len: u64,
44         cx: impl HasDataLayout
45     ) -> Self {
46         Value::ScalarPair(val.into(), Scalar::from_uint(len, cx.data_layout().pointer_size).into())
47     }
48
49     pub fn new_dyn_trait(val: Scalar, vtable: Pointer) -> Self {
50         Value::ScalarPair(val.into(), Scalar::Ptr(vtable).into())
51     }
52
53     #[inline]
54     pub fn to_scalar_or_undef(self) -> ScalarMaybeUndef {
55         match self {
56             Value::Scalar(val) => val,
57             Value::ScalarPair(..) => bug!("Got a fat pointer where a scalar was expected"),
58         }
59     }
60
61     #[inline]
62     pub fn to_scalar(self) -> EvalResult<'tcx, Scalar> {
63         self.to_scalar_or_undef().not_undef()
64     }
65
66     #[inline]
67     pub fn to_scalar_pair(self) -> EvalResult<'tcx, (Scalar, Scalar)> {
68         match self {
69             Value::Scalar(..) => bug!("Got a thin pointer where a scalar pair was expected"),
70             Value::ScalarPair(a, b) => Ok((a.not_undef()?, b.not_undef()?))
71         }
72     }
73
74     /// Convert the value into a pointer (or a pointer-sized integer).
75     /// Throws away the second half of a ScalarPair!
76     #[inline]
77     pub fn to_scalar_ptr(self) -> EvalResult<'tcx, Scalar> {
78         match self {
79             Value::Scalar(ptr) |
80             Value::ScalarPair(ptr, _) => ptr.not_undef(),
81         }
82     }
83 }
84
85 impl_stable_hash_for!(enum ::interpret::Value {
86     Scalar(x),
87     ScalarPair(x, y),
88 });
89
90 // ScalarPair needs a type to interpret, so we often have a value and a type together
91 // as input for binary and cast operations.
92 #[derive(Copy, Clone, Debug)]
93 pub struct ValTy<'tcx> {
94     value: Value,
95     pub layout: TyLayout<'tcx>,
96 }
97
98 impl<'tcx> ::std::ops::Deref for ValTy<'tcx> {
99     type Target = Value;
100     #[inline(always)]
101     fn deref(&self) -> &Value {
102         &self.value
103     }
104 }
105
106 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
107 /// or still in memory.  The latter is an optimization, to delay reading that chunk of
108 /// memory and to avoid having to store arbitrary-sized data here.
109 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
110 pub enum Operand<Id=AllocId> {
111     Immediate(Value<Id>),
112     Indirect(MemPlace<Id>),
113 }
114
115 impl Operand {
116     #[inline]
117     pub fn to_mem_place(self) -> MemPlace {
118         match self {
119             Operand::Indirect(mplace) => mplace,
120             _ => bug!("to_mem_place: expected Operand::Indirect, got {:?}", self),
121
122         }
123     }
124
125     #[inline]
126     pub fn to_immediate(self) -> Value {
127         match self {
128             Operand::Immediate(val) => val,
129             _ => bug!("to_immediate: expected Operand::Immediate, got {:?}", self),
130
131         }
132     }
133 }
134
135 impl_stable_hash_for!(enum ::interpret::Operand {
136     Immediate(x),
137     Indirect(x),
138 });
139
140 #[derive(Copy, Clone, Debug)]
141 pub struct OpTy<'tcx> {
142     crate op: Operand, // ideally we'd make this private, but const_prop needs this
143     pub layout: TyLayout<'tcx>,
144 }
145
146 impl<'tcx> ::std::ops::Deref for OpTy<'tcx> {
147     type Target = Operand;
148     #[inline(always)]
149     fn deref(&self) -> &Operand {
150         &self.op
151     }
152 }
153
154 impl<'tcx> From<MPlaceTy<'tcx>> for OpTy<'tcx> {
155     #[inline(always)]
156     fn from(mplace: MPlaceTy<'tcx>) -> Self {
157         OpTy {
158             op: Operand::Indirect(*mplace),
159             layout: mplace.layout
160         }
161     }
162 }
163
164 impl<'tcx> From<ValTy<'tcx>> for OpTy<'tcx> {
165     #[inline(always)]
166     fn from(val: ValTy<'tcx>) -> Self {
167         OpTy {
168             op: Operand::Immediate(val.value),
169             layout: val.layout
170         }
171     }
172 }
173
174 // Validation needs to hash OpTy, but we cannot hash Layout -- so we just hash the type
175 impl<'tcx> Hash for OpTy<'tcx> {
176     fn hash<H: Hasher>(&self, state: &mut H) {
177         self.op.hash(state);
178         self.layout.ty.hash(state);
179     }
180 }
181 impl<'tcx> PartialEq for OpTy<'tcx> {
182     fn eq(&self, other: &Self) -> bool {
183         self.op == other.op && self.layout.ty == other.layout.ty
184     }
185 }
186 impl<'tcx> Eq for OpTy<'tcx> {}
187
188 // Use the existing layout if given (but sanity check in debug mode),
189 // or compute the layout.
190 #[inline(always)]
191 fn from_known_layout<'tcx>(
192     layout: Option<TyLayout<'tcx>>,
193     compute: impl FnOnce() -> EvalResult<'tcx, TyLayout<'tcx>>
194 ) -> EvalResult<'tcx, TyLayout<'tcx>> {
195     match layout {
196         None => compute(),
197         Some(layout) => {
198             if cfg!(debug_assertions) {
199                 let layout2 = compute()?;
200                 assert_eq!(layout.details, layout2.details,
201                     "Mismatch in layout of supposedly equal-layout types {:?} and {:?}",
202                     layout.ty, layout2.ty);
203             }
204             Ok(layout)
205         }
206     }
207 }
208
209 impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
210     /// Try reading a value in memory; this is interesting particularily for ScalarPair.
211     /// Return None if the layout does not permit loading this as a value.
212     pub(super) fn try_read_value_from_mplace(
213         &self,
214         mplace: MPlaceTy<'tcx>,
215     ) -> EvalResult<'tcx, Option<Value>> {
216         if mplace.layout.is_unsized() {
217             // Dont touch unsized
218             return Ok(None);
219         }
220         let (ptr, ptr_align) = mplace.to_scalar_ptr_align();
221
222         if mplace.layout.is_zst() {
223             // Not all ZSTs have a layout we would handle below, so just short-circuit them
224             // all here.
225             self.memory.check_align(ptr, ptr_align)?;
226             return Ok(Some(Value::Scalar(Scalar::zst().into())));
227         }
228
229         let ptr = ptr.to_ptr()?;
230         match mplace.layout.abi {
231             layout::Abi::Scalar(..) => {
232                 let scalar = self.memory.read_scalar(ptr, ptr_align, mplace.layout.size)?;
233                 Ok(Some(Value::Scalar(scalar)))
234             }
235             layout::Abi::ScalarPair(ref a, ref b) => {
236                 let (a, b) = (&a.value, &b.value);
237                 let (a_size, b_size) = (a.size(self), b.size(self));
238                 let a_ptr = ptr;
239                 let b_offset = a_size.abi_align(b.align(self));
240                 assert!(b_offset.bytes() > 0); // we later use the offset to test which field to use
241                 let b_ptr = ptr.offset(b_offset, self)?.into();
242                 let a_val = self.memory.read_scalar(a_ptr, ptr_align, a_size)?;
243                 let b_val = self.memory.read_scalar(b_ptr, ptr_align, b_size)?;
244                 Ok(Some(Value::ScalarPair(a_val, b_val)))
245             }
246             _ => Ok(None),
247         }
248     }
249
250     /// Try returning an immediate value for the operand.
251     /// If the layout does not permit loading this as a value, return where in memory
252     /// we can find the data.
253     /// Note that for a given layout, this operation will either always fail or always
254     /// succeed!  Whether it succeeds depends on whether the layout can be represented
255     /// in a `Value`, not on which data is stored there currently.
256     pub(crate) fn try_read_value(
257         &self,
258         src: OpTy<'tcx>,
259     ) -> EvalResult<'tcx, Result<Value, MemPlace>> {
260         Ok(match src.try_as_mplace() {
261             Ok(mplace) => {
262                 if let Some(val) = self.try_read_value_from_mplace(mplace)? {
263                     Ok(val)
264                 } else {
265                     Err(*mplace)
266                 }
267             },
268             Err(val) => Ok(val),
269         })
270     }
271
272     /// Read a value from a place, asserting that that is possible with the given layout.
273     #[inline(always)]
274     pub fn read_value(&self, op: OpTy<'tcx>) -> EvalResult<'tcx, ValTy<'tcx>> {
275         if let Ok(value) = self.try_read_value(op)? {
276             Ok(ValTy { value, layout: op.layout })
277         } else {
278             bug!("primitive read failed for type: {:?}", op.layout.ty);
279         }
280     }
281
282     /// Read a scalar from a place
283     pub fn read_scalar(&self, op: OpTy<'tcx>) -> EvalResult<'tcx, ScalarMaybeUndef> {
284         match *self.read_value(op)? {
285             Value::ScalarPair(..) => bug!("got ScalarPair for type: {:?}", op.layout.ty),
286             Value::Scalar(val) => Ok(val),
287         }
288     }
289
290     // Turn the MPlace into a string (must already be dereferenced!)
291     pub fn read_str(
292         &self,
293         mplace: MPlaceTy<'tcx>,
294     ) -> EvalResult<'tcx, &str> {
295         let len = mplace.len(self)?;
296         let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?;
297         let str = ::std::str::from_utf8(bytes)
298             .map_err(|err| EvalErrorKind::ValidationFailure(err.to_string()))?;
299         Ok(str)
300     }
301
302     pub fn uninit_operand(&mut self, layout: TyLayout<'tcx>) -> EvalResult<'tcx, Operand> {
303         // This decides which types we will use the Immediate optimization for, and hence should
304         // match what `try_read_value` and `eval_place_to_op` support.
305         if layout.is_zst() {
306             return Ok(Operand::Immediate(Value::Scalar(Scalar::zst().into())));
307         }
308
309         Ok(match layout.abi {
310             layout::Abi::Scalar(..) =>
311                 Operand::Immediate(Value::Scalar(ScalarMaybeUndef::Undef)),
312             layout::Abi::ScalarPair(..) =>
313                 Operand::Immediate(Value::ScalarPair(
314                     ScalarMaybeUndef::Undef,
315                     ScalarMaybeUndef::Undef,
316                 )),
317             _ => {
318                 trace!("Forcing allocation for local of type {:?}", layout.ty);
319                 Operand::Indirect(
320                     *self.allocate(layout, MemoryKind::Stack)?
321                 )
322             }
323         })
324     }
325
326     /// Projection functions
327     pub fn operand_field(
328         &self,
329         op: OpTy<'tcx>,
330         field: u64,
331     ) -> EvalResult<'tcx, OpTy<'tcx>> {
332         let base = match op.try_as_mplace() {
333             Ok(mplace) => {
334                 // The easy case
335                 let field = self.mplace_field(mplace, field)?;
336                 return Ok(field.into());
337             },
338             Err(value) => value
339         };
340
341         let field = field.try_into().unwrap();
342         let field_layout = op.layout.field(self, field)?;
343         if field_layout.is_zst() {
344             let val = Value::Scalar(Scalar::zst().into());
345             return Ok(OpTy { op: Operand::Immediate(val), layout: field_layout });
346         }
347         let offset = op.layout.fields.offset(field);
348         let value = match base {
349             // the field covers the entire type
350             _ if offset.bytes() == 0 && field_layout.size == op.layout.size => base,
351             // extract fields from types with `ScalarPair` ABI
352             Value::ScalarPair(a, b) => {
353                 let val = if offset.bytes() == 0 { a } else { b };
354                 Value::Scalar(val)
355             },
356             Value::Scalar(val) =>
357                 bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
358         };
359         Ok(OpTy { op: Operand::Immediate(value), layout: field_layout })
360     }
361
362     pub fn operand_downcast(
363         &self,
364         op: OpTy<'tcx>,
365         variant: usize,
366     ) -> EvalResult<'tcx, OpTy<'tcx>> {
367         // Downcasts only change the layout
368         Ok(match op.try_as_mplace() {
369             Ok(mplace) => {
370                 self.mplace_downcast(mplace, variant)?.into()
371             },
372             Err(..) => {
373                 let layout = op.layout.for_variant(self, variant);
374                 OpTy { layout, ..op }
375             }
376         })
377     }
378
379     // Take an operand, representing a pointer, and dereference it to a place -- that
380     // will always be a MemPlace.
381     pub(super) fn deref_operand(
382         &self,
383         src: OpTy<'tcx>,
384     ) -> EvalResult<'tcx, MPlaceTy<'tcx>> {
385         let val = self.read_value(src)?;
386         trace!("deref to {} on {:?}", val.layout.ty, *val);
387         Ok(self.ref_to_mplace(val)?)
388     }
389
390     pub fn operand_projection(
391         &self,
392         base: OpTy<'tcx>,
393         proj_elem: &mir::PlaceElem<'tcx>,
394     ) -> EvalResult<'tcx, OpTy<'tcx>> {
395         use rustc::mir::ProjectionElem::*;
396         Ok(match *proj_elem {
397             Field(field, _) => self.operand_field(base, field.index() as u64)?,
398             Downcast(_, variant) => self.operand_downcast(base, variant)?,
399             Deref => self.deref_operand(base)?.into(),
400             Subslice { .. } | ConstantIndex { .. } | Index(_) => if base.layout.is_zst() {
401                 OpTy {
402                     op: Operand::Immediate(Value::Scalar(Scalar::zst().into())),
403                     // the actual index doesn't matter, so we just pick a convenient one like 0
404                     layout: base.layout.field(self, 0)?,
405                 }
406             } else {
407                 // The rest should only occur as mplace, we do not use Immediates for types
408                 // allowing such operations.  This matches place_projection forcing an allocation.
409                 let mplace = base.to_mem_place();
410                 self.mplace_projection(mplace, proj_elem)?.into()
411             }
412         })
413     }
414
415     // Evaluate a place with the goal of reading from it.  This lets us sometimes
416     // avoid allocations.  If you already know the layout, you can pass it in
417     // to avoid looking it up again.
418     fn eval_place_to_op(
419         &self,
420         mir_place: &mir::Place<'tcx>,
421         layout: Option<TyLayout<'tcx>>,
422     ) -> EvalResult<'tcx, OpTy<'tcx>> {
423         use rustc::mir::Place::*;
424         let op = match *mir_place {
425             Local(mir::RETURN_PLACE) => return err!(ReadFromReturnPointer),
426             Local(local) => {
427                 let op = *self.frame().locals[local].access()?;
428                 let layout = from_known_layout(layout,
429                     || self.layout_of_local(self.cur_frame(), local))?;
430                 OpTy { op, layout }
431             },
432
433             Projection(ref proj) => {
434                 let op = self.eval_place_to_op(&proj.base, None)?;
435                 self.operand_projection(op, &proj.elem)?
436             }
437
438             _ => self.eval_place_to_mplace(mir_place)?.into(),
439         };
440
441         trace!("eval_place_to_op: got {:?}", *op);
442         Ok(op)
443     }
444
445     /// Evaluate the operand, returning a place where you can then find the data.
446     /// if you already know the layout, you can save two some table lookups
447     /// by passing it in here.
448     pub fn eval_operand(
449         &self,
450         mir_op: &mir::Operand<'tcx>,
451         layout: Option<TyLayout<'tcx>>,
452     ) -> EvalResult<'tcx, OpTy<'tcx>> {
453         use rustc::mir::Operand::*;
454         let op = match *mir_op {
455             // FIXME: do some more logic on `move` to invalidate the old location
456             Copy(ref place) |
457             Move(ref place) =>
458                 self.eval_place_to_op(place, layout)?,
459
460             Constant(ref constant) => {
461                 let layout = from_known_layout(layout, || {
462                     let ty = self.monomorphize(mir_op.ty(self.mir(), *self.tcx), self.substs());
463                     self.layout_of(ty)
464                 })?;
465                 let op = self.const_value_to_op(constant.literal.val)?;
466                 OpTy { op, layout }
467             }
468         };
469         trace!("{:?}: {:?}", mir_op, *op);
470         Ok(op)
471     }
472
473     /// Evaluate a bunch of operands at once
474     pub(super) fn eval_operands(
475         &self,
476         ops: &[mir::Operand<'tcx>],
477     ) -> EvalResult<'tcx, Vec<OpTy<'tcx>>> {
478         ops.into_iter()
479             .map(|op| self.eval_operand(op, None))
480             .collect()
481     }
482
483     // Also used e.g. when miri runs into a constant.
484     pub(super) fn const_value_to_op(
485         &self,
486         val: ConstValue<'tcx>,
487     ) -> EvalResult<'tcx, Operand> {
488         trace!("const_value_to_op: {:?}", val);
489         match val {
490             ConstValue::Unevaluated(def_id, substs) => {
491                 let instance = self.resolve(def_id, substs)?;
492                 self.global_to_op(GlobalId {
493                     instance,
494                     promoted: None,
495                 })
496             }
497             ConstValue::ByRef(id, alloc, offset) => {
498                 // We rely on mutability being set correctly in that allocation to prevent writes
499                 // where none should happen -- and for `static mut`, we copy on demand anyway.
500                 Ok(Operand::Indirect(MemPlace::from_ptr(Pointer::new(id, offset), alloc.align)))
501             },
502             ConstValue::ScalarPair(a, b) =>
503                 Ok(Operand::Immediate(Value::ScalarPair(a.into(), b))),
504             ConstValue::Scalar(x) =>
505                 Ok(Operand::Immediate(Value::Scalar(x.into()))),
506         }
507     }
508     pub fn const_to_op(
509         &self,
510         cnst: &ty::Const<'tcx>,
511     ) -> EvalResult<'tcx, OpTy<'tcx>> {
512         let op = self.const_value_to_op(cnst.val)?;
513         Ok(OpTy { op, layout: self.layout_of(cnst.ty)? })
514     }
515
516     pub(super) fn global_to_op(&self, gid: GlobalId<'tcx>) -> EvalResult<'tcx, Operand> {
517         let cv = self.const_eval(gid)?;
518         self.const_value_to_op(cv.val)
519     }
520
521     /// Read discriminant, return the runtime value as well as the variant index.
522     pub fn read_discriminant(
523         &self,
524         rval: OpTy<'tcx>,
525     ) -> EvalResult<'tcx, (u128, usize)> {
526         trace!("read_discriminant_value {:#?}", rval.layout);
527         if rval.layout.abi == layout::Abi::Uninhabited {
528             return err!(Unreachable);
529         }
530
531         match rval.layout.variants {
532             layout::Variants::Single { index } => {
533                 let discr_val = rval.layout.ty.ty_adt_def().map_or(
534                     index as u128,
535                     |def| def.discriminant_for_variant(*self.tcx, index).val);
536                 return Ok((discr_val, index));
537             }
538             layout::Variants::Tagged { .. } |
539             layout::Variants::NicheFilling { .. } => {},
540         }
541         // read raw discriminant value
542         let discr_op = self.operand_field(rval, 0)?;
543         let discr_val = self.read_value(discr_op)?;
544         let raw_discr = discr_val.to_scalar()?;
545         trace!("discr value: {:?}", raw_discr);
546         // post-process
547         Ok(match rval.layout.variants {
548             layout::Variants::Single { .. } => bug!(),
549             layout::Variants::Tagged { .. } => {
550                 let real_discr = if discr_val.layout.ty.is_signed() {
551                     let i = raw_discr.to_bits(discr_val.layout.size)? as i128;
552                     // going from layout tag type to typeck discriminant type
553                     // requires first sign extending with the layout discriminant
554                     let shift = 128 - discr_val.layout.size.bits();
555                     let sexted = (i << shift) >> shift;
556                     // and then zeroing with the typeck discriminant type
557                     let discr_ty = rval.layout.ty
558                         .ty_adt_def().expect("tagged layout corresponds to adt")
559                         .repr
560                         .discr_type();
561                     let discr_ty = layout::Integer::from_attr(self.tcx.tcx, discr_ty);
562                     let shift = 128 - discr_ty.size().bits();
563                     let truncatee = sexted as u128;
564                     (truncatee << shift) >> shift
565                 } else {
566                     raw_discr.to_bits(discr_val.layout.size)?
567                 };
568                 // Make sure we catch invalid discriminants
569                 let index = rval.layout.ty
570                     .ty_adt_def()
571                     .expect("tagged layout for non adt")
572                     .discriminants(self.tcx.tcx)
573                     .position(|var| var.val == real_discr)
574                     .ok_or_else(|| EvalErrorKind::InvalidDiscriminant(real_discr))?;
575                 (real_discr, index)
576             },
577             layout::Variants::NicheFilling {
578                 dataful_variant,
579                 ref niche_variants,
580                 niche_start,
581                 ..
582             } => {
583                 let variants_start = *niche_variants.start() as u128;
584                 let variants_end = *niche_variants.end() as u128;
585                 let real_discr = match raw_discr {
586                     Scalar::Ptr(_) => {
587                         // The niche must be just 0 (which a pointer value never is)
588                         assert!(niche_start == 0);
589                         assert!(variants_start == variants_end);
590                         dataful_variant as u128
591                     },
592                     Scalar::Bits { bits: raw_discr, size } => {
593                         assert_eq!(size as u64, discr_val.layout.size.bytes());
594                         let discr = raw_discr.wrapping_sub(niche_start)
595                             .wrapping_add(variants_start);
596                         if variants_start <= discr && discr <= variants_end {
597                             discr
598                         } else {
599                             dataful_variant as u128
600                         }
601                     },
602                 };
603                 let index = real_discr as usize;
604                 assert_eq!(index as u128, real_discr);
605                 assert!(index < rval.layout.ty
606                     .ty_adt_def()
607                     .expect("tagged layout for non adt")
608                     .variants.len());
609                 (real_discr, index)
610             }
611         })
612     }
613
614 }