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