Implement a -trace command line option and a trace option in the interpreter.
[oota-llvm.git] / lib / ExecutionEngine / Interpreter / Execution.cpp
1 //===-- Execution.cpp - Implement code to simulate the program ------------===//
2 // 
3 //  This file contains the actual instruction interpreter.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "Interpreter.h"
8 #include "ExecutionAnnotations.h"
9 #include "llvm/iOther.h"
10 #include "llvm/iTerminators.h"
11 #include "llvm/iMemory.h"
12 #include "llvm/Type.h"
13 #include "llvm/ConstPoolVals.h"
14 #include "llvm/Assembly/Writer.h"
15 #include "llvm/Support/DataTypes.h"
16 #include "llvm/Target/TargetData.h"
17 #include "llvm/GlobalVariable.h"
18
19 // Create a TargetData structure to handle memory addressing and size/alignment
20 // computations
21 //
22 static TargetData TD("lli Interpreter");
23
24 //===----------------------------------------------------------------------===//
25 //                     Value Manipulation code
26 //===----------------------------------------------------------------------===//
27
28 static unsigned getOperandSlot(Value *V) {
29   SlotNumber *SN = (SlotNumber*)V->getAnnotation(SlotNumberAID);
30   assert(SN && "Operand does not have a slot number annotation!");
31   return SN->SlotNum;
32 }
33
34 #define GET_CONST_VAL(TY, CLASS) \
35   case Type::TY##TyID: Result.TY##Val = cast<CLASS>(CPV)->getValue(); break
36
37 static GenericValue getOperandValue(Value *V, ExecutionContext &SF) {
38   if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(V)) {
39     GenericValue Result;
40     switch (CPV->getType()->getPrimitiveID()) {
41       GET_CONST_VAL(Bool   , ConstPoolBool);
42       GET_CONST_VAL(UByte  , ConstPoolUInt);
43       GET_CONST_VAL(SByte  , ConstPoolSInt);
44       GET_CONST_VAL(UShort , ConstPoolUInt);
45       GET_CONST_VAL(Short  , ConstPoolSInt);
46       GET_CONST_VAL(UInt   , ConstPoolUInt);
47       GET_CONST_VAL(Int    , ConstPoolSInt);
48       GET_CONST_VAL(ULong  , ConstPoolUInt);
49       GET_CONST_VAL(Long   , ConstPoolSInt);
50       GET_CONST_VAL(Float  , ConstPoolFP);
51       GET_CONST_VAL(Double , ConstPoolFP);
52     case Type::PointerTyID:
53       if (isa<ConstPoolPointerNull>(CPV)) {
54         Result.ULongVal = 0;
55       } else if (ConstPoolPointerRef *CPR =dyn_cast<ConstPoolPointerRef>(CPV)) {
56         assert(0 && "Not implemented!");
57       } else {
58         assert(0 && "Unknown constant pointer type!");
59       }
60       break;
61     default:
62       cout << "ERROR: Constant unimp for type: " << CPV->getType() << endl;
63     }
64     return Result;
65   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
66     GlobalAddress *Address = 
67       (GlobalAddress*)GV->getOrCreateAnnotation(GlobalAddressAID);
68     GenericValue Result;
69     Result.ULongVal = (uint64_t)(GenericValue*)Address->Ptr;
70     return Result;
71   } else {
72     unsigned TyP = V->getType()->getUniqueID();   // TypePlane for value
73     return SF.Values[TyP][getOperandSlot(V)];
74   }
75 }
76
77 static void printOperandInfo(Value *V, ExecutionContext &SF) {
78   if (isa<ConstPoolVal>(V)) {
79     cout << "Constant Pool Value\n";
80   } else if (isa<GlobalValue>(V)) {
81     cout << "Global Value\n";
82   } else {
83     unsigned TyP  = V->getType()->getUniqueID();   // TypePlane for value
84     unsigned Slot = getOperandSlot(V);
85     cout << "Value=" << (void*)V << " TypeID=" << TyP << " Slot=" << Slot
86          << " Addr=" << &SF.Values[TyP][Slot] << " SF=" << &SF << endl;
87   }
88 }
89
90
91
92 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
93   unsigned TyP = V->getType()->getUniqueID();   // TypePlane for value
94
95   //cout << "Setting value: " << &SF.Values[TyP][getOperandSlot(V)] << endl;
96   SF.Values[TyP][getOperandSlot(V)] = Val;
97 }
98
99
100 //===----------------------------------------------------------------------===//
101 //                    Annotation Wrangling code
102 //===----------------------------------------------------------------------===//
103
104 void Interpreter::initializeExecutionEngine() {
105   AnnotationManager::registerAnnotationFactory(MethodInfoAID,
106                                                &MethodInfo::Create);
107   AnnotationManager::registerAnnotationFactory(GlobalAddressAID, 
108                                                &GlobalAddress::Create);
109 }
110
111 // InitializeMemory - Recursive function to apply a ConstPool value into the
112 // specified memory location...
113 //
114 static void InitializeMemory(ConstPoolVal *Init, char *Addr) {
115 #define INITIALIZE_MEMORY(TYID, CLASS, TY)  \
116   case Type::TYID##TyID: {                  \
117     TY Tmp = cast<CLASS>(Init)->getValue(); \
118     memcpy(Addr, &Tmp, sizeof(TY));         \
119   } return
120
121   switch (Init->getType()->getPrimitiveID()) {
122     INITIALIZE_MEMORY(Bool   , ConstPoolBool, bool);
123     INITIALIZE_MEMORY(UByte  , ConstPoolUInt, unsigned char);
124     INITIALIZE_MEMORY(SByte  , ConstPoolSInt, signed   char);
125     INITIALIZE_MEMORY(UShort , ConstPoolUInt, unsigned short);
126     INITIALIZE_MEMORY(Short  , ConstPoolSInt, signed   short);
127     INITIALIZE_MEMORY(UInt   , ConstPoolUInt, unsigned int);
128     INITIALIZE_MEMORY(Int    , ConstPoolSInt, signed   int);
129     INITIALIZE_MEMORY(ULong  , ConstPoolUInt, uint64_t);
130     INITIALIZE_MEMORY(Long   , ConstPoolSInt,  int64_t);
131     INITIALIZE_MEMORY(Float  , ConstPoolFP  , float);
132     INITIALIZE_MEMORY(Double , ConstPoolFP  , double);
133 #undef INITIALIZE_MEMORY
134
135   case Type::ArrayTyID: {
136     ConstPoolArray *CPA = cast<ConstPoolArray>(Init);
137     const vector<Use> &Val = CPA->getValues();
138     unsigned ElementSize = 
139       TD.getTypeSize(cast<ArrayType>(CPA->getType())->getElementType());
140     for (unsigned i = 0; i < Val.size(); ++i)
141       InitializeMemory(cast<ConstPoolVal>(Val[i].get()), Addr+i*ElementSize);
142     return;
143   }
144
145   case Type::StructTyID: {
146     ConstPoolStruct *CPS = cast<ConstPoolStruct>(Init);
147     const StructLayout *SL=TD.getStructLayout(cast<StructType>(CPS->getType()));
148     const vector<Use> &Val = CPS->getValues();
149     for (unsigned i = 0; i < Val.size(); ++i)
150       InitializeMemory(cast<ConstPoolVal>(Val[i].get()),
151                        Addr+SL->MemberOffsets[i]);
152     return;
153   }
154
155   case Type::PointerTyID:
156     if (isa<ConstPoolPointerNull>(Init)) {
157       *(void**)Addr = 0;
158     } else if (ConstPoolPointerRef *CPR = dyn_cast<ConstPoolPointerRef>(Init)) {
159       GlobalAddress *Address = 
160        (GlobalAddress*)CPR->getValue()->getOrCreateAnnotation(GlobalAddressAID);
161       *(void**)Addr = (GenericValue*)Address->Ptr;
162     } else {
163       assert(0 && "Unknown Constant pointer type!");
164     }
165     return;
166
167   default:
168     cout << "Bad Type: " << Init->getType()->getDescription() << endl;
169     assert(0 && "Unknown constant type to initialize memory with!");
170   }
171 }
172
173 Annotation *GlobalAddress::Create(AnnotationID AID, const Annotable *O, void *){
174   assert(AID == GlobalAddressAID);
175
176   // This annotation will only be created on GlobalValue objects...
177   GlobalValue *GVal = cast<GlobalValue>((Value*)O);
178
179   if (isa<Method>(GVal)) {
180     // The GlobalAddress object for a method is just a pointer to method itself.
181     // Don't delete it when the annotation is gone though!
182     return new GlobalAddress(GVal, false);
183   }
184
185   // Handle the case of a global variable...
186   assert(isa<GlobalVariable>(GVal) && 
187          "Global value found that isn't a method or global variable!");
188   GlobalVariable *GV = cast<GlobalVariable>(GVal);
189   
190   // First off, we must allocate space for the global variable to point at...
191   const Type *Ty = GV->getType()->getValueType();  // Type to be allocated
192   unsigned NumElements = 1;
193
194   if (isa<ArrayType>(Ty) && cast<ArrayType>(Ty)->isUnsized()) {
195     assert(GV->hasInitializer() && "Const val must have an initializer!");
196     // Allocating a unsized array type?
197     Ty = cast<const ArrayType>(Ty)->getElementType();  // Get the actual type...
198
199     // Get the number of elements being allocated by the array...
200     NumElements =cast<ConstPoolArray>(GV->getInitializer())->getValues().size();
201   }
202
203   // Allocate enough memory to hold the type...
204   void *Addr = malloc(NumElements * TD.getTypeSize(Ty));
205   assert(Addr != 0 && "Null pointer returned by malloc!");
206
207   // Initialize the memory if there is an initializer...
208   if (GV->hasInitializer())
209     InitializeMemory(GV->getInitializer(), (char*)Addr);
210
211   return new GlobalAddress(Addr, true);  // Simply invoke the ctor
212 }
213
214
215 //===----------------------------------------------------------------------===//
216 //                    Binary Instruction Implementations
217 //===----------------------------------------------------------------------===//
218
219 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
220    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
221
222 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2, 
223                                    const Type *Ty, ExecutionContext &SF) {
224   GenericValue Dest;
225   switch (Ty->getPrimitiveID()) {
226     IMPLEMENT_BINARY_OPERATOR(+, UByte);
227     IMPLEMENT_BINARY_OPERATOR(+, SByte);
228     IMPLEMENT_BINARY_OPERATOR(+, UShort);
229     IMPLEMENT_BINARY_OPERATOR(+, Short);
230     IMPLEMENT_BINARY_OPERATOR(+, UInt);
231     IMPLEMENT_BINARY_OPERATOR(+, Int);
232     IMPLEMENT_BINARY_OPERATOR(+, ULong);
233     IMPLEMENT_BINARY_OPERATOR(+, Long);
234     IMPLEMENT_BINARY_OPERATOR(+, Float);
235     IMPLEMENT_BINARY_OPERATOR(+, Double);
236     IMPLEMENT_BINARY_OPERATOR(+, Pointer);
237   default:
238     cout << "Unhandled type for Add instruction: " << Ty << endl;
239   }
240   return Dest;
241 }
242
243 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2, 
244                                    const Type *Ty, ExecutionContext &SF) {
245   GenericValue Dest;
246   switch (Ty->getPrimitiveID()) {
247     IMPLEMENT_BINARY_OPERATOR(-, UByte);
248     IMPLEMENT_BINARY_OPERATOR(-, SByte);
249     IMPLEMENT_BINARY_OPERATOR(-, UShort);
250     IMPLEMENT_BINARY_OPERATOR(-, Short);
251     IMPLEMENT_BINARY_OPERATOR(-, UInt);
252     IMPLEMENT_BINARY_OPERATOR(-, Int);
253     IMPLEMENT_BINARY_OPERATOR(-, ULong);
254     IMPLEMENT_BINARY_OPERATOR(-, Long);
255     IMPLEMENT_BINARY_OPERATOR(-, Float);
256     IMPLEMENT_BINARY_OPERATOR(-, Double);
257     IMPLEMENT_BINARY_OPERATOR(-, Pointer);
258   default:
259     cout << "Unhandled type for Sub instruction: " << Ty << endl;
260   }
261   return Dest;
262 }
263
264 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2, 
265                                    const Type *Ty, ExecutionContext &SF) {
266   GenericValue Dest;
267   switch (Ty->getPrimitiveID()) {
268     IMPLEMENT_BINARY_OPERATOR(*, UByte);
269     IMPLEMENT_BINARY_OPERATOR(*, SByte);
270     IMPLEMENT_BINARY_OPERATOR(*, UShort);
271     IMPLEMENT_BINARY_OPERATOR(*, Short);
272     IMPLEMENT_BINARY_OPERATOR(*, UInt);
273     IMPLEMENT_BINARY_OPERATOR(*, Int);
274     IMPLEMENT_BINARY_OPERATOR(*, ULong);
275     IMPLEMENT_BINARY_OPERATOR(*, Long);
276     IMPLEMENT_BINARY_OPERATOR(*, Float);
277     IMPLEMENT_BINARY_OPERATOR(*, Double);
278     IMPLEMENT_BINARY_OPERATOR(*, Pointer);
279   default:
280     cout << "Unhandled type for Mul instruction: " << Ty << endl;
281   }
282   return Dest;
283 }
284
285 static GenericValue executeDivInst(GenericValue Src1, GenericValue Src2, 
286                                    const Type *Ty, ExecutionContext &SF) {
287   GenericValue Dest;
288   switch (Ty->getPrimitiveID()) {
289     IMPLEMENT_BINARY_OPERATOR(/, UByte);
290     IMPLEMENT_BINARY_OPERATOR(/, SByte);
291     IMPLEMENT_BINARY_OPERATOR(/, UShort);
292     IMPLEMENT_BINARY_OPERATOR(/, Short);
293     IMPLEMENT_BINARY_OPERATOR(/, UInt);
294     IMPLEMENT_BINARY_OPERATOR(/, Int);
295     IMPLEMENT_BINARY_OPERATOR(/, ULong);
296     IMPLEMENT_BINARY_OPERATOR(/, Long);
297     IMPLEMENT_BINARY_OPERATOR(/, Float);
298     IMPLEMENT_BINARY_OPERATOR(/, Double);
299     IMPLEMENT_BINARY_OPERATOR(/, Pointer);
300   default:
301     cout << "Unhandled type for Mul instruction: " << Ty << endl;
302   }
303   return Dest;
304 }
305
306 #define IMPLEMENT_SETCC(OP, TY) \
307    case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
308
309 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2, 
310                                      const Type *Ty, ExecutionContext &SF) {
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_SETCC(==, Pointer);
324   default:
325     cout << "Unhandled type for SetEQ instruction: " << Ty << endl;
326   }
327   return Dest;
328 }
329
330 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2, 
331                                      const Type *Ty, ExecutionContext &SF) {
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_SETCC(!=, Pointer);
345   default:
346     cout << "Unhandled type for SetNE instruction: " << Ty << endl;
347   }
348   return Dest;
349 }
350
351 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2, 
352                                      const Type *Ty, ExecutionContext &SF) {
353   GenericValue Dest;
354   switch (Ty->getPrimitiveID()) {
355     IMPLEMENT_SETCC(<=, UByte);
356     IMPLEMENT_SETCC(<=, SByte);
357     IMPLEMENT_SETCC(<=, UShort);
358     IMPLEMENT_SETCC(<=, Short);
359     IMPLEMENT_SETCC(<=, UInt);
360     IMPLEMENT_SETCC(<=, Int);
361     IMPLEMENT_SETCC(<=, ULong);
362     IMPLEMENT_SETCC(<=, Long);
363     IMPLEMENT_SETCC(<=, Float);
364     IMPLEMENT_SETCC(<=, Double);
365     IMPLEMENT_SETCC(<=, Pointer);
366   default:
367     cout << "Unhandled type for SetLE instruction: " << Ty << endl;
368   }
369   return Dest;
370 }
371
372 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2, 
373                                      const Type *Ty, ExecutionContext &SF) {
374   GenericValue Dest;
375   switch (Ty->getPrimitiveID()) {
376     IMPLEMENT_SETCC(>=, UByte);
377     IMPLEMENT_SETCC(>=, SByte);
378     IMPLEMENT_SETCC(>=, UShort);
379     IMPLEMENT_SETCC(>=, Short);
380     IMPLEMENT_SETCC(>=, UInt);
381     IMPLEMENT_SETCC(>=, Int);
382     IMPLEMENT_SETCC(>=, ULong);
383     IMPLEMENT_SETCC(>=, Long);
384     IMPLEMENT_SETCC(>=, Float);
385     IMPLEMENT_SETCC(>=, Double);
386     IMPLEMENT_SETCC(>=, Pointer);
387   default:
388     cout << "Unhandled type for SetGE instruction: " << Ty << endl;
389   }
390   return Dest;
391 }
392
393 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2, 
394                                      const Type *Ty, ExecutionContext &SF) {
395   GenericValue Dest;
396   switch (Ty->getPrimitiveID()) {
397     IMPLEMENT_SETCC(<, UByte);
398     IMPLEMENT_SETCC(<, SByte);
399     IMPLEMENT_SETCC(<, UShort);
400     IMPLEMENT_SETCC(<, Short);
401     IMPLEMENT_SETCC(<, UInt);
402     IMPLEMENT_SETCC(<, Int);
403     IMPLEMENT_SETCC(<, ULong);
404     IMPLEMENT_SETCC(<, Long);
405     IMPLEMENT_SETCC(<, Float);
406     IMPLEMENT_SETCC(<, Double);
407     IMPLEMENT_SETCC(<, Pointer);
408   default:
409     cout << "Unhandled type for SetLT instruction: " << Ty << endl;
410   }
411   return Dest;
412 }
413
414 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2, 
415                                      const Type *Ty, ExecutionContext &SF) {
416   GenericValue Dest;
417   switch (Ty->getPrimitiveID()) {
418     IMPLEMENT_SETCC(>, UByte);
419     IMPLEMENT_SETCC(>, SByte);
420     IMPLEMENT_SETCC(>, UShort);
421     IMPLEMENT_SETCC(>, Short);
422     IMPLEMENT_SETCC(>, UInt);
423     IMPLEMENT_SETCC(>, Int);
424     IMPLEMENT_SETCC(>, ULong);
425     IMPLEMENT_SETCC(>, Long);
426     IMPLEMENT_SETCC(>, Float);
427     IMPLEMENT_SETCC(>, Double);
428     IMPLEMENT_SETCC(>, Pointer);
429   default:
430     cout << "Unhandled type for SetGT instruction: " << Ty << endl;
431   }
432   return Dest;
433 }
434
435 static void executeBinaryInst(BinaryOperator *I, ExecutionContext &SF) {
436   const Type *Ty = I->getOperand(0)->getType();
437   GenericValue Src1  = getOperandValue(I->getOperand(0), SF);
438   GenericValue Src2  = getOperandValue(I->getOperand(1), SF);
439   GenericValue R;   // Result
440
441   switch (I->getOpcode()) {
442   case Instruction::Add: R = executeAddInst(Src1, Src2, Ty, SF); break;
443   case Instruction::Sub: R = executeSubInst(Src1, Src2, Ty, SF); break;
444   case Instruction::Mul: R = executeMulInst(Src1, Src2, Ty, SF); break;
445   case Instruction::Div: R = executeDivInst(Src1, Src2, Ty, SF); break;
446   case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty, SF); break;
447   case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty, SF); break;
448   case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty, SF); break;
449   case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty, SF); break;
450   case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty, SF); break;
451   case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty, SF); break;
452   default:
453     cout << "Don't know how to handle this binary operator!\n-->" << I;
454   }
455
456   SetValue(I, R, SF);
457 }
458
459 //===----------------------------------------------------------------------===//
460 //                     Terminator Instruction Implementations
461 //===----------------------------------------------------------------------===//
462
463 void Interpreter::exitCalled(GenericValue GV) {
464   cout << "Program returned ";
465   print(Type::IntTy, GV);
466   cout << " via 'void exit(int)'\n";
467
468   ExitCode = GV.SByteVal;
469   ECStack.clear();
470 }
471
472 void Interpreter::executeRetInst(ReturnInst *I, ExecutionContext &SF) {
473   const Type *RetTy = 0;
474   GenericValue Result;
475
476   // Save away the return value... (if we are not 'ret void')
477   if (I->getNumOperands()) {
478     RetTy  = I->getReturnValue()->getType();
479     Result = getOperandValue(I->getReturnValue(), SF);
480   }
481
482   // Save previously executing meth
483   const Method *M = ECStack.back().CurMethod;
484
485   // Pop the current stack frame... this invalidates SF
486   ECStack.pop_back();
487
488   if (ECStack.empty()) {  // Finished main.  Put result into exit code...
489     if (RetTy) {          // Nonvoid return type?
490       cout << "Method " << M->getType() << " \"" << M->getName()
491            << "\" returned ";
492       print(RetTy, Result);
493       cout << endl;
494
495       if (RetTy->isIntegral())
496         ExitCode = Result.SByteVal;   // Capture the exit code of the program
497     } else {
498       ExitCode = 0;
499     }
500     return;
501   }
502
503   // If we have a previous stack frame, and we have a previous call, fill in
504   // the return value...
505   //
506   ExecutionContext &NewSF = ECStack.back();
507   if (NewSF.Caller) {
508     if (NewSF.Caller->getType() != Type::VoidTy)             // Save result...
509       SetValue(NewSF.Caller, Result, NewSF);
510
511     NewSF.Caller = 0;          // We returned from the call...
512   } else {
513     // This must be a function that is executing because of a user 'call'
514     // instruction.
515     cout << "Method " << M->getType() << " \"" << M->getName()
516          << "\" returned ";
517     print(RetTy, Result);
518     cout << endl;
519   }
520 }
521
522 void Interpreter::executeBrInst(BranchInst *I, ExecutionContext &SF) {
523   SF.PrevBB = SF.CurBB;               // Update PrevBB so that PHI nodes work...
524   BasicBlock *Dest;
525
526   Dest = I->getSuccessor(0);          // Uncond branches have a fixed dest...
527   if (!I->isUnconditional()) {
528     if (getOperandValue(I->getCondition(), SF).BoolVal == 0) // If false cond...
529       Dest = I->getSuccessor(1);    
530   }
531   SF.CurBB   = Dest;                  // Update CurBB to branch destination
532   SF.CurInst = SF.CurBB->begin();     // Update new instruction ptr...
533 }
534
535 //===----------------------------------------------------------------------===//
536 //                     Memory Instruction Implementations
537 //===----------------------------------------------------------------------===//
538
539 void Interpreter::executeAllocInst(AllocationInst *I, ExecutionContext &SF) {
540   const Type *Ty = I->getType()->getValueType();  // Type to be allocated
541   unsigned NumElements = 1;
542
543   if (I->getNumOperands()) {   // Allocating a unsized array type?
544     assert(isa<ArrayType>(Ty) && cast<const ArrayType>(Ty)->isUnsized() && 
545            "Allocation inst with size operand for !unsized array type???");
546     Ty = cast<const ArrayType>(Ty)->getElementType();  // Get the actual type...
547
548     // Get the number of elements being allocated by the array...
549     GenericValue NumEl = getOperandValue(I->getOperand(0), SF);
550     NumElements = NumEl.UIntVal;
551   }
552
553   // Allocate enough memory to hold the type...
554   GenericValue Result;
555   Result.ULongVal = (uint64_t)malloc(NumElements * TD.getTypeSize(Ty));
556   assert(Result.ULongVal != 0 && "Null pointer returned by malloc!");
557   SetValue(I, Result, SF);
558
559   if (I->getOpcode() == Instruction::Alloca) {
560     // TODO: FIXME: alloca should keep track of memory to free it later...
561   }
562 }
563
564 static void executeFreeInst(FreeInst *I, ExecutionContext &SF) {
565   assert(I->getOperand(0)->getType()->isPointerType() && "Freeing nonptr?");
566   GenericValue Value = getOperandValue(I->getOperand(0), SF);
567   // TODO: Check to make sure memory is allocated
568   free((void*)Value.ULongVal);   // Free memory
569 }
570
571 static void executeLoadInst(LoadInst *I, ExecutionContext &SF) {
572   assert(I->getNumOperands() == 1 && "NI!");
573   GenericValue *Ptr =
574     (GenericValue*)getOperandValue(I->getPtrOperand(), SF).ULongVal;
575   GenericValue Result;
576
577   switch (I->getType()->getPrimitiveID()) {
578   case Type::BoolTyID:
579   case Type::UByteTyID:
580   case Type::SByteTyID:   Result.SByteVal = Ptr->SByteVal; break;
581   case Type::UShortTyID:
582   case Type::ShortTyID:   Result.ShortVal = Ptr->ShortVal; break;
583   case Type::UIntTyID:
584   case Type::IntTyID:     Result.IntVal = Ptr->IntVal; break;
585   case Type::ULongTyID:
586   case Type::LongTyID:
587   case Type::PointerTyID: Result.ULongVal = Ptr->ULongVal; break;
588   case Type::FloatTyID:   Result.FloatVal = Ptr->FloatVal; break;
589   case Type::DoubleTyID:  Result.DoubleVal = Ptr->DoubleVal; break;
590   default:
591     cout << "Cannot load value of type " << I->getType() << "!\n";
592   }
593
594   SetValue(I, Result, SF);
595 }
596
597 static void executeStoreInst(StoreInst *I, ExecutionContext &SF) {
598   GenericValue *Ptr =
599     (GenericValue *)getOperandValue(I->getPtrOperand(), SF).ULongVal;
600   GenericValue Val = getOperandValue(I->getOperand(0), SF);
601   assert(I->getNumOperands() == 2 && "NI!");
602
603   switch (I->getOperand(0)->getType()->getPrimitiveID()) {
604   case Type::BoolTyID:
605   case Type::UByteTyID:
606   case Type::SByteTyID:   Ptr->SByteVal = Val.SByteVal; break;
607   case Type::UShortTyID:
608   case Type::ShortTyID:   Ptr->ShortVal = Val.ShortVal; break;
609   case Type::UIntTyID:
610   case Type::IntTyID:     Ptr->IntVal = Val.IntVal; break;
611   case Type::ULongTyID:
612   case Type::LongTyID:
613   case Type::PointerTyID: Ptr->LongVal = Val.LongVal; break;
614   case Type::FloatTyID:   Ptr->FloatVal = Val.FloatVal; break;
615   case Type::DoubleTyID:  Ptr->DoubleVal = Val.DoubleVal; break;
616   default:
617     cout << "Cannot store value of type " << I->getType() << "!\n";
618   }
619 }
620
621
622 //===----------------------------------------------------------------------===//
623 //                 Miscellaneous Instruction Implementations
624 //===----------------------------------------------------------------------===//
625
626 void Interpreter::executeCallInst(CallInst *I, ExecutionContext &SF) {
627   ECStack.back().Caller = I;
628   vector<GenericValue> ArgVals;
629   ArgVals.reserve(I->getNumOperands()-1);
630   for (unsigned i = 1; i < I->getNumOperands(); ++i)
631     ArgVals.push_back(getOperandValue(I->getOperand(i), SF));
632
633   callMethod(I->getCalledMethod(), ArgVals);
634 }
635
636 static void executePHINode(PHINode *I, ExecutionContext &SF) {
637   BasicBlock *PrevBB = SF.PrevBB;
638   Value *IncomingValue = 0;
639
640   // Search for the value corresponding to this previous bb...
641   for (unsigned i = I->getNumIncomingValues(); i > 0;) {
642     if (I->getIncomingBlock(--i) == PrevBB) {
643       IncomingValue = I->getIncomingValue(i);
644       break;
645     }
646   }
647   assert(IncomingValue && "No PHI node predecessor for current PrevBB!");
648
649   // Found the value, set as the result...
650   SetValue(I, getOperandValue(IncomingValue, SF), SF);
651 }
652
653 #define IMPLEMENT_SHIFT(OP, TY) \
654    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
655
656 static void executeShlInst(ShiftInst *I, ExecutionContext &SF) {
657   const Type *Ty = I->getOperand(0)->getType();
658   GenericValue Src1  = getOperandValue(I->getOperand(0), SF);
659   GenericValue Src2  = getOperandValue(I->getOperand(1), SF);
660   GenericValue Dest;
661
662   switch (Ty->getPrimitiveID()) {
663     IMPLEMENT_SHIFT(<<, UByte);
664     IMPLEMENT_SHIFT(<<, SByte);
665     IMPLEMENT_SHIFT(<<, UShort);
666     IMPLEMENT_SHIFT(<<, Short);
667     IMPLEMENT_SHIFT(<<, UInt);
668     IMPLEMENT_SHIFT(<<, Int);
669     IMPLEMENT_SHIFT(<<, ULong);
670     IMPLEMENT_SHIFT(<<, Long);
671   default:
672     cout << "Unhandled type for Shl instruction: " << Ty << endl;
673   }
674   SetValue(I, Dest, SF);
675 }
676
677 static void executeShrInst(ShiftInst *I, ExecutionContext &SF) {
678   const Type *Ty = I->getOperand(0)->getType();
679   GenericValue Src1  = getOperandValue(I->getOperand(0), SF);
680   GenericValue Src2  = getOperandValue(I->getOperand(1), SF);
681   GenericValue Dest;
682
683   switch (Ty->getPrimitiveID()) {
684     IMPLEMENT_SHIFT(>>, UByte);
685     IMPLEMENT_SHIFT(>>, SByte);
686     IMPLEMENT_SHIFT(>>, UShort);
687     IMPLEMENT_SHIFT(>>, Short);
688     IMPLEMENT_SHIFT(>>, UInt);
689     IMPLEMENT_SHIFT(>>, Int);
690     IMPLEMENT_SHIFT(>>, ULong);
691     IMPLEMENT_SHIFT(>>, Long);
692   default:
693     cout << "Unhandled type for Shr instruction: " << Ty << endl;
694   }
695   SetValue(I, Dest, SF);
696 }
697
698 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
699    case Type::STY##TyID: Dest.DTY##Val = (DCTY)Src.STY##Val; break;
700
701 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY)    \
702   case Type::DESTTY##TyID:                      \
703     switch (SrcTy->getPrimitiveID()) {          \
704       IMPLEMENT_CAST(DESTTY, DESTCTY, UByte);   \
705       IMPLEMENT_CAST(DESTTY, DESTCTY, SByte);   \
706       IMPLEMENT_CAST(DESTTY, DESTCTY, UShort);  \
707       IMPLEMENT_CAST(DESTTY, DESTCTY, Short);   \
708       IMPLEMENT_CAST(DESTTY, DESTCTY, UInt);    \
709       IMPLEMENT_CAST(DESTTY, DESTCTY, Int);     \
710       IMPLEMENT_CAST(DESTTY, DESTCTY, ULong);   \
711       IMPLEMENT_CAST(DESTTY, DESTCTY, Long);    \
712       IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
713
714 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
715       IMPLEMENT_CAST(DESTTY, DESTCTY, Float);   \
716       IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
717
718 #define IMPLEMENT_CAST_CASE_END()    \
719     default: cout << "Unhandled cast: " << SrcTy << " to " << Ty << endl;  \
720       break;                                    \
721     }                                           \
722     break
723
724 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
725    IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY);   \
726    IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
727    IMPLEMENT_CAST_CASE_END()
728
729 static void executeCastInst(CastInst *I, ExecutionContext &SF) {
730   const Type *Ty = I->getType();
731   const Type *SrcTy = I->getOperand(0)->getType();
732   GenericValue Src  = getOperandValue(I->getOperand(0), SF);
733   GenericValue Dest;
734
735   switch (Ty->getPrimitiveID()) {
736     IMPLEMENT_CAST_CASE(UByte , unsigned char);
737     IMPLEMENT_CAST_CASE(SByte ,   signed char);
738     IMPLEMENT_CAST_CASE(UShort, unsigned short);
739     IMPLEMENT_CAST_CASE(Short ,   signed char);
740     IMPLEMENT_CAST_CASE(UInt  , unsigned int );
741     IMPLEMENT_CAST_CASE(Int   ,   signed int );
742     IMPLEMENT_CAST_CASE(ULong , uint64_t );
743     IMPLEMENT_CAST_CASE(Long  ,  int64_t );
744     IMPLEMENT_CAST_CASE(Pointer, uint64_t);
745     IMPLEMENT_CAST_CASE(Float ,          float);
746     IMPLEMENT_CAST_CASE(Double,          double);
747   default:
748     cout << "Unhandled dest type for cast instruction: " << Ty << endl;
749   }
750   SetValue(I, Dest, SF);
751 }
752
753
754
755
756 //===----------------------------------------------------------------------===//
757 //                        Dispatch and Execution Code
758 //===----------------------------------------------------------------------===//
759
760 MethodInfo::MethodInfo(Method *M) : Annotation(MethodInfoAID) {
761   // Assign slot numbers to the method arguments...
762   const Method::ArgumentListType &ArgList = M->getArgumentList();
763   for (Method::ArgumentListType::const_iterator AI = ArgList.begin(), 
764          AE = ArgList.end(); AI != AE; ++AI) {
765     MethodArgument *MA = *AI;
766     MA->addAnnotation(new SlotNumber(getValueSlot(MA)));
767   }
768
769   // Iterate over all of the instructions...
770   unsigned InstNum = 0;
771   for (Method::inst_iterator MI = M->inst_begin(), ME = M->inst_end();
772        MI != ME; ++MI) {
773     Instruction *I = *MI;                          // For each instruction...
774     I->addAnnotation(new InstNumber(++InstNum, getValueSlot(I))); // Add Annote
775   }
776 }
777
778 unsigned MethodInfo::getValueSlot(const Value *V) {
779   unsigned Plane = V->getType()->getUniqueID();
780   if (Plane >= NumPlaneElements.size())
781     NumPlaneElements.resize(Plane+1, 0);
782   return NumPlaneElements[Plane]++;
783 }
784
785
786 //===----------------------------------------------------------------------===//
787 // callMethod - Execute the specified method...
788 //
789 void Interpreter::callMethod(Method *M, const vector<GenericValue> &ArgVals) {
790   assert((ECStack.empty() || ECStack.back().Caller == 0 || 
791           ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
792          "Incorrect number of arguments passed into function call!");
793   if (M->isExternal()) {
794     callExternalMethod(M, ArgVals);
795     return;
796   }
797
798   // Process the method, assigning instruction numbers to the instructions in
799   // the method.  Also calculate the number of values for each type slot active.
800   //
801   MethodInfo *MethInfo = (MethodInfo*)M->getOrCreateAnnotation(MethodInfoAID);
802   ECStack.push_back(ExecutionContext());         // Make a new stack frame...
803
804   ExecutionContext &StackFrame = ECStack.back(); // Fill it in...
805   StackFrame.CurMethod = M;
806   StackFrame.CurBB     = M->front();
807   StackFrame.CurInst   = StackFrame.CurBB->begin();
808   StackFrame.MethInfo  = MethInfo;
809
810   // Initialize the values to nothing...
811   StackFrame.Values.resize(MethInfo->NumPlaneElements.size());
812   for (unsigned i = 0; i < MethInfo->NumPlaneElements.size(); ++i)
813     StackFrame.Values[i].resize(MethInfo->NumPlaneElements[i]);
814
815   StackFrame.PrevBB = 0;  // No previous BB for PHI nodes...
816
817
818   // Run through the method arguments and initialize their values...
819   assert(ArgVals.size() == M->getArgumentList().size() &&
820          "Invalid number of values passed to method invocation!");
821   unsigned i = 0;
822   for (Method::ArgumentListType::iterator MI = M->getArgumentList().begin(),
823          ME = M->getArgumentList().end(); MI != ME; ++MI, ++i) {
824     SetValue(*MI, ArgVals[i], StackFrame);
825   }
826 }
827
828 // executeInstruction - Interpret a single instruction, increment the "PC", and
829 // return true if the next instruction is a breakpoint...
830 //
831 bool Interpreter::executeInstruction() {
832   assert(!ECStack.empty() && "No program running, cannot execute inst!");
833
834   ExecutionContext &SF = ECStack.back();  // Current stack frame
835   Instruction *I = *SF.CurInst++;         // Increment before execute
836
837   if (Trace)
838     cout << "Run:" << I;
839
840   if (I->isBinaryOp()) {
841     executeBinaryInst((BinaryOperator*)I, SF);
842   } else {
843     switch (I->getOpcode()) {
844       // Terminators
845     case Instruction::Ret:     executeRetInst   ((ReturnInst*)I, SF); break;
846     case Instruction::Br:      executeBrInst    ((BranchInst*)I, SF); break;
847       // Memory Instructions
848     case Instruction::Alloca:
849     case Instruction::Malloc:  executeAllocInst ((AllocationInst*)I, SF); break;
850     case Instruction::Free:    executeFreeInst  (cast<FreeInst> (I), SF); break;
851     case Instruction::Load:    executeLoadInst  (cast<LoadInst> (I), SF); break;
852     case Instruction::Store:   executeStoreInst (cast<StoreInst>(I), SF); break;
853
854       // Miscellaneous Instructions
855     case Instruction::Call:    executeCallInst  (cast<CallInst> (I), SF); break;
856     case Instruction::PHINode: executePHINode   (cast<PHINode>  (I), SF); break;
857     case Instruction::Shl:     executeShlInst   (cast<ShiftInst>(I), SF); break;
858     case Instruction::Shr:     executeShrInst   (cast<ShiftInst>(I), SF); break;
859     case Instruction::Cast:    executeCastInst  (cast<CastInst> (I), SF); break;
860     default:
861       cout << "Don't know how to execute this instruction!\n-->" << I;
862     }
863   }
864   
865   // Reset the current frame location to the top of stack
866   CurFrame = ECStack.size()-1;
867
868   if (CurFrame == -1) return false;  // No breakpoint if no code
869
870   // Return true if there is a breakpoint annotation on the instruction...
871   return (*ECStack[CurFrame].CurInst)->getAnnotation(BreakpointAID) != 0;
872 }
873
874 void Interpreter::stepInstruction() {  // Do the 'step' command
875   if (ECStack.empty()) {
876     cout << "Error: no program running, cannot step!\n";
877     return;
878   }
879
880   // Run an instruction...
881   executeInstruction();
882
883   // Print the next instruction to execute...
884   printCurrentInstruction();
885 }
886
887 // --- UI Stuff...
888 void Interpreter::nextInstruction() {  // Do the 'next' command
889   if (ECStack.empty()) {
890     cout << "Error: no program running, cannot 'next'!\n";
891     return;
892   }
893
894   // If this is a call instruction, step over the call instruction...
895   // TODO: ICALL, CALL WITH, ...
896   if ((*ECStack.back().CurInst)->getOpcode() == Instruction::Call) {
897     // Step into the function...
898     if (executeInstruction()) {
899       // Hit a breakpoint, print current instruction, then return to user...
900       cout << "Breakpoint hit!\n";
901       printCurrentInstruction();
902       return;
903     }
904
905     // Finish executing the function...
906     finish();
907   } else {
908     // Normal instruction, just step...
909     stepInstruction();
910   }
911 }
912
913 void Interpreter::run() {
914   if (ECStack.empty()) {
915     cout << "Error: no program running, cannot run!\n";
916     return;
917   }
918
919   bool HitBreakpoint = false;
920   while (!ECStack.empty() && !HitBreakpoint) {
921     // Run an instruction...
922     HitBreakpoint = executeInstruction();
923   }
924
925   if (HitBreakpoint) {
926     cout << "Breakpoint hit!\n";
927   }
928   // Print the next instruction to execute...
929   printCurrentInstruction();
930 }
931
932 void Interpreter::finish() {
933   if (ECStack.empty()) {
934     cout << "Error: no program running, cannot run!\n";
935     return;
936   }
937
938   unsigned StackSize = ECStack.size();
939   bool HitBreakpoint = false;
940   while (ECStack.size() >= StackSize && !HitBreakpoint) {
941     // Run an instruction...
942     HitBreakpoint = executeInstruction();
943   }
944
945   if (HitBreakpoint) {
946     cout << "Breakpoint hit!\n";
947   }
948
949   // Print the next instruction to execute...
950   printCurrentInstruction();
951 }
952
953
954
955 // printCurrentInstruction - Print out the instruction that the virtual PC is
956 // at, or fail silently if no program is running.
957 //
958 void Interpreter::printCurrentInstruction() {
959   if (!ECStack.empty()) {
960     Instruction *I = *ECStack.back().CurInst;
961     InstNumber *IN = (InstNumber*)I->getAnnotation(SlotNumberAID);
962     assert(IN && "Instruction has no numbering annotation!");
963     cout << "#" << IN->InstNum << I;
964   }
965 }
966
967 void Interpreter::printValue(const Type *Ty, GenericValue V) {
968   switch (Ty->getPrimitiveID()) {
969   case Type::BoolTyID:   cout << (V.BoolVal?"true":"false"); break;
970   case Type::SByteTyID:  cout << V.SByteVal;  break;
971   case Type::UByteTyID:  cout << V.UByteVal;  break;
972   case Type::ShortTyID:  cout << V.ShortVal;  break;
973   case Type::UShortTyID: cout << V.UShortVal; break;
974   case Type::IntTyID:    cout << V.IntVal;    break;
975   case Type::UIntTyID:   cout << V.UIntVal;   break;
976   case Type::LongTyID:   cout << V.LongVal;   break;
977   case Type::ULongTyID:  cout << V.ULongVal;  break;
978   case Type::FloatTyID:  cout << V.FloatVal;  break;
979   case Type::DoubleTyID: cout << V.DoubleVal; break;
980   case Type::PointerTyID:cout << (void*)V.ULongVal; break;
981   default:
982     cout << "- Don't know how to print value of this type!";
983     break;
984   }
985 }
986
987 void Interpreter::print(const Type *Ty, GenericValue V) {
988   cout << Ty << " ";
989   printValue(Ty, V);
990 }
991
992 void Interpreter::print(const string &Name) {
993   Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
994   if (!PickedVal) return;
995
996   if (const Method *M = dyn_cast<const Method>(PickedVal)) {
997     cout << M;  // Print the method
998   } else {      // Otherwise there should be an annotation for the slot#
999     print(PickedVal->getType(), 
1000           getOperandValue(PickedVal, ECStack[CurFrame]));
1001     cout << endl;
1002   }
1003     
1004 }
1005
1006 void Interpreter::infoValue(const string &Name) {
1007   Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1008   if (!PickedVal) return;
1009
1010   cout << "Value: ";
1011   print(PickedVal->getType(), 
1012         getOperandValue(PickedVal, ECStack[CurFrame]));
1013   cout << endl;
1014   printOperandInfo(PickedVal, ECStack[CurFrame]);
1015 }
1016
1017 void Interpreter::list() {
1018   if (ECStack.empty())
1019     cout << "Error: No program executing!\n";
1020   else
1021     cout << ECStack[CurFrame].CurMethod;   // Just print the method out...
1022 }
1023
1024 void Interpreter::printStackTrace() {
1025   if (ECStack.empty()) cout << "No program executing!\n";
1026
1027   for (unsigned i = 0; i < ECStack.size(); ++i) {
1028     cout << (((int)i == CurFrame) ? '>' : '-');
1029     cout << "#" << i << ". " << ECStack[i].CurMethod->getType() << " \""
1030          << ECStack[i].CurMethod->getName() << "\"(";
1031     // TODO: Print Args
1032     cout << ")" << endl;
1033     cout << *ECStack[i].CurInst;
1034   }
1035 }