]> git.lizzy.rs Git - rust.git/blob - src/interpreter/mod.rs
make sure globals that yield function pointers aren't treated like functions
[rust.git] / src / interpreter / mod.rs
1 use rustc::middle::const_val;
2 use rustc::hir::def_id::DefId;
3 use rustc::mir::mir_map::MirMap;
4 use rustc::mir::repr as mir;
5 use rustc::traits::{self, ProjectionMode};
6 use rustc::ty::fold::TypeFoldable;
7 use rustc::ty::layout::{self, Layout, Size};
8 use rustc::ty::subst::{self, Subst, Substs};
9 use rustc::ty::{self, Ty, TyCtxt};
10 use rustc::util::nodemap::DefIdMap;
11 use std::cell::RefCell;
12 use std::ops::{Deref, DerefMut};
13 use std::rc::Rc;
14 use std::{iter, mem};
15 use syntax::ast;
16 use syntax::attr;
17 use syntax::codemap::{self, DUMMY_SP};
18
19 use error::{EvalError, EvalResult};
20 use memory::{Memory, Pointer};
21 use primval::{self, PrimVal};
22
23 use std::collections::HashMap;
24
25 mod stepper;
26
27 struct GlobalEvalContext<'a, 'tcx: 'a> {
28     /// The results of the type checker, from rustc.
29     tcx: TyCtxt<'a, 'tcx, 'tcx>,
30
31     /// A mapping from NodeIds to Mir, from rustc. Only contains MIR for crate-local items.
32     mir_map: &'a MirMap<'tcx>,
33
34     /// A local cache from DefIds to Mir for non-crate-local items.
35     mir_cache: RefCell<DefIdMap<Rc<mir::Mir<'tcx>>>>,
36
37     /// The virtual memory system.
38     memory: Memory,
39
40     /// Precomputed statics, constants and promoteds
41     statics: HashMap<ConstantId<'tcx>, Pointer>,
42 }
43
44 struct FnEvalContext<'a, 'b: 'a + 'mir, 'mir, 'tcx: 'b> {
45     gecx: &'a mut GlobalEvalContext<'b, 'tcx>,
46
47     /// The virtual call stack.
48     stack: Vec<Frame<'mir, 'tcx>>,
49 }
50
51 impl<'a, 'b, 'mir, 'tcx> Deref for FnEvalContext<'a, 'b, 'mir, 'tcx> {
52     type Target = GlobalEvalContext<'b, 'tcx>;
53     fn deref(&self) -> &Self::Target {
54         self.gecx
55     }
56 }
57
58 impl<'a, 'b, 'mir, 'tcx> DerefMut for FnEvalContext<'a, 'b, 'mir, 'tcx> {
59     fn deref_mut(&mut self) -> &mut Self::Target {
60         self.gecx
61     }
62 }
63
64 /// A stack frame.
65 struct Frame<'a, 'tcx: 'a> {
66     /// The def_id of the current function
67     def_id: DefId,
68
69     /// The span of the call site
70     span: codemap::Span,
71
72     /// type substitutions for the current function invocation
73     substs: &'tcx Substs<'tcx>,
74
75     /// The MIR for the function called on this frame.
76     mir: CachedMir<'a, 'tcx>,
77
78     /// The block that is currently executed (or will be executed after the above call stacks return)
79     next_block: mir::BasicBlock,
80
81     /// A pointer for writing the return value of the current call if it's not a diverging call.
82     return_ptr: Option<Pointer>,
83
84     /// The list of locals for the current function, stored in order as
85     /// `[arguments..., variables..., temporaries...]`. The variables begin at `self.var_offset`
86     /// and the temporaries at `self.temp_offset`.
87     locals: Vec<Pointer>,
88
89     /// The offset of the first variable in `self.locals`.
90     var_offset: usize,
91
92     /// The offset of the first temporary in `self.locals`.
93     temp_offset: usize,
94
95     /// The index of the currently evaluated statment
96     stmt: usize,
97 }
98
99 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
100 struct Lvalue {
101     ptr: Pointer,
102     extra: LvalueExtra,
103 }
104
105 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
106 enum LvalueExtra {
107     None,
108     Length(u64),
109     // TODO(solson): Vtable(memory::AllocId),
110     DowncastVariant(usize),
111 }
112
113 #[derive(Clone)]
114 enum CachedMir<'mir, 'tcx: 'mir> {
115     Ref(&'mir mir::Mir<'tcx>),
116     Owned(Rc<mir::Mir<'tcx>>)
117 }
118
119 /// Represents the action to be taken in the main loop as a result of executing a terminator.
120 enum TerminatorTarget {
121     /// Make a local jump to the next block
122     Block,
123
124     /// Start executing from the new current frame. (For function calls.)
125     Call,
126
127     /// Stop executing the current frame and resume the previous frame.
128     Return,
129 }
130
131 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
132 /// Uniquely identifies a specific constant or static
133 struct ConstantId<'tcx> {
134     /// the def id of the constant/static or in case of promoteds, the def id of the function they belong to
135     def_id: DefId,
136     /// In case of statics and constants this is `Substs::empty()`, so only promoteds and associated
137     /// constants actually have something useful here. We could special case statics and constants,
138     /// but that would only require more branching when working with constants, and not bring any
139     /// real benefits.
140     substs: &'tcx Substs<'tcx>,
141     kind: ConstantKind,
142 }
143
144 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
145 enum ConstantKind {
146     Promoted(usize),
147     /// Statics, constants and associated constants
148     Global,
149 }
150
151 impl<'a, 'tcx> GlobalEvalContext<'a, 'tcx> {
152     fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, mir_map: &'a MirMap<'tcx>) -> Self {
153         GlobalEvalContext {
154             tcx: tcx,
155             mir_map: mir_map,
156             mir_cache: RefCell::new(DefIdMap()),
157             memory: Memory::new(tcx.sess
158                                    .target
159                                    .uint_type
160                                    .bit_width()
161                                    .expect("Session::target::uint_type was usize")/8),
162             statics: HashMap::new(),
163         }
164     }
165
166     fn call(&mut self, mir: &mir::Mir<'tcx>, def_id: DefId) -> EvalResult<Option<Pointer>> {
167         let substs = self.tcx.mk_substs(subst::Substs::empty());
168         let return_ptr = self.alloc_ret_ptr(mir.return_ty, substs);
169
170         let mut nested_fecx = FnEvalContext::new(self);
171
172         nested_fecx.push_stack_frame(def_id, mir.span, CachedMir::Ref(mir), substs, None);
173
174         nested_fecx.frame_mut().return_ptr = return_ptr;
175
176         nested_fecx.run()?;
177         Ok(return_ptr)
178     }
179
180     fn alloc_ret_ptr(&mut self, output_ty: ty::FnOutput<'tcx>, substs: &'tcx Substs<'tcx>) -> Option<Pointer> {
181         match output_ty {
182             ty::FnConverging(ty) => {
183                 let size = self.type_size(ty, substs);
184                 Some(self.memory.allocate(size))
185             }
186             ty::FnDiverging => None,
187         }
188     }
189
190     // TODO(solson): Try making const_to_primval instead.
191     fn const_to_ptr(&mut self, const_val: &const_val::ConstVal) -> EvalResult<Pointer> {
192         use rustc::middle::const_val::ConstVal::*;
193         match *const_val {
194             Float(_f) => unimplemented!(),
195             Integral(int) => {
196                 // TODO(solson): Check int constant type.
197                 let ptr = self.memory.allocate(8);
198                 self.memory.write_uint(ptr, int.to_u64_unchecked(), 8)?;
199                 Ok(ptr)
200             }
201             Str(ref s) => {
202                 let psize = self.memory.pointer_size;
203                 let static_ptr = self.memory.allocate(s.len());
204                 let ptr = self.memory.allocate(psize * 2);
205                 self.memory.write_bytes(static_ptr, s.as_bytes())?;
206                 self.memory.write_ptr(ptr, static_ptr)?;
207                 self.memory.write_usize(ptr.offset(psize as isize), s.len() as u64)?;
208                 Ok(ptr)
209             }
210             ByteStr(ref bs) => {
211                 let psize = self.memory.pointer_size;
212                 let static_ptr = self.memory.allocate(bs.len());
213                 let ptr = self.memory.allocate(psize);
214                 self.memory.write_bytes(static_ptr, bs)?;
215                 self.memory.write_ptr(ptr, static_ptr)?;
216                 Ok(ptr)
217             }
218             Bool(b) => {
219                 let ptr = self.memory.allocate(1);
220                 self.memory.write_bool(ptr, b)?;
221                 Ok(ptr)
222             }
223             Char(_c)          => unimplemented!(),
224             Struct(_node_id)  => unimplemented!(),
225             Tuple(_node_id)   => unimplemented!(),
226             Function(_def_id) => unimplemented!(),
227             Array(_, _)       => unimplemented!(),
228             Repeat(_, _)      => unimplemented!(),
229             Dummy             => unimplemented!(),
230         }
231     }
232
233     fn type_needs_drop(&self, ty: Ty<'tcx>) -> bool {
234         self.tcx.type_needs_drop_given_env(ty, &self.tcx.empty_parameter_environment())
235     }
236
237     fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
238         ty.is_sized(self.tcx, &self.tcx.empty_parameter_environment(), DUMMY_SP)
239     }
240
241     fn fulfill_obligation(&self, trait_ref: ty::PolyTraitRef<'tcx>) -> traits::Vtable<'tcx, ()> {
242         // Do the initial selection for the obligation. This yields the shallow result we are
243         // looking for -- that is, what specific impl.
244         self.tcx.normalizing_infer_ctxt(ProjectionMode::Any).enter(|infcx| {
245             let mut selcx = traits::SelectionContext::new(&infcx);
246
247             let obligation = traits::Obligation::new(
248                 traits::ObligationCause::misc(DUMMY_SP, ast::DUMMY_NODE_ID),
249                 trait_ref.to_poly_trait_predicate(),
250             );
251             let selection = selcx.select(&obligation).unwrap().unwrap();
252
253             // Currently, we use a fulfillment context to completely resolve all nested obligations.
254             // This is because they can inform the inference of the impl's type parameters.
255             let mut fulfill_cx = traits::FulfillmentContext::new();
256             let vtable = selection.map(|predicate| {
257                 fulfill_cx.register_predicate_obligation(&infcx, predicate);
258             });
259             infcx.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &vtable)
260         })
261     }
262
263     /// Trait method, which has to be resolved to an impl method.
264     pub fn trait_method(
265         &self,
266         def_id: DefId,
267         substs: &'tcx Substs<'tcx>
268     ) -> (DefId, &'tcx Substs<'tcx>) {
269         let method_item = self.tcx.impl_or_trait_item(def_id);
270         let trait_id = method_item.container().id();
271         let trait_ref = ty::Binder(substs.to_trait_ref(self.tcx, trait_id));
272         match self.fulfill_obligation(trait_ref) {
273             traits::VtableImpl(vtable_impl) => {
274                 let impl_did = vtable_impl.impl_def_id;
275                 let mname = self.tcx.item_name(def_id);
276                 // Create a concatenated set of substitutions which includes those from the impl
277                 // and those from the method:
278                 let impl_substs = vtable_impl.substs.with_method_from(substs);
279                 let substs = self.tcx.mk_substs(impl_substs);
280                 let mth = get_impl_method(self.tcx, impl_did, substs, mname);
281
282                 (mth.method.def_id, mth.substs)
283             }
284
285             traits::VtableClosure(vtable_closure) =>
286                 (vtable_closure.closure_def_id, vtable_closure.substs.func_substs),
287
288             traits::VtableFnPointer(_fn_ty) => {
289                 let _trait_closure_kind = self.tcx.lang_items.fn_trait_kind(trait_id).unwrap();
290                 unimplemented!()
291                 // let llfn = trans_fn_pointer_shim(ccx, trait_closure_kind, fn_ty);
292
293                 // let method_ty = def_ty(tcx, def_id, substs);
294                 // let fn_ptr_ty = match method_ty.sty {
295                 //     ty::TyFnDef(_, _, fty) => tcx.mk_ty(ty::TyFnPtr(fty)),
296                 //     _ => unreachable!("expected fn item type, found {}",
297                 //                       method_ty)
298                 // };
299                 // Callee::ptr(immediate_rvalue(llfn, fn_ptr_ty))
300             }
301
302             traits::VtableObject(ref _data) => {
303                 unimplemented!()
304                 // Callee {
305                 //     data: Virtual(traits::get_vtable_index_of_object_method(
306                 //                   tcx, data, def_id)),
307                 //                   ty: def_ty(tcx, def_id, substs)
308                 // }
309             }
310             vtable => unreachable!("resolved vtable bad vtable {:?} in trans", vtable),
311         }
312     }
313
314     fn load_mir(&self, def_id: DefId) -> CachedMir<'a, 'tcx> {
315         match self.tcx.map.as_local_node_id(def_id) {
316             Some(node_id) => CachedMir::Ref(self.mir_map.map.get(&node_id).unwrap()),
317             None => {
318                 let mut mir_cache = self.mir_cache.borrow_mut();
319                 if let Some(mir) = mir_cache.get(&def_id) {
320                     return CachedMir::Owned(mir.clone());
321                 }
322
323                 let cs = &self.tcx.sess.cstore;
324                 let mir = cs.maybe_get_item_mir(self.tcx, def_id).unwrap_or_else(|| {
325                     panic!("no mir for {:?}", def_id);
326                 });
327                 let cached = Rc::new(mir);
328                 mir_cache.insert(def_id, cached.clone());
329                 CachedMir::Owned(cached)
330             }
331         }
332     }
333
334     fn monomorphize(&self, ty: Ty<'tcx>, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
335         let substituted = ty.subst(self.tcx, substs);
336         self.tcx.normalize_associated_type(&substituted)
337     }
338
339     fn type_size(&self, ty: Ty<'tcx>, substs: &'tcx Substs<'tcx>) -> usize {
340         self.type_layout(ty, substs).size(&self.tcx.data_layout).bytes() as usize
341     }
342
343     fn type_layout(&self, ty: Ty<'tcx>, substs: &'tcx Substs<'tcx>) -> &'tcx Layout {
344         // TODO(solson): Is this inefficient? Needs investigation.
345         let ty = self.monomorphize(ty, substs);
346
347         self.tcx.normalizing_infer_ctxt(ProjectionMode::Any).enter(|infcx| {
348             // TODO(solson): Report this error properly.
349             ty.layout(&infcx).unwrap()
350         })
351     }
352 }
353
354 impl<'a, 'b, 'mir, 'tcx> FnEvalContext<'a, 'b, 'mir, 'tcx> {
355     fn new(gecx: &'a mut GlobalEvalContext<'b, 'tcx>) -> Self {
356         FnEvalContext {
357             gecx: gecx,
358             stack: Vec::new(),
359         }
360     }
361
362     #[inline(never)]
363     #[cold]
364     fn report(&self, e: &EvalError) {
365         let stmt = self.frame().stmt;
366         let block = self.basic_block();
367         let span = if stmt < block.statements.len() {
368             block.statements[stmt].span
369         } else {
370             block.terminator().span
371         };
372         let mut err = self.tcx.sess.struct_span_err(span, &e.to_string());
373         for &Frame{ def_id, substs, span, .. } in self.stack.iter().rev() {
374             // FIXME(solson): Find a way to do this without this Display impl hack.
375             use rustc::util::ppaux;
376             use std::fmt;
377             struct Instance<'tcx>(DefId, &'tcx Substs<'tcx>);
378             impl<'tcx> fmt::Display for Instance<'tcx> {
379                 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
380                     ppaux::parameterized(f, self.1, self.0, ppaux::Ns::Value, &[],
381                         |tcx| tcx.lookup_item_type(self.0).generics)
382                 }
383             }
384             err.span_note(span, &format!("inside call to {}", Instance(def_id, substs)));
385         }
386         err.emit();
387     }
388
389     fn maybe_report<T>(&self, r: EvalResult<T>) -> EvalResult<T> {
390         if let Err(ref e) = r {
391             self.report(e);
392         }
393         r
394     }
395
396     fn run(&mut self) -> EvalResult<()> {
397         let mut stepper = stepper::Stepper::new(self);
398         while stepper.step()? {}
399         Ok(())
400     }
401
402     fn push_stack_frame(&mut self, def_id: DefId, span: codemap::Span, mir: CachedMir<'mir, 'tcx>, substs: &'tcx Substs<'tcx>,
403         return_ptr: Option<Pointer>)
404     {
405         let arg_tys = mir.arg_decls.iter().map(|a| a.ty);
406         let var_tys = mir.var_decls.iter().map(|v| v.ty);
407         let temp_tys = mir.temp_decls.iter().map(|t| t.ty);
408
409         let num_args = mir.arg_decls.len();
410         let num_vars = mir.var_decls.len();
411
412         ::log_settings::settings().indentation += 1;
413
414         self.stack.push(Frame {
415             mir: mir.clone(),
416             next_block: mir::START_BLOCK,
417             return_ptr: return_ptr,
418             locals: Vec::new(),
419             var_offset: num_args,
420             temp_offset: num_args + num_vars,
421             span: span,
422             def_id: def_id,
423             substs: substs,
424             stmt: 0,
425         });
426
427         let locals: Vec<Pointer> = arg_tys.chain(var_tys).chain(temp_tys).map(|ty| {
428             let size = self.type_size(ty);
429             self.memory.allocate(size)
430         }).collect();
431
432         self.frame_mut().locals = locals;
433     }
434
435     fn pop_stack_frame(&mut self) {
436         ::log_settings::settings().indentation -= 1;
437         let _frame = self.stack.pop().expect("tried to pop a stack frame, but there were none");
438         // TODO(solson): Deallocate local variables.
439     }
440
441     fn eval_terminator(&mut self, terminator: &mir::Terminator<'tcx>)
442             -> EvalResult<TerminatorTarget> {
443         use rustc::mir::repr::TerminatorKind::*;
444         let target = match terminator.kind {
445             Return => TerminatorTarget::Return,
446
447             Goto { target } => {
448                 self.frame_mut().next_block = target;
449                 TerminatorTarget::Block
450             },
451
452             If { ref cond, targets: (then_target, else_target) } => {
453                 let cond_ptr = self.eval_operand(cond)?;
454                 let cond_val = self.memory.read_bool(cond_ptr)?;
455                 self.frame_mut().next_block = if cond_val { then_target } else { else_target };
456                 TerminatorTarget::Block
457             }
458
459             SwitchInt { ref discr, ref values, ref targets, .. } => {
460                 let discr_ptr = self.eval_lvalue(discr)?.to_ptr();
461                 let discr_size = self
462                     .type_layout(self.lvalue_ty(discr))
463                     .size(&self.tcx.data_layout)
464                     .bytes() as usize;
465                 let discr_val = self.memory.read_uint(discr_ptr, discr_size)?;
466
467                 // Branch to the `otherwise` case by default, if no match is found.
468                 let mut target_block = targets[targets.len() - 1];
469
470                 for (index, val_const) in values.iter().enumerate() {
471                     let ptr = self.const_to_ptr(val_const)?;
472                     let val = self.memory.read_uint(ptr, discr_size)?;
473                     if discr_val == val {
474                         target_block = targets[index];
475                         break;
476                     }
477                 }
478
479                 self.frame_mut().next_block = target_block;
480                 TerminatorTarget::Block
481             }
482
483             Switch { ref discr, ref targets, adt_def } => {
484                 let adt_ptr = self.eval_lvalue(discr)?.to_ptr();
485                 let adt_ty = self.lvalue_ty(discr);
486                 let discr_val = self.read_discriminant_value(adt_ptr, adt_ty)?;
487                 let matching = adt_def.variants.iter()
488                     .position(|v| discr_val == v.disr_val.to_u64_unchecked());
489
490                 match matching {
491                     Some(i) => {
492                         self.frame_mut().next_block = targets[i];
493                         TerminatorTarget::Block
494                     },
495                     None => return Err(EvalError::InvalidDiscriminant),
496                 }
497             }
498
499             Call { ref func, ref args, ref destination, .. } => {
500                 let mut return_ptr = None;
501                 if let Some((ref lv, target)) = *destination {
502                     self.frame_mut().next_block = target;
503                     return_ptr = Some(self.eval_lvalue(lv)?.to_ptr());
504                 }
505
506                 let func_ty = self.operand_ty(func);
507                 match func_ty.sty {
508                     ty::TyFnDef(def_id, substs, fn_ty) => {
509                         use syntax::abi::Abi;
510                         match fn_ty.abi {
511                             Abi::RustIntrinsic => {
512                                 let name = self.tcx.item_name(def_id).as_str();
513                                 match fn_ty.sig.0.output {
514                                     ty::FnConverging(ty) => {
515                                         let size = self.type_size(ty);
516                                         let ret = return_ptr.unwrap();
517                                         self.call_intrinsic(&name, substs, args, ret, size)?
518                                     }
519                                     ty::FnDiverging => unimplemented!(),
520                                 }
521                             }
522
523                             Abi::C => {
524                                 match fn_ty.sig.0.output {
525                                     ty::FnConverging(ty) => {
526                                         let size = self.type_size(ty);
527                                         self.call_c_abi(def_id, args, return_ptr.unwrap(), size)?
528                                     }
529                                     ty::FnDiverging => unimplemented!(),
530                                 }
531                             }
532
533                             Abi::Rust | Abi::RustCall => {
534                                 // TODO(solson): Adjust the first argument when calling a Fn or
535                                 // FnMut closure via FnOnce::call_once.
536
537                                 // Only trait methods can have a Self parameter.
538                                 let (resolved_def_id, resolved_substs) = if substs.self_ty().is_some() {
539                                     self.trait_method(def_id, substs)
540                                 } else {
541                                     (def_id, substs)
542                                 };
543
544                                 let mut arg_srcs = Vec::new();
545                                 for arg in args {
546                                     let src = self.eval_operand(arg)?;
547                                     let src_ty = self.operand_ty(arg);
548                                     arg_srcs.push((src, src_ty));
549                                 }
550
551                                 if fn_ty.abi == Abi::RustCall && !args.is_empty() {
552                                     arg_srcs.pop();
553                                     let last_arg = args.last().unwrap();
554                                     let last = self.eval_operand(last_arg)?;
555                                     let last_ty = self.operand_ty(last_arg);
556                                     let last_layout = self.type_layout(last_ty);
557                                     match (&last_ty.sty, last_layout) {
558                                         (&ty::TyTuple(fields),
559                                          &Layout::Univariant { ref variant, .. }) => {
560                                             let offsets = iter::once(0)
561                                                 .chain(variant.offset_after_field.iter()
562                                                     .map(|s| s.bytes()));
563                                             for (offset, ty) in offsets.zip(fields) {
564                                                 let src = last.offset(offset as isize);
565                                                 arg_srcs.push((src, ty));
566                                             }
567                                         }
568                                         ty => panic!("expected tuple as last argument in function with 'rust-call' ABI, got {:?}", ty),
569                                     }
570                                 }
571
572                                 let mir = self.load_mir(resolved_def_id);
573                                 self.push_stack_frame(def_id, terminator.span, mir, resolved_substs, return_ptr);
574
575                                 for (i, (src, src_ty)) in arg_srcs.into_iter().enumerate() {
576                                     let dest = self.frame().locals[i];
577                                     self.move_(src, dest, src_ty)?;
578                                 }
579
580                                 TerminatorTarget::Call
581                             }
582
583                             abi => return Err(EvalError::Unimplemented(format!("can't handle function with {:?} ABI", abi))),
584                         }
585                     }
586
587                     _ => return Err(EvalError::Unimplemented(format!("can't handle callee of type {:?}", func_ty))),
588                 }
589             }
590
591             Drop { ref value, target, .. } => {
592                 let ptr = self.eval_lvalue(value)?.to_ptr();
593                 let ty = self.lvalue_ty(value);
594                 self.drop(ptr, ty)?;
595                 self.frame_mut().next_block = target;
596                 TerminatorTarget::Block
597             }
598
599             Resume => unimplemented!(),
600         };
601
602         Ok(target)
603     }
604
605     fn drop(&mut self, ptr: Pointer, ty: Ty<'tcx>) -> EvalResult<()> {
606         if !self.type_needs_drop(ty) {
607             debug!("no need to drop {:?}", ty);
608             return Ok(());
609         }
610         trace!("-need to drop {:?}", ty);
611
612         // TODO(solson): Call user-defined Drop::drop impls.
613
614         match ty.sty {
615             ty::TyBox(contents_ty) => {
616                 match self.memory.read_ptr(ptr) {
617                     Ok(contents_ptr) => {
618                         self.drop(contents_ptr, contents_ty)?;
619                         trace!("-deallocating box");
620                         self.memory.deallocate(contents_ptr)?;
621                     }
622                     Err(EvalError::ReadBytesAsPointer) => {
623                         let size = self.memory.pointer_size;
624                         let possible_drop_fill = self.memory.read_bytes(ptr, size)?;
625                         if possible_drop_fill.iter().all(|&b| b == mem::POST_DROP_U8) {
626                             return Ok(());
627                         } else {
628                             return Err(EvalError::ReadBytesAsPointer);
629                         }
630                     }
631                     Err(e) => return Err(e),
632                 }
633             }
634
635             // TODO(solson): Implement drop for other relevant types (e.g. aggregates).
636             _ => {}
637         }
638
639         // Filling drop.
640         // FIXME(solson): Trait objects (with no static size) probably get filled, too.
641         let size = self.type_size(ty);
642         self.memory.drop_fill(ptr, size)?;
643
644         Ok(())
645     }
646
647     fn read_discriminant_value(&self, adt_ptr: Pointer, adt_ty: Ty<'tcx>) -> EvalResult<u64> {
648         use rustc::ty::layout::Layout::*;
649         let adt_layout = self.type_layout(adt_ty);
650
651         let discr_val = match *adt_layout {
652             General { discr, .. } | CEnum { discr, .. } => {
653                 let discr_size = discr.size().bytes();
654                 self.memory.read_uint(adt_ptr, discr_size as usize)?
655             }
656
657             RawNullablePointer { nndiscr, .. } => {
658                 self.read_nonnull_discriminant_value(adt_ptr, nndiscr)?
659             }
660
661             StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => {
662                 let offset = self.nonnull_offset(adt_ty, nndiscr, discrfield)?;
663                 let nonnull = adt_ptr.offset(offset.bytes() as isize);
664                 self.read_nonnull_discriminant_value(nonnull, nndiscr)?
665             }
666
667             // The discriminant_value intrinsic returns 0 for non-sum types.
668             Array { .. } | FatPointer { .. } | Scalar { .. } | Univariant { .. } |
669             Vector { .. } => 0,
670         };
671
672         Ok(discr_val)
673     }
674
675     fn read_nonnull_discriminant_value(&self, ptr: Pointer, nndiscr: u64) -> EvalResult<u64> {
676         let not_null = match self.memory.read_usize(ptr) {
677             Ok(0) => false,
678             Ok(_) | Err(EvalError::ReadPointerAsBytes) => true,
679             Err(e) => return Err(e),
680         };
681         assert!(nndiscr == 0 || nndiscr == 1);
682         Ok(if not_null { nndiscr } else { 1 - nndiscr })
683     }
684
685     fn call_intrinsic(
686         &mut self,
687         name: &str,
688         substs: &'tcx Substs<'tcx>,
689         args: &[mir::Operand<'tcx>],
690         dest: Pointer,
691         dest_size: usize
692     ) -> EvalResult<TerminatorTarget> {
693         let args_res: EvalResult<Vec<Pointer>> = args.iter()
694             .map(|arg| self.eval_operand(arg))
695             .collect();
696         let args = args_res?;
697
698         match name {
699             // FIXME(solson): Handle different integer types correctly.
700             "add_with_overflow" => {
701                 let ty = *substs.types.get(subst::FnSpace, 0);
702                 let size = self.type_size(ty);
703                 let left = self.memory.read_int(args[0], size)?;
704                 let right = self.memory.read_int(args[1], size)?;
705                 let (n, overflowed) = unsafe {
706                     ::std::intrinsics::add_with_overflow::<i64>(left, right)
707                 };
708                 self.memory.write_int(dest, n, size)?;
709                 self.memory.write_bool(dest.offset(size as isize), overflowed)?;
710             }
711
712             "assume" => {}
713
714             "copy_nonoverlapping" => {
715                 let elem_ty = *substs.types.get(subst::FnSpace, 0);
716                 let elem_size = self.type_size(elem_ty);
717                 let src = self.memory.read_ptr(args[0])?;
718                 let dest = self.memory.read_ptr(args[1])?;
719                 let count = self.memory.read_isize(args[2])?;
720                 self.memory.copy(src, dest, count as usize * elem_size)?;
721             }
722
723             "discriminant_value" => {
724                 let ty = *substs.types.get(subst::FnSpace, 0);
725                 let adt_ptr = self.memory.read_ptr(args[0])?;
726                 let discr_val = self.read_discriminant_value(adt_ptr, ty)?;
727                 self.memory.write_uint(dest, discr_val, dest_size)?;
728             }
729
730             "forget" => {
731                 let arg_ty = *substs.types.get(subst::FnSpace, 0);
732                 let arg_size = self.type_size(arg_ty);
733                 self.memory.drop_fill(args[0], arg_size)?;
734             }
735
736             "init" => self.memory.write_repeat(dest, 0, dest_size)?,
737
738             "min_align_of" => {
739                 self.memory.write_int(dest, 1, dest_size)?;
740             }
741
742             "move_val_init" => {
743                 let ty = *substs.types.get(subst::FnSpace, 0);
744                 let ptr = self.memory.read_ptr(args[0])?;
745                 self.move_(args[1], ptr, ty)?;
746             }
747
748             // FIXME(solson): Handle different integer types correctly.
749             "mul_with_overflow" => {
750                 let ty = *substs.types.get(subst::FnSpace, 0);
751                 let size = self.type_size(ty);
752                 let left = self.memory.read_int(args[0], size)?;
753                 let right = self.memory.read_int(args[1], size)?;
754                 let (n, overflowed) = unsafe {
755                     ::std::intrinsics::mul_with_overflow::<i64>(left, right)
756                 };
757                 self.memory.write_int(dest, n, size)?;
758                 self.memory.write_bool(dest.offset(size as isize), overflowed)?;
759             }
760
761             "offset" => {
762                 let pointee_ty = *substs.types.get(subst::FnSpace, 0);
763                 let pointee_size = self.type_size(pointee_ty) as isize;
764                 let ptr_arg = args[0];
765                 let offset = self.memory.read_isize(args[1])?;
766
767                 match self.memory.read_ptr(ptr_arg) {
768                     Ok(ptr) => {
769                         let result_ptr = ptr.offset(offset as isize * pointee_size);
770                         self.memory.write_ptr(dest, result_ptr)?;
771                     }
772                     Err(EvalError::ReadBytesAsPointer) => {
773                         let addr = self.memory.read_isize(ptr_arg)?;
774                         let result_addr = addr + offset * pointee_size as i64;
775                         self.memory.write_isize(dest, result_addr)?;
776                     }
777                     Err(e) => return Err(e),
778                 }
779             }
780
781             // FIXME(solson): Handle different integer types correctly. Use primvals?
782             "overflowing_sub" => {
783                 let ty = *substs.types.get(subst::FnSpace, 0);
784                 let size = self.type_size(ty);
785                 let left = self.memory.read_int(args[0], size)?;
786                 let right = self.memory.read_int(args[1], size)?;
787                 let n = left.wrapping_sub(right);
788                 self.memory.write_int(dest, n, size)?;
789             }
790
791             "size_of" => {
792                 let ty = *substs.types.get(subst::FnSpace, 0);
793                 let size = self.type_size(ty) as u64;
794                 self.memory.write_uint(dest, size, dest_size)?;
795             }
796
797             "size_of_val" => {
798                 let ty = *substs.types.get(subst::FnSpace, 0);
799                 if self.type_is_sized(ty) {
800                     let size = self.type_size(ty) as u64;
801                     self.memory.write_uint(dest, size, dest_size)?;
802                 } else {
803                     match ty.sty {
804                         ty::TySlice(_) | ty::TyStr => {
805                             let elem_ty = ty.sequence_element_type(self.tcx);
806                             let elem_size = self.type_size(elem_ty) as u64;
807                             let ptr_size = self.memory.pointer_size as isize;
808                             let n = self.memory.read_usize(args[0].offset(ptr_size))?;
809                             self.memory.write_uint(dest, n * elem_size, dest_size)?;
810                         }
811
812                         _ => return Err(EvalError::Unimplemented(format!("unimplemented: size_of_val::<{:?}>", ty))),
813                     }
814                 }
815             }
816
817             "transmute" => {
818                 let ty = *substs.types.get(subst::FnSpace, 0);
819                 self.move_(args[0], dest, ty)?;
820             }
821             "uninit" => self.memory.mark_definedness(dest, dest_size, false)?,
822
823             name => return Err(EvalError::Unimplemented(format!("unimplemented intrinsic: {}", name))),
824         }
825
826         // Since we pushed no stack frame, the main loop will act
827         // as if the call just completed and it's returning to the
828         // current frame.
829         Ok(TerminatorTarget::Call)
830     }
831
832     fn call_c_abi(
833         &mut self,
834         def_id: DefId,
835         args: &[mir::Operand<'tcx>],
836         dest: Pointer,
837         dest_size: usize,
838     ) -> EvalResult<TerminatorTarget> {
839         let name = self.tcx.item_name(def_id);
840         let attrs = self.tcx.get_attrs(def_id);
841         let link_name = match attr::first_attr_value_str_by_name(&attrs, "link_name") {
842             Some(ln) => ln.clone(),
843             None => name.as_str(),
844         };
845
846         let args_res: EvalResult<Vec<Pointer>> = args.iter()
847             .map(|arg| self.eval_operand(arg))
848             .collect();
849         let args = args_res?;
850
851         match &link_name[..] {
852             "__rust_allocate" => {
853                 let size = self.memory.read_usize(args[0])?;
854                 let ptr = self.memory.allocate(size as usize);
855                 self.memory.write_ptr(dest, ptr)?;
856             }
857
858             "__rust_reallocate" => {
859                 let ptr = self.memory.read_ptr(args[0])?;
860                 let size = self.memory.read_usize(args[2])?;
861                 self.memory.reallocate(ptr, size as usize)?;
862                 self.memory.write_ptr(dest, ptr)?;
863             }
864
865             "memcmp" => {
866                 let left = self.memory.read_ptr(args[0])?;
867                 let right = self.memory.read_ptr(args[1])?;
868                 let n = self.memory.read_usize(args[2])? as usize;
869
870                 let result = {
871                     let left_bytes = self.memory.read_bytes(left, n)?;
872                     let right_bytes = self.memory.read_bytes(right, n)?;
873
874                     use std::cmp::Ordering::*;
875                     match left_bytes.cmp(right_bytes) {
876                         Less => -1,
877                         Equal => 0,
878                         Greater => 1,
879                     }
880                 };
881
882                 self.memory.write_int(dest, result, dest_size)?;
883             }
884
885             _ => return Err(EvalError::Unimplemented(format!("can't call C ABI function: {}", link_name))),
886         }
887
888         // Since we pushed no stack frame, the main loop will act
889         // as if the call just completed and it's returning to the
890         // current frame.
891         Ok(TerminatorTarget::Call)
892     }
893
894     fn assign_fields<I: IntoIterator<Item = u64>>(
895         &mut self,
896         dest: Pointer,
897         offsets: I,
898         operands: &[mir::Operand<'tcx>],
899     ) -> EvalResult<()> {
900         for (offset, operand) in offsets.into_iter().zip(operands) {
901             let src = self.eval_operand(operand)?;
902             let src_ty = self.operand_ty(operand);
903             let field_dest = dest.offset(offset as isize);
904             self.move_(src, field_dest, src_ty)?;
905         }
906         Ok(())
907     }
908
909     fn eval_assignment(&mut self, lvalue: &mir::Lvalue<'tcx>, rvalue: &mir::Rvalue<'tcx>)
910         -> EvalResult<()>
911     {
912         let dest = self.eval_lvalue(lvalue)?.to_ptr();
913         let dest_ty = self.lvalue_ty(lvalue);
914         let dest_layout = self.type_layout(dest_ty);
915
916         use rustc::mir::repr::Rvalue::*;
917         match *rvalue {
918             Use(ref operand) => {
919                 let src = self.eval_operand(operand)?;
920                 self.move_(src, dest, dest_ty)?;
921             }
922
923             BinaryOp(bin_op, ref left, ref right) => {
924                 let left_ptr = self.eval_operand(left)?;
925                 let left_ty = self.operand_ty(left);
926                 let left_val = self.read_primval(left_ptr, left_ty)?;
927
928                 let right_ptr = self.eval_operand(right)?;
929                 let right_ty = self.operand_ty(right);
930                 let right_val = self.read_primval(right_ptr, right_ty)?;
931
932                 let val = primval::binary_op(bin_op, left_val, right_val)?;
933                 self.memory.write_primval(dest, val)?;
934             }
935
936             UnaryOp(un_op, ref operand) => {
937                 let ptr = self.eval_operand(operand)?;
938                 let ty = self.operand_ty(operand);
939                 let val = self.read_primval(ptr, ty)?;
940                 self.memory.write_primval(dest, primval::unary_op(un_op, val)?)?;
941             }
942
943             Aggregate(ref kind, ref operands) => {
944                 use rustc::ty::layout::Layout::*;
945                 match *dest_layout {
946                     Univariant { ref variant, .. } => {
947                         let offsets = iter::once(0)
948                             .chain(variant.offset_after_field.iter().map(|s| s.bytes()));
949                         self.assign_fields(dest, offsets, operands)?;
950                     }
951
952                     Array { .. } => {
953                         let elem_size = match dest_ty.sty {
954                             ty::TyArray(elem_ty, _) => self.type_size(elem_ty) as u64,
955                             _ => panic!("tried to assign {:?} to non-array type {:?}",
956                                         kind, dest_ty),
957                         };
958                         let offsets = (0..).map(|i| i * elem_size);
959                         self.assign_fields(dest, offsets, operands)?;
960                     }
961
962                     General { discr, ref variants, .. } => {
963                         if let mir::AggregateKind::Adt(adt_def, variant, _) = *kind {
964                             let discr_val = adt_def.variants[variant].disr_val.to_u64_unchecked();
965                             let discr_size = discr.size().bytes() as usize;
966                             self.memory.write_uint(dest, discr_val, discr_size)?;
967
968                             let offsets = variants[variant].offset_after_field.iter()
969                                 .map(|s| s.bytes());
970                             self.assign_fields(dest, offsets, operands)?;
971                         } else {
972                             panic!("tried to assign {:?} to Layout::General", kind);
973                         }
974                     }
975
976                     RawNullablePointer { nndiscr, .. } => {
977                         if let mir::AggregateKind::Adt(_, variant, _) = *kind {
978                             if nndiscr == variant as u64 {
979                                 assert_eq!(operands.len(), 1);
980                                 let operand = &operands[0];
981                                 let src = self.eval_operand(operand)?;
982                                 let src_ty = self.operand_ty(operand);
983                                 self.move_(src, dest, src_ty)?;
984                             } else {
985                                 assert_eq!(operands.len(), 0);
986                                 self.memory.write_isize(dest, 0)?;
987                             }
988                         } else {
989                             panic!("tried to assign {:?} to Layout::RawNullablePointer", kind);
990                         }
991                     }
992
993                     StructWrappedNullablePointer { nndiscr, ref nonnull, ref discrfield } => {
994                         if let mir::AggregateKind::Adt(_, variant, _) = *kind {
995                             if nndiscr == variant as u64 {
996                                 let offsets = iter::once(0)
997                                     .chain(nonnull.offset_after_field.iter().map(|s| s.bytes()));
998                                 try!(self.assign_fields(dest, offsets, operands));
999                             } else {
1000                                 assert_eq!(operands.len(), 0);
1001                                 let offset = self.nonnull_offset(dest_ty, nndiscr, discrfield)?;
1002                                 let dest = dest.offset(offset.bytes() as isize);
1003                                 try!(self.memory.write_isize(dest, 0));
1004                             }
1005                         } else {
1006                             panic!("tried to assign {:?} to Layout::RawNullablePointer", kind);
1007                         }
1008                     }
1009
1010                     CEnum { discr, signed, .. } => {
1011                         assert_eq!(operands.len(), 0);
1012                         if let mir::AggregateKind::Adt(adt_def, variant, _) = *kind {
1013                             let val = adt_def.variants[variant].disr_val.to_u64_unchecked();
1014                             let size = discr.size().bytes() as usize;
1015
1016                             if signed {
1017                                 self.memory.write_int(dest, val as i64, size)?;
1018                             } else {
1019                                 self.memory.write_uint(dest, val, size)?;
1020                             }
1021                         } else {
1022                             panic!("tried to assign {:?} to Layout::CEnum", kind);
1023                         }
1024                     }
1025
1026                     _ => return Err(EvalError::Unimplemented(format!("can't handle destination layout {:?} when assigning {:?}", dest_layout, kind))),
1027                 }
1028             }
1029
1030             Repeat(ref operand, _) => {
1031                 let (elem_size, length) = match dest_ty.sty {
1032                     ty::TyArray(elem_ty, n) => (self.type_size(elem_ty), n),
1033                     _ => panic!("tried to assign array-repeat to non-array type {:?}", dest_ty),
1034                 };
1035
1036                 let src = self.eval_operand(operand)?;
1037                 for i in 0..length {
1038                     let elem_dest = dest.offset((i * elem_size) as isize);
1039                     self.memory.copy(src, elem_dest, elem_size)?;
1040                 }
1041             }
1042
1043             Len(ref lvalue) => {
1044                 let src = self.eval_lvalue(lvalue)?;
1045                 let ty = self.lvalue_ty(lvalue);
1046                 let len = match ty.sty {
1047                     ty::TyArray(_, n) => n as u64,
1048                     ty::TySlice(_) => if let LvalueExtra::Length(n) = src.extra {
1049                         n
1050                     } else {
1051                         panic!("Rvalue::Len of a slice given non-slice pointer: {:?}", src);
1052                     },
1053                     _ => panic!("Rvalue::Len expected array or slice, got {:?}", ty),
1054                 };
1055                 self.memory.write_usize(dest, len)?;
1056             }
1057
1058             Ref(_, _, ref lvalue) => {
1059                 let lv = self.eval_lvalue(lvalue)?;
1060                 self.memory.write_ptr(dest, lv.ptr)?;
1061                 match lv.extra {
1062                     LvalueExtra::None => {},
1063                     LvalueExtra::Length(len) => {
1064                         let len_ptr = dest.offset(self.memory.pointer_size as isize);
1065                         self.memory.write_usize(len_ptr, len)?;
1066                     }
1067                     LvalueExtra::DowncastVariant(..) =>
1068                         panic!("attempted to take a reference to an enum downcast lvalue"),
1069                 }
1070             }
1071
1072             Box(ty) => {
1073                 let size = self.type_size(ty);
1074                 let ptr = self.memory.allocate(size);
1075                 self.memory.write_ptr(dest, ptr)?;
1076             }
1077
1078             Cast(kind, ref operand, dest_ty) => {
1079                 let src = self.eval_operand(operand)?;
1080                 let src_ty = self.operand_ty(operand);
1081
1082                 use rustc::mir::repr::CastKind::*;
1083                 match kind {
1084                     Unsize => {
1085                         self.move_(src, dest, src_ty)?;
1086                         let src_pointee_ty = pointee_type(src_ty).unwrap();
1087                         let dest_pointee_ty = pointee_type(dest_ty).unwrap();
1088
1089                         match (&src_pointee_ty.sty, &dest_pointee_ty.sty) {
1090                             (&ty::TyArray(_, length), &ty::TySlice(_)) => {
1091                                 let len_ptr = dest.offset(self.memory.pointer_size as isize);
1092                                 self.memory.write_usize(len_ptr, length as u64)?;
1093                             }
1094
1095                             _ => return Err(EvalError::Unimplemented(format!("can't handle cast: {:?}", rvalue))),
1096                         }
1097                     }
1098
1099                     Misc => {
1100                         // FIXME(solson): Wrong for almost everything.
1101                         let size = dest_layout.size(&self.tcx.data_layout).bytes() as usize;
1102                         self.memory.copy(src, dest, size)?;
1103                     }
1104
1105                     _ => return Err(EvalError::Unimplemented(format!("can't handle cast: {:?}", rvalue))),
1106                 }
1107             }
1108
1109             Slice { .. } => unimplemented!(),
1110             InlineAsm { .. } => unimplemented!(),
1111         }
1112
1113         Ok(())
1114     }
1115
1116     fn nonnull_offset(&self, ty: Ty<'tcx>, nndiscr: u64, discrfield: &[u32]) -> EvalResult<Size> {
1117         // Skip the constant 0 at the start meant for LLVM GEP.
1118         let mut path = discrfield.iter().skip(1).map(|&i| i as usize);
1119
1120         // Handle the field index for the outer non-null variant.
1121         let inner_ty = match ty.sty {
1122             ty::TyEnum(adt_def, substs) => {
1123                 let variant = &adt_def.variants[nndiscr as usize];
1124                 let index = path.next().unwrap();
1125                 let field = &variant.fields[index];
1126                 field.ty(self.tcx, substs)
1127             }
1128             _ => panic!(
1129                 "non-enum for StructWrappedNullablePointer: {}",
1130                 ty,
1131             ),
1132         };
1133
1134         self.field_path_offset(inner_ty, path)
1135     }
1136
1137     fn field_path_offset<I: Iterator<Item = usize>>(&self, mut ty: Ty<'tcx>, path: I) -> EvalResult<Size> {
1138         let mut offset = Size::from_bytes(0);
1139
1140         // Skip the initial 0 intended for LLVM GEP.
1141         for field_index in path {
1142             let field_offset = self.get_field_offset(ty, field_index)?;
1143             ty = self.get_field_ty(ty, field_index)?;
1144             offset = offset.checked_add(field_offset, &self.tcx.data_layout).unwrap();
1145         }
1146
1147         Ok(offset)
1148     }
1149
1150     fn get_field_ty(&self, ty: Ty<'tcx>, field_index: usize) -> EvalResult<Ty<'tcx>> {
1151         match ty.sty {
1152             ty::TyStruct(adt_def, substs) => {
1153                 Ok(adt_def.struct_variant().fields[field_index].ty(self.tcx, substs))
1154             }
1155
1156             ty::TyRef(_, ty::TypeAndMut { ty, .. }) |
1157             ty::TyRawPtr(ty::TypeAndMut { ty, .. }) |
1158             ty::TyBox(ty) => {
1159                 assert_eq!(field_index, 0);
1160                 Ok(ty)
1161             }
1162             _ => Err(EvalError::Unimplemented(format!("can't handle type: {:?}", ty))),
1163         }
1164     }
1165
1166     fn get_field_offset(&self, ty: Ty<'tcx>, field_index: usize) -> EvalResult<Size> {
1167         let layout = self.type_layout(ty);
1168
1169         use rustc::ty::layout::Layout::*;
1170         match *layout {
1171             Univariant { .. } => {
1172                 assert_eq!(field_index, 0);
1173                 Ok(Size::from_bytes(0))
1174             }
1175             FatPointer { .. } => {
1176                 let bytes = layout::FAT_PTR_ADDR * self.memory.pointer_size;
1177                 Ok(Size::from_bytes(bytes as u64))
1178             }
1179             _ => Err(EvalError::Unimplemented(format!("can't handle type: {:?}, with layout: {:?}", ty, layout))),
1180         }
1181     }
1182
1183     fn eval_operand(&mut self, op: &mir::Operand<'tcx>) -> EvalResult<Pointer> {
1184         use rustc::mir::repr::Operand::*;
1185         match *op {
1186             Consume(ref lvalue) => Ok(self.eval_lvalue(lvalue)?.to_ptr()),
1187             Constant(mir::Constant { ref literal, ty, .. }) => {
1188                 use rustc::mir::repr::Literal::*;
1189                 match *literal {
1190                     Value { ref value } => Ok(self.const_to_ptr(value)?),
1191                     Item { def_id, substs } => {
1192                         if let ty::TyFnDef(..) = ty.sty {
1193                             Err(EvalError::Unimplemented("unimplemented: mentions of function items".to_string()))
1194                         } else {
1195                             let cid = ConstantId {
1196                                 def_id: def_id,
1197                                 substs: substs,
1198                                 kind: ConstantKind::Global,
1199                             };
1200                             Ok(*self.statics.get(&cid).expect("static should have been cached (rvalue)"))
1201                         }
1202                     },
1203                     Promoted { index } => {
1204                         let cid = ConstantId {
1205                             def_id: self.frame().def_id,
1206                             substs: self.substs(),
1207                             kind: ConstantKind::Promoted(index),
1208                         };
1209                         Ok(*self.statics.get(&cid).expect("a promoted constant hasn't been precomputed"))
1210                     },
1211                 }
1212             }
1213         }
1214     }
1215
1216     fn eval_lvalue(&mut self, lvalue: &mir::Lvalue<'tcx>) -> EvalResult<Lvalue> {
1217         use rustc::mir::repr::Lvalue::*;
1218         let ptr = match *lvalue {
1219             ReturnPointer => self.frame().return_ptr
1220                 .expect("ReturnPointer used in a function with no return value"),
1221             Arg(i) => self.frame().locals[i as usize],
1222             Var(i) => self.frame().locals[self.frame().var_offset + i as usize],
1223             Temp(i) => self.frame().locals[self.frame().temp_offset + i as usize],
1224
1225             Static(def_id) => {
1226                 let substs = self.tcx.mk_substs(subst::Substs::empty());
1227                 let cid = ConstantId {
1228                     def_id: def_id,
1229                     substs: substs,
1230                     kind: ConstantKind::Global,
1231                 };
1232                 *self.gecx.statics.get(&cid).expect("static should have been cached (lvalue)")
1233             },
1234
1235             Projection(ref proj) => {
1236                 let base = self.eval_lvalue(&proj.base)?;
1237                 let base_ty = self.lvalue_ty(&proj.base);
1238                 let base_layout = self.type_layout(base_ty);
1239
1240                 use rustc::mir::repr::ProjectionElem::*;
1241                 match proj.elem {
1242                     Field(field, _) => {
1243                         use rustc::ty::layout::Layout::*;
1244                         let variant = match *base_layout {
1245                             Univariant { ref variant, .. } => variant,
1246                             General { ref variants, .. } => {
1247                                 if let LvalueExtra::DowncastVariant(variant_idx) = base.extra {
1248                                     &variants[variant_idx]
1249                                 } else {
1250                                     panic!("field access on enum had no variant index");
1251                                 }
1252                             }
1253                             RawNullablePointer { .. } => {
1254                                 assert_eq!(field.index(), 0);
1255                                 return Ok(base);
1256                             }
1257                             StructWrappedNullablePointer { ref nonnull, .. } => nonnull,
1258                             _ => panic!("field access on non-product type: {:?}", base_layout),
1259                         };
1260
1261                         let offset = variant.field_offset(field.index()).bytes();
1262                         base.ptr.offset(offset as isize)
1263                     },
1264
1265                     Downcast(_, variant) => {
1266                         use rustc::ty::layout::Layout::*;
1267                         match *base_layout {
1268                             General { discr, .. } => {
1269                                 return Ok(Lvalue {
1270                                     ptr: base.ptr.offset(discr.size().bytes() as isize),
1271                                     extra: LvalueExtra::DowncastVariant(variant),
1272                                 });
1273                             }
1274                             RawNullablePointer { .. } | StructWrappedNullablePointer { .. } => {
1275                                 return Ok(base);
1276                             }
1277                             _ => panic!("variant downcast on non-aggregate: {:?}", base_layout),
1278                         }
1279                     },
1280
1281                     Deref => {
1282                         let pointee_ty = pointee_type(base_ty).expect("Deref of non-pointer");
1283                         let ptr = self.memory.read_ptr(base.ptr)?;
1284                         let extra = match pointee_ty.sty {
1285                             ty::TySlice(_) | ty::TyStr => {
1286                                 let len_ptr = base.ptr.offset(self.memory.pointer_size as isize);
1287                                 let len = self.memory.read_usize(len_ptr)?;
1288                                 LvalueExtra::Length(len)
1289                             }
1290                             ty::TyTrait(_) => unimplemented!(),
1291                             _ => LvalueExtra::None,
1292                         };
1293                         return Ok(Lvalue { ptr: ptr, extra: extra });
1294                     }
1295
1296                     Index(ref operand) => {
1297                         let elem_size = match base_ty.sty {
1298                             ty::TyArray(elem_ty, _) |
1299                             ty::TySlice(elem_ty) => self.type_size(elem_ty),
1300                             _ => panic!("indexing expected an array or slice, got {:?}", base_ty),
1301                         };
1302                         let n_ptr = self.eval_operand(operand)?;
1303                         let n = self.memory.read_usize(n_ptr)?;
1304                         base.ptr.offset(n as isize * elem_size as isize)
1305                     }
1306
1307                     ConstantIndex { .. } => unimplemented!(),
1308                 }
1309             }
1310         };
1311
1312         Ok(Lvalue { ptr: ptr, extra: LvalueExtra::None })
1313     }
1314
1315     fn lvalue_ty(&self, lvalue: &mir::Lvalue<'tcx>) -> Ty<'tcx> {
1316         self.monomorphize(self.mir().lvalue_ty(self.tcx, lvalue).to_ty(self.tcx))
1317     }
1318
1319     fn operand_ty(&self, operand: &mir::Operand<'tcx>) -> Ty<'tcx> {
1320         self.monomorphize(self.mir().operand_ty(self.tcx, operand))
1321     }
1322
1323     fn monomorphize(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1324         self.gecx.monomorphize(ty, self.substs())
1325     }
1326
1327     fn move_(&mut self, src: Pointer, dest: Pointer, ty: Ty<'tcx>) -> EvalResult<()> {
1328         let size = self.type_size(ty);
1329         self.memory.copy(src, dest, size)?;
1330         if self.type_needs_drop(ty) {
1331             self.memory.drop_fill(src, size)?;
1332         }
1333         Ok(())
1334     }
1335
1336     fn type_size(&self, ty: Ty<'tcx>) -> usize {
1337         self.gecx.type_size(ty, self.substs())
1338     }
1339
1340     fn type_layout(&self, ty: Ty<'tcx>) -> &'tcx Layout {
1341         self.gecx.type_layout(ty, self.substs())
1342     }
1343
1344     pub fn read_primval(&mut self, ptr: Pointer, ty: Ty<'tcx>) -> EvalResult<PrimVal> {
1345         use syntax::ast::{IntTy, UintTy};
1346         let val = match (self.memory.pointer_size, &ty.sty) {
1347             (_, &ty::TyBool)              => PrimVal::Bool(self.memory.read_bool(ptr)?),
1348             (_, &ty::TyInt(IntTy::I8))    => PrimVal::I8(self.memory.read_int(ptr, 1)? as i8),
1349             (2, &ty::TyInt(IntTy::Is)) |
1350             (_, &ty::TyInt(IntTy::I16))   => PrimVal::I16(self.memory.read_int(ptr, 2)? as i16),
1351             (4, &ty::TyInt(IntTy::Is)) |
1352             (_, &ty::TyInt(IntTy::I32))   => PrimVal::I32(self.memory.read_int(ptr, 4)? as i32),
1353             (8, &ty::TyInt(IntTy::Is)) |
1354             (_, &ty::TyInt(IntTy::I64))   => PrimVal::I64(self.memory.read_int(ptr, 8)? as i64),
1355             (_, &ty::TyUint(UintTy::U8))  => PrimVal::U8(self.memory.read_uint(ptr, 1)? as u8),
1356             (2, &ty::TyUint(UintTy::Us)) |
1357             (_, &ty::TyUint(UintTy::U16)) => PrimVal::U16(self.memory.read_uint(ptr, 2)? as u16),
1358             (4, &ty::TyUint(UintTy::Us)) |
1359             (_, &ty::TyUint(UintTy::U32)) => PrimVal::U32(self.memory.read_uint(ptr, 4)? as u32),
1360             (8, &ty::TyUint(UintTy::Us)) |
1361             (_, &ty::TyUint(UintTy::U64)) => PrimVal::U64(self.memory.read_uint(ptr, 8)? as u64),
1362
1363             (_, &ty::TyRef(_, ty::TypeAndMut { ty, .. })) |
1364             (_, &ty::TyRawPtr(ty::TypeAndMut { ty, .. })) => {
1365                 if self.type_is_sized(ty) {
1366                     match self.memory.read_ptr(ptr) {
1367                         Ok(p) => PrimVal::AbstractPtr(p),
1368                         Err(EvalError::ReadBytesAsPointer) => {
1369                             PrimVal::IntegerPtr(self.memory.read_usize(ptr)?)
1370                         }
1371                         Err(e) => return Err(e),
1372                     }
1373                 } else {
1374                     return Err(EvalError::Unimplemented(format!("unimplemented: primitive read of fat pointer type: {:?}", ty)));
1375                 }
1376             }
1377
1378             _ => panic!("primitive read of non-primitive type: {:?}", ty),
1379         };
1380         Ok(val)
1381     }
1382
1383     fn frame(&self) -> &Frame<'mir, 'tcx> {
1384         self.stack.last().expect("no call frames exist")
1385     }
1386
1387     fn basic_block(&self) -> &mir::BasicBlockData<'tcx> {
1388         let frame = self.frame();
1389         frame.mir.basic_block_data(frame.next_block)
1390     }
1391
1392     fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx> {
1393         self.stack.last_mut().expect("no call frames exist")
1394     }
1395
1396     fn mir(&self) -> CachedMir<'mir, 'tcx> {
1397         self.frame().mir.clone()
1398     }
1399
1400     fn substs(&self) -> &'tcx Substs<'tcx> {
1401         self.frame().substs
1402     }
1403 }
1404
1405 fn pointee_type(ptr_ty: ty::Ty) -> Option<ty::Ty> {
1406     match ptr_ty.sty {
1407         ty::TyRef(_, ty::TypeAndMut { ty, .. }) |
1408         ty::TyRawPtr(ty::TypeAndMut { ty, .. }) |
1409         ty::TyBox(ty) => {
1410             Some(ty)
1411         }
1412         _ => None,
1413     }
1414 }
1415
1416 impl Lvalue {
1417     fn to_ptr(self) -> Pointer {
1418         assert_eq!(self.extra, LvalueExtra::None);
1419         self.ptr
1420     }
1421 }
1422
1423 impl<'mir, 'tcx: 'mir> Deref for CachedMir<'mir, 'tcx> {
1424     type Target = mir::Mir<'tcx>;
1425     fn deref(&self) -> &mir::Mir<'tcx> {
1426         match *self {
1427             CachedMir::Ref(r) => r,
1428             CachedMir::Owned(ref rc) => rc,
1429         }
1430     }
1431 }
1432
1433 #[derive(Debug)]
1434 pub struct ImplMethod<'tcx> {
1435     pub method: Rc<ty::Method<'tcx>>,
1436     pub substs: &'tcx Substs<'tcx>,
1437     pub is_provided: bool,
1438 }
1439
1440 /// Locates the applicable definition of a method, given its name.
1441 pub fn get_impl_method<'a, 'tcx>(
1442     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1443     impl_def_id: DefId,
1444     substs: &'tcx Substs<'tcx>,
1445     name: ast::Name,
1446 ) -> ImplMethod<'tcx> {
1447     assert!(!substs.types.needs_infer());
1448
1449     let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
1450     let trait_def = tcx.lookup_trait_def(trait_def_id);
1451
1452     match trait_def.ancestors(impl_def_id).fn_defs(tcx, name).next() {
1453         Some(node_item) => {
1454             let substs = tcx.normalizing_infer_ctxt(ProjectionMode::Any).enter(|infcx| {
1455                 let substs = traits::translate_substs(&infcx, impl_def_id,
1456                                                       substs, node_item.node);
1457                 tcx.lift(&substs).unwrap_or_else(|| {
1458                     bug!("trans::meth::get_impl_method: translate_substs \
1459                           returned {:?} which contains inference types/regions",
1460                          substs);
1461                 })
1462             });
1463             ImplMethod {
1464                 method: node_item.item,
1465                 substs: substs,
1466                 is_provided: node_item.node.is_from_trait(),
1467             }
1468         }
1469         None => {
1470             bug!("method {:?} not found in {:?}", name, impl_def_id)
1471         }
1472     }
1473 }
1474
1475 pub fn interpret_start_points<'a, 'tcx>(
1476     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1477     mir_map: &MirMap<'tcx>,
1478 ) {
1479     let initial_indentation = ::log_settings::settings().indentation;
1480     for (&id, mir) in &mir_map.map {
1481         for attr in tcx.map.attrs(id) {
1482             use syntax::attr::AttrMetaMethods;
1483             if attr.check_name("miri_run") {
1484                 let item = tcx.map.expect_item(id);
1485
1486                 ::log_settings::settings().indentation = initial_indentation;
1487
1488                 debug!("Interpreting: {}", item.name);
1489
1490                 let mut gecx = GlobalEvalContext::new(tcx, mir_map);
1491                 match gecx.call(mir, tcx.map.local_def_id(id)) {
1492                     Ok(Some(return_ptr)) => if log_enabled!(::log::LogLevel::Debug) {
1493                         gecx.memory.dump(return_ptr.alloc_id);
1494                     },
1495                     Ok(None) => warn!("diverging function returned"),
1496                     Err(_e) => {
1497                         // TODO(solson): Detect whether the error was already reported or not.
1498                         // tcx.sess.err(&e.to_string());
1499                     }
1500                 }
1501             }
1502         }
1503     }
1504 }
1505
1506 // TODO(solson): Upstream these methods into rustc::ty::layout.
1507
1508 trait IntegerExt {
1509     fn size(self) -> Size;
1510 }
1511
1512 impl IntegerExt for layout::Integer {
1513     fn size(self) -> Size {
1514         use rustc::ty::layout::Integer::*;
1515         match self {
1516             I1 | I8 => Size::from_bits(8),
1517             I16 => Size::from_bits(16),
1518             I32 => Size::from_bits(32),
1519             I64 => Size::from_bits(64),
1520         }
1521     }
1522 }
1523
1524 trait StructExt {
1525     fn field_offset(&self, index: usize) -> Size;
1526 }
1527
1528 impl StructExt for layout::Struct {
1529     fn field_offset(&self, index: usize) -> Size {
1530         if index == 0 {
1531             Size::from_bytes(0)
1532         } else {
1533             self.offset_after_field[index - 1]
1534         }
1535     }
1536 }