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