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