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