Reduce the number of #includes.
[oota-llvm.git] / lib / ExecutionEngine / Interpreter / Execution.cpp
1 //===-- Execution.cpp - Implement code to simulate the program ------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 // 
10 //  This file contains the actual instruction interpreter.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Interpreter.h"
15 #include "llvm/Function.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Constants.h"
19 #include "Support/Statistic.h"
20 #include <cmath>  // For fmod
21
22 Interpreter *TheEE = 0;
23
24 namespace {
25   Statistic<> NumDynamicInsts("lli", "Number of dynamic instructions executed");
26 }
27
28 //===----------------------------------------------------------------------===//
29 //                     Value Manipulation code
30 //===----------------------------------------------------------------------===//
31
32 // Operations used by constant expr implementations...
33 static GenericValue executeCastOperation(Value *Src, const Type *DestTy,
34                                          ExecutionContext &SF);
35 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2, 
36                                    const Type *Ty);
37
38 GenericValue Interpreter::getOperandValue(Value *V, ExecutionContext &SF) {
39   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
40     switch (CE->getOpcode()) {
41     case Instruction::Cast:
42       return executeCastOperation(CE->getOperand(0), CE->getType(), SF);
43     case Instruction::GetElementPtr:
44       return TheEE->executeGEPOperation(CE->getOperand(0), CE->op_begin()+1,
45                                         CE->op_end(), SF);
46     case Instruction::Add:
47       return executeAddInst(getOperandValue(CE->getOperand(0), SF),
48                             getOperandValue(CE->getOperand(1), SF),
49                             CE->getType());
50     default:
51       std::cerr << "Unhandled ConstantExpr: " << CE << "\n";
52       abort();
53       return GenericValue();
54     }
55   } else if (Constant *CPV = dyn_cast<Constant>(V)) {
56     return TheEE->getConstantValue(CPV);
57   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
58     return PTOGV(TheEE->getPointerToGlobal(GV));
59   } else {
60     return SF.Values[V];
61   }
62 }
63
64 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
65   SF.Values[V] = Val;
66 }
67
68 //===----------------------------------------------------------------------===//
69 //                    Annotation Wrangling code
70 //===----------------------------------------------------------------------===//
71
72 void Interpreter::initializeExecutionEngine() {
73   TheEE = this;
74 }
75
76 //===----------------------------------------------------------------------===//
77 //                    Binary Instruction Implementations
78 //===----------------------------------------------------------------------===//
79
80 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
81    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
82
83 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2, 
84                                    const Type *Ty) {
85   GenericValue Dest;
86   switch (Ty->getPrimitiveID()) {
87     IMPLEMENT_BINARY_OPERATOR(+, UByte);
88     IMPLEMENT_BINARY_OPERATOR(+, SByte);
89     IMPLEMENT_BINARY_OPERATOR(+, UShort);
90     IMPLEMENT_BINARY_OPERATOR(+, Short);
91     IMPLEMENT_BINARY_OPERATOR(+, UInt);
92     IMPLEMENT_BINARY_OPERATOR(+, Int);
93     IMPLEMENT_BINARY_OPERATOR(+, ULong);
94     IMPLEMENT_BINARY_OPERATOR(+, Long);
95     IMPLEMENT_BINARY_OPERATOR(+, Float);
96     IMPLEMENT_BINARY_OPERATOR(+, Double);
97   default:
98     std::cout << "Unhandled type for Add instruction: " << *Ty << "\n";
99     abort();
100   }
101   return Dest;
102 }
103
104 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2, 
105                                    const Type *Ty) {
106   GenericValue Dest;
107   switch (Ty->getPrimitiveID()) {
108     IMPLEMENT_BINARY_OPERATOR(-, UByte);
109     IMPLEMENT_BINARY_OPERATOR(-, SByte);
110     IMPLEMENT_BINARY_OPERATOR(-, UShort);
111     IMPLEMENT_BINARY_OPERATOR(-, Short);
112     IMPLEMENT_BINARY_OPERATOR(-, UInt);
113     IMPLEMENT_BINARY_OPERATOR(-, Int);
114     IMPLEMENT_BINARY_OPERATOR(-, ULong);
115     IMPLEMENT_BINARY_OPERATOR(-, Long);
116     IMPLEMENT_BINARY_OPERATOR(-, Float);
117     IMPLEMENT_BINARY_OPERATOR(-, Double);
118   default:
119     std::cout << "Unhandled type for Sub instruction: " << *Ty << "\n";
120     abort();
121   }
122   return Dest;
123 }
124
125 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2, 
126                                    const Type *Ty) {
127   GenericValue Dest;
128   switch (Ty->getPrimitiveID()) {
129     IMPLEMENT_BINARY_OPERATOR(*, UByte);
130     IMPLEMENT_BINARY_OPERATOR(*, SByte);
131     IMPLEMENT_BINARY_OPERATOR(*, UShort);
132     IMPLEMENT_BINARY_OPERATOR(*, Short);
133     IMPLEMENT_BINARY_OPERATOR(*, UInt);
134     IMPLEMENT_BINARY_OPERATOR(*, Int);
135     IMPLEMENT_BINARY_OPERATOR(*, ULong);
136     IMPLEMENT_BINARY_OPERATOR(*, Long);
137     IMPLEMENT_BINARY_OPERATOR(*, Float);
138     IMPLEMENT_BINARY_OPERATOR(*, Double);
139   default:
140     std::cout << "Unhandled type for Mul instruction: " << Ty << "\n";
141     abort();
142   }
143   return Dest;
144 }
145
146 static GenericValue executeDivInst(GenericValue Src1, GenericValue Src2, 
147                                    const Type *Ty) {
148   GenericValue Dest;
149   switch (Ty->getPrimitiveID()) {
150     IMPLEMENT_BINARY_OPERATOR(/, UByte);
151     IMPLEMENT_BINARY_OPERATOR(/, SByte);
152     IMPLEMENT_BINARY_OPERATOR(/, UShort);
153     IMPLEMENT_BINARY_OPERATOR(/, Short);
154     IMPLEMENT_BINARY_OPERATOR(/, UInt);
155     IMPLEMENT_BINARY_OPERATOR(/, Int);
156     IMPLEMENT_BINARY_OPERATOR(/, ULong);
157     IMPLEMENT_BINARY_OPERATOR(/, Long);
158     IMPLEMENT_BINARY_OPERATOR(/, Float);
159     IMPLEMENT_BINARY_OPERATOR(/, Double);
160   default:
161     std::cout << "Unhandled type for Div instruction: " << *Ty << "\n";
162     abort();
163   }
164   return Dest;
165 }
166
167 static GenericValue executeRemInst(GenericValue Src1, GenericValue Src2, 
168                                    const Type *Ty) {
169   GenericValue Dest;
170   switch (Ty->getPrimitiveID()) {
171     IMPLEMENT_BINARY_OPERATOR(%, UByte);
172     IMPLEMENT_BINARY_OPERATOR(%, SByte);
173     IMPLEMENT_BINARY_OPERATOR(%, UShort);
174     IMPLEMENT_BINARY_OPERATOR(%, Short);
175     IMPLEMENT_BINARY_OPERATOR(%, UInt);
176     IMPLEMENT_BINARY_OPERATOR(%, Int);
177     IMPLEMENT_BINARY_OPERATOR(%, ULong);
178     IMPLEMENT_BINARY_OPERATOR(%, Long);
179   case Type::FloatTyID:
180     Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
181     break;
182   case Type::DoubleTyID:
183     Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
184     break;
185   default:
186     std::cout << "Unhandled type for Rem instruction: " << *Ty << "\n";
187     abort();
188   }
189   return Dest;
190 }
191
192 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2, 
193                                    const Type *Ty) {
194   GenericValue Dest;
195   switch (Ty->getPrimitiveID()) {
196     IMPLEMENT_BINARY_OPERATOR(&, Bool);
197     IMPLEMENT_BINARY_OPERATOR(&, UByte);
198     IMPLEMENT_BINARY_OPERATOR(&, SByte);
199     IMPLEMENT_BINARY_OPERATOR(&, UShort);
200     IMPLEMENT_BINARY_OPERATOR(&, Short);
201     IMPLEMENT_BINARY_OPERATOR(&, UInt);
202     IMPLEMENT_BINARY_OPERATOR(&, Int);
203     IMPLEMENT_BINARY_OPERATOR(&, ULong);
204     IMPLEMENT_BINARY_OPERATOR(&, Long);
205   default:
206     std::cout << "Unhandled type for And instruction: " << *Ty << "\n";
207     abort();
208   }
209   return Dest;
210 }
211
212 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2, 
213                                   const Type *Ty) {
214   GenericValue Dest;
215   switch (Ty->getPrimitiveID()) {
216     IMPLEMENT_BINARY_OPERATOR(|, Bool);
217     IMPLEMENT_BINARY_OPERATOR(|, UByte);
218     IMPLEMENT_BINARY_OPERATOR(|, SByte);
219     IMPLEMENT_BINARY_OPERATOR(|, UShort);
220     IMPLEMENT_BINARY_OPERATOR(|, Short);
221     IMPLEMENT_BINARY_OPERATOR(|, UInt);
222     IMPLEMENT_BINARY_OPERATOR(|, Int);
223     IMPLEMENT_BINARY_OPERATOR(|, ULong);
224     IMPLEMENT_BINARY_OPERATOR(|, Long);
225   default:
226     std::cout << "Unhandled type for Or instruction: " << *Ty << "\n";
227     abort();
228   }
229   return Dest;
230 }
231
232 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2, 
233                                    const Type *Ty) {
234   GenericValue Dest;
235   switch (Ty->getPrimitiveID()) {
236     IMPLEMENT_BINARY_OPERATOR(^, Bool);
237     IMPLEMENT_BINARY_OPERATOR(^, UByte);
238     IMPLEMENT_BINARY_OPERATOR(^, SByte);
239     IMPLEMENT_BINARY_OPERATOR(^, UShort);
240     IMPLEMENT_BINARY_OPERATOR(^, Short);
241     IMPLEMENT_BINARY_OPERATOR(^, UInt);
242     IMPLEMENT_BINARY_OPERATOR(^, Int);
243     IMPLEMENT_BINARY_OPERATOR(^, ULong);
244     IMPLEMENT_BINARY_OPERATOR(^, Long);
245   default:
246     std::cout << "Unhandled type for Xor instruction: " << *Ty << "\n";
247     abort();
248   }
249   return Dest;
250 }
251
252 #define IMPLEMENT_SETCC(OP, TY) \
253    case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
254
255 // Handle pointers specially because they must be compared with only as much
256 // width as the host has.  We _do not_ want to be comparing 64 bit values when
257 // running on a 32-bit target, otherwise the upper 32 bits might mess up
258 // comparisons if they contain garbage.
259 #define IMPLEMENT_POINTERSETCC(OP) \
260    case Type::PointerTyID: \
261         Dest.BoolVal = (void*)(intptr_t)Src1.PointerVal OP \
262                        (void*)(intptr_t)Src2.PointerVal; break
263
264 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2, 
265                                      const Type *Ty) {
266   GenericValue Dest;
267   switch (Ty->getPrimitiveID()) {
268     IMPLEMENT_SETCC(==, UByte);
269     IMPLEMENT_SETCC(==, SByte);
270     IMPLEMENT_SETCC(==, UShort);
271     IMPLEMENT_SETCC(==, Short);
272     IMPLEMENT_SETCC(==, UInt);
273     IMPLEMENT_SETCC(==, Int);
274     IMPLEMENT_SETCC(==, ULong);
275     IMPLEMENT_SETCC(==, Long);
276     IMPLEMENT_SETCC(==, Float);
277     IMPLEMENT_SETCC(==, Double);
278     IMPLEMENT_POINTERSETCC(==);
279   default:
280     std::cout << "Unhandled type for SetEQ instruction: " << *Ty << "\n";
281     abort();
282   }
283   return Dest;
284 }
285
286 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2, 
287                                      const Type *Ty) {
288   GenericValue Dest;
289   switch (Ty->getPrimitiveID()) {
290     IMPLEMENT_SETCC(!=, UByte);
291     IMPLEMENT_SETCC(!=, SByte);
292     IMPLEMENT_SETCC(!=, UShort);
293     IMPLEMENT_SETCC(!=, Short);
294     IMPLEMENT_SETCC(!=, UInt);
295     IMPLEMENT_SETCC(!=, Int);
296     IMPLEMENT_SETCC(!=, ULong);
297     IMPLEMENT_SETCC(!=, Long);
298     IMPLEMENT_SETCC(!=, Float);
299     IMPLEMENT_SETCC(!=, Double);
300     IMPLEMENT_POINTERSETCC(!=);
301
302   default:
303     std::cout << "Unhandled type for SetNE instruction: " << *Ty << "\n";
304     abort();
305   }
306   return Dest;
307 }
308
309 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2, 
310                                      const Type *Ty) {
311   GenericValue Dest;
312   switch (Ty->getPrimitiveID()) {
313     IMPLEMENT_SETCC(<=, UByte);
314     IMPLEMENT_SETCC(<=, SByte);
315     IMPLEMENT_SETCC(<=, UShort);
316     IMPLEMENT_SETCC(<=, Short);
317     IMPLEMENT_SETCC(<=, UInt);
318     IMPLEMENT_SETCC(<=, Int);
319     IMPLEMENT_SETCC(<=, ULong);
320     IMPLEMENT_SETCC(<=, Long);
321     IMPLEMENT_SETCC(<=, Float);
322     IMPLEMENT_SETCC(<=, Double);
323     IMPLEMENT_POINTERSETCC(<=);
324   default:
325     std::cout << "Unhandled type for SetLE instruction: " << Ty << "\n";
326     abort();
327   }
328   return Dest;
329 }
330
331 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2, 
332                                      const Type *Ty) {
333   GenericValue Dest;
334   switch (Ty->getPrimitiveID()) {
335     IMPLEMENT_SETCC(>=, UByte);
336     IMPLEMENT_SETCC(>=, SByte);
337     IMPLEMENT_SETCC(>=, UShort);
338     IMPLEMENT_SETCC(>=, Short);
339     IMPLEMENT_SETCC(>=, UInt);
340     IMPLEMENT_SETCC(>=, Int);
341     IMPLEMENT_SETCC(>=, ULong);
342     IMPLEMENT_SETCC(>=, Long);
343     IMPLEMENT_SETCC(>=, Float);
344     IMPLEMENT_SETCC(>=, Double);
345     IMPLEMENT_POINTERSETCC(>=);
346   default:
347     std::cout << "Unhandled type for SetGE instruction: " << *Ty << "\n";
348     abort();
349   }
350   return Dest;
351 }
352
353 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2, 
354                                      const Type *Ty) {
355   GenericValue Dest;
356   switch (Ty->getPrimitiveID()) {
357     IMPLEMENT_SETCC(<, UByte);
358     IMPLEMENT_SETCC(<, SByte);
359     IMPLEMENT_SETCC(<, UShort);
360     IMPLEMENT_SETCC(<, Short);
361     IMPLEMENT_SETCC(<, UInt);
362     IMPLEMENT_SETCC(<, Int);
363     IMPLEMENT_SETCC(<, ULong);
364     IMPLEMENT_SETCC(<, Long);
365     IMPLEMENT_SETCC(<, Float);
366     IMPLEMENT_SETCC(<, Double);
367     IMPLEMENT_POINTERSETCC(<);
368   default:
369     std::cout << "Unhandled type for SetLT instruction: " << *Ty << "\n";
370     abort();
371   }
372   return Dest;
373 }
374
375 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2, 
376                                      const Type *Ty) {
377   GenericValue Dest;
378   switch (Ty->getPrimitiveID()) {
379     IMPLEMENT_SETCC(>, UByte);
380     IMPLEMENT_SETCC(>, SByte);
381     IMPLEMENT_SETCC(>, UShort);
382     IMPLEMENT_SETCC(>, Short);
383     IMPLEMENT_SETCC(>, UInt);
384     IMPLEMENT_SETCC(>, Int);
385     IMPLEMENT_SETCC(>, ULong);
386     IMPLEMENT_SETCC(>, Long);
387     IMPLEMENT_SETCC(>, Float);
388     IMPLEMENT_SETCC(>, Double);
389     IMPLEMENT_POINTERSETCC(>);
390   default:
391     std::cout << "Unhandled type for SetGT instruction: " << *Ty << "\n";
392     abort();
393   }
394   return Dest;
395 }
396
397 void Interpreter::visitBinaryOperator(BinaryOperator &I) {
398   ExecutionContext &SF = ECStack.back();
399   const Type *Ty    = I.getOperand(0)->getType();
400   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
401   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
402   GenericValue R;   // Result
403
404   switch (I.getOpcode()) {
405   case Instruction::Add:   R = executeAddInst  (Src1, Src2, Ty); break;
406   case Instruction::Sub:   R = executeSubInst  (Src1, Src2, Ty); break;
407   case Instruction::Mul:   R = executeMulInst  (Src1, Src2, Ty); break;
408   case Instruction::Div:   R = executeDivInst  (Src1, Src2, Ty); break;
409   case Instruction::Rem:   R = executeRemInst  (Src1, Src2, Ty); break;
410   case Instruction::And:   R = executeAndInst  (Src1, Src2, Ty); break;
411   case Instruction::Or:    R = executeOrInst   (Src1, Src2, Ty); break;
412   case Instruction::Xor:   R = executeXorInst  (Src1, Src2, Ty); break;
413   case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty); break;
414   case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty); break;
415   case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty); break;
416   case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty); break;
417   case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty); break;
418   case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty); break;
419   default:
420     std::cout << "Don't know how to handle this binary operator!\n-->" << I;
421     abort();
422   }
423
424   SetValue(&I, R, SF);
425 }
426
427 //===----------------------------------------------------------------------===//
428 //                     Terminator Instruction Implementations
429 //===----------------------------------------------------------------------===//
430
431 void Interpreter::exitCalled(GenericValue GV) {
432   ExitCode = GV.SByteVal;
433   ECStack.clear();
434 }
435
436 void Interpreter::visitReturnInst(ReturnInst &I) {
437   ExecutionContext &SF = ECStack.back();
438   const Type *RetTy = 0;
439   GenericValue Result;
440
441   // Save away the return value... (if we are not 'ret void')
442   if (I.getNumOperands()) {
443     RetTy  = I.getReturnValue()->getType();
444     Result = getOperandValue(I.getReturnValue(), SF);
445   }
446
447   // Pop the current stack frame... this invalidates SF
448   ECStack.pop_back();
449
450   if (ECStack.empty()) {  // Finished main.  Put result into exit code...
451     if (RetTy && RetTy->isIntegral()) {          // Nonvoid return type?
452       ExitCode = Result.IntVal;   // Capture the exit code of the program
453     } else {
454       ExitCode = 0;
455     }
456   } else {
457     // If we have a previous stack frame, and we have a previous call,
458     // fill in the return value...
459     ExecutionContext &NewSF = ECStack.back();
460     if (NewSF.Caller) {
461       if (NewSF.Caller->getType() != Type::VoidTy)      // Save result...
462         SetValue(NewSF.Caller, Result, NewSF);
463       NewSF.Caller = 0;          // We returned from the call...
464     }
465   }
466 }
467
468 void Interpreter::visitBranchInst(BranchInst &I) {
469   ExecutionContext &SF = ECStack.back();
470   BasicBlock *Dest;
471
472   Dest = I.getSuccessor(0);          // Uncond branches have a fixed dest...
473   if (!I.isUnconditional()) {
474     Value *Cond = I.getCondition();
475     if (getOperandValue(Cond, SF).BoolVal == 0) // If false cond...
476       Dest = I.getSuccessor(1);    
477   }
478   SwitchToNewBasicBlock(Dest, SF);
479 }
480
481 void Interpreter::visitSwitchInst(SwitchInst &I) {
482   ExecutionContext &SF = ECStack.back();
483   GenericValue CondVal = getOperandValue(I.getOperand(0), SF);
484   const Type *ElTy = I.getOperand(0)->getType();
485
486   // Check to see if any of the cases match...
487   BasicBlock *Dest = 0;
488   for (unsigned i = 2, e = I.getNumOperands(); i != e; i += 2)
489     if (executeSetEQInst(CondVal,
490                          getOperandValue(I.getOperand(i), SF), ElTy).BoolVal) {
491       Dest = cast<BasicBlock>(I.getOperand(i+1));
492       break;
493     }
494   
495   if (!Dest) Dest = I.getDefaultDest();   // No cases matched: use default
496   SwitchToNewBasicBlock(Dest, SF);
497 }
498
499 // SwitchToNewBasicBlock - This method is used to jump to a new basic block.
500 // This function handles the actual updating of block and instruction iterators
501 // as well as execution of all of the PHI nodes in the destination block.
502 //
503 // This method does this because all of the PHI nodes must be executed
504 // atomically, reading their inputs before any of the results are updated.  Not
505 // doing this can cause problems if the PHI nodes depend on other PHI nodes for
506 // their inputs.  If the input PHI node is updated before it is read, incorrect
507 // results can happen.  Thus we use a two phase approach.
508 //
509 void Interpreter::SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF){
510   BasicBlock *PrevBB = SF.CurBB;      // Remember where we came from...
511   SF.CurBB   = Dest;                  // Update CurBB to branch destination
512   SF.CurInst = SF.CurBB->begin();     // Update new instruction ptr...
513
514   if (!isa<PHINode>(SF.CurInst)) return;  // Nothing fancy to do
515
516   // Loop over all of the PHI nodes in the current block, reading their inputs.
517   std::vector<GenericValue> ResultValues;
518
519   for (; PHINode *PN = dyn_cast<PHINode>(SF.CurInst); ++SF.CurInst) {
520     // Search for the value corresponding to this previous bb...
521     int i = PN->getBasicBlockIndex(PrevBB);
522     assert(i != -1 && "PHINode doesn't contain entry for predecessor??");
523     Value *IncomingValue = PN->getIncomingValue(i);
524     
525     // Save the incoming value for this PHI node...
526     ResultValues.push_back(getOperandValue(IncomingValue, SF));
527   }
528
529   // Now loop over all of the PHI nodes setting their values...
530   SF.CurInst = SF.CurBB->begin();
531   for (unsigned i = 0; PHINode *PN = dyn_cast<PHINode>(SF.CurInst);
532        ++SF.CurInst, ++i)
533     SetValue(PN, ResultValues[i], SF);
534 }
535
536 //===----------------------------------------------------------------------===//
537 //                     Memory Instruction Implementations
538 //===----------------------------------------------------------------------===//
539
540 void Interpreter::visitAllocationInst(AllocationInst &I) {
541   ExecutionContext &SF = ECStack.back();
542
543   const Type *Ty = I.getType()->getElementType();  // Type to be allocated
544
545   // Get the number of elements being allocated by the array...
546   unsigned NumElements = getOperandValue(I.getOperand(0), SF).UIntVal;
547
548   // Allocate enough memory to hold the type...
549   // FIXME: Don't use CALLOC, use a tainted malloc.
550   void *Memory = calloc(NumElements, TD.getTypeSize(Ty));
551
552   GenericValue Result = PTOGV(Memory);
553   assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
554   SetValue(&I, Result, SF);
555
556   if (I.getOpcode() == Instruction::Alloca)
557     ECStack.back().Allocas.add(Memory);
558 }
559
560 void Interpreter::visitFreeInst(FreeInst &I) {
561   ExecutionContext &SF = ECStack.back();
562   assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
563   GenericValue Value = getOperandValue(I.getOperand(0), SF);
564   // TODO: Check to make sure memory is allocated
565   free(GVTOP(Value));   // Free memory
566 }
567
568 // getElementOffset - The workhorse for getelementptr.
569 //
570 GenericValue Interpreter::executeGEPOperation(Value *Ptr, User::op_iterator I,
571                                               User::op_iterator E,
572                                               ExecutionContext &SF) {
573   assert(isa<PointerType>(Ptr->getType()) &&
574          "Cannot getElementOffset of a nonpointer type!");
575
576   PointerTy Total = 0;
577   const Type *Ty = Ptr->getType();
578
579   for (; I != E; ++I) {
580     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
581       const StructLayout *SLO = TD.getStructLayout(STy);
582       
583       // Indices must be ubyte constants...
584       const ConstantUInt *CPU = cast<ConstantUInt>(*I);
585       assert(CPU->getType() == Type::UByteTy);
586       unsigned Index = CPU->getValue();
587       
588       Total += SLO->MemberOffsets[Index];
589       Ty = STy->getElementTypes()[Index];
590     } else if (const SequentialType *ST = cast<SequentialType>(Ty)) {
591       // Get the index number for the array... which must be long type...
592       assert((*I)->getType() == Type::LongTy);
593       unsigned Idx = getOperandValue(*I, SF).LongVal;
594       Ty = ST->getElementType();
595       unsigned Size = TD.getTypeSize(Ty);
596       Total += Size*Idx;
597     }
598   }
599
600   GenericValue Result;
601   Result.PointerVal = getOperandValue(Ptr, SF).PointerVal + Total;
602   return Result;
603 }
604
605 void Interpreter::visitGetElementPtrInst(GetElementPtrInst &I) {
606   ExecutionContext &SF = ECStack.back();
607   SetValue(&I, TheEE->executeGEPOperation(I.getPointerOperand(),
608                                    I.idx_begin(), I.idx_end(), SF), SF);
609 }
610
611 void Interpreter::visitLoadInst(LoadInst &I) {
612   ExecutionContext &SF = ECStack.back();
613   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
614   GenericValue *Ptr = (GenericValue*)GVTOP(SRC);
615   GenericValue Result = LoadValueFromMemory(Ptr, I.getType());
616   SetValue(&I, Result, SF);
617 }
618
619 void Interpreter::visitStoreInst(StoreInst &I) {
620   ExecutionContext &SF = ECStack.back();
621   GenericValue Val = getOperandValue(I.getOperand(0), SF);
622   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
623   StoreValueToMemory(Val, (GenericValue *)GVTOP(SRC),
624                      I.getOperand(0)->getType());
625 }
626
627 //===----------------------------------------------------------------------===//
628 //                 Miscellaneous Instruction Implementations
629 //===----------------------------------------------------------------------===//
630
631 void Interpreter::visitCallInst(CallInst &I) {
632   ExecutionContext &SF = ECStack.back();
633   SF.Caller = &I;
634   std::vector<GenericValue> ArgVals;
635   ArgVals.reserve(I.getNumOperands()-1);
636   for (unsigned i = 1; i < I.getNumOperands(); ++i) {
637     ArgVals.push_back(getOperandValue(I.getOperand(i), SF));
638     // Promote all integral types whose size is < sizeof(int) into ints.  We do
639     // this by zero or sign extending the value as appropriate according to the
640     // source type.
641     if (I.getOperand(i)->getType()->isIntegral() &&
642         I.getOperand(i)->getType()->getPrimitiveSize() < 4) {
643       const Type *Ty = I.getOperand(i)->getType();
644       if (Ty == Type::ShortTy)
645         ArgVals.back().IntVal = ArgVals.back().ShortVal;
646       else if (Ty == Type::UShortTy)
647         ArgVals.back().UIntVal = ArgVals.back().UShortVal;
648       else if (Ty == Type::SByteTy)
649         ArgVals.back().IntVal = ArgVals.back().SByteVal;
650       else if (Ty == Type::UByteTy)
651         ArgVals.back().UIntVal = ArgVals.back().UByteVal;
652       else if (Ty == Type::BoolTy)
653         ArgVals.back().UIntVal = ArgVals.back().BoolVal;
654       else
655         assert(0 && "Unknown type!");
656     }
657   }
658
659   // To handle indirect calls, we must get the pointer value from the argument 
660   // and treat it as a function pointer.
661   GenericValue SRC = getOperandValue(I.getCalledValue(), SF);  
662   callFunction((Function*)GVTOP(SRC), ArgVals);
663 }
664
665 #define IMPLEMENT_SHIFT(OP, TY) \
666    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
667
668 void Interpreter::visitShl(ShiftInst &I) {
669   ExecutionContext &SF = ECStack.back();
670   const Type *Ty    = I.getOperand(0)->getType();
671   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
672   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
673   GenericValue Dest;
674
675   switch (Ty->getPrimitiveID()) {
676     IMPLEMENT_SHIFT(<<, UByte);
677     IMPLEMENT_SHIFT(<<, SByte);
678     IMPLEMENT_SHIFT(<<, UShort);
679     IMPLEMENT_SHIFT(<<, Short);
680     IMPLEMENT_SHIFT(<<, UInt);
681     IMPLEMENT_SHIFT(<<, Int);
682     IMPLEMENT_SHIFT(<<, ULong);
683     IMPLEMENT_SHIFT(<<, Long);
684   default:
685     std::cout << "Unhandled type for Shl instruction: " << *Ty << "\n";
686   }
687   SetValue(&I, Dest, SF);
688 }
689
690 void Interpreter::visitShr(ShiftInst &I) {
691   ExecutionContext &SF = ECStack.back();
692   const Type *Ty    = I.getOperand(0)->getType();
693   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
694   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
695   GenericValue Dest;
696
697   switch (Ty->getPrimitiveID()) {
698     IMPLEMENT_SHIFT(>>, UByte);
699     IMPLEMENT_SHIFT(>>, SByte);
700     IMPLEMENT_SHIFT(>>, UShort);
701     IMPLEMENT_SHIFT(>>, Short);
702     IMPLEMENT_SHIFT(>>, UInt);
703     IMPLEMENT_SHIFT(>>, Int);
704     IMPLEMENT_SHIFT(>>, ULong);
705     IMPLEMENT_SHIFT(>>, Long);
706   default:
707     std::cout << "Unhandled type for Shr instruction: " << *Ty << "\n";
708     abort();
709   }
710   SetValue(&I, Dest, SF);
711 }
712
713 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
714    case Type::STY##TyID: Dest.DTY##Val = DCTY Src.STY##Val; break;
715
716 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY)    \
717   case Type::DESTTY##TyID:                      \
718     switch (SrcTy->getPrimitiveID()) {          \
719       IMPLEMENT_CAST(DESTTY, DESTCTY, Bool);    \
720       IMPLEMENT_CAST(DESTTY, DESTCTY, UByte);   \
721       IMPLEMENT_CAST(DESTTY, DESTCTY, SByte);   \
722       IMPLEMENT_CAST(DESTTY, DESTCTY, UShort);  \
723       IMPLEMENT_CAST(DESTTY, DESTCTY, Short);   \
724       IMPLEMENT_CAST(DESTTY, DESTCTY, UInt);    \
725       IMPLEMENT_CAST(DESTTY, DESTCTY, Int);     \
726       IMPLEMENT_CAST(DESTTY, DESTCTY, ULong);   \
727       IMPLEMENT_CAST(DESTTY, DESTCTY, Long);    \
728       IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
729
730 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
731       IMPLEMENT_CAST(DESTTY, DESTCTY, Float);   \
732       IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
733
734 #define IMPLEMENT_CAST_CASE_END()    \
735     default: std::cout << "Unhandled cast: " << SrcTy << " to " << Ty << "\n"; \
736       abort();                                  \
737     }                                           \
738     break
739
740 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
741    IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY);   \
742    IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
743    IMPLEMENT_CAST_CASE_END()
744
745 GenericValue Interpreter::executeCastOperation(Value *SrcVal, const Type *Ty,
746                                                ExecutionContext &SF) {
747   const Type *SrcTy = SrcVal->getType();
748   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
749
750   switch (Ty->getPrimitiveID()) {
751     IMPLEMENT_CAST_CASE(UByte  , (unsigned char));
752     IMPLEMENT_CAST_CASE(SByte  , (  signed char));
753     IMPLEMENT_CAST_CASE(UShort , (unsigned short));
754     IMPLEMENT_CAST_CASE(Short  , (  signed short));
755     IMPLEMENT_CAST_CASE(UInt   , (unsigned int ));
756     IMPLEMENT_CAST_CASE(Int    , (  signed int ));
757     IMPLEMENT_CAST_CASE(ULong  , (uint64_t));
758     IMPLEMENT_CAST_CASE(Long   , ( int64_t));
759     IMPLEMENT_CAST_CASE(Pointer, (PointerTy));
760     IMPLEMENT_CAST_CASE(Float  , (float));
761     IMPLEMENT_CAST_CASE(Double , (double));
762     IMPLEMENT_CAST_CASE(Bool   , (bool));
763   default:
764     std::cout << "Unhandled dest type for cast instruction: " << *Ty << "\n";
765     abort();
766   }
767
768   return Dest;
769 }
770
771 void Interpreter::visitCastInst(CastInst &I) {
772   ExecutionContext &SF = ECStack.back();
773   SetValue(&I, executeCastOperation(I.getOperand(0), I.getType(), SF), SF);
774 }
775
776 void Interpreter::visitVANextInst(VANextInst &I) {
777   ExecutionContext &SF = ECStack.back();
778
779   // Get the incoming valist element.  LLI treats the valist as an integer.
780   GenericValue VAList = getOperandValue(I.getOperand(0), SF);
781   
782   // Move to the next operand.
783   unsigned Argument = VAList.IntVal++;
784   assert(Argument < SF.VarArgs.size() &&
785          "Accessing past the last vararg argument!");
786   SetValue(&I, VAList, SF);
787 }
788
789 //===----------------------------------------------------------------------===//
790 //                        Dispatch and Execution Code
791 //===----------------------------------------------------------------------===//
792
793 //===----------------------------------------------------------------------===//
794 // callFunction - Execute the specified function...
795 //
796 void Interpreter::callFunction(Function *F,
797                                const std::vector<GenericValue> &ArgVals) {
798   assert((ECStack.empty() || ECStack.back().Caller == 0 || 
799           ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
800          "Incorrect number of arguments passed into function call!");
801   if (F->isExternal()) {
802     GenericValue Result = callExternalFunction(F, ArgVals);
803     const Type *RetTy = F->getReturnType();
804
805     // Copy the result back into the result variable if we are not returning
806     // void.
807     if (RetTy != Type::VoidTy) {
808       if (!ECStack.empty() && ECStack.back().Caller) {
809         ExecutionContext &SF = ECStack.back();
810         SetValue(SF.Caller, Result, SF);
811         SF.Caller = 0;          // We returned from the call...
812       }
813     }
814
815     return;
816   }
817
818   // Process the function, assigning instruction numbers to the instructions in
819   // the function.  Also calculate the number of values for each type slot
820   // active.
821   //
822
823   // Make a new stack frame... and fill it in.
824   ECStack.push_back(ExecutionContext());
825   ExecutionContext &StackFrame = ECStack.back();
826   StackFrame.CurFunction = F;
827   StackFrame.CurBB     = F->begin();
828   StackFrame.CurInst   = StackFrame.CurBB->begin();
829
830   // Run through the function arguments and initialize their values...
831   assert((ArgVals.size() == F->asize() ||
832          (ArgVals.size() > F->asize() && F->getFunctionType()->isVarArg())) &&
833          "Invalid number of values passed to function invocation!");
834
835   // Handle non-varargs arguments...
836   unsigned i = 0;
837   for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI, ++i)
838     SetValue(AI, ArgVals[i], StackFrame);
839
840   // Handle varargs arguments...
841   StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
842 }
843
844 void Interpreter::run() {
845   while (!ECStack.empty()) {
846     // Interpret a single instruction & increment the "PC".
847     ExecutionContext &SF = ECStack.back();  // Current stack frame
848     Instruction &I = *SF.CurInst++;         // Increment before execute
849     
850     // Track the number of dynamic instructions executed.
851     ++NumDynamicInsts;
852
853     visit(I);   // Dispatch to one of the visit* methods...
854   }
855 }