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