Add support to count the number of dynamic instructions executed by LLI
[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/iPHINode.h"
10 #include "llvm/iOther.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/DerivedTypes.h"
14 #include "llvm/Constants.h"
15 #include "llvm/Assembly/Writer.h"
16 #include "llvm/Target/TargetData.h"
17 #include "Support/CommandLine.h"
18 #include "Support/Statistic.h"
19 #include <math.h>  // For fmod
20 #include <signal.h>
21 #include <setjmp.h>
22 using std::vector;
23 using std::cout;
24 using std::cerr;
25
26 namespace {
27   Statistic<> NumDynamicInsts("lli", "Number of dynamic instructions executed");
28 }
29
30 static cl::opt<bool>
31 QuietMode("quiet", cl::desc("Do not emit any non-program output"));
32
33 static cl::alias 
34 QuietModeA("q", cl::desc("Alias for -quiet"), cl::aliasopt(QuietMode));
35
36 static cl::opt<bool>
37 ArrayChecksEnabled("array-checks", cl::desc("Enable array bound checks"));
38
39 static cl::opt<bool>
40 AbortOnExceptions("abort-on-exception",
41                   cl::desc("Halt execution on a machine exception"));
42
43 // Create a TargetData structure to handle memory addressing and size/alignment
44 // computations
45 //
46 TargetData TD("lli Interpreter");
47 CachedWriter CW;     // Object to accelerate printing of LLVM
48
49
50 #ifdef PROFILE_STRUCTURE_FIELDS
51 static cl::opt<bool>
52 ProfileStructureFields("profilestructfields", 
53                        cl::desc("Profile Structure Field Accesses"));
54 #include <map>
55 static std::map<const StructType *, vector<unsigned> > FieldAccessCounts;
56 #endif
57
58 sigjmp_buf SignalRecoverBuffer;
59 static bool InInstruction = false;
60
61 extern "C" {
62 static void SigHandler(int Signal) {
63   if (InInstruction)
64     siglongjmp(SignalRecoverBuffer, Signal);
65 }
66 }
67
68 static void initializeSignalHandlers() {
69   struct sigaction Action;
70   Action.sa_handler = SigHandler;
71   Action.sa_flags   = SA_SIGINFO;
72   sigemptyset(&Action.sa_mask);
73   sigaction(SIGSEGV, &Action, 0);
74   sigaction(SIGBUS, &Action, 0);
75   sigaction(SIGINT, &Action, 0);
76   sigaction(SIGFPE, &Action, 0);
77 }
78
79
80 //===----------------------------------------------------------------------===//
81 //                     Value Manipulation code
82 //===----------------------------------------------------------------------===//
83
84 static unsigned getOperandSlot(Value *V) {
85   SlotNumber *SN = (SlotNumber*)V->getAnnotation(SlotNumberAID);
86   assert(SN && "Operand does not have a slot number annotation!");
87   return SN->SlotNum;
88 }
89
90 #define GET_CONST_VAL(TY, CLASS) \
91   case Type::TY##TyID: Result.TY##Val = cast<CLASS>(C)->getValue(); break
92
93 // Operations used by constant expr implementations...
94 static GenericValue executeCastOperation(Value *Src, const Type *DestTy,
95                                          ExecutionContext &SF);
96 static GenericValue executeGEPOperation(Value *Src, User::op_iterator IdxBegin,
97                                         User::op_iterator IdxEnd,
98                                         ExecutionContext &SF);
99 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2, 
100                                    const Type *Ty, ExecutionContext &SF);
101
102 static GenericValue getConstantValue(const Constant *C) {
103   GenericValue Result;
104   switch (C->getType()->getPrimitiveID()) {
105     GET_CONST_VAL(Bool   , ConstantBool);
106     GET_CONST_VAL(UByte  , ConstantUInt);
107     GET_CONST_VAL(SByte  , ConstantSInt);
108     GET_CONST_VAL(UShort , ConstantUInt);
109     GET_CONST_VAL(Short  , ConstantSInt);
110     GET_CONST_VAL(UInt   , ConstantUInt);
111     GET_CONST_VAL(Int    , ConstantSInt);
112     GET_CONST_VAL(ULong  , ConstantUInt);
113     GET_CONST_VAL(Long   , ConstantSInt);
114     GET_CONST_VAL(Float  , ConstantFP);
115     GET_CONST_VAL(Double , ConstantFP);
116   case Type::PointerTyID:
117     if (isa<ConstantPointerNull>(C)) {
118       Result.PointerVal = 0;
119     } else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)){
120       GlobalAddress *Address = 
121        (GlobalAddress*)CPR->getValue()->getOrCreateAnnotation(GlobalAddressAID);
122       Result.PointerVal = (PointerTy)Address->Ptr;
123     } else {
124       assert(0 && "Unknown constant pointer type!");
125     }
126     break;
127   default:
128     cout << "ERROR: Constant unimp for type: " << C->getType() << "\n";
129   }
130   return Result;
131 }
132
133 static GenericValue getOperandValue(Value *V, ExecutionContext &SF) {
134   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
135     switch (CE->getOpcode()) {
136     case Instruction::Cast:
137       return executeCastOperation(CE->getOperand(0), CE->getType(), SF);
138     case Instruction::GetElementPtr:
139       return executeGEPOperation(CE->getOperand(0), CE->op_begin()+1,
140                                  CE->op_end(), SF);
141     case Instruction::Add:
142       return executeAddInst(getOperandValue(CE->getOperand(0), SF),
143                             getOperandValue(CE->getOperand(1), SF),
144                             CE->getType(), SF);
145     default:
146       cerr << "Unhandled ConstantExpr: " << CE << "\n";
147       abort();
148       { GenericValue V; return V; }
149     }
150   } else if (Constant *CPV = dyn_cast<Constant>(V)) {
151     return getConstantValue(CPV);
152   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
153     GlobalAddress *Address = 
154       (GlobalAddress*)GV->getOrCreateAnnotation(GlobalAddressAID);
155     GenericValue Result;
156     Result.PointerVal = (PointerTy)(GenericValue*)Address->Ptr;
157     return Result;
158   } else {
159     unsigned TyP = V->getType()->getUniqueID();   // TypePlane for value
160     unsigned OpSlot = getOperandSlot(V);
161     assert(TyP < SF.Values.size() && 
162            OpSlot < SF.Values[TyP].size() && "Value out of range!");
163     return SF.Values[TyP][getOperandSlot(V)];
164   }
165 }
166
167 static void printOperandInfo(Value *V, ExecutionContext &SF) {
168   if (isa<Constant>(V)) {
169     cout << "Constant Pool Value\n";
170   } else if (isa<GlobalValue>(V)) {
171     cout << "Global Value\n";
172   } else {
173     unsigned TyP  = V->getType()->getUniqueID();   // TypePlane for value
174     unsigned Slot = getOperandSlot(V);
175     cout << "Value=" << (void*)V << " TypeID=" << TyP << " Slot=" << Slot
176          << " Addr=" << &SF.Values[TyP][Slot] << " SF=" << &SF
177          << " Contents=0x";
178
179     const unsigned char *Buf = (const unsigned char*)&SF.Values[TyP][Slot];
180     for (unsigned i = 0; i < sizeof(GenericValue); ++i) {
181       unsigned char Cur = Buf[i];
182       cout << ( Cur     >= 160? char((Cur>>4)+'A'-10) : char((Cur>>4) + '0'))
183            << ((Cur&15) >=  10? char((Cur&15)+'A'-10) : char((Cur&15) + '0'));
184     }
185     cout << "\n";
186   }
187 }
188
189
190
191 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
192   unsigned TyP = V->getType()->getUniqueID();   // TypePlane for value
193
194   //cout << "Setting value: " << &SF.Values[TyP][getOperandSlot(V)] << "\n";
195   SF.Values[TyP][getOperandSlot(V)] = Val;
196 }
197
198
199 //===----------------------------------------------------------------------===//
200 //                    Annotation Wrangling code
201 //===----------------------------------------------------------------------===//
202
203 void Interpreter::initializeExecutionEngine() {
204   AnnotationManager::registerAnnotationFactory(MethodInfoAID,
205                                                &MethodInfo::Create);
206   AnnotationManager::registerAnnotationFactory(GlobalAddressAID, 
207                                                &GlobalAddress::Create);
208   initializeSignalHandlers();
209 }
210
211 static void StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
212                                const Type *Ty);
213
214 // InitializeMemory - Recursive function to apply a Constant value into the
215 // specified memory location...
216 //
217 static void InitializeMemory(const Constant *Init, char *Addr) {
218
219   if (Init->getType()->isFirstClassType()) {
220     GenericValue Val = getConstantValue(Init);
221     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
222     return;
223   }
224
225   switch (Init->getType()->getPrimitiveID()) {
226   case Type::ArrayTyID: {
227     const ConstantArray *CPA = cast<ConstantArray>(Init);
228     const vector<Use> &Val = CPA->getValues();
229     unsigned ElementSize = 
230       TD.getTypeSize(cast<ArrayType>(CPA->getType())->getElementType());
231     for (unsigned i = 0; i < Val.size(); ++i)
232       InitializeMemory(cast<Constant>(Val[i].get()), Addr+i*ElementSize);
233     return;
234   }
235
236   case Type::StructTyID: {
237     const ConstantStruct *CPS = cast<ConstantStruct>(Init);
238     const StructLayout *SL=TD.getStructLayout(cast<StructType>(CPS->getType()));
239     const vector<Use> &Val = CPS->getValues();
240     for (unsigned i = 0; i < Val.size(); ++i)
241       InitializeMemory(cast<Constant>(Val[i].get()),
242                        Addr+SL->MemberOffsets[i]);
243     return;
244   }
245
246   default:
247     CW << "Bad Type: " << Init->getType() << "\n";
248     assert(0 && "Unknown constant type to initialize memory with!");
249   }
250 }
251
252 Annotation *GlobalAddress::Create(AnnotationID AID, const Annotable *O, void *){
253   assert(AID == GlobalAddressAID);
254
255   // This annotation will only be created on GlobalValue objects...
256   GlobalValue *GVal = cast<GlobalValue>((Value*)O);
257
258   if (isa<Function>(GVal)) {
259     // The GlobalAddress object for a function is just a pointer to function
260     // itself.  Don't delete it when the annotation is gone though!
261     return new GlobalAddress(GVal, false);
262   }
263
264   // Handle the case of a global variable...
265   assert(isa<GlobalVariable>(GVal) && 
266          "Global value found that isn't a function or global variable!");
267   GlobalVariable *GV = cast<GlobalVariable>(GVal);
268   
269   // First off, we must allocate space for the global variable to point at...
270   const Type *Ty = GV->getType()->getElementType();  // Type to be allocated
271
272   // Allocate enough memory to hold the type...
273   void *Addr = calloc(1, TD.getTypeSize(Ty));
274   assert(Addr != 0 && "Null pointer returned by malloc!");
275
276   // Initialize the memory if there is an initializer...
277   if (GV->hasInitializer())
278     InitializeMemory(GV->getInitializer(), (char*)Addr);
279
280   return new GlobalAddress(Addr, true);  // Simply invoke the ctor
281 }
282
283 //===----------------------------------------------------------------------===//
284 //                    Binary Instruction Implementations
285 //===----------------------------------------------------------------------===//
286
287 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
288    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
289
290 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2, 
291                                    const Type *Ty, ExecutionContext &SF) {
292   GenericValue Dest;
293   switch (Ty->getPrimitiveID()) {
294     IMPLEMENT_BINARY_OPERATOR(+, UByte);
295     IMPLEMENT_BINARY_OPERATOR(+, SByte);
296     IMPLEMENT_BINARY_OPERATOR(+, UShort);
297     IMPLEMENT_BINARY_OPERATOR(+, Short);
298     IMPLEMENT_BINARY_OPERATOR(+, UInt);
299     IMPLEMENT_BINARY_OPERATOR(+, Int);
300     IMPLEMENT_BINARY_OPERATOR(+, ULong);
301     IMPLEMENT_BINARY_OPERATOR(+, Long);
302     IMPLEMENT_BINARY_OPERATOR(+, Float);
303     IMPLEMENT_BINARY_OPERATOR(+, Double);
304     IMPLEMENT_BINARY_OPERATOR(+, Pointer);
305   default:
306     cout << "Unhandled type for Add instruction: " << Ty << "\n";
307   }
308   return Dest;
309 }
310
311 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2, 
312                                    const Type *Ty, ExecutionContext &SF) {
313   GenericValue Dest;
314   switch (Ty->getPrimitiveID()) {
315     IMPLEMENT_BINARY_OPERATOR(-, UByte);
316     IMPLEMENT_BINARY_OPERATOR(-, SByte);
317     IMPLEMENT_BINARY_OPERATOR(-, UShort);
318     IMPLEMENT_BINARY_OPERATOR(-, Short);
319     IMPLEMENT_BINARY_OPERATOR(-, UInt);
320     IMPLEMENT_BINARY_OPERATOR(-, Int);
321     IMPLEMENT_BINARY_OPERATOR(-, ULong);
322     IMPLEMENT_BINARY_OPERATOR(-, Long);
323     IMPLEMENT_BINARY_OPERATOR(-, Float);
324     IMPLEMENT_BINARY_OPERATOR(-, Double);
325     IMPLEMENT_BINARY_OPERATOR(-, Pointer);
326   default:
327     cout << "Unhandled type for Sub instruction: " << Ty << "\n";
328   }
329   return Dest;
330 }
331
332 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2, 
333                                    const Type *Ty, ExecutionContext &SF) {
334   GenericValue Dest;
335   switch (Ty->getPrimitiveID()) {
336     IMPLEMENT_BINARY_OPERATOR(*, UByte);
337     IMPLEMENT_BINARY_OPERATOR(*, SByte);
338     IMPLEMENT_BINARY_OPERATOR(*, UShort);
339     IMPLEMENT_BINARY_OPERATOR(*, Short);
340     IMPLEMENT_BINARY_OPERATOR(*, UInt);
341     IMPLEMENT_BINARY_OPERATOR(*, Int);
342     IMPLEMENT_BINARY_OPERATOR(*, ULong);
343     IMPLEMENT_BINARY_OPERATOR(*, Long);
344     IMPLEMENT_BINARY_OPERATOR(*, Float);
345     IMPLEMENT_BINARY_OPERATOR(*, Double);
346     IMPLEMENT_BINARY_OPERATOR(*, Pointer);
347   default:
348     cout << "Unhandled type for Mul instruction: " << Ty << "\n";
349   }
350   return Dest;
351 }
352
353 static GenericValue executeDivInst(GenericValue Src1, GenericValue Src2, 
354                                    const Type *Ty, ExecutionContext &SF) {
355   GenericValue Dest;
356   switch (Ty->getPrimitiveID()) {
357     IMPLEMENT_BINARY_OPERATOR(/, UByte);
358     IMPLEMENT_BINARY_OPERATOR(/, SByte);
359     IMPLEMENT_BINARY_OPERATOR(/, UShort);
360     IMPLEMENT_BINARY_OPERATOR(/, Short);
361     IMPLEMENT_BINARY_OPERATOR(/, UInt);
362     IMPLEMENT_BINARY_OPERATOR(/, Int);
363     IMPLEMENT_BINARY_OPERATOR(/, ULong);
364     IMPLEMENT_BINARY_OPERATOR(/, Long);
365     IMPLEMENT_BINARY_OPERATOR(/, Float);
366     IMPLEMENT_BINARY_OPERATOR(/, Double);
367     IMPLEMENT_BINARY_OPERATOR(/, Pointer);
368   default:
369     cout << "Unhandled type for Div instruction: " << Ty << "\n";
370   }
371   return Dest;
372 }
373
374 static GenericValue executeRemInst(GenericValue Src1, GenericValue Src2, 
375                                    const Type *Ty, ExecutionContext &SF) {
376   GenericValue Dest;
377   switch (Ty->getPrimitiveID()) {
378     IMPLEMENT_BINARY_OPERATOR(%, UByte);
379     IMPLEMENT_BINARY_OPERATOR(%, SByte);
380     IMPLEMENT_BINARY_OPERATOR(%, UShort);
381     IMPLEMENT_BINARY_OPERATOR(%, Short);
382     IMPLEMENT_BINARY_OPERATOR(%, UInt);
383     IMPLEMENT_BINARY_OPERATOR(%, Int);
384     IMPLEMENT_BINARY_OPERATOR(%, ULong);
385     IMPLEMENT_BINARY_OPERATOR(%, Long);
386     IMPLEMENT_BINARY_OPERATOR(%, Pointer);
387   case Type::FloatTyID:
388     Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
389     break;
390   case Type::DoubleTyID:
391     Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
392     break;
393   default:
394     cout << "Unhandled type for Rem instruction: " << Ty << "\n";
395   }
396   return Dest;
397 }
398
399 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2, 
400                                    const Type *Ty, ExecutionContext &SF) {
401   GenericValue Dest;
402   switch (Ty->getPrimitiveID()) {
403     IMPLEMENT_BINARY_OPERATOR(&, UByte);
404     IMPLEMENT_BINARY_OPERATOR(&, SByte);
405     IMPLEMENT_BINARY_OPERATOR(&, UShort);
406     IMPLEMENT_BINARY_OPERATOR(&, Short);
407     IMPLEMENT_BINARY_OPERATOR(&, UInt);
408     IMPLEMENT_BINARY_OPERATOR(&, Int);
409     IMPLEMENT_BINARY_OPERATOR(&, ULong);
410     IMPLEMENT_BINARY_OPERATOR(&, Long);
411     IMPLEMENT_BINARY_OPERATOR(&, Pointer);
412   default:
413     cout << "Unhandled type for And instruction: " << Ty << "\n";
414   }
415   return Dest;
416 }
417
418
419 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2, 
420                                   const Type *Ty, ExecutionContext &SF) {
421   GenericValue Dest;
422   switch (Ty->getPrimitiveID()) {
423     IMPLEMENT_BINARY_OPERATOR(|, UByte);
424     IMPLEMENT_BINARY_OPERATOR(|, SByte);
425     IMPLEMENT_BINARY_OPERATOR(|, UShort);
426     IMPLEMENT_BINARY_OPERATOR(|, Short);
427     IMPLEMENT_BINARY_OPERATOR(|, UInt);
428     IMPLEMENT_BINARY_OPERATOR(|, Int);
429     IMPLEMENT_BINARY_OPERATOR(|, ULong);
430     IMPLEMENT_BINARY_OPERATOR(|, Long);
431     IMPLEMENT_BINARY_OPERATOR(|, Pointer);
432   default:
433     cout << "Unhandled type for Or instruction: " << Ty << "\n";
434   }
435   return Dest;
436 }
437
438
439 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2, 
440                                    const Type *Ty, ExecutionContext &SF) {
441   GenericValue Dest;
442   switch (Ty->getPrimitiveID()) {
443     IMPLEMENT_BINARY_OPERATOR(^, UByte);
444     IMPLEMENT_BINARY_OPERATOR(^, SByte);
445     IMPLEMENT_BINARY_OPERATOR(^, UShort);
446     IMPLEMENT_BINARY_OPERATOR(^, Short);
447     IMPLEMENT_BINARY_OPERATOR(^, UInt);
448     IMPLEMENT_BINARY_OPERATOR(^, Int);
449     IMPLEMENT_BINARY_OPERATOR(^, ULong);
450     IMPLEMENT_BINARY_OPERATOR(^, Long);
451     IMPLEMENT_BINARY_OPERATOR(^, Pointer);
452   default:
453     cout << "Unhandled type for Xor instruction: " << Ty << "\n";
454   }
455   return Dest;
456 }
457
458
459 #define IMPLEMENT_SETCC(OP, TY) \
460    case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
461
462 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2, 
463                                      const Type *Ty, ExecutionContext &SF) {
464   GenericValue Dest;
465   switch (Ty->getPrimitiveID()) {
466     IMPLEMENT_SETCC(==, UByte);
467     IMPLEMENT_SETCC(==, SByte);
468     IMPLEMENT_SETCC(==, UShort);
469     IMPLEMENT_SETCC(==, Short);
470     IMPLEMENT_SETCC(==, UInt);
471     IMPLEMENT_SETCC(==, Int);
472     IMPLEMENT_SETCC(==, ULong);
473     IMPLEMENT_SETCC(==, Long);
474     IMPLEMENT_SETCC(==, Float);
475     IMPLEMENT_SETCC(==, Double);
476     IMPLEMENT_SETCC(==, Pointer);
477   default:
478     cout << "Unhandled type for SetEQ instruction: " << Ty << "\n";
479   }
480   return Dest;
481 }
482
483 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2, 
484                                      const Type *Ty, ExecutionContext &SF) {
485   GenericValue Dest;
486   switch (Ty->getPrimitiveID()) {
487     IMPLEMENT_SETCC(!=, UByte);
488     IMPLEMENT_SETCC(!=, SByte);
489     IMPLEMENT_SETCC(!=, UShort);
490     IMPLEMENT_SETCC(!=, Short);
491     IMPLEMENT_SETCC(!=, UInt);
492     IMPLEMENT_SETCC(!=, Int);
493     IMPLEMENT_SETCC(!=, ULong);
494     IMPLEMENT_SETCC(!=, Long);
495     IMPLEMENT_SETCC(!=, Float);
496     IMPLEMENT_SETCC(!=, Double);
497     IMPLEMENT_SETCC(!=, Pointer);
498
499   default:
500     cout << "Unhandled type for SetNE instruction: " << Ty << "\n";
501   }
502   return Dest;
503 }
504
505 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2, 
506                                      const Type *Ty, ExecutionContext &SF) {
507   GenericValue Dest;
508   switch (Ty->getPrimitiveID()) {
509     IMPLEMENT_SETCC(<=, UByte);
510     IMPLEMENT_SETCC(<=, SByte);
511     IMPLEMENT_SETCC(<=, UShort);
512     IMPLEMENT_SETCC(<=, Short);
513     IMPLEMENT_SETCC(<=, UInt);
514     IMPLEMENT_SETCC(<=, Int);
515     IMPLEMENT_SETCC(<=, ULong);
516     IMPLEMENT_SETCC(<=, Long);
517     IMPLEMENT_SETCC(<=, Float);
518     IMPLEMENT_SETCC(<=, Double);
519     IMPLEMENT_SETCC(<=, Pointer);
520   default:
521     cout << "Unhandled type for SetLE instruction: " << Ty << "\n";
522   }
523   return Dest;
524 }
525
526 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2, 
527                                      const Type *Ty, ExecutionContext &SF) {
528   GenericValue Dest;
529   switch (Ty->getPrimitiveID()) {
530     IMPLEMENT_SETCC(>=, UByte);
531     IMPLEMENT_SETCC(>=, SByte);
532     IMPLEMENT_SETCC(>=, UShort);
533     IMPLEMENT_SETCC(>=, Short);
534     IMPLEMENT_SETCC(>=, UInt);
535     IMPLEMENT_SETCC(>=, Int);
536     IMPLEMENT_SETCC(>=, ULong);
537     IMPLEMENT_SETCC(>=, Long);
538     IMPLEMENT_SETCC(>=, Float);
539     IMPLEMENT_SETCC(>=, Double);
540     IMPLEMENT_SETCC(>=, Pointer);
541   default:
542     cout << "Unhandled type for SetGE instruction: " << Ty << "\n";
543   }
544   return Dest;
545 }
546
547 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2, 
548                                      const Type *Ty, ExecutionContext &SF) {
549   GenericValue Dest;
550   switch (Ty->getPrimitiveID()) {
551     IMPLEMENT_SETCC(<, UByte);
552     IMPLEMENT_SETCC(<, SByte);
553     IMPLEMENT_SETCC(<, UShort);
554     IMPLEMENT_SETCC(<, Short);
555     IMPLEMENT_SETCC(<, UInt);
556     IMPLEMENT_SETCC(<, Int);
557     IMPLEMENT_SETCC(<, ULong);
558     IMPLEMENT_SETCC(<, Long);
559     IMPLEMENT_SETCC(<, Float);
560     IMPLEMENT_SETCC(<, Double);
561     IMPLEMENT_SETCC(<, Pointer);
562   default:
563     cout << "Unhandled type for SetLT instruction: " << Ty << "\n";
564   }
565   return Dest;
566 }
567
568 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2, 
569                                      const Type *Ty, ExecutionContext &SF) {
570   GenericValue Dest;
571   switch (Ty->getPrimitiveID()) {
572     IMPLEMENT_SETCC(>, UByte);
573     IMPLEMENT_SETCC(>, SByte);
574     IMPLEMENT_SETCC(>, UShort);
575     IMPLEMENT_SETCC(>, Short);
576     IMPLEMENT_SETCC(>, UInt);
577     IMPLEMENT_SETCC(>, Int);
578     IMPLEMENT_SETCC(>, ULong);
579     IMPLEMENT_SETCC(>, Long);
580     IMPLEMENT_SETCC(>, Float);
581     IMPLEMENT_SETCC(>, Double);
582     IMPLEMENT_SETCC(>, Pointer);
583   default:
584     cout << "Unhandled type for SetGT instruction: " << Ty << "\n";
585   }
586   return Dest;
587 }
588
589 static void executeBinaryInst(BinaryOperator &I, ExecutionContext &SF) {
590   const Type *Ty    = I.getOperand(0)->getType();
591   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
592   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
593   GenericValue R;   // Result
594
595   switch (I.getOpcode()) {
596   case Instruction::Add:   R = executeAddInst  (Src1, Src2, Ty, SF); break;
597   case Instruction::Sub:   R = executeSubInst  (Src1, Src2, Ty, SF); break;
598   case Instruction::Mul:   R = executeMulInst  (Src1, Src2, Ty, SF); break;
599   case Instruction::Div:   R = executeDivInst  (Src1, Src2, Ty, SF); break;
600   case Instruction::Rem:   R = executeRemInst  (Src1, Src2, Ty, SF); break;
601   case Instruction::And:   R = executeAndInst  (Src1, Src2, Ty, SF); break;
602   case Instruction::Or:    R = executeOrInst   (Src1, Src2, Ty, SF); break;
603   case Instruction::Xor:   R = executeXorInst  (Src1, Src2, Ty, SF); break;
604   case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty, SF); break;
605   case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty, SF); break;
606   case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty, SF); break;
607   case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty, SF); break;
608   case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty, SF); break;
609   case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty, SF); break;
610   default:
611     cout << "Don't know how to handle this binary operator!\n-->" << I;
612     R = Src1;
613   }
614
615   SetValue(&I, R, SF);
616 }
617
618 //===----------------------------------------------------------------------===//
619 //                     Terminator Instruction Implementations
620 //===----------------------------------------------------------------------===//
621
622 static void PerformExitStuff() {
623 #ifdef PROFILE_STRUCTURE_FIELDS
624   // Print out structure field accounting information...
625   if (!FieldAccessCounts.empty()) {
626     CW << "Profile Field Access Counts:\n";
627     std::map<const StructType *, vector<unsigned> >::iterator 
628       I = FieldAccessCounts.begin(), E = FieldAccessCounts.end();
629     for (; I != E; ++I) {
630       vector<unsigned> &OfC = I->second;
631       CW << "  '" << (Value*)I->first << "'\t- Sum=";
632       
633       unsigned Sum = 0;
634       for (unsigned i = 0; i < OfC.size(); ++i)
635         Sum += OfC[i];
636       CW << Sum << " - ";
637       
638       for (unsigned i = 0; i < OfC.size(); ++i) {
639         if (i) CW << ", ";
640         CW << OfC[i];
641       }
642       CW << "\n";
643     }
644     CW << "\n";
645
646     CW << "Profile Field Access Percentages:\n";
647     cout.precision(3);
648     for (I = FieldAccessCounts.begin(); I != E; ++I) {
649       vector<unsigned> &OfC = I->second;
650       unsigned Sum = 0;
651       for (unsigned i = 0; i < OfC.size(); ++i)
652         Sum += OfC[i];
653       
654       CW << "  '" << (Value*)I->first << "'\t- ";
655       for (unsigned i = 0; i < OfC.size(); ++i) {
656         if (i) CW << ", ";
657         CW << double(OfC[i])/Sum;
658       }
659       CW << "\n";
660     }
661     CW << "\n";
662
663     FieldAccessCounts.clear();
664   }
665 #endif
666 }
667
668 void Interpreter::exitCalled(GenericValue GV) {
669   if (!QuietMode) {
670     cout << "Program returned ";
671     print(Type::IntTy, GV);
672     cout << " via 'void exit(int)'\n";
673   }
674
675   ExitCode = GV.SByteVal;
676   ECStack.clear();
677   PerformExitStuff();
678 }
679
680 void Interpreter::executeRetInst(ReturnInst &I, ExecutionContext &SF) {
681   const Type *RetTy = 0;
682   GenericValue Result;
683
684   // Save away the return value... (if we are not 'ret void')
685   if (I.getNumOperands()) {
686     RetTy  = I.getReturnValue()->getType();
687     Result = getOperandValue(I.getReturnValue(), SF);
688   }
689
690   // Save previously executing meth
691   const Function *M = ECStack.back().CurMethod;
692
693   // Pop the current stack frame... this invalidates SF
694   ECStack.pop_back();
695
696   if (ECStack.empty()) {  // Finished main.  Put result into exit code...
697     if (RetTy) {          // Nonvoid return type?
698       if (!QuietMode) {
699         CW << "Function " << M->getType() << " \"" << M->getName()
700            << "\" returned ";
701         print(RetTy, Result);
702         cout << "\n";
703       }
704
705       if (RetTy->isIntegral())
706         ExitCode = Result.IntVal;   // Capture the exit code of the program
707     } else {
708       ExitCode = 0;
709     }
710
711     PerformExitStuff();
712     return;
713   }
714
715   // If we have a previous stack frame, and we have a previous call, fill in
716   // the return value...
717   //
718   ExecutionContext &NewSF = ECStack.back();
719   if (NewSF.Caller) {
720     if (NewSF.Caller->getType() != Type::VoidTy)             // Save result...
721       SetValue(NewSF.Caller, Result, NewSF);
722
723     NewSF.Caller = 0;          // We returned from the call...
724   } else if (!QuietMode) {
725     // This must be a function that is executing because of a user 'call'
726     // instruction.
727     CW << "Function " << M->getType() << " \"" << M->getName()
728        << "\" returned ";
729     print(RetTy, Result);
730     cout << "\n";
731   }
732 }
733
734 void Interpreter::executeBrInst(BranchInst &I, ExecutionContext &SF) {
735   SF.PrevBB = SF.CurBB;               // Update PrevBB so that PHI nodes work...
736   BasicBlock *Dest;
737
738   Dest = I.getSuccessor(0);          // Uncond branches have a fixed dest...
739   if (!I.isUnconditional()) {
740     Value *Cond = I.getCondition();
741     GenericValue CondVal = getOperandValue(Cond, SF);
742     if (CondVal.BoolVal == 0) // If false cond...
743       Dest = I.getSuccessor(1);    
744   }
745   SF.CurBB   = Dest;                  // Update CurBB to branch destination
746   SF.CurInst = SF.CurBB->begin();     // Update new instruction ptr...
747 }
748
749 //===----------------------------------------------------------------------===//
750 //                     Memory Instruction Implementations
751 //===----------------------------------------------------------------------===//
752
753 void Interpreter::executeAllocInst(AllocationInst &I, ExecutionContext &SF) {
754   const Type *Ty = I.getType()->getElementType();  // Type to be allocated
755
756   // Get the number of elements being allocated by the array...
757   unsigned NumElements = getOperandValue(I.getOperand(0), SF).UIntVal;
758
759   // Allocate enough memory to hold the type...
760   // FIXME: Don't use CALLOC, use a tainted malloc.
761   void *Memory = calloc(NumElements, TD.getTypeSize(Ty));
762
763   GenericValue Result;
764   Result.PointerVal = (PointerTy)Memory;
765   assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
766   SetValue(&I, Result, SF);
767
768   if (I.getOpcode() == Instruction::Alloca)
769     ECStack.back().Allocas.add(Memory);
770 }
771
772 static void executeFreeInst(FreeInst &I, ExecutionContext &SF) {
773   assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
774   GenericValue Value = getOperandValue(I.getOperand(0), SF);
775   // TODO: Check to make sure memory is allocated
776   free((void*)Value.PointerVal);   // Free memory
777 }
778
779
780 // getElementOffset - The workhorse for getelementptr.
781 //
782 static GenericValue executeGEPOperation(Value *Ptr, User::op_iterator I,
783                                         User::op_iterator E,
784                                         ExecutionContext &SF) {
785   assert(isa<PointerType>(Ptr->getType()) &&
786          "Cannot getElementOffset of a nonpointer type!");
787
788   PointerTy Total = 0;
789   const Type *Ty = Ptr->getType();
790
791   for (; I != E; ++I) {
792     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
793       const StructLayout *SLO = TD.getStructLayout(STy);
794       
795       // Indicies must be ubyte constants...
796       const ConstantUInt *CPU = cast<ConstantUInt>(*I);
797       assert(CPU->getType() == Type::UByteTy);
798       unsigned Index = CPU->getValue();
799       
800 #ifdef PROFILE_STRUCTURE_FIELDS
801       if (ProfileStructureFields) {
802         // Do accounting for this field...
803         vector<unsigned> &OfC = FieldAccessCounts[STy];
804         if (OfC.size() == 0) OfC.resize(STy->getElementTypes().size());
805         OfC[Index]++;
806       }
807 #endif
808       
809       Total += SLO->MemberOffsets[Index];
810       Ty = STy->getElementTypes()[Index];
811     } else if (const SequentialType *ST = cast<SequentialType>(Ty)) {
812
813       // Get the index number for the array... which must be uint type...
814       assert((*I)->getType() == Type::LongTy);
815       unsigned Idx = getOperandValue(*I, SF).LongVal;
816       if (const ArrayType *AT = dyn_cast<ArrayType>(ST))
817         if (Idx >= AT->getNumElements() && ArrayChecksEnabled) {
818           cerr << "Out of range memory access to element #" << Idx
819                << " of a " << AT->getNumElements() << " element array."
820                << " Subscript #" << *I << "\n";
821           // Get outta here!!!
822           siglongjmp(SignalRecoverBuffer, SIGTRAP);
823         }
824
825       Ty = ST->getElementType();
826       unsigned Size = TD.getTypeSize(Ty);
827       Total += Size*Idx;
828     }  
829   }
830
831   GenericValue Result;
832   Result.PointerVal = getOperandValue(Ptr, SF).PointerVal + Total;
833   return Result;
834 }
835
836 static void executeGEPInst(GetElementPtrInst &I, ExecutionContext &SF) {
837   SetValue(&I, executeGEPOperation(I.getPointerOperand(),
838                                    I.idx_begin(), I.idx_end(), SF), SF);
839 }
840
841 static void executeLoadInst(LoadInst &I, ExecutionContext &SF) {
842   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
843   GenericValue *Ptr = (GenericValue*)SRC.PointerVal;
844   GenericValue Result;
845
846   if (TD.isLittleEndian()) {
847     switch (I.getType()->getPrimitiveID()) {
848     case Type::BoolTyID:
849     case Type::UByteTyID:
850     case Type::SByteTyID:   Result.UByteVal = Ptr->Untyped[0]; break;
851     case Type::UShortTyID:
852     case Type::ShortTyID:   Result.UShortVal = (unsigned)Ptr->Untyped[0] |
853                                               ((unsigned)Ptr->Untyped[1] << 8);
854                             break;
855     case Type::FloatTyID:
856     case Type::UIntTyID:
857     case Type::IntTyID:     Result.UIntVal = (unsigned)Ptr->Untyped[0] |
858                                             ((unsigned)Ptr->Untyped[1] <<  8) |
859                                             ((unsigned)Ptr->Untyped[2] << 16) |
860                                             ((unsigned)Ptr->Untyped[3] << 24);
861                             break;
862     case Type::DoubleTyID:
863     case Type::ULongTyID:
864     case Type::LongTyID:    
865     case Type::PointerTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
866                                              ((uint64_t)Ptr->Untyped[1] <<  8) |
867                                              ((uint64_t)Ptr->Untyped[2] << 16) |
868                                              ((uint64_t)Ptr->Untyped[3] << 24) |
869                                              ((uint64_t)Ptr->Untyped[4] << 32) |
870                                              ((uint64_t)Ptr->Untyped[5] << 40) |
871                                              ((uint64_t)Ptr->Untyped[6] << 48) |
872                                              ((uint64_t)Ptr->Untyped[7] << 56);
873                             break;
874     default:
875       cout << "Cannot load value of type " << I.getType() << "!\n";
876     }
877   } else {
878     switch (I.getType()->getPrimitiveID()) {
879     case Type::BoolTyID:
880     case Type::UByteTyID:
881     case Type::SByteTyID:   Result.UByteVal = Ptr->Untyped[0]; break;
882     case Type::UShortTyID:
883     case Type::ShortTyID:   Result.UShortVal = (unsigned)Ptr->Untyped[1] |
884                                               ((unsigned)Ptr->Untyped[0] << 8);
885                             break;
886     case Type::FloatTyID:
887     case Type::UIntTyID:
888     case Type::IntTyID:     Result.UIntVal = (unsigned)Ptr->Untyped[3] |
889                                             ((unsigned)Ptr->Untyped[2] <<  8) |
890                                             ((unsigned)Ptr->Untyped[1] << 16) |
891                                             ((unsigned)Ptr->Untyped[0] << 24);
892                             break;
893     case Type::DoubleTyID:
894     case Type::ULongTyID:
895     case Type::LongTyID:    
896     case Type::PointerTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
897                                              ((uint64_t)Ptr->Untyped[6] <<  8) |
898                                              ((uint64_t)Ptr->Untyped[5] << 16) |
899                                              ((uint64_t)Ptr->Untyped[4] << 24) |
900                                              ((uint64_t)Ptr->Untyped[3] << 32) |
901                                              ((uint64_t)Ptr->Untyped[2] << 40) |
902                                              ((uint64_t)Ptr->Untyped[1] << 48) |
903                                              ((uint64_t)Ptr->Untyped[0] << 56);
904                             break;
905     default:
906       cout << "Cannot load value of type " << I.getType() << "!\n";
907     }
908   }
909
910   SetValue(&I, Result, SF);
911 }
912
913 static void StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
914                                const Type *Ty) {
915   if (TD.isLittleEndian()) {
916     switch (Ty->getPrimitiveID()) {
917     case Type::BoolTyID:
918     case Type::UByteTyID:
919     case Type::SByteTyID:   Ptr->Untyped[0] = Val.UByteVal; break;
920     case Type::UShortTyID:
921     case Type::ShortTyID:   Ptr->Untyped[0] = Val.UShortVal & 255;
922                             Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
923                             break;
924     case Type::FloatTyID:
925     case Type::UIntTyID:
926     case Type::IntTyID:     Ptr->Untyped[0] =  Val.UIntVal        & 255;
927                             Ptr->Untyped[1] = (Val.UIntVal >>  8) & 255;
928                             Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
929                             Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
930                             break;
931     case Type::DoubleTyID:
932     case Type::ULongTyID:
933     case Type::LongTyID:    
934     case Type::PointerTyID: Ptr->Untyped[0] =  Val.ULongVal        & 255;
935                             Ptr->Untyped[1] = (Val.ULongVal >>  8) & 255;
936                             Ptr->Untyped[2] = (Val.ULongVal >> 16) & 255;
937                             Ptr->Untyped[3] = (Val.ULongVal >> 24) & 255;
938                             Ptr->Untyped[4] = (Val.ULongVal >> 32) & 255;
939                             Ptr->Untyped[5] = (Val.ULongVal >> 40) & 255;
940                             Ptr->Untyped[6] = (Val.ULongVal >> 48) & 255;
941                             Ptr->Untyped[7] = (Val.ULongVal >> 56) & 255;
942                             break;
943     default:
944       cout << "Cannot store value of type " << Ty << "!\n";
945     }
946   } else {
947     switch (Ty->getPrimitiveID()) {
948     case Type::BoolTyID:
949     case Type::UByteTyID:
950     case Type::SByteTyID:   Ptr->Untyped[0] = Val.UByteVal; break;
951     case Type::UShortTyID:
952     case Type::ShortTyID:   Ptr->Untyped[1] = Val.UShortVal & 255;
953                             Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
954                             break;
955     case Type::FloatTyID:
956     case Type::UIntTyID:
957     case Type::IntTyID:     Ptr->Untyped[3] =  Val.UIntVal        & 255;
958                             Ptr->Untyped[2] = (Val.UIntVal >>  8) & 255;
959                             Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
960                             Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
961                             break;
962     case Type::DoubleTyID:
963     case Type::ULongTyID:
964     case Type::LongTyID:    
965     case Type::PointerTyID: Ptr->Untyped[7] =  Val.ULongVal        & 255;
966                             Ptr->Untyped[6] = (Val.ULongVal >>  8) & 255;
967                             Ptr->Untyped[5] = (Val.ULongVal >> 16) & 255;
968                             Ptr->Untyped[4] = (Val.ULongVal >> 24) & 255;
969                             Ptr->Untyped[3] = (Val.ULongVal >> 32) & 255;
970                             Ptr->Untyped[2] = (Val.ULongVal >> 40) & 255;
971                             Ptr->Untyped[1] = (Val.ULongVal >> 48) & 255;
972                             Ptr->Untyped[0] = (Val.ULongVal >> 56) & 255;
973                             break;
974     default:
975       cout << "Cannot store value of type " << Ty << "!\n";
976     }
977   }
978 }
979
980 static void executeStoreInst(StoreInst &I, ExecutionContext &SF) {
981   GenericValue Val = getOperandValue(I.getOperand(0), SF);
982   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
983   StoreValueToMemory(Val, (GenericValue *)SRC.PointerVal,
984                      I.getOperand(0)->getType());
985 }
986
987
988 GenericValue Interpreter::CreateArgv(const std::vector<std::string> &InputArgv){
989   // Pointers are 64 bits...
990   PointerTy *Result = new PointerTy[InputArgv.size()+1];  // 64 bit assumption
991
992   for (unsigned i = 0; i < InputArgv.size(); ++i) {
993     unsigned Size = InputArgv[i].size()+1;
994     char *Dest = new char[Size];
995     copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
996     Dest[Size-1] = 0;
997
998     GenericValue GV; GV.PointerVal = (PointerTy)Dest;
999     // Endian safe: Result[i] = (PointerTy)Dest;
1000     StoreValueToMemory(GV, (GenericValue*)(Result+i),
1001                        Type::LongTy);  // 64 bit assumption
1002   }
1003
1004   Result[InputArgv.size()] = 0;
1005   GenericValue GV; GV.PointerVal = (PointerTy)Result;
1006   return GV;
1007 }
1008
1009
1010 //===----------------------------------------------------------------------===//
1011 //                 Miscellaneous Instruction Implementations
1012 //===----------------------------------------------------------------------===//
1013
1014 void Interpreter::executeCallInst(CallInst &I, ExecutionContext &SF) {
1015   ECStack.back().Caller = &I;
1016   vector<GenericValue> ArgVals;
1017   ArgVals.reserve(I.getNumOperands()-1);
1018   for (unsigned i = 1; i < I.getNumOperands(); ++i)
1019     ArgVals.push_back(getOperandValue(I.getOperand(i), SF));
1020
1021   // To handle indirect calls, we must get the pointer value from the argument 
1022   // and treat it as a function pointer.
1023   GenericValue SRC = getOperandValue(I.getCalledValue(), SF);
1024   
1025   callMethod((Function*)SRC.PointerVal, ArgVals);
1026 }
1027
1028 static void executePHINode(PHINode &I, ExecutionContext &SF) {
1029   BasicBlock *PrevBB = SF.PrevBB;
1030   Value *IncomingValue = 0;
1031
1032   // Search for the value corresponding to this previous bb...
1033   for (unsigned i = I.getNumIncomingValues(); i > 0;) {
1034     if (I.getIncomingBlock(--i) == PrevBB) {
1035       IncomingValue = I.getIncomingValue(i);
1036       break;
1037     }
1038   }
1039   assert(IncomingValue && "No PHI node predecessor for current PrevBB!");
1040
1041   // Found the value, set as the result...
1042   SetValue(&I, getOperandValue(IncomingValue, SF), SF);
1043 }
1044
1045 #define IMPLEMENT_SHIFT(OP, TY) \
1046    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
1047
1048 static void executeShlInst(ShiftInst &I, ExecutionContext &SF) {
1049   const Type *Ty    = I.getOperand(0)->getType();
1050   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
1051   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
1052   GenericValue Dest;
1053
1054   switch (Ty->getPrimitiveID()) {
1055     IMPLEMENT_SHIFT(<<, UByte);
1056     IMPLEMENT_SHIFT(<<, SByte);
1057     IMPLEMENT_SHIFT(<<, UShort);
1058     IMPLEMENT_SHIFT(<<, Short);
1059     IMPLEMENT_SHIFT(<<, UInt);
1060     IMPLEMENT_SHIFT(<<, Int);
1061     IMPLEMENT_SHIFT(<<, ULong);
1062     IMPLEMENT_SHIFT(<<, Long);
1063     IMPLEMENT_SHIFT(<<, Pointer);
1064   default:
1065     cout << "Unhandled type for Shl instruction: " << Ty << "\n";
1066   }
1067   SetValue(&I, Dest, SF);
1068 }
1069
1070 static void executeShrInst(ShiftInst &I, ExecutionContext &SF) {
1071   const Type *Ty    = I.getOperand(0)->getType();
1072   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
1073   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
1074   GenericValue Dest;
1075
1076   switch (Ty->getPrimitiveID()) {
1077     IMPLEMENT_SHIFT(>>, UByte);
1078     IMPLEMENT_SHIFT(>>, SByte);
1079     IMPLEMENT_SHIFT(>>, UShort);
1080     IMPLEMENT_SHIFT(>>, Short);
1081     IMPLEMENT_SHIFT(>>, UInt);
1082     IMPLEMENT_SHIFT(>>, Int);
1083     IMPLEMENT_SHIFT(>>, ULong);
1084     IMPLEMENT_SHIFT(>>, Long);
1085     IMPLEMENT_SHIFT(>>, Pointer);
1086   default:
1087     cout << "Unhandled type for Shr instruction: " << Ty << "\n";
1088   }
1089   SetValue(&I, Dest, SF);
1090 }
1091
1092 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
1093    case Type::STY##TyID: Dest.DTY##Val = DCTY Src.STY##Val; break;
1094
1095 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY)    \
1096   case Type::DESTTY##TyID:                      \
1097     switch (SrcTy->getPrimitiveID()) {          \
1098       IMPLEMENT_CAST(DESTTY, DESTCTY, Bool);    \
1099       IMPLEMENT_CAST(DESTTY, DESTCTY, UByte);   \
1100       IMPLEMENT_CAST(DESTTY, DESTCTY, SByte);   \
1101       IMPLEMENT_CAST(DESTTY, DESTCTY, UShort);  \
1102       IMPLEMENT_CAST(DESTTY, DESTCTY, Short);   \
1103       IMPLEMENT_CAST(DESTTY, DESTCTY, UInt);    \
1104       IMPLEMENT_CAST(DESTTY, DESTCTY, Int);     \
1105       IMPLEMENT_CAST(DESTTY, DESTCTY, ULong);   \
1106       IMPLEMENT_CAST(DESTTY, DESTCTY, Long);    \
1107       IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
1108
1109 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
1110       IMPLEMENT_CAST(DESTTY, DESTCTY, Float);   \
1111       IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
1112
1113 #define IMPLEMENT_CAST_CASE_END()    \
1114     default: cout << "Unhandled cast: " << SrcTy << " to " << Ty << "\n";  \
1115       break;                                    \
1116     }                                           \
1117     break
1118
1119 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
1120    IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY);   \
1121    IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
1122    IMPLEMENT_CAST_CASE_END()
1123
1124 static GenericValue executeCastOperation(Value *SrcVal, const Type *Ty,
1125                                          ExecutionContext &SF) {
1126   const Type *SrcTy = SrcVal->getType();
1127   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1128
1129   switch (Ty->getPrimitiveID()) {
1130     IMPLEMENT_CAST_CASE(UByte  , (unsigned char));
1131     IMPLEMENT_CAST_CASE(SByte  , (  signed char));
1132     IMPLEMENT_CAST_CASE(UShort , (unsigned short));
1133     IMPLEMENT_CAST_CASE(Short  , (  signed short));
1134     IMPLEMENT_CAST_CASE(UInt   , (unsigned int ));
1135     IMPLEMENT_CAST_CASE(Int    , (  signed int ));
1136     IMPLEMENT_CAST_CASE(ULong  , (uint64_t));
1137     IMPLEMENT_CAST_CASE(Long   , ( int64_t));
1138     IMPLEMENT_CAST_CASE(Pointer, (PointerTy));
1139     IMPLEMENT_CAST_CASE(Float  , (float));
1140     IMPLEMENT_CAST_CASE(Double , (double));
1141   default:
1142     cout << "Unhandled dest type for cast instruction: " << Ty << "\n";
1143   }
1144
1145   return Dest;
1146 }
1147
1148
1149 static void executeCastInst(CastInst &I, ExecutionContext &SF) {
1150   SetValue(&I, executeCastOperation(I.getOperand(0), I.getType(), SF), SF);
1151 }
1152
1153
1154 //===----------------------------------------------------------------------===//
1155 //                        Dispatch and Execution Code
1156 //===----------------------------------------------------------------------===//
1157
1158 MethodInfo::MethodInfo(Function *F) : Annotation(MethodInfoAID) {
1159   // Assign slot numbers to the function arguments...
1160   for (Function::const_aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
1161     AI->addAnnotation(new SlotNumber(getValueSlot(AI)));
1162
1163   // Iterate over all of the instructions...
1164   unsigned InstNum = 0;
1165   for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
1166     for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II)
1167       // For each instruction... Add Annote
1168       II->addAnnotation(new InstNumber(++InstNum, getValueSlot(II)));
1169 }
1170
1171 unsigned MethodInfo::getValueSlot(const Value *V) {
1172   unsigned Plane = V->getType()->getUniqueID();
1173   if (Plane >= NumPlaneElements.size())
1174     NumPlaneElements.resize(Plane+1, 0);
1175   return NumPlaneElements[Plane]++;
1176 }
1177
1178
1179 //===----------------------------------------------------------------------===//
1180 // callMethod - Execute the specified function...
1181 //
1182 void Interpreter::callMethod(Function *M, const vector<GenericValue> &ArgVals) {
1183   assert((ECStack.empty() || ECStack.back().Caller == 0 || 
1184           ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
1185          "Incorrect number of arguments passed into function call!");
1186   if (M->isExternal()) {
1187     GenericValue Result = callExternalMethod(M, ArgVals);
1188     const Type *RetTy = M->getReturnType();
1189
1190     // Copy the result back into the result variable if we are not returning
1191     // void.
1192     if (RetTy != Type::VoidTy) {
1193       if (!ECStack.empty() && ECStack.back().Caller) {
1194         ExecutionContext &SF = ECStack.back();
1195         SetValue(SF.Caller, Result, SF);
1196       
1197         SF.Caller = 0;          // We returned from the call...
1198       } else if (!QuietMode) {
1199         // print it.
1200         CW << "Function " << M->getType() << " \"" << M->getName()
1201            << "\" returned ";
1202         print(RetTy, Result); 
1203         cout << "\n";
1204         
1205         if (RetTy->isIntegral())
1206           ExitCode = Result.IntVal;   // Capture the exit code of the program
1207       }
1208     }
1209
1210     return;
1211   }
1212
1213   // Process the function, assigning instruction numbers to the instructions in
1214   // the function.  Also calculate the number of values for each type slot
1215   // active.
1216   //
1217   MethodInfo *MethInfo = (MethodInfo*)M->getOrCreateAnnotation(MethodInfoAID);
1218   ECStack.push_back(ExecutionContext());         // Make a new stack frame...
1219
1220   ExecutionContext &StackFrame = ECStack.back(); // Fill it in...
1221   StackFrame.CurMethod = M;
1222   StackFrame.CurBB     = M->begin();
1223   StackFrame.CurInst   = StackFrame.CurBB->begin();
1224   StackFrame.MethInfo  = MethInfo;
1225
1226   // Initialize the values to nothing...
1227   StackFrame.Values.resize(MethInfo->NumPlaneElements.size());
1228   for (unsigned i = 0; i < MethInfo->NumPlaneElements.size(); ++i) {
1229     StackFrame.Values[i].resize(MethInfo->NumPlaneElements[i]);
1230
1231     // Taint the initial values of stuff
1232     memset(&StackFrame.Values[i][0], 42,
1233            MethInfo->NumPlaneElements[i]*sizeof(GenericValue));
1234   }
1235
1236   StackFrame.PrevBB = 0;  // No previous BB for PHI nodes...
1237
1238
1239   // Run through the function arguments and initialize their values...
1240   assert(ArgVals.size() == M->asize() &&
1241          "Invalid number of values passed to function invocation!");
1242   unsigned i = 0;
1243   for (Function::aiterator AI = M->abegin(), E = M->aend(); AI != E; ++AI, ++i)
1244     SetValue(AI, ArgVals[i], StackFrame);
1245 }
1246
1247 // executeInstruction - Interpret a single instruction, increment the "PC", and
1248 // return true if the next instruction is a breakpoint...
1249 //
1250 bool Interpreter::executeInstruction() {
1251   assert(!ECStack.empty() && "No program running, cannot execute inst!");
1252
1253   ExecutionContext &SF = ECStack.back();  // Current stack frame
1254   Instruction &I = *SF.CurInst++;         // Increment before execute
1255
1256   if (Trace)
1257     CW << "Run:" << I;
1258
1259   // Track the number of dynamic instructions executed.
1260   ++NumDynamicInsts;
1261
1262   // Set a sigsetjmp buffer so that we can recover if an error happens during
1263   // instruction execution...
1264   //
1265   if (int SigNo = sigsetjmp(SignalRecoverBuffer, 1)) {
1266     --SF.CurInst;   // Back up to erroring instruction
1267     if (SigNo != SIGINT) {
1268       cout << "EXCEPTION OCCURRED [" << strsignal(SigNo) << "]:\n";
1269       printStackTrace();
1270       // If -abort-on-exception was specified, terminate LLI instead of trying
1271       // to debug it.
1272       //
1273       if (AbortOnExceptions) exit(1);
1274     } else if (SigNo == SIGINT) {
1275       cout << "CTRL-C Detected, execution halted.\n";
1276     }
1277     InInstruction = false;
1278     return true;
1279   }
1280
1281   InInstruction = true;
1282   if (I.isBinaryOp()) {
1283     executeBinaryInst(cast<BinaryOperator>(I), SF);
1284   } else {
1285     switch (I.getOpcode()) {
1286       // Terminators
1287     case Instruction::Ret:     executeRetInst  (cast<ReturnInst>(I), SF); break;
1288     case Instruction::Br:      executeBrInst   (cast<BranchInst>(I), SF); break;
1289       // Memory Instructions
1290     case Instruction::Alloca:
1291     case Instruction::Malloc:  executeAllocInst((AllocationInst&)I, SF); break;
1292     case Instruction::Free:    executeFreeInst (cast<FreeInst> (I), SF); break;
1293     case Instruction::Load:    executeLoadInst (cast<LoadInst> (I), SF); break;
1294     case Instruction::Store:   executeStoreInst(cast<StoreInst>(I), SF); break;
1295     case Instruction::GetElementPtr:
1296                           executeGEPInst(cast<GetElementPtrInst>(I), SF); break;
1297
1298       // Miscellaneous Instructions
1299     case Instruction::Call:    executeCallInst (cast<CallInst> (I), SF); break;
1300     case Instruction::PHINode: executePHINode  (cast<PHINode>  (I), SF); break;
1301     case Instruction::Shl:     executeShlInst  (cast<ShiftInst>(I), SF); break;
1302     case Instruction::Shr:     executeShrInst  (cast<ShiftInst>(I), SF); break;
1303     case Instruction::Cast:    executeCastInst (cast<CastInst> (I), SF); break;
1304     default:
1305       cout << "Don't know how to execute this instruction!\n-->" << I;
1306     }
1307   }
1308   InInstruction = false;
1309   
1310   // Reset the current frame location to the top of stack
1311   CurFrame = ECStack.size()-1;
1312
1313   if (CurFrame == -1) return false;  // No breakpoint if no code
1314
1315   // Return true if there is a breakpoint annotation on the instruction...
1316   return ECStack[CurFrame].CurInst->getAnnotation(BreakpointAID) != 0;
1317 }
1318
1319 void Interpreter::stepInstruction() {  // Do the 'step' command
1320   if (ECStack.empty()) {
1321     cout << "Error: no program running, cannot step!\n";
1322     return;
1323   }
1324
1325   // Run an instruction...
1326   executeInstruction();
1327
1328   // Print the next instruction to execute...
1329   printCurrentInstruction();
1330 }
1331
1332 // --- UI Stuff...
1333 void Interpreter::nextInstruction() {  // Do the 'next' command
1334   if (ECStack.empty()) {
1335     cout << "Error: no program running, cannot 'next'!\n";
1336     return;
1337   }
1338
1339   // If this is a call instruction, step over the call instruction...
1340   // TODO: ICALL, CALL WITH, ...
1341   if (ECStack.back().CurInst->getOpcode() == Instruction::Call) {
1342     unsigned StackSize = ECStack.size();
1343     // Step into the function...
1344     if (executeInstruction()) {
1345       // Hit a breakpoint, print current instruction, then return to user...
1346       cout << "Breakpoint hit!\n";
1347       printCurrentInstruction();
1348       return;
1349     }
1350
1351     // If we we able to step into the function, finish it now.  We might not be
1352     // able the step into a function, if it's external for example.
1353     if (ECStack.size() != StackSize)
1354       finish(); // Finish executing the function...
1355     else
1356       printCurrentInstruction();
1357
1358   } else {
1359     // Normal instruction, just step...
1360     stepInstruction();
1361   }
1362 }
1363
1364 void Interpreter::run() {
1365   if (ECStack.empty()) {
1366     cout << "Error: no program running, cannot run!\n";
1367     return;
1368   }
1369
1370   bool HitBreakpoint = false;
1371   while (!ECStack.empty() && !HitBreakpoint) {
1372     // Run an instruction...
1373     HitBreakpoint = executeInstruction();
1374   }
1375
1376   if (HitBreakpoint) {
1377     cout << "Breakpoint hit!\n";
1378   }
1379   // Print the next instruction to execute...
1380   printCurrentInstruction();
1381 }
1382
1383 void Interpreter::finish() {
1384   if (ECStack.empty()) {
1385     cout << "Error: no program running, cannot run!\n";
1386     return;
1387   }
1388
1389   unsigned StackSize = ECStack.size();
1390   bool HitBreakpoint = false;
1391   while (ECStack.size() >= StackSize && !HitBreakpoint) {
1392     // Run an instruction...
1393     HitBreakpoint = executeInstruction();
1394   }
1395
1396   if (HitBreakpoint) {
1397     cout << "Breakpoint hit!\n";
1398   }
1399
1400   // Print the next instruction to execute...
1401   printCurrentInstruction();
1402 }
1403
1404
1405
1406 // printCurrentInstruction - Print out the instruction that the virtual PC is
1407 // at, or fail silently if no program is running.
1408 //
1409 void Interpreter::printCurrentInstruction() {
1410   if (!ECStack.empty()) {
1411     if (ECStack.back().CurBB->begin() == ECStack.back().CurInst)  // print label
1412       WriteAsOperand(cout, ECStack.back().CurBB) << ":\n";
1413
1414     Instruction &I = *ECStack.back().CurInst;
1415     InstNumber *IN = (InstNumber*)I.getAnnotation(SlotNumberAID);
1416     assert(IN && "Instruction has no numbering annotation!");
1417     cout << "#" << IN->InstNum << I;
1418   }
1419 }
1420
1421 void Interpreter::printValue(const Type *Ty, GenericValue V) {
1422   switch (Ty->getPrimitiveID()) {
1423   case Type::BoolTyID:   cout << (V.BoolVal?"true":"false"); break;
1424   case Type::SByteTyID:
1425     cout << (int)V.SByteVal << " '" << V.SByteVal << "'";  break;
1426   case Type::UByteTyID:
1427     cout << (unsigned)V.UByteVal << " '" << V.UByteVal << "'";  break;
1428   case Type::ShortTyID:  cout << V.ShortVal;  break;
1429   case Type::UShortTyID: cout << V.UShortVal; break;
1430   case Type::IntTyID:    cout << V.IntVal;    break;
1431   case Type::UIntTyID:   cout << V.UIntVal;   break;
1432   case Type::LongTyID:   cout << (long)V.LongVal;   break;
1433   case Type::ULongTyID:  cout << (unsigned long)V.ULongVal;  break;
1434   case Type::FloatTyID:  cout << V.FloatVal;  break;
1435   case Type::DoubleTyID: cout << V.DoubleVal; break;
1436   case Type::PointerTyID:cout << (void*)V.PointerVal; break;
1437   default:
1438     cout << "- Don't know how to print value of this type!";
1439     break;
1440   }
1441 }
1442
1443 void Interpreter::print(const Type *Ty, GenericValue V) {
1444   CW << Ty << " ";
1445   printValue(Ty, V);
1446 }
1447
1448 void Interpreter::print(const std::string &Name) {
1449   Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1450   if (!PickedVal) return;
1451
1452   if (const Function *F = dyn_cast<const Function>(PickedVal)) {
1453     CW << F;  // Print the function
1454   } else if (const Type *Ty = dyn_cast<const Type>(PickedVal)) {
1455     CW << "type %" << Name << " = " << Ty->getDescription() << "\n";
1456   } else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(PickedVal)) {
1457     CW << BB;   // Print the basic block
1458   } else {      // Otherwise there should be an annotation for the slot#
1459     print(PickedVal->getType(), 
1460           getOperandValue(PickedVal, ECStack[CurFrame]));
1461     cout << "\n";
1462   }
1463 }
1464
1465 void Interpreter::infoValue(const std::string &Name) {
1466   Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1467   if (!PickedVal) return;
1468
1469   cout << "Value: ";
1470   print(PickedVal->getType(), 
1471         getOperandValue(PickedVal, ECStack[CurFrame]));
1472   cout << "\n";
1473   printOperandInfo(PickedVal, ECStack[CurFrame]);
1474 }
1475
1476 // printStackFrame - Print information about the specified stack frame, or -1
1477 // for the default one.
1478 //
1479 void Interpreter::printStackFrame(int FrameNo) {
1480   if (FrameNo == -1) FrameNo = CurFrame;
1481   Function *F = ECStack[FrameNo].CurMethod;
1482   const Type *RetTy = F->getReturnType();
1483
1484   CW << ((FrameNo == CurFrame) ? '>' : '-') << "#" << FrameNo << ". "
1485      << (Value*)RetTy << " \"" << F->getName() << "\"(";
1486   
1487   unsigned i = 0;
1488   for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++i) {
1489     if (i != 0) cout << ", ";
1490     CW << *I << "=";
1491     
1492     printValue(I->getType(), getOperandValue(I, ECStack[FrameNo]));
1493   }
1494
1495   cout << ")\n";
1496
1497   if (FrameNo != int(ECStack.size()-1)) {
1498     BasicBlock::iterator I = ECStack[FrameNo].CurInst;
1499     CW << --I;
1500   } else {
1501     CW << *ECStack[FrameNo].CurInst;
1502   }
1503 }
1504