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