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