]> git.lizzy.rs Git - rust.git/blob - src/interpreter/mod.rs
improve the docs of ConstantId
[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         let mut done = false;
399         while !done {
400             use self::stepper::Event::*;
401             stepper.step(|event| match event {
402                 Block(b) => trace!("// {:?}", b),
403                 Assignment(a) => trace!("{:?}", a),
404                 Terminator(t) => trace!("{:?}", t.kind),
405                 Done => done = true,
406                 _ => {},
407             })?;
408         }
409         Ok(())
410     }
411
412     fn push_stack_frame(&mut self, def_id: DefId, span: codemap::Span, mir: CachedMir<'mir, 'tcx>, substs: &'tcx Substs<'tcx>,
413         return_ptr: Option<Pointer>)
414     {
415         let arg_tys = mir.arg_decls.iter().map(|a| a.ty);
416         let var_tys = mir.var_decls.iter().map(|v| v.ty);
417         let temp_tys = mir.temp_decls.iter().map(|t| t.ty);
418
419         let num_args = mir.arg_decls.len();
420         let num_vars = mir.var_decls.len();
421
422         ::log_settings::settings().indentation += 1;
423
424         self.stack.push(Frame {
425             mir: mir.clone(),
426             next_block: mir::START_BLOCK,
427             return_ptr: return_ptr,
428             locals: Vec::new(),
429             var_offset: num_args,
430             temp_offset: num_args + num_vars,
431             span: span,
432             def_id: def_id,
433             substs: substs,
434             stmt: 0,
435         });
436
437         let locals: Vec<Pointer> = arg_tys.chain(var_tys).chain(temp_tys).map(|ty| {
438             let size = self.type_size(ty);
439             self.memory.allocate(size)
440         }).collect();
441
442         self.frame_mut().locals = locals;
443     }
444
445     fn pop_stack_frame(&mut self) {
446         ::log_settings::settings().indentation -= 1;
447         let _frame = self.stack.pop().expect("tried to pop a stack frame, but there were none");
448         // TODO(solson): Deallocate local variables.
449     }
450
451     fn eval_terminator(&mut self, terminator: &mir::Terminator<'tcx>)
452             -> EvalResult<TerminatorTarget> {
453         use rustc::mir::repr::TerminatorKind::*;
454         let target = match terminator.kind {
455             Return => TerminatorTarget::Return,
456
457             Goto { target } => {
458                 self.frame_mut().next_block = target;
459                 TerminatorTarget::Block
460             },
461
462             If { ref cond, targets: (then_target, else_target) } => {
463                 let cond_ptr = self.eval_operand(cond)?;
464                 let cond_val = self.memory.read_bool(cond_ptr)?;
465                 self.frame_mut().next_block = if cond_val { then_target } else { else_target };
466                 TerminatorTarget::Block
467             }
468
469             SwitchInt { ref discr, ref values, ref targets, .. } => {
470                 let discr_ptr = self.eval_lvalue(discr)?.to_ptr();
471                 let discr_size = self
472                     .type_layout(self.lvalue_ty(discr))
473                     .size(&self.tcx.data_layout)
474                     .bytes() as usize;
475                 let discr_val = self.memory.read_uint(discr_ptr, discr_size)?;
476
477                 // Branch to the `otherwise` case by default, if no match is found.
478                 let mut target_block = targets[targets.len() - 1];
479
480                 for (index, val_const) in values.iter().enumerate() {
481                     let ptr = self.const_to_ptr(val_const)?;
482                     let val = self.memory.read_uint(ptr, discr_size)?;
483                     if discr_val == val {
484                         target_block = targets[index];
485                         break;
486                     }
487                 }
488
489                 self.frame_mut().next_block = target_block;
490                 TerminatorTarget::Block
491             }
492
493             Switch { ref discr, ref targets, adt_def } => {
494                 let adt_ptr = self.eval_lvalue(discr)?.to_ptr();
495                 let adt_ty = self.lvalue_ty(discr);
496                 let discr_val = self.read_discriminant_value(adt_ptr, adt_ty)?;
497                 let matching = adt_def.variants.iter()
498                     .position(|v| discr_val == v.disr_val.to_u64_unchecked());
499
500                 match matching {
501                     Some(i) => {
502                         self.frame_mut().next_block = targets[i];
503                         TerminatorTarget::Block
504                     },
505                     None => return Err(EvalError::InvalidDiscriminant),
506                 }
507             }
508
509             Call { ref func, ref args, ref destination, .. } => {
510                 let mut return_ptr = None;
511                 if let Some((ref lv, target)) = *destination {
512                     self.frame_mut().next_block = target;
513                     return_ptr = Some(self.eval_lvalue(lv)?.to_ptr());
514                 }
515
516                 let func_ty = self.operand_ty(func);
517                 match func_ty.sty {
518                     ty::TyFnDef(def_id, substs, fn_ty) => {
519                         use syntax::abi::Abi;
520                         match fn_ty.abi {
521                             Abi::RustIntrinsic => {
522                                 let name = self.tcx.item_name(def_id).as_str();
523                                 match fn_ty.sig.0.output {
524                                     ty::FnConverging(ty) => {
525                                         let size = self.type_size(ty);
526                                         let ret = return_ptr.unwrap();
527                                         self.call_intrinsic(&name, substs, args, ret, size)?
528                                     }
529                                     ty::FnDiverging => unimplemented!(),
530                                 }
531                             }
532
533                             Abi::C => {
534                                 match fn_ty.sig.0.output {
535                                     ty::FnConverging(ty) => {
536                                         let size = self.type_size(ty);
537                                         self.call_c_abi(def_id, args, return_ptr.unwrap(), size)?
538                                     }
539                                     ty::FnDiverging => unimplemented!(),
540                                 }
541                             }
542
543                             Abi::Rust | Abi::RustCall => {
544                                 // TODO(solson): Adjust the first argument when calling a Fn or
545                                 // FnMut closure via FnOnce::call_once.
546
547                                 // Only trait methods can have a Self parameter.
548                                 let (resolved_def_id, resolved_substs) = if substs.self_ty().is_some() {
549                                     self.trait_method(def_id, substs)
550                                 } else {
551                                     (def_id, substs)
552                                 };
553
554                                 let mut arg_srcs = Vec::new();
555                                 for arg in args {
556                                     let src = self.eval_operand(arg)?;
557                                     let src_ty = self.operand_ty(arg);
558                                     arg_srcs.push((src, src_ty));
559                                 }
560
561                                 if fn_ty.abi == Abi::RustCall && !args.is_empty() {
562                                     arg_srcs.pop();
563                                     let last_arg = args.last().unwrap();
564                                     let last = self.eval_operand(last_arg)?;
565                                     let last_ty = self.operand_ty(last_arg);
566                                     let last_layout = self.type_layout(last_ty);
567                                     match (&last_ty.sty, last_layout) {
568                                         (&ty::TyTuple(fields),
569                                          &Layout::Univariant { ref variant, .. }) => {
570                                             let offsets = iter::once(0)
571                                                 .chain(variant.offset_after_field.iter()
572                                                     .map(|s| s.bytes()));
573                                             for (offset, ty) in offsets.zip(fields) {
574                                                 let src = last.offset(offset as isize);
575                                                 arg_srcs.push((src, ty));
576                                             }
577                                         }
578                                         ty => panic!("expected tuple as last argument in function with 'rust-call' ABI, got {:?}", ty),
579                                     }
580                                 }
581
582                                 let mir = self.load_mir(resolved_def_id);
583                                 self.push_stack_frame(def_id, terminator.span, mir, resolved_substs, return_ptr);
584
585                                 for (i, (src, src_ty)) in arg_srcs.into_iter().enumerate() {
586                                     let dest = self.frame().locals[i];
587                                     self.move_(src, dest, src_ty)?;
588                                 }
589
590                                 TerminatorTarget::Call
591                             }
592
593                             abi => return Err(EvalError::Unimplemented(format!("can't handle function with {:?} ABI", abi))),
594                         }
595                     }
596
597                     _ => return Err(EvalError::Unimplemented(format!("can't handle callee of type {:?}", func_ty))),
598                 }
599             }
600
601             Drop { ref value, target, .. } => {
602                 let ptr = self.eval_lvalue(value)?.to_ptr();
603                 let ty = self.lvalue_ty(value);
604                 self.drop(ptr, ty)?;
605                 self.frame_mut().next_block = target;
606                 TerminatorTarget::Block
607             }
608
609             Resume => unimplemented!(),
610         };
611
612         Ok(target)
613     }
614
615     fn drop(&mut self, ptr: Pointer, ty: Ty<'tcx>) -> EvalResult<()> {
616         if !self.type_needs_drop(ty) {
617             debug!("no need to drop {:?}", ty);
618             return Ok(());
619         }
620         trace!("-need to drop {:?}", ty);
621
622         // TODO(solson): Call user-defined Drop::drop impls.
623
624         match ty.sty {
625             ty::TyBox(contents_ty) => {
626                 match self.memory.read_ptr(ptr) {
627                     Ok(contents_ptr) => {
628                         self.drop(contents_ptr, contents_ty)?;
629                         trace!("-deallocating box");
630                         self.memory.deallocate(contents_ptr)?;
631                     }
632                     Err(EvalError::ReadBytesAsPointer) => {
633                         let size = self.memory.pointer_size;
634                         let possible_drop_fill = self.memory.read_bytes(ptr, size)?;
635                         if possible_drop_fill.iter().all(|&b| b == mem::POST_DROP_U8) {
636                             return Ok(());
637                         } else {
638                             return Err(EvalError::ReadBytesAsPointer);
639                         }
640                     }
641                     Err(e) => return Err(e),
642                 }
643             }
644
645             // TODO(solson): Implement drop for other relevant types (e.g. aggregates).
646             _ => {}
647         }
648
649         // Filling drop.
650         // FIXME(solson): Trait objects (with no static size) probably get filled, too.
651         let size = self.type_size(ty);
652         self.memory.drop_fill(ptr, size)?;
653
654         Ok(())
655     }
656
657     fn read_discriminant_value(&self, adt_ptr: Pointer, adt_ty: Ty<'tcx>) -> EvalResult<u64> {
658         use rustc::ty::layout::Layout::*;
659         let adt_layout = self.type_layout(adt_ty);
660
661         let discr_val = match *adt_layout {
662             General { discr, .. } | CEnum { discr, .. } => {
663                 let discr_size = discr.size().bytes();
664                 self.memory.read_uint(adt_ptr, discr_size as usize)?
665             }
666
667             RawNullablePointer { nndiscr, .. } => {
668                 self.read_nonnull_discriminant_value(adt_ptr, nndiscr)?
669             }
670
671             StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => {
672                 let offset = self.nonnull_offset(adt_ty, nndiscr, discrfield)?;
673                 let nonnull = adt_ptr.offset(offset.bytes() as isize);
674                 self.read_nonnull_discriminant_value(nonnull, nndiscr)?
675             }
676
677             // The discriminant_value intrinsic returns 0 for non-sum types.
678             Array { .. } | FatPointer { .. } | Scalar { .. } | Univariant { .. } |
679             Vector { .. } => 0,
680         };
681
682         Ok(discr_val)
683     }
684
685     fn read_nonnull_discriminant_value(&self, ptr: Pointer, nndiscr: u64) -> EvalResult<u64> {
686         let not_null = match self.memory.read_usize(ptr) {
687             Ok(0) => false,
688             Ok(_) | Err(EvalError::ReadPointerAsBytes) => true,
689             Err(e) => return Err(e),
690         };
691         assert!(nndiscr == 0 || nndiscr == 1);
692         Ok(if not_null { nndiscr } else { 1 - nndiscr })
693     }
694
695     fn call_intrinsic(
696         &mut self,
697         name: &str,
698         substs: &'tcx Substs<'tcx>,
699         args: &[mir::Operand<'tcx>],
700         dest: Pointer,
701         dest_size: usize
702     ) -> EvalResult<TerminatorTarget> {
703         let args_res: EvalResult<Vec<Pointer>> = args.iter()
704             .map(|arg| self.eval_operand(arg))
705             .collect();
706         let args = args_res?;
707
708         match name {
709             // FIXME(solson): Handle different integer types correctly.
710             "add_with_overflow" => {
711                 let ty = *substs.types.get(subst::FnSpace, 0);
712                 let size = self.type_size(ty);
713                 let left = self.memory.read_int(args[0], size)?;
714                 let right = self.memory.read_int(args[1], size)?;
715                 let (n, overflowed) = unsafe {
716                     ::std::intrinsics::add_with_overflow::<i64>(left, right)
717                 };
718                 self.memory.write_int(dest, n, size)?;
719                 self.memory.write_bool(dest.offset(size as isize), overflowed)?;
720             }
721
722             "assume" => {}
723
724             "copy_nonoverlapping" => {
725                 let elem_ty = *substs.types.get(subst::FnSpace, 0);
726                 let elem_size = self.type_size(elem_ty);
727                 let src = self.memory.read_ptr(args[0])?;
728                 let dest = self.memory.read_ptr(args[1])?;
729                 let count = self.memory.read_isize(args[2])?;
730                 self.memory.copy(src, dest, count as usize * elem_size)?;
731             }
732
733             "discriminant_value" => {
734                 let ty = *substs.types.get(subst::FnSpace, 0);
735                 let adt_ptr = self.memory.read_ptr(args[0])?;
736                 let discr_val = self.read_discriminant_value(adt_ptr, ty)?;
737                 self.memory.write_uint(dest, discr_val, dest_size)?;
738             }
739
740             "forget" => {
741                 let arg_ty = *substs.types.get(subst::FnSpace, 0);
742                 let arg_size = self.type_size(arg_ty);
743                 self.memory.drop_fill(args[0], arg_size)?;
744             }
745
746             "init" => self.memory.write_repeat(dest, 0, dest_size)?,
747
748             "min_align_of" => {
749                 self.memory.write_int(dest, 1, dest_size)?;
750             }
751
752             "move_val_init" => {
753                 let ty = *substs.types.get(subst::FnSpace, 0);
754                 let ptr = self.memory.read_ptr(args[0])?;
755                 self.move_(args[1], ptr, ty)?;
756             }
757
758             // FIXME(solson): Handle different integer types correctly.
759             "mul_with_overflow" => {
760                 let ty = *substs.types.get(subst::FnSpace, 0);
761                 let size = self.type_size(ty);
762                 let left = self.memory.read_int(args[0], size)?;
763                 let right = self.memory.read_int(args[1], size)?;
764                 let (n, overflowed) = unsafe {
765                     ::std::intrinsics::mul_with_overflow::<i64>(left, right)
766                 };
767                 self.memory.write_int(dest, n, size)?;
768                 self.memory.write_bool(dest.offset(size as isize), overflowed)?;
769             }
770
771             "offset" => {
772                 let pointee_ty = *substs.types.get(subst::FnSpace, 0);
773                 let pointee_size = self.type_size(pointee_ty) as isize;
774                 let ptr_arg = args[0];
775                 let offset = self.memory.read_isize(args[1])?;
776
777                 match self.memory.read_ptr(ptr_arg) {
778                     Ok(ptr) => {
779                         let result_ptr = ptr.offset(offset as isize * pointee_size);
780                         self.memory.write_ptr(dest, result_ptr)?;
781                     }
782                     Err(EvalError::ReadBytesAsPointer) => {
783                         let addr = self.memory.read_isize(ptr_arg)?;
784                         let result_addr = addr + offset * pointee_size as i64;
785                         self.memory.write_isize(dest, result_addr)?;
786                     }
787                     Err(e) => return Err(e),
788                 }
789             }
790
791             // FIXME(solson): Handle different integer types correctly. Use primvals?
792             "overflowing_sub" => {
793                 let ty = *substs.types.get(subst::FnSpace, 0);
794                 let size = self.type_size(ty);
795                 let left = self.memory.read_int(args[0], size)?;
796                 let right = self.memory.read_int(args[1], size)?;
797                 let n = left.wrapping_sub(right);
798                 self.memory.write_int(dest, n, size)?;
799             }
800
801             "size_of" => {
802                 let ty = *substs.types.get(subst::FnSpace, 0);
803                 let size = self.type_size(ty) as u64;
804                 self.memory.write_uint(dest, size, dest_size)?;
805             }
806
807             "size_of_val" => {
808                 let ty = *substs.types.get(subst::FnSpace, 0);
809                 if self.type_is_sized(ty) {
810                     let size = self.type_size(ty) as u64;
811                     self.memory.write_uint(dest, size, dest_size)?;
812                 } else {
813                     match ty.sty {
814                         ty::TySlice(_) | ty::TyStr => {
815                             let elem_ty = ty.sequence_element_type(self.tcx);
816                             let elem_size = self.type_size(elem_ty) as u64;
817                             let ptr_size = self.memory.pointer_size as isize;
818                             let n = self.memory.read_usize(args[0].offset(ptr_size))?;
819                             self.memory.write_uint(dest, n * elem_size, dest_size)?;
820                         }
821
822                         _ => return Err(EvalError::Unimplemented(format!("unimplemented: size_of_val::<{:?}>", ty))),
823                     }
824                 }
825             }
826
827             "transmute" => {
828                 let ty = *substs.types.get(subst::FnSpace, 0);
829                 self.move_(args[0], dest, ty)?;
830             }
831             "uninit" => self.memory.mark_definedness(dest, dest_size, false)?,
832
833             name => return Err(EvalError::Unimplemented(format!("unimplemented intrinsic: {}", name))),
834         }
835
836         // Since we pushed no stack frame, the main loop will act
837         // as if the call just completed and it's returning to the
838         // current frame.
839         Ok(TerminatorTarget::Call)
840     }
841
842     fn call_c_abi(
843         &mut self,
844         def_id: DefId,
845         args: &[mir::Operand<'tcx>],
846         dest: Pointer,
847         dest_size: usize,
848     ) -> EvalResult<TerminatorTarget> {
849         let name = self.tcx.item_name(def_id);
850         let attrs = self.tcx.get_attrs(def_id);
851         let link_name = match attr::first_attr_value_str_by_name(&attrs, "link_name") {
852             Some(ln) => ln.clone(),
853             None => name.as_str(),
854         };
855
856         let args_res: EvalResult<Vec<Pointer>> = args.iter()
857             .map(|arg| self.eval_operand(arg))
858             .collect();
859         let args = args_res?;
860
861         match &link_name[..] {
862             "__rust_allocate" => {
863                 let size = self.memory.read_usize(args[0])?;
864                 let ptr = self.memory.allocate(size as usize);
865                 self.memory.write_ptr(dest, ptr)?;
866             }
867
868             "__rust_reallocate" => {
869                 let ptr = self.memory.read_ptr(args[0])?;
870                 let size = self.memory.read_usize(args[2])?;
871                 self.memory.reallocate(ptr, size as usize)?;
872                 self.memory.write_ptr(dest, ptr)?;
873             }
874
875             "memcmp" => {
876                 let left = self.memory.read_ptr(args[0])?;
877                 let right = self.memory.read_ptr(args[1])?;
878                 let n = self.memory.read_usize(args[2])? as usize;
879
880                 let result = {
881                     let left_bytes = self.memory.read_bytes(left, n)?;
882                     let right_bytes = self.memory.read_bytes(right, n)?;
883
884                     use std::cmp::Ordering::*;
885                     match left_bytes.cmp(right_bytes) {
886                         Less => -1,
887                         Equal => 0,
888                         Greater => 1,
889                     }
890                 };
891
892                 self.memory.write_int(dest, result, dest_size)?;
893             }
894
895             _ => return Err(EvalError::Unimplemented(format!("can't call C ABI function: {}", link_name))),
896         }
897
898         // Since we pushed no stack frame, the main loop will act
899         // as if the call just completed and it's returning to the
900         // current frame.
901         Ok(TerminatorTarget::Call)
902     }
903
904     fn assign_fields<I: IntoIterator<Item = u64>>(
905         &mut self,
906         dest: Pointer,
907         offsets: I,
908         operands: &[mir::Operand<'tcx>],
909     ) -> EvalResult<()> {
910         for (offset, operand) in offsets.into_iter().zip(operands) {
911             let src = self.eval_operand(operand)?;
912             let src_ty = self.operand_ty(operand);
913             let field_dest = dest.offset(offset as isize);
914             self.move_(src, field_dest, src_ty)?;
915         }
916         Ok(())
917     }
918
919     fn eval_assignment(&mut self, lvalue: &mir::Lvalue<'tcx>, rvalue: &mir::Rvalue<'tcx>)
920         -> EvalResult<()>
921     {
922         let dest = self.eval_lvalue(lvalue)?.to_ptr();
923         let dest_ty = self.lvalue_ty(lvalue);
924         let dest_layout = self.type_layout(dest_ty);
925
926         use rustc::mir::repr::Rvalue::*;
927         match *rvalue {
928             Use(ref operand) => {
929                 let src = self.eval_operand(operand)?;
930                 self.move_(src, dest, dest_ty)?;
931             }
932
933             BinaryOp(bin_op, ref left, ref right) => {
934                 let left_ptr = self.eval_operand(left)?;
935                 let left_ty = self.operand_ty(left);
936                 let left_val = self.read_primval(left_ptr, left_ty)?;
937
938                 let right_ptr = self.eval_operand(right)?;
939                 let right_ty = self.operand_ty(right);
940                 let right_val = self.read_primval(right_ptr, right_ty)?;
941
942                 let val = primval::binary_op(bin_op, left_val, right_val)?;
943                 self.memory.write_primval(dest, val)?;
944             }
945
946             UnaryOp(un_op, ref operand) => {
947                 let ptr = self.eval_operand(operand)?;
948                 let ty = self.operand_ty(operand);
949                 let val = self.read_primval(ptr, ty)?;
950                 self.memory.write_primval(dest, primval::unary_op(un_op, val)?)?;
951             }
952
953             Aggregate(ref kind, ref operands) => {
954                 use rustc::ty::layout::Layout::*;
955                 match *dest_layout {
956                     Univariant { ref variant, .. } => {
957                         let offsets = iter::once(0)
958                             .chain(variant.offset_after_field.iter().map(|s| s.bytes()));
959                         self.assign_fields(dest, offsets, operands)?;
960                     }
961
962                     Array { .. } => {
963                         let elem_size = match dest_ty.sty {
964                             ty::TyArray(elem_ty, _) => self.type_size(elem_ty) as u64,
965                             _ => panic!("tried to assign {:?} to non-array type {:?}",
966                                         kind, dest_ty),
967                         };
968                         let offsets = (0..).map(|i| i * elem_size);
969                         self.assign_fields(dest, offsets, operands)?;
970                     }
971
972                     General { discr, ref variants, .. } => {
973                         if let mir::AggregateKind::Adt(adt_def, variant, _) = *kind {
974                             let discr_val = adt_def.variants[variant].disr_val.to_u64_unchecked();
975                             let discr_size = discr.size().bytes() as usize;
976                             self.memory.write_uint(dest, discr_val, discr_size)?;
977
978                             let offsets = variants[variant].offset_after_field.iter()
979                                 .map(|s| s.bytes());
980                             self.assign_fields(dest, offsets, operands)?;
981                         } else {
982                             panic!("tried to assign {:?} to Layout::General", kind);
983                         }
984                     }
985
986                     RawNullablePointer { nndiscr, .. } => {
987                         if let mir::AggregateKind::Adt(_, variant, _) = *kind {
988                             if nndiscr == variant as u64 {
989                                 assert_eq!(operands.len(), 1);
990                                 let operand = &operands[0];
991                                 let src = self.eval_operand(operand)?;
992                                 let src_ty = self.operand_ty(operand);
993                                 self.move_(src, dest, src_ty)?;
994                             } else {
995                                 assert_eq!(operands.len(), 0);
996                                 self.memory.write_isize(dest, 0)?;
997                             }
998                         } else {
999                             panic!("tried to assign {:?} to Layout::RawNullablePointer", kind);
1000                         }
1001                     }
1002
1003                     StructWrappedNullablePointer { nndiscr, ref nonnull, ref discrfield } => {
1004                         if let mir::AggregateKind::Adt(_, variant, _) = *kind {
1005                             if nndiscr == variant as u64 {
1006                                 let offsets = iter::once(0)
1007                                     .chain(nonnull.offset_after_field.iter().map(|s| s.bytes()));
1008                                 try!(self.assign_fields(dest, offsets, operands));
1009                             } else {
1010                                 assert_eq!(operands.len(), 0);
1011                                 let offset = self.nonnull_offset(dest_ty, nndiscr, discrfield)?;
1012                                 let dest = dest.offset(offset.bytes() as isize);
1013                                 try!(self.memory.write_isize(dest, 0));
1014                             }
1015                         } else {
1016                             panic!("tried to assign {:?} to Layout::RawNullablePointer", kind);
1017                         }
1018                     }
1019
1020                     CEnum { discr, signed, .. } => {
1021                         assert_eq!(operands.len(), 0);
1022                         if let mir::AggregateKind::Adt(adt_def, variant, _) = *kind {
1023                             let val = adt_def.variants[variant].disr_val.to_u64_unchecked();
1024                             let size = discr.size().bytes() as usize;
1025
1026                             if signed {
1027                                 self.memory.write_int(dest, val as i64, size)?;
1028                             } else {
1029                                 self.memory.write_uint(dest, val, size)?;
1030                             }
1031                         } else {
1032                             panic!("tried to assign {:?} to Layout::CEnum", kind);
1033                         }
1034                     }
1035
1036                     _ => return Err(EvalError::Unimplemented(format!("can't handle destination layout {:?} when assigning {:?}", dest_layout, kind))),
1037                 }
1038             }
1039
1040             Repeat(ref operand, _) => {
1041                 let (elem_size, length) = match dest_ty.sty {
1042                     ty::TyArray(elem_ty, n) => (self.type_size(elem_ty), n),
1043                     _ => panic!("tried to assign array-repeat to non-array type {:?}", dest_ty),
1044                 };
1045
1046                 let src = self.eval_operand(operand)?;
1047                 for i in 0..length {
1048                     let elem_dest = dest.offset((i * elem_size) as isize);
1049                     self.memory.copy(src, elem_dest, elem_size)?;
1050                 }
1051             }
1052
1053             Len(ref lvalue) => {
1054                 let src = self.eval_lvalue(lvalue)?;
1055                 let ty = self.lvalue_ty(lvalue);
1056                 let len = match ty.sty {
1057                     ty::TyArray(_, n) => n as u64,
1058                     ty::TySlice(_) => if let LvalueExtra::Length(n) = src.extra {
1059                         n
1060                     } else {
1061                         panic!("Rvalue::Len of a slice given non-slice pointer: {:?}", src);
1062                     },
1063                     _ => panic!("Rvalue::Len expected array or slice, got {:?}", ty),
1064                 };
1065                 self.memory.write_usize(dest, len)?;
1066             }
1067
1068             Ref(_, _, ref lvalue) => {
1069                 let lv = self.eval_lvalue(lvalue)?;
1070                 self.memory.write_ptr(dest, lv.ptr)?;
1071                 match lv.extra {
1072                     LvalueExtra::None => {},
1073                     LvalueExtra::Length(len) => {
1074                         let len_ptr = dest.offset(self.memory.pointer_size as isize);
1075                         self.memory.write_usize(len_ptr, len)?;
1076                     }
1077                     LvalueExtra::DowncastVariant(..) =>
1078                         panic!("attempted to take a reference to an enum downcast lvalue"),
1079                 }
1080             }
1081
1082             Box(ty) => {
1083                 let size = self.type_size(ty);
1084                 let ptr = self.memory.allocate(size);
1085                 self.memory.write_ptr(dest, ptr)?;
1086             }
1087
1088             Cast(kind, ref operand, dest_ty) => {
1089                 let src = self.eval_operand(operand)?;
1090                 let src_ty = self.operand_ty(operand);
1091
1092                 use rustc::mir::repr::CastKind::*;
1093                 match kind {
1094                     Unsize => {
1095                         self.move_(src, dest, src_ty)?;
1096                         let src_pointee_ty = pointee_type(src_ty).unwrap();
1097                         let dest_pointee_ty = pointee_type(dest_ty).unwrap();
1098
1099                         match (&src_pointee_ty.sty, &dest_pointee_ty.sty) {
1100                             (&ty::TyArray(_, length), &ty::TySlice(_)) => {
1101                                 let len_ptr = dest.offset(self.memory.pointer_size as isize);
1102                                 self.memory.write_usize(len_ptr, length as u64)?;
1103                             }
1104
1105                             _ => return Err(EvalError::Unimplemented(format!("can't handle cast: {:?}", rvalue))),
1106                         }
1107                     }
1108
1109                     Misc => {
1110                         // FIXME(solson): Wrong for almost everything.
1111                         let size = dest_layout.size(&self.tcx.data_layout).bytes() as usize;
1112                         self.memory.copy(src, dest, size)?;
1113                     }
1114
1115                     _ => return Err(EvalError::Unimplemented(format!("can't handle cast: {:?}", rvalue))),
1116                 }
1117             }
1118
1119             Slice { .. } => unimplemented!(),
1120             InlineAsm { .. } => unimplemented!(),
1121         }
1122
1123         Ok(())
1124     }
1125
1126     fn nonnull_offset(&self, ty: Ty<'tcx>, nndiscr: u64, discrfield: &[u32]) -> EvalResult<Size> {
1127         // Skip the constant 0 at the start meant for LLVM GEP.
1128         let mut path = discrfield.iter().skip(1).map(|&i| i as usize);
1129
1130         // Handle the field index for the outer non-null variant.
1131         let inner_ty = match ty.sty {
1132             ty::TyEnum(adt_def, substs) => {
1133                 let variant = &adt_def.variants[nndiscr as usize];
1134                 let index = path.next().unwrap();
1135                 let field = &variant.fields[index];
1136                 field.ty(self.tcx, substs)
1137             }
1138             _ => panic!(
1139                 "non-enum for StructWrappedNullablePointer: {}",
1140                 ty,
1141             ),
1142         };
1143
1144         self.field_path_offset(inner_ty, path)
1145     }
1146
1147     fn field_path_offset<I: Iterator<Item = usize>>(&self, mut ty: Ty<'tcx>, path: I) -> EvalResult<Size> {
1148         let mut offset = Size::from_bytes(0);
1149
1150         // Skip the initial 0 intended for LLVM GEP.
1151         for field_index in path {
1152             let field_offset = self.get_field_offset(ty, field_index)?;
1153             ty = self.get_field_ty(ty, field_index)?;
1154             offset = offset.checked_add(field_offset, &self.tcx.data_layout).unwrap();
1155         }
1156
1157         Ok(offset)
1158     }
1159
1160     fn get_field_ty(&self, ty: Ty<'tcx>, field_index: usize) -> EvalResult<Ty<'tcx>> {
1161         match ty.sty {
1162             ty::TyStruct(adt_def, substs) => {
1163                 Ok(adt_def.struct_variant().fields[field_index].ty(self.tcx, substs))
1164             }
1165
1166             ty::TyRef(_, ty::TypeAndMut { ty, .. }) |
1167             ty::TyRawPtr(ty::TypeAndMut { ty, .. }) |
1168             ty::TyBox(ty) => {
1169                 assert_eq!(field_index, 0);
1170                 Ok(ty)
1171             }
1172             _ => Err(EvalError::Unimplemented(format!("can't handle type: {:?}", ty))),
1173         }
1174     }
1175
1176     fn get_field_offset(&self, ty: Ty<'tcx>, field_index: usize) -> EvalResult<Size> {
1177         let layout = self.type_layout(ty);
1178
1179         use rustc::ty::layout::Layout::*;
1180         match *layout {
1181             Univariant { .. } => {
1182                 assert_eq!(field_index, 0);
1183                 Ok(Size::from_bytes(0))
1184             }
1185             FatPointer { .. } => {
1186                 let bytes = layout::FAT_PTR_ADDR * self.memory.pointer_size;
1187                 Ok(Size::from_bytes(bytes as u64))
1188             }
1189             _ => Err(EvalError::Unimplemented(format!("can't handle type: {:?}, with layout: {:?}", ty, layout))),
1190         }
1191     }
1192
1193     fn eval_operand(&mut self, op: &mir::Operand<'tcx>) -> EvalResult<Pointer> {
1194         use rustc::mir::repr::Operand::*;
1195         match *op {
1196             Consume(ref lvalue) => Ok(self.eval_lvalue(lvalue)?.to_ptr()),
1197             Constant(mir::Constant { ref literal, .. }) => {
1198                 use rustc::mir::repr::Literal::*;
1199                 match *literal {
1200                     Value { ref value } => Ok(self.const_to_ptr(value)?),
1201                     Item { def_id, substs } => {
1202                         let item_ty = self.tcx.lookup_item_type(def_id).subst(self.tcx, substs);
1203                         if item_ty.ty.is_fn() {
1204                             Err(EvalError::Unimplemented("unimplemented: mentions of function items".to_string()))
1205                         } else {
1206                             let cid = ConstantId {
1207                                 def_id: def_id,
1208                                 substs: substs,
1209                                 kind: ConstantKind::Global,
1210                             };
1211                             Ok(*self.statics.get(&cid).expect("static should have been cached (rvalue)"))
1212                         }
1213                     },
1214                     Promoted { index } => {
1215                         let cid = ConstantId {
1216                             def_id: self.frame().def_id,
1217                             substs: self.substs(),
1218                             kind: ConstantKind::Promoted(index),
1219                         };
1220                         Ok(*self.statics.get(&cid).expect("a promoted constant hasn't been precomputed"))
1221                     },
1222                 }
1223             }
1224         }
1225     }
1226
1227     fn eval_lvalue(&mut self, lvalue: &mir::Lvalue<'tcx>) -> EvalResult<Lvalue> {
1228         use rustc::mir::repr::Lvalue::*;
1229         let ptr = match *lvalue {
1230             ReturnPointer => self.frame().return_ptr
1231                 .expect("ReturnPointer used in a function with no return value"),
1232             Arg(i) => self.frame().locals[i as usize],
1233             Var(i) => self.frame().locals[self.frame().var_offset + i as usize],
1234             Temp(i) => self.frame().locals[self.frame().temp_offset + i as usize],
1235
1236             Static(def_id) => {
1237                 let substs = self.tcx.mk_substs(subst::Substs::empty());
1238                 let cid = ConstantId {
1239                     def_id: def_id,
1240                     substs: substs,
1241                     kind: ConstantKind::Global,
1242                 };
1243                 *self.gecx.statics.get(&cid).expect("static should have been cached (lvalue)")
1244             },
1245
1246             Projection(ref proj) => {
1247                 let base = self.eval_lvalue(&proj.base)?;
1248                 let base_ty = self.lvalue_ty(&proj.base);
1249                 let base_layout = self.type_layout(base_ty);
1250
1251                 use rustc::mir::repr::ProjectionElem::*;
1252                 match proj.elem {
1253                     Field(field, _) => {
1254                         use rustc::ty::layout::Layout::*;
1255                         let variant = match *base_layout {
1256                             Univariant { ref variant, .. } => variant,
1257                             General { ref variants, .. } => {
1258                                 if let LvalueExtra::DowncastVariant(variant_idx) = base.extra {
1259                                     &variants[variant_idx]
1260                                 } else {
1261                                     panic!("field access on enum had no variant index");
1262                                 }
1263                             }
1264                             RawNullablePointer { .. } => {
1265                                 assert_eq!(field.index(), 0);
1266                                 return Ok(base);
1267                             }
1268                             StructWrappedNullablePointer { ref nonnull, .. } => nonnull,
1269                             _ => panic!("field access on non-product type: {:?}", base_layout),
1270                         };
1271
1272                         let offset = variant.field_offset(field.index()).bytes();
1273                         base.ptr.offset(offset as isize)
1274                     },
1275
1276                     Downcast(_, variant) => {
1277                         use rustc::ty::layout::Layout::*;
1278                         match *base_layout {
1279                             General { discr, .. } => {
1280                                 return Ok(Lvalue {
1281                                     ptr: base.ptr.offset(discr.size().bytes() as isize),
1282                                     extra: LvalueExtra::DowncastVariant(variant),
1283                                 });
1284                             }
1285                             RawNullablePointer { .. } | StructWrappedNullablePointer { .. } => {
1286                                 return Ok(base);
1287                             }
1288                             _ => panic!("variant downcast on non-aggregate: {:?}", base_layout),
1289                         }
1290                     },
1291
1292                     Deref => {
1293                         let pointee_ty = pointee_type(base_ty).expect("Deref of non-pointer");
1294                         let ptr = self.memory.read_ptr(base.ptr)?;
1295                         let extra = match pointee_ty.sty {
1296                             ty::TySlice(_) | ty::TyStr => {
1297                                 let len_ptr = base.ptr.offset(self.memory.pointer_size as isize);
1298                                 let len = self.memory.read_usize(len_ptr)?;
1299                                 LvalueExtra::Length(len)
1300                             }
1301                             ty::TyTrait(_) => unimplemented!(),
1302                             _ => LvalueExtra::None,
1303                         };
1304                         return Ok(Lvalue { ptr: ptr, extra: extra });
1305                     }
1306
1307                     Index(ref operand) => {
1308                         let elem_size = match base_ty.sty {
1309                             ty::TyArray(elem_ty, _) |
1310                             ty::TySlice(elem_ty) => self.type_size(elem_ty),
1311                             _ => panic!("indexing expected an array or slice, got {:?}", base_ty),
1312                         };
1313                         let n_ptr = self.eval_operand(operand)?;
1314                         let n = self.memory.read_usize(n_ptr)?;
1315                         base.ptr.offset(n as isize * elem_size as isize)
1316                     }
1317
1318                     ConstantIndex { .. } => unimplemented!(),
1319                 }
1320             }
1321         };
1322
1323         Ok(Lvalue { ptr: ptr, extra: LvalueExtra::None })
1324     }
1325
1326     fn lvalue_ty(&self, lvalue: &mir::Lvalue<'tcx>) -> Ty<'tcx> {
1327         self.monomorphize(self.mir().lvalue_ty(self.tcx, lvalue).to_ty(self.tcx))
1328     }
1329
1330     fn operand_ty(&self, operand: &mir::Operand<'tcx>) -> Ty<'tcx> {
1331         self.monomorphize(self.mir().operand_ty(self.tcx, operand))
1332     }
1333
1334     fn monomorphize(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1335         self.gecx.monomorphize(ty, self.substs())
1336     }
1337
1338     fn move_(&mut self, src: Pointer, dest: Pointer, ty: Ty<'tcx>) -> EvalResult<()> {
1339         let size = self.type_size(ty);
1340         self.memory.copy(src, dest, size)?;
1341         if self.type_needs_drop(ty) {
1342             self.memory.drop_fill(src, size)?;
1343         }
1344         Ok(())
1345     }
1346
1347     fn type_size(&self, ty: Ty<'tcx>) -> usize {
1348         self.gecx.type_size(ty, self.substs())
1349     }
1350
1351     fn type_layout(&self, ty: Ty<'tcx>) -> &'tcx Layout {
1352         self.gecx.type_layout(ty, self.substs())
1353     }
1354
1355     pub fn read_primval(&mut self, ptr: Pointer, ty: Ty<'tcx>) -> EvalResult<PrimVal> {
1356         use syntax::ast::{IntTy, UintTy};
1357         let val = match (self.memory.pointer_size, &ty.sty) {
1358             (_, &ty::TyBool)              => PrimVal::Bool(self.memory.read_bool(ptr)?),
1359             (_, &ty::TyInt(IntTy::I8))    => PrimVal::I8(self.memory.read_int(ptr, 1)? as i8),
1360             (2, &ty::TyInt(IntTy::Is)) |
1361             (_, &ty::TyInt(IntTy::I16))   => PrimVal::I16(self.memory.read_int(ptr, 2)? as i16),
1362             (4, &ty::TyInt(IntTy::Is)) |
1363             (_, &ty::TyInt(IntTy::I32))   => PrimVal::I32(self.memory.read_int(ptr, 4)? as i32),
1364             (8, &ty::TyInt(IntTy::Is)) |
1365             (_, &ty::TyInt(IntTy::I64))   => PrimVal::I64(self.memory.read_int(ptr, 8)? as i64),
1366             (_, &ty::TyUint(UintTy::U8))  => PrimVal::U8(self.memory.read_uint(ptr, 1)? as u8),
1367             (2, &ty::TyUint(UintTy::Us)) |
1368             (_, &ty::TyUint(UintTy::U16)) => PrimVal::U16(self.memory.read_uint(ptr, 2)? as u16),
1369             (4, &ty::TyUint(UintTy::Us)) |
1370             (_, &ty::TyUint(UintTy::U32)) => PrimVal::U32(self.memory.read_uint(ptr, 4)? as u32),
1371             (8, &ty::TyUint(UintTy::Us)) |
1372             (_, &ty::TyUint(UintTy::U64)) => PrimVal::U64(self.memory.read_uint(ptr, 8)? as u64),
1373
1374             (_, &ty::TyRef(_, ty::TypeAndMut { ty, .. })) |
1375             (_, &ty::TyRawPtr(ty::TypeAndMut { ty, .. })) => {
1376                 if self.type_is_sized(ty) {
1377                     match self.memory.read_ptr(ptr) {
1378                         Ok(p) => PrimVal::AbstractPtr(p),
1379                         Err(EvalError::ReadBytesAsPointer) => {
1380                             PrimVal::IntegerPtr(self.memory.read_usize(ptr)?)
1381                         }
1382                         Err(e) => return Err(e),
1383                     }
1384                 } else {
1385                     return Err(EvalError::Unimplemented(format!("unimplemented: primitive read of fat pointer type: {:?}", ty)));
1386                 }
1387             }
1388
1389             _ => panic!("primitive read of non-primitive type: {:?}", ty),
1390         };
1391         Ok(val)
1392     }
1393
1394     fn frame(&self) -> &Frame<'mir, 'tcx> {
1395         self.stack.last().expect("no call frames exist")
1396     }
1397
1398     fn basic_block(&self) -> &mir::BasicBlockData<'tcx> {
1399         let frame = self.frame();
1400         frame.mir.basic_block_data(frame.next_block)
1401     }
1402
1403     fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx> {
1404         self.stack.last_mut().expect("no call frames exist")
1405     }
1406
1407     fn mir(&self) -> CachedMir<'mir, 'tcx> {
1408         self.frame().mir.clone()
1409     }
1410
1411     fn substs(&self) -> &'tcx Substs<'tcx> {
1412         self.frame().substs
1413     }
1414 }
1415
1416 fn pointee_type(ptr_ty: ty::Ty) -> Option<ty::Ty> {
1417     match ptr_ty.sty {
1418         ty::TyRef(_, ty::TypeAndMut { ty, .. }) |
1419         ty::TyRawPtr(ty::TypeAndMut { ty, .. }) |
1420         ty::TyBox(ty) => {
1421             Some(ty)
1422         }
1423         _ => None,
1424     }
1425 }
1426
1427 impl Lvalue {
1428     fn to_ptr(self) -> Pointer {
1429         assert_eq!(self.extra, LvalueExtra::None);
1430         self.ptr
1431     }
1432 }
1433
1434 impl<'mir, 'tcx: 'mir> Deref for CachedMir<'mir, 'tcx> {
1435     type Target = mir::Mir<'tcx>;
1436     fn deref(&self) -> &mir::Mir<'tcx> {
1437         match *self {
1438             CachedMir::Ref(r) => r,
1439             CachedMir::Owned(ref rc) => rc,
1440         }
1441     }
1442 }
1443
1444 #[derive(Debug)]
1445 pub struct ImplMethod<'tcx> {
1446     pub method: Rc<ty::Method<'tcx>>,
1447     pub substs: &'tcx Substs<'tcx>,
1448     pub is_provided: bool,
1449 }
1450
1451 /// Locates the applicable definition of a method, given its name.
1452 pub fn get_impl_method<'a, 'tcx>(
1453     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1454     impl_def_id: DefId,
1455     substs: &'tcx Substs<'tcx>,
1456     name: ast::Name,
1457 ) -> ImplMethod<'tcx> {
1458     assert!(!substs.types.needs_infer());
1459
1460     let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
1461     let trait_def = tcx.lookup_trait_def(trait_def_id);
1462
1463     match trait_def.ancestors(impl_def_id).fn_defs(tcx, name).next() {
1464         Some(node_item) => {
1465             let substs = tcx.normalizing_infer_ctxt(ProjectionMode::Any).enter(|infcx| {
1466                 let substs = traits::translate_substs(&infcx, impl_def_id,
1467                                                       substs, node_item.node);
1468                 tcx.lift(&substs).unwrap_or_else(|| {
1469                     bug!("trans::meth::get_impl_method: translate_substs \
1470                           returned {:?} which contains inference types/regions",
1471                          substs);
1472                 })
1473             });
1474             ImplMethod {
1475                 method: node_item.item,
1476                 substs: substs,
1477                 is_provided: node_item.node.is_from_trait(),
1478             }
1479         }
1480         None => {
1481             bug!("method {:?} not found in {:?}", name, impl_def_id)
1482         }
1483     }
1484 }
1485
1486 pub fn interpret_start_points<'a, 'tcx>(
1487     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1488     mir_map: &MirMap<'tcx>,
1489 ) {
1490     let initial_indentation = ::log_settings::settings().indentation;
1491     for (&id, mir) in &mir_map.map {
1492         for attr in tcx.map.attrs(id) {
1493             use syntax::attr::AttrMetaMethods;
1494             if attr.check_name("miri_run") {
1495                 let item = tcx.map.expect_item(id);
1496
1497                 ::log_settings::settings().indentation = initial_indentation;
1498
1499                 debug!("Interpreting: {}", item.name);
1500
1501                 let mut gecx = GlobalEvalContext::new(tcx, mir_map);
1502                 match gecx.call(mir, tcx.map.local_def_id(id)) {
1503                     Ok(Some(return_ptr)) => if log_enabled!(::log::LogLevel::Debug) {
1504                         gecx.memory.dump(return_ptr.alloc_id);
1505                     },
1506                     Ok(None) => warn!("diverging function returned"),
1507                     Err(_e) => {
1508                         // TODO(solson): Detect whether the error was already reported or not.
1509                         // tcx.sess.err(&e.to_string());
1510                     }
1511                 }
1512             }
1513         }
1514     }
1515 }
1516
1517 // TODO(solson): Upstream these methods into rustc::ty::layout.
1518
1519 trait IntegerExt {
1520     fn size(self) -> Size;
1521 }
1522
1523 impl IntegerExt for layout::Integer {
1524     fn size(self) -> Size {
1525         use rustc::ty::layout::Integer::*;
1526         match self {
1527             I1 | I8 => Size::from_bits(8),
1528             I16 => Size::from_bits(16),
1529             I32 => Size::from_bits(32),
1530             I64 => Size::from_bits(64),
1531         }
1532     }
1533 }
1534
1535 trait StructExt {
1536     fn field_offset(&self, index: usize) -> Size;
1537 }
1538
1539 impl StructExt for layout::Struct {
1540     fn field_offset(&self, index: usize) -> Size {
1541         if index == 0 {
1542             Size::from_bytes(0)
1543         } else {
1544             self.offset_after_field[index - 1]
1545         }
1546     }
1547 }