]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/eval_context.rs
Auto merge of #49891 - cuviper:compiletest-crash, r=alexcrichton
[rust.git] / src / librustc_mir / interpret / eval_context.rs
1 use std::fmt::Write;
2
3 use rustc::hir::def_id::DefId;
4 use rustc::hir::def::Def;
5 use rustc::hir::map::definitions::DefPathData;
6 use rustc::middle::const_val::{ConstVal, ErrKind};
7 use rustc::mir;
8 use rustc::ty::layout::{self, Size, Align, HasDataLayout, IntegerExt, LayoutOf, TyLayout};
9 use rustc::ty::subst::{Subst, Substs};
10 use rustc::ty::{self, Ty, TyCtxt};
11 use rustc::ty::maps::TyCtxtAt;
12 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
13 use rustc::middle::const_val::FrameInfo;
14 use syntax::codemap::{self, Span};
15 use syntax::ast::Mutability;
16 use rustc::mir::interpret::{
17     GlobalId, Value, Pointer, PrimVal, PrimValKind,
18     EvalError, EvalResult, EvalErrorKind, MemoryPointer,
19 };
20 use std::mem;
21
22 use super::{Place, PlaceExtra, Memory,
23             HasMemory, MemoryKind,
24             Machine};
25
26 pub struct EvalContext<'a, 'mir, 'tcx: 'a + 'mir, M: Machine<'mir, 'tcx>> {
27     /// Stores the `Machine` instance.
28     pub machine: M,
29
30     /// The results of the type checker, from rustc.
31     pub tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
32
33     /// Bounds in scope for polymorphic evaluations.
34     pub param_env: ty::ParamEnv<'tcx>,
35
36     /// The virtual memory system.
37     pub memory: Memory<'a, 'mir, 'tcx, M>,
38
39     /// The virtual call stack.
40     pub(crate) stack: Vec<Frame<'mir, 'tcx>>,
41
42     /// The maximum number of stack frames allowed
43     pub(crate) stack_limit: usize,
44
45     /// The maximum number of terminators that may be evaluated.
46     /// This prevents infinite loops and huge computations from freezing up const eval.
47     /// Remove once halting problem is solved.
48     pub(crate) terminators_remaining: usize,
49 }
50
51 /// A stack frame.
52 pub struct Frame<'mir, 'tcx: 'mir> {
53     ////////////////////////////////////////////////////////////////////////////////
54     // Function and callsite information
55     ////////////////////////////////////////////////////////////////////////////////
56     /// The MIR for the function called on this frame.
57     pub mir: &'mir mir::Mir<'tcx>,
58
59     /// The def_id and substs of the current function
60     pub instance: ty::Instance<'tcx>,
61
62     /// The span of the call site.
63     pub span: codemap::Span,
64
65     ////////////////////////////////////////////////////////////////////////////////
66     // Return place and locals
67     ////////////////////////////////////////////////////////////////////////////////
68     /// The block to return to when returning from the current stack frame
69     pub return_to_block: StackPopCleanup,
70
71     /// The location where the result of the current stack frame should be written to.
72     pub return_place: Place,
73
74     /// The list of locals for this stack frame, stored in order as
75     /// `[return_ptr, arguments..., variables..., temporaries...]`. The locals are stored as `Option<Value>`s.
76     /// `None` represents a local that is currently dead, while a live local
77     /// can either directly contain `PrimVal` or refer to some part of an `Allocation`.
78     ///
79     /// Before being initialized, arguments are `Value::ByVal(PrimVal::Undef)` and other locals are `None`.
80     pub locals: IndexVec<mir::Local, Option<Value>>,
81
82     ////////////////////////////////////////////////////////////////////////////////
83     // Current position within the function
84     ////////////////////////////////////////////////////////////////////////////////
85     /// The block that is currently executed (or will be executed after the above call stacks
86     /// return).
87     pub block: mir::BasicBlock,
88
89     /// The index of the currently evaluated statement.
90     pub stmt: usize,
91 }
92
93 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
94 pub enum StackPopCleanup {
95     /// The stackframe existed to compute the initial value of a static/constant, make sure it
96     /// isn't modifyable afterwards in case of constants.
97     /// In case of `static mut`, mark the memory to ensure it's never marked as immutable through
98     /// references or deallocated
99     MarkStatic(Mutability),
100     /// A regular stackframe added due to a function call will need to get forwarded to the next
101     /// block
102     Goto(mir::BasicBlock),
103     /// The main function and diverging functions have nowhere to return to
104     None,
105 }
106
107 #[derive(Copy, Clone, Debug)]
108 pub struct TyAndPacked<'tcx> {
109     pub ty: Ty<'tcx>,
110     pub packed: bool,
111 }
112
113 #[derive(Copy, Clone, Debug)]
114 pub struct ValTy<'tcx> {
115     pub value: Value,
116     pub ty: Ty<'tcx>,
117 }
118
119 impl<'tcx> ValTy<'tcx> {
120     pub fn from(val: &ty::Const<'tcx>) -> Option<Self> {
121         match val.val {
122             ConstVal::Value(value) => Some(ValTy { value, ty: val.ty }),
123             ConstVal::Unevaluated { .. } => None,
124         }
125     }
126 }
127
128 impl<'tcx> ::std::ops::Deref for ValTy<'tcx> {
129     type Target = Value;
130     fn deref(&self) -> &Value {
131         &self.value
132     }
133 }
134
135 impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for &'a EvalContext<'a, 'mir, 'tcx, M> {
136     #[inline]
137     fn data_layout(&self) -> &layout::TargetDataLayout {
138         &self.tcx.data_layout
139     }
140 }
141
142 impl<'c, 'b, 'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout
143     for &'c &'b mut EvalContext<'a, 'mir, 'tcx, M> {
144     #[inline]
145     fn data_layout(&self) -> &layout::TargetDataLayout {
146         &self.tcx.data_layout
147     }
148 }
149
150 impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> layout::HasTyCtxt<'tcx> for &'a EvalContext<'a, 'mir, 'tcx, M> {
151     #[inline]
152     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
153         *self.tcx
154     }
155 }
156
157 impl<'c, 'b, 'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> layout::HasTyCtxt<'tcx>
158     for &'c &'b mut EvalContext<'a, 'mir, 'tcx, M> {
159     #[inline]
160     fn tcx<'d>(&'d self) -> TyCtxt<'d, 'tcx, 'tcx> {
161         *self.tcx
162     }
163 }
164
165 impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> LayoutOf for &'a EvalContext<'a, 'mir, 'tcx, M> {
166     type Ty = Ty<'tcx>;
167     type TyLayout = EvalResult<'tcx, TyLayout<'tcx>>;
168
169     fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
170         self.tcx.layout_of(self.param_env.and(ty))
171             .map_err(|layout| EvalErrorKind::Layout(layout).into())
172     }
173 }
174
175 impl<'c, 'b, 'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> LayoutOf
176     for &'c &'b mut EvalContext<'a, 'mir, 'tcx, M> {
177     type Ty = Ty<'tcx>;
178     type TyLayout = EvalResult<'tcx, TyLayout<'tcx>>;
179
180     #[inline]
181     fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
182         (&**self).layout_of(ty)
183     }
184 }
185
186 impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
187     pub fn new(
188         tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
189         param_env: ty::ParamEnv<'tcx>,
190         machine: M,
191         memory_data: M::MemoryData,
192     ) -> Self {
193         EvalContext {
194             machine,
195             tcx,
196             param_env,
197             memory: Memory::new(tcx, memory_data),
198             stack: Vec::new(),
199             stack_limit: tcx.sess.const_eval_stack_frame_limit,
200             terminators_remaining: 1_000_000,
201         }
202     }
203
204     pub fn alloc_ptr(&mut self, ty: Ty<'tcx>) -> EvalResult<'tcx, MemoryPointer> {
205         let layout = self.layout_of(ty)?;
206         assert!(!layout.is_unsized(), "cannot alloc memory for unsized type");
207
208         let size = layout.size.bytes();
209         self.memory.allocate(size, layout.align, Some(MemoryKind::Stack))
210     }
211
212     pub fn memory(&self) -> &Memory<'a, 'mir, 'tcx, M> {
213         &self.memory
214     }
215
216     pub fn memory_mut(&mut self) -> &mut Memory<'a, 'mir, 'tcx, M> {
217         &mut self.memory
218     }
219
220     pub fn stack(&self) -> &[Frame<'mir, 'tcx>] {
221         &self.stack
222     }
223
224     #[inline]
225     pub fn cur_frame(&self) -> usize {
226         assert!(self.stack.len() > 0);
227         self.stack.len() - 1
228     }
229
230     pub fn str_to_value(&mut self, s: &str) -> EvalResult<'tcx, Value> {
231         let ptr = self.memory.allocate_cached(s.as_bytes());
232         Ok(Value::ByValPair(
233             PrimVal::Ptr(ptr),
234             PrimVal::from_u128(s.len() as u128),
235         ))
236     }
237
238     pub(super) fn const_to_value(&self, const_val: &ConstVal<'tcx>, ty: Ty<'tcx>) -> EvalResult<'tcx, Value> {
239         match *const_val {
240             ConstVal::Unevaluated(def_id, substs) => {
241                 let instance = self.resolve(def_id, substs)?;
242                 self.read_global_as_value(GlobalId {
243                     instance,
244                     promoted: None,
245                 }, ty)
246             }
247             ConstVal::Value(val) => Ok(val),
248         }
249     }
250
251     pub(super) fn resolve(&self, def_id: DefId, substs: &'tcx Substs<'tcx>) -> EvalResult<'tcx, ty::Instance<'tcx>> {
252         trace!("resolve: {:?}, {:#?}", def_id, substs);
253         trace!("substs: {:#?}", self.substs());
254         trace!("param_env: {:#?}", self.param_env);
255         let substs = self.tcx.subst_and_normalize_erasing_regions(
256             self.substs(),
257             self.param_env,
258             &substs,
259         );
260         ty::Instance::resolve(
261             *self.tcx,
262             self.param_env,
263             def_id,
264             substs,
265         ).ok_or_else(|| EvalErrorKind::TypeckError.into()) // turn error prop into a panic to expose associated type in const issue
266     }
267
268     pub(super) fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
269         ty.is_sized(self.tcx, self.param_env)
270     }
271
272     pub fn load_mir(
273         &self,
274         instance: ty::InstanceDef<'tcx>,
275     ) -> EvalResult<'tcx, &'tcx mir::Mir<'tcx>> {
276         // do not continue if typeck errors occurred (can only occur in local crate)
277         let did = instance.def_id();
278         if did.is_local() && self.tcx.has_typeck_tables(did) && self.tcx.typeck_tables_of(did).tainted_by_errors {
279             return err!(TypeckError);
280         }
281         trace!("load mir {:?}", instance);
282         match instance {
283             ty::InstanceDef::Item(def_id) => {
284                 self.tcx.maybe_optimized_mir(def_id).ok_or_else(||
285                     EvalErrorKind::NoMirFor(self.tcx.item_path_str(def_id)).into()
286                 )
287             }
288             _ => Ok(self.tcx.instance_mir(instance)),
289         }
290     }
291
292     pub fn monomorphize(&self, ty: Ty<'tcx>, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
293         // miri doesn't care about lifetimes, and will choke on some crazy ones
294         // let's simply get rid of them
295         let substituted = ty.subst(*self.tcx, substs);
296         self.tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), substituted)
297     }
298
299     /// Return the size and aligment of the value at the given type.
300     /// Note that the value does not matter if the type is sized. For unsized types,
301     /// the value has to be a fat pointer, and we only care about the "extra" data in it.
302     pub fn size_and_align_of_dst(
303         &mut self,
304         ty: Ty<'tcx>,
305         value: Value,
306     ) -> EvalResult<'tcx, (Size, Align)> {
307         let layout = self.layout_of(ty)?;
308         if !layout.is_unsized() {
309             Ok(layout.size_and_align())
310         } else {
311             match ty.sty {
312                 ty::TyAdt(..) | ty::TyTuple(..) => {
313                     // First get the size of all statically known fields.
314                     // Don't use type_of::sizing_type_of because that expects t to be sized,
315                     // and it also rounds up to alignment, which we want to avoid,
316                     // as the unsized field's alignment could be smaller.
317                     assert!(!ty.is_simd());
318                     debug!("DST {} layout: {:?}", ty, layout);
319
320                     let sized_size = layout.fields.offset(layout.fields.count() - 1);
321                     let sized_align = layout.align;
322                     debug!(
323                         "DST {} statically sized prefix size: {:?} align: {:?}",
324                         ty,
325                         sized_size,
326                         sized_align
327                     );
328
329                     // Recurse to get the size of the dynamically sized field (must be
330                     // the last field).
331                     let field_ty = layout.field(&self, layout.fields.count() - 1)?.ty;
332                     let (unsized_size, unsized_align) =
333                         self.size_and_align_of_dst(field_ty, value)?;
334
335                     // FIXME (#26403, #27023): We should be adding padding
336                     // to `sized_size` (to accommodate the `unsized_align`
337                     // required of the unsized field that follows) before
338                     // summing it with `sized_size`. (Note that since #26403
339                     // is unfixed, we do not yet add the necessary padding
340                     // here. But this is where the add would go.)
341
342                     // Return the sum of sizes and max of aligns.
343                     let size = sized_size + unsized_size;
344
345                     // Choose max of two known alignments (combined value must
346                     // be aligned according to more restrictive of the two).
347                     let align = sized_align.max(unsized_align);
348
349                     // Issue #27023: must add any necessary padding to `size`
350                     // (to make it a multiple of `align`) before returning it.
351                     //
352                     // Namely, the returned size should be, in C notation:
353                     //
354                     //   `size + ((size & (align-1)) ? align : 0)`
355                     //
356                     // emulated via the semi-standard fast bit trick:
357                     //
358                     //   `(size + (align-1)) & -align`
359
360                     Ok((size.abi_align(align), align))
361                 }
362                 ty::TyDynamic(..) => {
363                     let (_, vtable) = self.into_ptr_vtable_pair(value)?;
364                     // the second entry in the vtable is the dynamic size of the object.
365                     self.read_size_and_align_from_vtable(vtable)
366                 }
367
368                 ty::TySlice(_) | ty::TyStr => {
369                     let (elem_size, align) = layout.field(&self, 0)?.size_and_align();
370                     let (_, len) = self.into_slice(value)?;
371                     Ok((elem_size * len, align))
372                 }
373
374                 _ => bug!("size_of_val::<{:?}>", ty),
375             }
376         }
377     }
378
379     pub fn push_stack_frame(
380         &mut self,
381         instance: ty::Instance<'tcx>,
382         span: codemap::Span,
383         mir: &'mir mir::Mir<'tcx>,
384         return_place: Place,
385         return_to_block: StackPopCleanup,
386     ) -> EvalResult<'tcx> {
387         ::log_settings::settings().indentation += 1;
388
389         let locals = if mir.local_decls.len() > 1 {
390             let mut locals = IndexVec::from_elem(Some(Value::ByVal(PrimVal::Undef)), &mir.local_decls);
391             match self.tcx.describe_def(instance.def_id()) {
392                 // statics and constants don't have `Storage*` statements, no need to look for them
393                 Some(Def::Static(..)) | Some(Def::Const(..)) | Some(Def::AssociatedConst(..)) => {},
394                 _ => {
395                     trace!("push_stack_frame: {:?}: num_bbs: {}", span, mir.basic_blocks().len());
396                     for block in mir.basic_blocks() {
397                         for stmt in block.statements.iter() {
398                             use rustc::mir::StatementKind::{StorageDead, StorageLive};
399                             match stmt.kind {
400                                 StorageLive(local) |
401                                 StorageDead(local) => locals[local] = None,
402                                 _ => {}
403                             }
404                         }
405                     }
406                 },
407             }
408             locals
409         } else {
410             // don't allocate at all for trivial constants
411             IndexVec::new()
412         };
413
414         self.stack.push(Frame {
415             mir,
416             block: mir::START_BLOCK,
417             return_to_block,
418             return_place,
419             locals,
420             span,
421             instance,
422             stmt: 0,
423         });
424
425         self.memory.cur_frame = self.cur_frame();
426
427         if self.stack.len() > self.stack_limit {
428             err!(StackFrameLimitReached)
429         } else {
430             Ok(())
431         }
432     }
433
434     pub(super) fn pop_stack_frame(&mut self) -> EvalResult<'tcx> {
435         ::log_settings::settings().indentation -= 1;
436         M::end_region(self, None)?;
437         let frame = self.stack.pop().expect(
438             "tried to pop a stack frame, but there were none",
439         );
440         if !self.stack.is_empty() {
441             // TODO: Is this the correct time to start considering these accesses as originating from the returned-to stack frame?
442             self.memory.cur_frame = self.cur_frame();
443         }
444         match frame.return_to_block {
445             StackPopCleanup::MarkStatic(mutable) => {
446                 if let Place::Ptr { ptr, .. } = frame.return_place {
447                     // FIXME: to_ptr()? might be too extreme here, static zsts might reach this under certain conditions
448                     self.memory.mark_static_initialized(
449                         ptr.to_ptr()?.alloc_id,
450                         mutable,
451                     )?
452                 } else {
453                     bug!("StackPopCleanup::MarkStatic on: {:?}", frame.return_place);
454                 }
455             }
456             StackPopCleanup::Goto(target) => self.goto_block(target),
457             StackPopCleanup::None => {}
458         }
459         // deallocate all locals that are backed by an allocation
460         for local in frame.locals {
461             self.deallocate_local(local)?;
462         }
463
464         Ok(())
465     }
466
467     pub fn deallocate_local(&mut self, local: Option<Value>) -> EvalResult<'tcx> {
468         if let Some(Value::ByRef(ptr, _align)) = local {
469             trace!("deallocating local");
470             let ptr = ptr.to_ptr()?;
471             self.memory.dump_alloc(ptr.alloc_id);
472             self.memory.deallocate_local(ptr)?;
473         };
474         Ok(())
475     }
476
477     /// Evaluate an assignment statement.
478     ///
479     /// There is no separate `eval_rvalue` function. Instead, the code for handling each rvalue
480     /// type writes its results directly into the memory specified by the place.
481     pub(super) fn eval_rvalue_into_place(
482         &mut self,
483         rvalue: &mir::Rvalue<'tcx>,
484         place: &mir::Place<'tcx>,
485     ) -> EvalResult<'tcx> {
486         let dest = self.eval_place(place)?;
487         let dest_ty = self.place_ty(place);
488
489         use rustc::mir::Rvalue::*;
490         match *rvalue {
491             Use(ref operand) => {
492                 let value = self.eval_operand(operand)?.value;
493                 let valty = ValTy {
494                     value,
495                     ty: dest_ty,
496                 };
497                 self.write_value(valty, dest)?;
498             }
499
500             BinaryOp(bin_op, ref left, ref right) => {
501                 let left = self.eval_operand(left)?;
502                 let right = self.eval_operand(right)?;
503                 if self.intrinsic_overflowing(
504                     bin_op,
505                     left,
506                     right,
507                     dest,
508                     dest_ty,
509                 )?
510                 {
511                     // There was an overflow in an unchecked binop.  Right now, we consider this an error and bail out.
512                     // The rationale is that the reason rustc emits unchecked binops in release mode (vs. the checked binops
513                     // it emits in debug mode) is performance, but it doesn't cost us any performance in miri.
514                     // If, however, the compiler ever starts transforming unchecked intrinsics into unchecked binops,
515                     // we have to go back to just ignoring the overflow here.
516                     return err!(OverflowingMath);
517                 }
518             }
519
520             CheckedBinaryOp(bin_op, ref left, ref right) => {
521                 let left = self.eval_operand(left)?;
522                 let right = self.eval_operand(right)?;
523                 self.intrinsic_with_overflow(
524                     bin_op,
525                     left,
526                     right,
527                     dest,
528                     dest_ty,
529                 )?;
530             }
531
532             UnaryOp(un_op, ref operand) => {
533                 let val = self.eval_operand_to_primval(operand)?;
534                 let val = self.unary_op(un_op, val, dest_ty)?;
535                 self.write_primval(
536                     dest,
537                     val,
538                     dest_ty,
539                 )?;
540             }
541
542             Aggregate(ref kind, ref operands) => {
543                 self.inc_step_counter_and_check_limit(operands.len());
544
545                 let (dest, active_field_index) = match **kind {
546                     mir::AggregateKind::Adt(adt_def, variant_index, _, active_field_index) => {
547                         self.write_discriminant_value(dest_ty, dest, variant_index)?;
548                         if adt_def.is_enum() {
549                             (self.place_downcast(dest, variant_index)?, active_field_index)
550                         } else {
551                             (dest, active_field_index)
552                         }
553                     }
554                     _ => (dest, None)
555                 };
556
557                 let layout = self.layout_of(dest_ty)?;
558                 for (i, operand) in operands.iter().enumerate() {
559                     let value = self.eval_operand(operand)?;
560                     // Ignore zero-sized fields.
561                     if !self.layout_of(value.ty)?.is_zst() {
562                         let field_index = active_field_index.unwrap_or(i);
563                         let (field_dest, _) = self.place_field(dest, mir::Field::new(field_index), layout)?;
564                         self.write_value(value, field_dest)?;
565                     }
566                 }
567             }
568
569             Repeat(ref operand, _) => {
570                 let (elem_ty, length) = match dest_ty.sty {
571                     ty::TyArray(elem_ty, n) => (elem_ty, n.val.unwrap_u64()),
572                     _ => {
573                         bug!(
574                             "tried to assign array-repeat to non-array type {:?}",
575                             dest_ty
576                         )
577                     }
578                 };
579                 let elem_size = self.layout_of(elem_ty)?.size.bytes();
580                 let value = self.eval_operand(operand)?.value;
581
582                 let (dest, dest_align) = self.force_allocation(dest)?.to_ptr_align();
583
584                 // FIXME: speed up repeat filling
585                 for i in 0..length {
586                     let elem_dest = dest.offset(i * elem_size, &self)?;
587                     self.write_value_to_ptr(value, elem_dest, dest_align, elem_ty)?;
588                 }
589             }
590
591             Len(ref place) => {
592                 // FIXME(CTFE): don't allow computing the length of arrays in const eval
593                 let src = self.eval_place(place)?;
594                 let ty = self.place_ty(place);
595                 let (_, len) = src.elem_ty_and_len(ty);
596                 self.write_primval(
597                     dest,
598                     PrimVal::from_u128(len as u128),
599                     dest_ty,
600                 )?;
601             }
602
603             Ref(_, _, ref place) => {
604                 let src = self.eval_place(place)?;
605                 // We ignore the alignment of the place here -- special handling for packed structs ends
606                 // at the `&` operator.
607                 let (ptr, _align, extra) = self.force_allocation(src)?.to_ptr_align_extra();
608
609                 let val = match extra {
610                     PlaceExtra::None => ptr.to_value(),
611                     PlaceExtra::Length(len) => ptr.to_value_with_len(len),
612                     PlaceExtra::Vtable(vtable) => ptr.to_value_with_vtable(vtable),
613                     PlaceExtra::DowncastVariant(..) => {
614                         bug!("attempted to take a reference to an enum downcast place")
615                     }
616                 };
617                 let valty = ValTy {
618                     value: val,
619                     ty: dest_ty,
620                 };
621                 self.write_value(valty, dest)?;
622             }
623
624             NullaryOp(mir::NullOp::Box, ty) => {
625                 let ty = self.monomorphize(ty, self.substs());
626                 M::box_alloc(self, ty, dest)?;
627             }
628
629             NullaryOp(mir::NullOp::SizeOf, ty) => {
630                 let ty = self.monomorphize(ty, self.substs());
631                 let layout = self.layout_of(ty)?;
632                 assert!(!layout.is_unsized(),
633                         "SizeOf nullary MIR operator called for unsized type");
634                 self.write_primval(
635                     dest,
636                     PrimVal::from_u128(layout.size.bytes() as u128),
637                     dest_ty,
638                 )?;
639             }
640
641             Cast(kind, ref operand, cast_ty) => {
642                 debug_assert_eq!(self.monomorphize(cast_ty, self.substs()), dest_ty);
643                 use rustc::mir::CastKind::*;
644                 match kind {
645                     Unsize => {
646                         let src = self.eval_operand(operand)?;
647                         let src_layout = self.layout_of(src.ty)?;
648                         let dst_layout = self.layout_of(dest_ty)?;
649                         self.unsize_into(src.value, src_layout, dest, dst_layout)?;
650                     }
651
652                     Misc => {
653                         let src = self.eval_operand(operand)?;
654                         if self.type_is_fat_ptr(src.ty) {
655                             match (src.value, self.type_is_fat_ptr(dest_ty)) {
656                                 (Value::ByRef { .. }, _) |
657                                 (Value::ByValPair(..), true) => {
658                                     let valty = ValTy {
659                                         value: src.value,
660                                         ty: dest_ty,
661                                     };
662                                     self.write_value(valty, dest)?;
663                                 }
664                                 (Value::ByValPair(data, _), false) => {
665                                     let valty = ValTy {
666                                         value: Value::ByVal(data),
667                                         ty: dest_ty,
668                                     };
669                                     self.write_value(valty, dest)?;
670                                 }
671                                 (Value::ByVal(_), _) => bug!("expected fat ptr"),
672                             }
673                         } else {
674                             let src_layout = self.layout_of(src.ty)?;
675                             match src_layout.variants {
676                                 layout::Variants::Single { index } => {
677                                     if let Some(def) = src.ty.ty_adt_def() {
678                                         let discr_val = def
679                                             .discriminant_for_variant(*self.tcx, index)
680                                             .val;
681                                         return self.write_primval(
682                                             dest,
683                                             PrimVal::Bytes(discr_val),
684                                             dest_ty);
685                                     }
686                                 }
687                                 layout::Variants::Tagged { .. } |
688                                 layout::Variants::NicheFilling { .. } => {},
689                             }
690
691                             let src_val = self.value_to_primval(src)?;
692                             let dest_val = self.cast_primval(src_val, src.ty, dest_ty)?;
693                             let valty = ValTy {
694                                 value: Value::ByVal(dest_val),
695                                 ty: dest_ty,
696                             };
697                             self.write_value(valty, dest)?;
698                         }
699                     }
700
701                     ReifyFnPointer => {
702                         match self.eval_operand(operand)?.ty.sty {
703                             ty::TyFnDef(def_id, substs) => {
704                                 if self.tcx.has_attr(def_id, "rustc_args_required_const") {
705                                     bug!("reifying a fn ptr that requires \
706                                           const arguments");
707                                 }
708                                 let instance: EvalResult<'tcx, _> = ty::Instance::resolve(
709                                     *self.tcx,
710                                     self.param_env,
711                                     def_id,
712                                     substs,
713                                 ).ok_or_else(|| EvalErrorKind::TypeckError.into());
714                                 let fn_ptr = self.memory.create_fn_alloc(instance?);
715                                 let valty = ValTy {
716                                     value: Value::ByVal(PrimVal::Ptr(fn_ptr)),
717                                     ty: dest_ty,
718                                 };
719                                 self.write_value(valty, dest)?;
720                             }
721                             ref other => bug!("reify fn pointer on {:?}", other),
722                         }
723                     }
724
725                     UnsafeFnPointer => {
726                         match dest_ty.sty {
727                             ty::TyFnPtr(_) => {
728                                 let mut src = self.eval_operand(operand)?;
729                                 src.ty = dest_ty;
730                                 self.write_value(src, dest)?;
731                             }
732                             ref other => bug!("fn to unsafe fn cast on {:?}", other),
733                         }
734                     }
735
736                     ClosureFnPointer => {
737                         match self.eval_operand(operand)?.ty.sty {
738                             ty::TyClosure(def_id, substs) => {
739                                 let substs = self.tcx.subst_and_normalize_erasing_regions(
740                                     self.substs(),
741                                     ty::ParamEnv::reveal_all(),
742                                     &substs,
743                                 );
744                                 let instance = ty::Instance::resolve_closure(
745                                     *self.tcx,
746                                     def_id,
747                                     substs,
748                                     ty::ClosureKind::FnOnce,
749                                 );
750                                 let fn_ptr = self.memory.create_fn_alloc(instance);
751                                 let valty = ValTy {
752                                     value: Value::ByVal(PrimVal::Ptr(fn_ptr)),
753                                     ty: dest_ty,
754                                 };
755                                 self.write_value(valty, dest)?;
756                             }
757                             ref other => bug!("closure fn pointer on {:?}", other),
758                         }
759                     }
760                 }
761             }
762
763             Discriminant(ref place) => {
764                 let ty = self.place_ty(place);
765                 let place = self.eval_place(place)?;
766                 let discr_val = self.read_discriminant_value(place, ty)?;
767                 self.write_primval(dest, PrimVal::Bytes(discr_val), dest_ty)?;
768             }
769         }
770
771         if log_enabled!(::log::Level::Trace) {
772             self.dump_local(dest);
773         }
774
775         Ok(())
776     }
777
778     pub(super) fn type_is_fat_ptr(&self, ty: Ty<'tcx>) -> bool {
779         match ty.sty {
780             ty::TyRawPtr(ref tam) |
781             ty::TyRef(_, ref tam) => !self.type_is_sized(tam.ty),
782             ty::TyAdt(def, _) if def.is_box() => !self.type_is_sized(ty.boxed_ty()),
783             _ => false,
784         }
785     }
786
787     pub(super) fn eval_operand_to_primval(
788         &mut self,
789         op: &mir::Operand<'tcx>,
790     ) -> EvalResult<'tcx, PrimVal> {
791         let valty = self.eval_operand(op)?;
792         self.value_to_primval(valty)
793     }
794
795     pub(crate) fn operands_to_args(
796         &mut self,
797         ops: &[mir::Operand<'tcx>],
798     ) -> EvalResult<'tcx, Vec<ValTy<'tcx>>> {
799         ops.into_iter()
800             .map(|op| self.eval_operand(op))
801             .collect()
802     }
803
804     pub fn eval_operand(&mut self, op: &mir::Operand<'tcx>) -> EvalResult<'tcx, ValTy<'tcx>> {
805         use rustc::mir::Operand::*;
806         let ty = self.monomorphize(op.ty(self.mir(), *self.tcx), self.substs());
807         match *op {
808             // FIXME: do some more logic on `move` to invalidate the old location
809             Copy(ref place) |
810             Move(ref place) => {
811                 Ok(ValTy {
812                     value: self.eval_and_read_place(place)?,
813                     ty
814                 })
815             },
816
817             Constant(ref constant) => {
818                 use rustc::mir::Literal;
819                 let mir::Constant { ref literal, .. } = **constant;
820                 let value = match *literal {
821                     Literal::Value { ref value } => self.const_to_value(&value.val, ty)?,
822
823                     Literal::Promoted { index } => {
824                         self.read_global_as_value(GlobalId {
825                             instance: self.frame().instance,
826                             promoted: Some(index),
827                         }, ty)?
828                     }
829                 };
830
831                 Ok(ValTy {
832                     value,
833                     ty,
834                 })
835             }
836         }
837     }
838
839     /// reads a tag and produces the corresponding variant index
840     pub fn read_discriminant_as_variant_index(
841         &mut self,
842         place: Place,
843         ty: Ty<'tcx>,
844     ) -> EvalResult<'tcx, usize> {
845         let layout = self.layout_of(ty)?;
846         match layout.variants {
847             ty::layout::Variants::Single { index } => Ok(index),
848             ty::layout::Variants::Tagged { .. } => {
849                 let discr_val = self.read_discriminant_value(place, ty)?;
850                 ty
851                     .ty_adt_def()
852                     .expect("tagged layout for non adt")
853                     .discriminants(self.tcx.tcx)
854                     .position(|var| var.val == discr_val)
855                     .ok_or_else(|| EvalErrorKind::InvalidDiscriminant.into())
856             }
857             ty::layout::Variants::NicheFilling { .. } => {
858                 let discr_val = self.read_discriminant_value(place, ty)?;
859                 assert_eq!(discr_val as usize as u128, discr_val);
860                 Ok(discr_val as usize)
861             },
862         }
863     }
864
865     pub fn read_discriminant_value(
866         &mut self,
867         place: Place,
868         ty: Ty<'tcx>,
869     ) -> EvalResult<'tcx, u128> {
870         let layout = self.layout_of(ty)?;
871         trace!("read_discriminant_value {:#?}", layout);
872         if layout.abi == layout::Abi::Uninhabited {
873             return Ok(0);
874         }
875
876         match layout.variants {
877             layout::Variants::Single { index } => {
878                 let discr_val = ty.ty_adt_def().map_or(
879                     index as u128,
880                     |def| def.discriminant_for_variant(*self.tcx, index).val);
881                 return Ok(discr_val);
882             }
883             layout::Variants::Tagged { .. } |
884             layout::Variants::NicheFilling { .. } => {},
885         }
886
887         let (discr_place, discr) = self.place_field(place, mir::Field::new(0), layout)?;
888         trace!("discr place: {:?}, {:?}", discr_place, discr);
889         let raw_discr = self.value_to_primval(ValTy {
890             value: self.read_place(discr_place)?,
891             ty: discr.ty
892         })?;
893         let discr_val = match layout.variants {
894             layout::Variants::Single { .. } => bug!(),
895             // FIXME: should we catch invalid discriminants here?
896             layout::Variants::Tagged { .. } => {
897                 if discr.ty.is_signed() {
898                     let i = raw_discr.to_bytes()? as i128;
899                     // going from layout tag type to typeck discriminant type
900                     // requires first sign extending with the layout discriminant
901                     let amt = 128 - discr.size.bits();
902                     let sexted = (i << amt) >> amt;
903                     // and then zeroing with the typeck discriminant type
904                     let discr_ty = ty
905                         .ty_adt_def().expect("tagged layout corresponds to adt")
906                         .repr
907                         .discr_type();
908                     let discr_ty = layout::Integer::from_attr(self.tcx.tcx, discr_ty);
909                     let amt = 128 - discr_ty.size().bits();
910                     let truncatee = sexted as u128;
911                     (truncatee << amt) >> amt
912                 } else {
913                     raw_discr.to_bytes()?
914                 }
915             },
916             layout::Variants::NicheFilling {
917                 dataful_variant,
918                 ref niche_variants,
919                 niche_start,
920                 ..
921             } => {
922                 let variants_start = niche_variants.start as u128;
923                 let variants_end = niche_variants.end as u128;
924                 match raw_discr {
925                     PrimVal::Ptr(_) => {
926                         assert!(niche_start == 0);
927                         assert!(variants_start == variants_end);
928                         dataful_variant as u128
929                     },
930                     PrimVal::Bytes(raw_discr) => {
931                         let discr = raw_discr.wrapping_sub(niche_start)
932                             .wrapping_add(variants_start);
933                         if variants_start <= discr && discr <= variants_end {
934                             discr
935                         } else {
936                             dataful_variant as u128
937                         }
938                     },
939                     PrimVal::Undef => return err!(ReadUndefBytes),
940                 }
941             }
942         };
943
944         Ok(discr_val)
945     }
946
947
948     pub fn write_discriminant_value(
949         &mut self,
950         dest_ty: Ty<'tcx>,
951         dest: Place,
952         variant_index: usize,
953     ) -> EvalResult<'tcx> {
954         let layout = self.layout_of(dest_ty)?;
955
956         match layout.variants {
957             layout::Variants::Single { index } => {
958                 if index != variant_index {
959                     // If the layout of an enum is `Single`, all
960                     // other variants are necessarily uninhabited.
961                     assert_eq!(layout.for_variant(&self, variant_index).abi,
962                                layout::Abi::Uninhabited);
963                 }
964             }
965             layout::Variants::Tagged { ref discr, .. } => {
966                 let discr_val = dest_ty.ty_adt_def().unwrap()
967                     .discriminant_for_variant(*self.tcx, variant_index)
968                     .val;
969
970                 // raw discriminants for enums are isize or bigger during
971                 // their computation, but the in-memory tag is the smallest possible
972                 // representation
973                 let size = discr.value.size(self.tcx.tcx).bits();
974                 let amt = 128 - size;
975                 let discr_val = (discr_val << amt) >> amt;
976
977                 let (discr_dest, discr) = self.place_field(dest, mir::Field::new(0), layout)?;
978                 self.write_primval(discr_dest, PrimVal::Bytes(discr_val), discr.ty)?;
979             }
980             layout::Variants::NicheFilling {
981                 dataful_variant,
982                 ref niche_variants,
983                 niche_start,
984                 ..
985             } => {
986                 if variant_index != dataful_variant {
987                     let (niche_dest, niche) =
988                         self.place_field(dest, mir::Field::new(0), layout)?;
989                     let niche_value = ((variant_index - niche_variants.start) as u128)
990                         .wrapping_add(niche_start);
991                     self.write_primval(niche_dest, PrimVal::Bytes(niche_value), niche.ty)?;
992                 }
993             }
994         }
995
996         Ok(())
997     }
998
999     pub fn read_global_as_value(&self, gid: GlobalId<'tcx>, ty: Ty<'tcx>) -> EvalResult<'tcx, Value> {
1000         if self.tcx.is_static(gid.instance.def_id()).is_some() {
1001             let alloc_id = self
1002                 .tcx
1003                 .interpret_interner
1004                 .cache_static(gid.instance.def_id());
1005             let layout = self.layout_of(ty)?;
1006             let ptr = MemoryPointer::new(alloc_id, 0);
1007             return Ok(Value::ByRef(ptr.into(), layout.align))
1008         }
1009         let cv = self.const_eval(gid)?;
1010         self.const_to_value(&cv.val, ty)
1011     }
1012
1013     pub fn const_eval(&self, gid: GlobalId<'tcx>) -> EvalResult<'tcx, &'tcx ty::Const<'tcx>> {
1014         let param_env = if self.tcx.is_static(gid.instance.def_id()).is_some() {
1015             ty::ParamEnv::reveal_all()
1016         } else {
1017             self.param_env
1018         };
1019         self.tcx.const_eval(param_env.and(gid)).map_err(|err| match *err.kind {
1020             ErrKind::Miri(ref err, _) => match err.kind {
1021                 EvalErrorKind::TypeckError |
1022                 EvalErrorKind::Layout(_) => EvalErrorKind::TypeckError.into(),
1023                 _ => EvalErrorKind::ReferencedConstant.into(),
1024             },
1025             ErrKind::TypeckError => EvalErrorKind::TypeckError.into(),
1026             ref other => bug!("const eval returned {:?}", other),
1027         })
1028     }
1029
1030     pub fn force_allocation(&mut self, place: Place) -> EvalResult<'tcx, Place> {
1031         let new_place = match place {
1032             Place::Local { frame, local } => {
1033                 match self.stack[frame].locals[local] {
1034                     None => return err!(DeadLocal),
1035                     Some(Value::ByRef(ptr, align)) => {
1036                         Place::Ptr {
1037                             ptr,
1038                             align,
1039                             extra: PlaceExtra::None,
1040                         }
1041                     }
1042                     Some(val) => {
1043                         let ty = self.stack[frame].mir.local_decls[local].ty;
1044                         let ty = self.monomorphize(ty, self.stack[frame].instance.substs);
1045                         let layout = self.layout_of(ty)?;
1046                         let ptr = self.alloc_ptr(ty)?;
1047                         self.stack[frame].locals[local] =
1048                             Some(Value::ByRef(ptr.into(), layout.align)); // it stays live
1049                         let place = Place::from_ptr(ptr, layout.align);
1050                         self.write_value(ValTy { value: val, ty }, place)?;
1051                         place
1052                     }
1053                 }
1054             }
1055             Place::Ptr { .. } => place,
1056         };
1057         Ok(new_place)
1058     }
1059
1060     /// ensures this Value is not a ByRef
1061     pub fn follow_by_ref_value(
1062         &self,
1063         value: Value,
1064         ty: Ty<'tcx>,
1065     ) -> EvalResult<'tcx, Value> {
1066         match value {
1067             Value::ByRef(ptr, align) => {
1068                 self.read_value(ptr, align, ty)
1069             }
1070             other => Ok(other),
1071         }
1072     }
1073
1074     pub fn value_to_primval(
1075         &self,
1076         ValTy { value, ty } : ValTy<'tcx>,
1077     ) -> EvalResult<'tcx, PrimVal> {
1078         match self.follow_by_ref_value(value, ty)? {
1079             Value::ByRef { .. } => bug!("follow_by_ref_value can't result in `ByRef`"),
1080
1081             Value::ByVal(primval) => {
1082                 // TODO: Do we really want insta-UB here?
1083                 self.ensure_valid_value(primval, ty)?;
1084                 Ok(primval)
1085             }
1086
1087             Value::ByValPair(..) => bug!("value_to_primval can't work with fat pointers"),
1088         }
1089     }
1090
1091     pub fn write_ptr(&mut self, dest: Place, val: Pointer, dest_ty: Ty<'tcx>) -> EvalResult<'tcx> {
1092         let valty = ValTy {
1093             value: val.to_value(),
1094             ty: dest_ty,
1095         };
1096         self.write_value(valty, dest)
1097     }
1098
1099     pub fn write_primval(
1100         &mut self,
1101         dest: Place,
1102         val: PrimVal,
1103         dest_ty: Ty<'tcx>,
1104     ) -> EvalResult<'tcx> {
1105         let valty = ValTy {
1106             value: Value::ByVal(val),
1107             ty: dest_ty,
1108         };
1109         self.write_value(valty, dest)
1110     }
1111
1112     pub fn write_value(
1113         &mut self,
1114         ValTy { value: src_val, ty: dest_ty } : ValTy<'tcx>,
1115         dest: Place,
1116     ) -> EvalResult<'tcx> {
1117         //trace!("Writing {:?} to {:?} at type {:?}", src_val, dest, dest_ty);
1118         // Note that it is really important that the type here is the right one, and matches the type things are read at.
1119         // In case `src_val` is a `ByValPair`, we don't do any magic here to handle padding properly, which is only
1120         // correct if we never look at this data with the wrong type.
1121
1122         match dest {
1123             Place::Ptr { ptr, align, extra } => {
1124                 assert_eq!(extra, PlaceExtra::None);
1125                 self.write_value_to_ptr(src_val, ptr, align, dest_ty)
1126             }
1127
1128             Place::Local { frame, local } => {
1129                 let dest = self.stack[frame].get_local(local)?;
1130                 self.write_value_possibly_by_val(
1131                     src_val,
1132                     |this, val| this.stack[frame].set_local(local, val),
1133                     dest,
1134                     dest_ty,
1135                 )
1136             }
1137         }
1138     }
1139
1140     // The cases here can be a bit subtle. Read carefully!
1141     fn write_value_possibly_by_val<F: FnOnce(&mut Self, Value) -> EvalResult<'tcx>>(
1142         &mut self,
1143         src_val: Value,
1144         write_dest: F,
1145         old_dest_val: Value,
1146         dest_ty: Ty<'tcx>,
1147     ) -> EvalResult<'tcx> {
1148         if let Value::ByRef(dest_ptr, align) = old_dest_val {
1149             // If the value is already `ByRef` (that is, backed by an `Allocation`),
1150             // then we must write the new value into this allocation, because there may be
1151             // other pointers into the allocation. These other pointers are logically
1152             // pointers into the local variable, and must be able to observe the change.
1153             //
1154             // Thus, it would be an error to replace the `ByRef` with a `ByVal`, unless we
1155             // knew for certain that there were no outstanding pointers to this allocation.
1156             self.write_value_to_ptr(src_val, dest_ptr, align, dest_ty)?;
1157         } else if let Value::ByRef(src_ptr, align) = src_val {
1158             // If the value is not `ByRef`, then we know there are no pointers to it
1159             // and we can simply overwrite the `Value` in the locals array directly.
1160             //
1161             // In this specific case, where the source value is `ByRef`, we must duplicate
1162             // the allocation, because this is a by-value operation. It would be incorrect
1163             // if they referred to the same allocation, since then a change to one would
1164             // implicitly change the other.
1165             //
1166             // It is a valid optimization to attempt reading a primitive value out of the
1167             // source and write that into the destination without making an allocation, so
1168             // we do so here.
1169             if let Ok(Some(src_val)) = self.try_read_value(src_ptr, align, dest_ty) {
1170                 write_dest(self, src_val)?;
1171             } else {
1172                 let dest_ptr = self.alloc_ptr(dest_ty)?.into();
1173                 let layout = self.layout_of(dest_ty)?;
1174                 self.memory.copy(src_ptr, align.min(layout.align), dest_ptr, layout.align, layout.size.bytes(), false)?;
1175                 write_dest(self, Value::ByRef(dest_ptr, layout.align))?;
1176             }
1177         } else {
1178             // Finally, we have the simple case where neither source nor destination are
1179             // `ByRef`. We may simply copy the source value over the the destintion.
1180             write_dest(self, src_val)?;
1181         }
1182         Ok(())
1183     }
1184
1185     pub fn write_value_to_ptr(
1186         &mut self,
1187         value: Value,
1188         dest: Pointer,
1189         dest_align: Align,
1190         dest_ty: Ty<'tcx>,
1191     ) -> EvalResult<'tcx> {
1192         let layout = self.layout_of(dest_ty)?;
1193         trace!("write_value_to_ptr: {:#?}, {}, {:#?}", value, dest_ty, layout);
1194         match value {
1195             Value::ByRef(ptr, align) => {
1196                 self.memory.copy(ptr, align.min(layout.align), dest, dest_align.min(layout.align), layout.size.bytes(), false)
1197             }
1198             Value::ByVal(primval) => {
1199                 let signed = match layout.abi {
1200                     layout::Abi::Scalar(ref scal) => match scal.value {
1201                         layout::Primitive::Int(_, signed) => signed,
1202                         _ => false,
1203                     },
1204                     _ if primval.is_undef() => false,
1205                     _ => bug!("write_value_to_ptr: invalid ByVal layout: {:#?}", layout)
1206                 };
1207                 self.memory.write_primval(dest, dest_align, primval, layout.size.bytes(), signed)
1208             }
1209             Value::ByValPair(a_val, b_val) => {
1210                 trace!("write_value_to_ptr valpair: {:#?}", layout);
1211                 let (a, b) = match layout.abi {
1212                     layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
1213                     _ => bug!("write_value_to_ptr: invalid ByValPair layout: {:#?}", layout)
1214                 };
1215                 let (a_size, b_size) = (a.size(&self), b.size(&self));
1216                 let a_ptr = dest;
1217                 let b_offset = a_size.abi_align(b.align(&self));
1218                 let b_ptr = dest.offset(b_offset.bytes(), &self)?.into();
1219                 // TODO: What about signedess?
1220                 self.memory.write_primval(a_ptr, dest_align, a_val, a_size.bytes(), false)?;
1221                 self.memory.write_primval(b_ptr, dest_align, b_val, b_size.bytes(), false)
1222             }
1223         }
1224     }
1225
1226     pub fn ty_to_primval_kind(&self, ty: Ty<'tcx>) -> EvalResult<'tcx, PrimValKind> {
1227         use syntax::ast::FloatTy;
1228
1229         let kind = match ty.sty {
1230             ty::TyBool => PrimValKind::Bool,
1231             ty::TyChar => PrimValKind::Char,
1232
1233             ty::TyInt(int_ty) => {
1234                 use syntax::ast::IntTy::*;
1235                 let size = match int_ty {
1236                     I8 => 1,
1237                     I16 => 2,
1238                     I32 => 4,
1239                     I64 => 8,
1240                     I128 => 16,
1241                     Isize => self.memory.pointer_size(),
1242                 };
1243                 PrimValKind::from_int_size(size)
1244             }
1245
1246             ty::TyUint(uint_ty) => {
1247                 use syntax::ast::UintTy::*;
1248                 let size = match uint_ty {
1249                     U8 => 1,
1250                     U16 => 2,
1251                     U32 => 4,
1252                     U64 => 8,
1253                     U128 => 16,
1254                     Usize => self.memory.pointer_size(),
1255                 };
1256                 PrimValKind::from_uint_size(size)
1257             }
1258
1259             ty::TyFloat(FloatTy::F32) => PrimValKind::F32,
1260             ty::TyFloat(FloatTy::F64) => PrimValKind::F64,
1261
1262             ty::TyFnPtr(_) => PrimValKind::FnPtr,
1263
1264             ty::TyRef(_, ref tam) |
1265             ty::TyRawPtr(ref tam) if self.type_is_sized(tam.ty) => PrimValKind::Ptr,
1266
1267             ty::TyAdt(def, _) if def.is_box() => PrimValKind::Ptr,
1268
1269             ty::TyAdt(..) => {
1270                 match self.layout_of(ty)?.abi {
1271                     layout::Abi::Scalar(ref scalar) => {
1272                         use rustc::ty::layout::Primitive::*;
1273                         match scalar.value {
1274                             Int(i, false) => PrimValKind::from_uint_size(i.size().bytes()),
1275                             Int(i, true) => PrimValKind::from_int_size(i.size().bytes()),
1276                             F32 => PrimValKind::F32,
1277                             F64 => PrimValKind::F64,
1278                             Pointer => PrimValKind::Ptr,
1279                         }
1280                     }
1281
1282                     _ => return err!(TypeNotPrimitive(ty)),
1283                 }
1284             }
1285
1286             _ => return err!(TypeNotPrimitive(ty)),
1287         };
1288
1289         Ok(kind)
1290     }
1291
1292     fn ensure_valid_value(&self, val: PrimVal, ty: Ty<'tcx>) -> EvalResult<'tcx> {
1293         match ty.sty {
1294             ty::TyBool if val.to_bytes()? > 1 => err!(InvalidBool),
1295
1296             ty::TyChar if ::std::char::from_u32(val.to_bytes()? as u32).is_none() => {
1297                 err!(InvalidChar(val.to_bytes()? as u32 as u128))
1298             }
1299
1300             _ => Ok(()),
1301         }
1302     }
1303
1304     pub fn read_value(&self, ptr: Pointer, align: Align, ty: Ty<'tcx>) -> EvalResult<'tcx, Value> {
1305         if let Some(val) = self.try_read_value(ptr, align, ty)? {
1306             Ok(val)
1307         } else {
1308             bug!("primitive read failed for type: {:?}", ty);
1309         }
1310     }
1311
1312     pub(crate) fn read_ptr(
1313         &self,
1314         ptr: MemoryPointer,
1315         ptr_align: Align,
1316         pointee_ty: Ty<'tcx>,
1317     ) -> EvalResult<'tcx, Value> {
1318         let ptr_size = self.memory.pointer_size();
1319         let p: Pointer = self.memory.read_ptr_sized(ptr, ptr_align)?.into();
1320         if self.type_is_sized(pointee_ty) {
1321             Ok(p.to_value())
1322         } else {
1323             trace!("reading fat pointer extra of type {}", pointee_ty);
1324             let extra = ptr.offset(ptr_size, self)?;
1325             match self.tcx.struct_tail(pointee_ty).sty {
1326                 ty::TyDynamic(..) => Ok(p.to_value_with_vtable(
1327                     self.memory.read_ptr_sized(extra, ptr_align)?.to_ptr()?,
1328                 )),
1329                 ty::TySlice(..) | ty::TyStr => {
1330                     let len = self
1331                         .memory
1332                         .read_ptr_sized(extra, ptr_align)?
1333                         .to_bytes()?;
1334                     Ok(p.to_value_with_len(len as u64))
1335                 },
1336                 _ => bug!("unsized primval ptr read from {:?}", pointee_ty),
1337             }
1338         }
1339     }
1340
1341     pub fn try_read_value(&self, ptr: Pointer, ptr_align: Align, ty: Ty<'tcx>) -> EvalResult<'tcx, Option<Value>> {
1342         use syntax::ast::FloatTy;
1343
1344         let layout = self.layout_of(ty)?;
1345         // do the strongest layout check of the two
1346         let align = layout.align.max(ptr_align);
1347         self.memory.check_align(ptr, align)?;
1348
1349         if layout.size.bytes() == 0 {
1350             return Ok(Some(Value::ByVal(PrimVal::Undef)));
1351         }
1352
1353         let ptr = ptr.to_ptr()?;
1354         let val = match ty.sty {
1355             ty::TyBool => {
1356                 let val = self.memory.read_primval(ptr, ptr_align, 1)?;
1357                 let val = match val {
1358                     PrimVal::Bytes(0) => false,
1359                     PrimVal::Bytes(1) => true,
1360                     // TODO: This seems a little overeager, should reading at bool type already be insta-UB?
1361                     _ => return err!(InvalidBool),
1362                 };
1363                 PrimVal::from_bool(val)
1364             }
1365             ty::TyChar => {
1366                 let c = self.memory.read_primval(ptr, ptr_align, 4)?.to_bytes()? as u32;
1367                 match ::std::char::from_u32(c) {
1368                     Some(ch) => PrimVal::from_char(ch),
1369                     None => return err!(InvalidChar(c as u128)),
1370                 }
1371             }
1372
1373             ty::TyInt(int_ty) => {
1374                 use syntax::ast::IntTy::*;
1375                 let size = match int_ty {
1376                     I8 => 1,
1377                     I16 => 2,
1378                     I32 => 4,
1379                     I64 => 8,
1380                     I128 => 16,
1381                     Isize => self.memory.pointer_size(),
1382                 };
1383                 self.memory.read_primval(ptr, ptr_align, size)?
1384             }
1385
1386             ty::TyUint(uint_ty) => {
1387                 use syntax::ast::UintTy::*;
1388                 let size = match uint_ty {
1389                     U8 => 1,
1390                     U16 => 2,
1391                     U32 => 4,
1392                     U64 => 8,
1393                     U128 => 16,
1394                     Usize => self.memory.pointer_size(),
1395                 };
1396                 self.memory.read_primval(ptr, ptr_align, size)?
1397             }
1398
1399             ty::TyFloat(FloatTy::F32) => {
1400                 PrimVal::Bytes(self.memory.read_primval(ptr, ptr_align, 4)?.to_bytes()?)
1401             }
1402             ty::TyFloat(FloatTy::F64) => {
1403                 PrimVal::Bytes(self.memory.read_primval(ptr, ptr_align, 8)?.to_bytes()?)
1404             }
1405
1406             ty::TyFnPtr(_) => self.memory.read_ptr_sized(ptr, ptr_align)?,
1407             ty::TyRef(_, ref tam) |
1408             ty::TyRawPtr(ref tam) => return self.read_ptr(ptr, ptr_align, tam.ty).map(Some),
1409
1410             ty::TyAdt(def, _) => {
1411                 if def.is_box() {
1412                     return self.read_ptr(ptr, ptr_align, ty.boxed_ty()).map(Some);
1413                 }
1414
1415                 if let layout::Abi::Scalar(ref scalar) = self.layout_of(ty)?.abi {
1416                     let size = scalar.value.size(self).bytes();
1417                     self.memory.read_primval(ptr, ptr_align, size)?
1418                 } else {
1419                     return Ok(None);
1420                 }
1421             }
1422
1423             _ => return Ok(None),
1424         };
1425
1426         Ok(Some(Value::ByVal(val)))
1427     }
1428
1429     pub fn frame(&self) -> &Frame<'mir, 'tcx> {
1430         self.stack.last().expect("no call frames exist")
1431     }
1432
1433     pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx> {
1434         self.stack.last_mut().expect("no call frames exist")
1435     }
1436
1437     pub(super) fn mir(&self) -> &'mir mir::Mir<'tcx> {
1438         self.frame().mir
1439     }
1440
1441     pub fn substs(&self) -> &'tcx Substs<'tcx> {
1442         if let Some(frame) = self.stack.last() {
1443             frame.instance.substs
1444         } else {
1445             Substs::empty()
1446         }
1447     }
1448
1449     fn unsize_into_ptr(
1450         &mut self,
1451         src: Value,
1452         src_ty: Ty<'tcx>,
1453         dest: Place,
1454         dest_ty: Ty<'tcx>,
1455         sty: Ty<'tcx>,
1456         dty: Ty<'tcx>,
1457     ) -> EvalResult<'tcx> {
1458         // A<Struct> -> A<Trait> conversion
1459         let (src_pointee_ty, dest_pointee_ty) = self.tcx.struct_lockstep_tails(sty, dty);
1460
1461         match (&src_pointee_ty.sty, &dest_pointee_ty.sty) {
1462             (&ty::TyArray(_, length), &ty::TySlice(_)) => {
1463                 let ptr = self.into_ptr(src)?;
1464                 // u64 cast is from usize to u64, which is always good
1465                 let valty = ValTy {
1466                     value: ptr.to_value_with_len(length.val.unwrap_u64() ),
1467                     ty: dest_ty,
1468                 };
1469                 self.write_value(valty, dest)
1470             }
1471             (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
1472                 // For now, upcasts are limited to changes in marker
1473                 // traits, and hence never actually require an actual
1474                 // change to the vtable.
1475                 let valty = ValTy {
1476                     value: src,
1477                     ty: dest_ty,
1478                 };
1479                 self.write_value(valty, dest)
1480             }
1481             (_, &ty::TyDynamic(ref data, _)) => {
1482                 let trait_ref = data.principal().unwrap().with_self_ty(
1483                     *self.tcx,
1484                     src_pointee_ty,
1485                 );
1486                 let trait_ref = self.tcx.erase_regions(&trait_ref);
1487                 let vtable = self.get_vtable(src_pointee_ty, trait_ref)?;
1488                 let ptr = self.into_ptr(src)?;
1489                 let valty = ValTy {
1490                     value: ptr.to_value_with_vtable(vtable),
1491                     ty: dest_ty,
1492                 };
1493                 self.write_value(valty, dest)
1494             }
1495
1496             _ => bug!("invalid unsizing {:?} -> {:?}", src_ty, dest_ty),
1497         }
1498     }
1499
1500     fn unsize_into(
1501         &mut self,
1502         src: Value,
1503         src_layout: TyLayout<'tcx>,
1504         dst: Place,
1505         dst_layout: TyLayout<'tcx>,
1506     ) -> EvalResult<'tcx> {
1507         match (&src_layout.ty.sty, &dst_layout.ty.sty) {
1508             (&ty::TyRef(_, ref s), &ty::TyRef(_, ref d)) |
1509             (&ty::TyRef(_, ref s), &ty::TyRawPtr(ref d)) |
1510             (&ty::TyRawPtr(ref s), &ty::TyRawPtr(ref d)) => {
1511                 self.unsize_into_ptr(src, src_layout.ty, dst, dst_layout.ty, s.ty, d.ty)
1512             }
1513             (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => {
1514                 assert_eq!(def_a, def_b);
1515                 if def_a.is_box() || def_b.is_box() {
1516                     if !def_a.is_box() || !def_b.is_box() {
1517                         bug!("invalid unsizing between {:?} -> {:?}", src_layout, dst_layout);
1518                     }
1519                     return self.unsize_into_ptr(
1520                         src,
1521                         src_layout.ty,
1522                         dst,
1523                         dst_layout.ty,
1524                         src_layout.ty.boxed_ty(),
1525                         dst_layout.ty.boxed_ty(),
1526                     );
1527                 }
1528
1529                 // unsizing of generic struct with pointer fields
1530                 // Example: `Arc<T>` -> `Arc<Trait>`
1531                 // here we need to increase the size of every &T thin ptr field to a fat ptr
1532                 for i in 0..src_layout.fields.count() {
1533                     let (dst_f_place, dst_field) =
1534                         self.place_field(dst, mir::Field::new(i), dst_layout)?;
1535                     if dst_field.is_zst() {
1536                         continue;
1537                     }
1538                     let (src_f_value, src_field) = match src {
1539                         Value::ByRef(ptr, align) => {
1540                             let src_place = Place::from_primval_ptr(ptr, align);
1541                             let (src_f_place, src_field) =
1542                                 self.place_field(src_place, mir::Field::new(i), src_layout)?;
1543                             (self.read_place(src_f_place)?, src_field)
1544                         }
1545                         Value::ByVal(_) | Value::ByValPair(..) => {
1546                             let src_field = src_layout.field(&self, i)?;
1547                             assert_eq!(src_layout.fields.offset(i).bytes(), 0);
1548                             assert_eq!(src_field.size, src_layout.size);
1549                             (src, src_field)
1550                         }
1551                     };
1552                     if src_field.ty == dst_field.ty {
1553                         self.write_value(ValTy {
1554                             value: src_f_value,
1555                             ty: src_field.ty,
1556                         }, dst_f_place)?;
1557                     } else {
1558                         self.unsize_into(src_f_value, src_field, dst_f_place, dst_field)?;
1559                     }
1560                 }
1561                 Ok(())
1562             }
1563             _ => {
1564                 bug!(
1565                     "unsize_into: invalid conversion: {:?} -> {:?}",
1566                     src_layout,
1567                     dst_layout
1568                 )
1569             }
1570         }
1571     }
1572
1573     pub fn dump_local(&self, place: Place) {
1574         // Debug output
1575         match place {
1576             Place::Local { frame, local } => {
1577                 let mut allocs = Vec::new();
1578                 let mut msg = format!("{:?}", local);
1579                 if frame != self.cur_frame() {
1580                     write!(msg, " ({} frames up)", self.cur_frame() - frame).unwrap();
1581                 }
1582                 write!(msg, ":").unwrap();
1583
1584                 match self.stack[frame].get_local(local) {
1585                     Err(err) => {
1586                         if let EvalErrorKind::DeadLocal = err.kind {
1587                             write!(msg, " is dead").unwrap();
1588                         } else {
1589                             panic!("Failed to access local: {:?}", err);
1590                         }
1591                     }
1592                     Ok(Value::ByRef(ptr, align)) => {
1593                         match ptr.into_inner_primval() {
1594                             PrimVal::Ptr(ptr) => {
1595                                 write!(msg, " by align({}) ref:", align.abi()).unwrap();
1596                                 allocs.push(ptr.alloc_id);
1597                             }
1598                             ptr => write!(msg, " integral by ref: {:?}", ptr).unwrap(),
1599                         }
1600                     }
1601                     Ok(Value::ByVal(val)) => {
1602                         write!(msg, " {:?}", val).unwrap();
1603                         if let PrimVal::Ptr(ptr) = val {
1604                             allocs.push(ptr.alloc_id);
1605                         }
1606                     }
1607                     Ok(Value::ByValPair(val1, val2)) => {
1608                         write!(msg, " ({:?}, {:?})", val1, val2).unwrap();
1609                         if let PrimVal::Ptr(ptr) = val1 {
1610                             allocs.push(ptr.alloc_id);
1611                         }
1612                         if let PrimVal::Ptr(ptr) = val2 {
1613                             allocs.push(ptr.alloc_id);
1614                         }
1615                     }
1616                 }
1617
1618                 trace!("{}", msg);
1619                 self.memory.dump_allocs(allocs);
1620             }
1621             Place::Ptr { ptr, align, .. } => {
1622                 match ptr.into_inner_primval() {
1623                     PrimVal::Ptr(ptr) => {
1624                         trace!("by align({}) ref:", align.abi());
1625                         self.memory.dump_alloc(ptr.alloc_id);
1626                     }
1627                     ptr => trace!(" integral by ref: {:?}", ptr),
1628                 }
1629             }
1630         }
1631     }
1632
1633     /// Convenience function to ensure correct usage of locals
1634     pub fn modify_local<F>(&mut self, frame: usize, local: mir::Local, f: F) -> EvalResult<'tcx>
1635     where
1636         F: FnOnce(&mut Self, Value) -> EvalResult<'tcx, Value>,
1637     {
1638         let val = self.stack[frame].get_local(local)?;
1639         let new_val = f(self, val)?;
1640         self.stack[frame].set_local(local, new_val)?;
1641         // FIXME(solson): Run this when setting to Undef? (See previous version of this code.)
1642         // if let Value::ByRef(ptr) = self.stack[frame].get_local(local) {
1643         //     self.memory.deallocate(ptr)?;
1644         // }
1645         Ok(())
1646     }
1647
1648     pub fn generate_stacktrace(&self, explicit_span: Option<Span>) -> (Vec<FrameInfo>, Span) {
1649         let mut last_span = None;
1650         let mut frames = Vec::new();
1651         // skip 1 because the last frame is just the environment of the constant
1652         for &Frame { instance, span, .. } in self.stack().iter().skip(1).rev() {
1653             // make sure we don't emit frames that are duplicates of the previous
1654             if explicit_span == Some(span) {
1655                 last_span = Some(span);
1656                 continue;
1657             }
1658             if let Some(last) = last_span {
1659                 if last == span {
1660                     continue;
1661                 }
1662             } else {
1663                 last_span = Some(span);
1664             }
1665             let location = if self.tcx.def_key(instance.def_id()).disambiguated_data.data == DefPathData::ClosureExpr {
1666                 "closure".to_owned()
1667             } else {
1668                 instance.to_string()
1669             };
1670             frames.push(FrameInfo { span, location });
1671         }
1672         trace!("generate stacktrace: {:#?}, {:?}", frames, explicit_span);
1673         (frames, self.tcx.span)
1674     }
1675
1676     pub fn report(&self, e: &mut EvalError, as_err: bool, explicit_span: Option<Span>) {
1677         match e.kind {
1678             EvalErrorKind::Layout(_) |
1679             EvalErrorKind::TypeckError => return,
1680             _ => {},
1681         }
1682         if let Some(ref mut backtrace) = e.backtrace {
1683             let mut trace_text = "\n\nAn error occurred in miri:\n".to_string();
1684             backtrace.resolve();
1685             write!(trace_text, "backtrace frames: {}\n", backtrace.frames().len()).unwrap();
1686             'frames: for (i, frame) in backtrace.frames().iter().enumerate() {
1687                 if frame.symbols().is_empty() {
1688                     write!(trace_text, "{}: no symbols\n", i).unwrap();
1689                 }
1690                 for symbol in frame.symbols() {
1691                     write!(trace_text, "{}: ", i).unwrap();
1692                     if let Some(name) = symbol.name() {
1693                         write!(trace_text, "{}\n", name).unwrap();
1694                     } else {
1695                         write!(trace_text, "<unknown>\n").unwrap();
1696                     }
1697                     write!(trace_text, "\tat ").unwrap();
1698                     if let Some(file_path) = symbol.filename() {
1699                         write!(trace_text, "{}", file_path.display()).unwrap();
1700                     } else {
1701                         write!(trace_text, "<unknown_file>").unwrap();
1702                     }
1703                     if let Some(line) = symbol.lineno() {
1704                         write!(trace_text, ":{}\n", line).unwrap();
1705                     } else {
1706                         write!(trace_text, "\n").unwrap();
1707                     }
1708                 }
1709             }
1710             error!("{}", trace_text);
1711         }
1712         if let Some(frame) = self.stack().last() {
1713             let block = &frame.mir.basic_blocks()[frame.block];
1714             let span = explicit_span.unwrap_or_else(|| if frame.stmt < block.statements.len() {
1715                 block.statements[frame.stmt].source_info.span
1716             } else {
1717                 block.terminator().source_info.span
1718             });
1719             trace!("reporting const eval failure at {:?}", span);
1720             let mut err = if as_err {
1721                 ::rustc::middle::const_val::struct_error(*self.tcx, span, "constant evaluation error")
1722             } else {
1723                 let node_id = self
1724                     .stack()
1725                     .iter()
1726                     .rev()
1727                     .filter_map(|frame| self.tcx.hir.as_local_node_id(frame.instance.def_id()))
1728                     .next()
1729                     .expect("some part of a failing const eval must be local");
1730                 self.tcx.struct_span_lint_node(
1731                     ::rustc::lint::builtin::CONST_ERR,
1732                     node_id,
1733                     span,
1734                     "constant evaluation error",
1735                 )
1736             };
1737             let (frames, span) = self.generate_stacktrace(explicit_span);
1738             err.span_label(span, e.to_string());
1739             for FrameInfo { span, location } in frames {
1740                 err.span_note(span, &format!("inside call to `{}`", location));
1741             }
1742             err.emit();
1743         } else {
1744             self.tcx.sess.err(&e.to_string());
1745         }
1746     }
1747
1748     pub fn sign_extend(&self, value: u128, ty: Ty<'tcx>) -> EvalResult<'tcx, u128> {
1749         super::sign_extend(self.tcx.tcx, value, ty)
1750     }
1751
1752     pub fn truncate(&self, value: u128, ty: Ty<'tcx>) -> EvalResult<'tcx, u128> {
1753         super::truncate(self.tcx.tcx, value, ty)
1754     }
1755 }
1756
1757 impl<'mir, 'tcx> Frame<'mir, 'tcx> {
1758     pub fn get_local(&self, local: mir::Local) -> EvalResult<'tcx, Value> {
1759         self.locals[local].ok_or_else(|| EvalErrorKind::DeadLocal.into())
1760     }
1761
1762     fn set_local(&mut self, local: mir::Local, value: Value) -> EvalResult<'tcx> {
1763         match self.locals[local] {
1764             None => err!(DeadLocal),
1765             Some(ref mut local) => {
1766                 *local = value;
1767                 Ok(())
1768             }
1769         }
1770     }
1771
1772     pub fn storage_live(&mut self, local: mir::Local) -> Option<Value> {
1773         trace!("{:?} is now live", local);
1774
1775         // StorageLive *always* kills the value that's currently stored
1776         mem::replace(&mut self.locals[local], Some(Value::ByVal(PrimVal::Undef)))
1777     }
1778
1779     /// Returns the old value of the local
1780     pub fn storage_dead(&mut self, local: mir::Local) -> Option<Value> {
1781         trace!("{:?} is now dead", local);
1782
1783         self.locals[local].take()
1784     }
1785 }