Fix testcase: SingleSource/UnitTests/2003-05-02-DependantPHI.c
[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   BasicBlock *Dest;
636
637   Dest = I.getSuccessor(0);          // Uncond branches have a fixed dest...
638   if (!I.isUnconditional()) {
639     Value *Cond = I.getCondition();
640     if (getOperandValue(Cond, SF).BoolVal == 0) // If false cond...
641       Dest = I.getSuccessor(1);    
642   }
643   SwitchToNewBasicBlock(Dest, SF);
644 }
645
646 void Interpreter::executeSwitchInst(SwitchInst &I, ExecutionContext &SF) {
647   GenericValue CondVal = getOperandValue(I.getOperand(0), SF);
648   const Type *ElTy = I.getOperand(0)->getType();
649
650   // Check to see if any of the cases match...
651   BasicBlock *Dest = 0;
652   for (unsigned i = 2, e = I.getNumOperands(); i != e; i += 2)
653     if (executeSetEQInst(CondVal,
654                          getOperandValue(I.getOperand(i), SF), ElTy).BoolVal) {
655       Dest = cast<BasicBlock>(I.getOperand(i+1));
656       break;
657     }
658   
659   if (!Dest) Dest = I.getDefaultDest();   // No cases matched: use default
660   SwitchToNewBasicBlock(Dest, SF);
661 }
662
663 // SwitchToNewBasicBlock - This method is used to jump to a new basic block.
664 // This function handles the actual updating of block and instruction iterators
665 // as well as execution of all of the PHI nodes in the destination block.
666 //
667 // This method does this because all of the PHI nodes must be executed
668 // atomically, reading their inputs before any of the results are updated.  Not
669 // doing this can cause problems if the PHI nodes depend on other PHI nodes for
670 // their inputs.  If the input PHI node is updated before it is read, incorrect
671 // results can happen.  Thus we use a two phase approach.
672 //
673 void Interpreter::SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF){
674   BasicBlock *PrevBB = SF.CurBB;      // Remember where we came from...
675   SF.CurBB   = Dest;                  // Update CurBB to branch destination
676   SF.CurInst = SF.CurBB->begin();     // Update new instruction ptr...
677
678   if (!isa<PHINode>(SF.CurInst)) return;  // Nothing fancy to do
679
680   // Loop over all of the PHI nodes in the current block, reading their inputs.
681   std::vector<GenericValue> ResultValues;
682
683   for (; PHINode *PN = dyn_cast<PHINode>(SF.CurInst); ++SF.CurInst) {
684     // Search for the value corresponding to this previous bb...
685     int i = PN->getBasicBlockIndex(PrevBB);
686     assert(i != -1 && "PHINode doesn't contain entry for predecessor??");
687     Value *IncomingValue = PN->getIncomingValue(i);
688     
689     // Save the incoming value for this PHI node...
690     ResultValues.push_back(getOperandValue(IncomingValue, SF));
691   }
692
693   // Now loop over all of the PHI nodes setting their values...
694   SF.CurInst = SF.CurBB->begin();
695   for (unsigned i = 0; PHINode *PN = dyn_cast<PHINode>(SF.CurInst);
696        ++SF.CurInst, ++i)
697     SetValue(PN, ResultValues[i], SF);
698 }
699
700
701 //===----------------------------------------------------------------------===//
702 //                     Memory Instruction Implementations
703 //===----------------------------------------------------------------------===//
704
705 void Interpreter::executeAllocInst(AllocationInst &I, ExecutionContext &SF) {
706   const Type *Ty = I.getType()->getElementType();  // Type to be allocated
707
708   // Get the number of elements being allocated by the array...
709   unsigned NumElements = getOperandValue(I.getOperand(0), SF).UIntVal;
710
711   // Allocate enough memory to hold the type...
712   // FIXME: Don't use CALLOC, use a tainted malloc.
713   void *Memory = calloc(NumElements, TD.getTypeSize(Ty));
714
715   GenericValue Result = PTOGV(Memory);
716   assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
717   SetValue(&I, Result, SF);
718
719   if (I.getOpcode() == Instruction::Alloca)
720     ECStack.back().Allocas.add(Memory);
721 }
722
723 static void executeFreeInst(FreeInst &I, ExecutionContext &SF) {
724   assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
725   GenericValue Value = getOperandValue(I.getOperand(0), SF);
726   // TODO: Check to make sure memory is allocated
727   free(GVTOP(Value));   // Free memory
728 }
729
730
731 // getElementOffset - The workhorse for getelementptr.
732 //
733 GenericValue Interpreter::executeGEPOperation(Value *Ptr, User::op_iterator I,
734                                               User::op_iterator E,
735                                               ExecutionContext &SF) {
736   assert(isa<PointerType>(Ptr->getType()) &&
737          "Cannot getElementOffset of a nonpointer type!");
738
739   PointerTy Total = 0;
740   const Type *Ty = Ptr->getType();
741
742   for (; I != E; ++I) {
743     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
744       const StructLayout *SLO = TD.getStructLayout(STy);
745       
746       // Indicies must be ubyte constants...
747       const ConstantUInt *CPU = cast<ConstantUInt>(*I);
748       assert(CPU->getType() == Type::UByteTy);
749       unsigned Index = CPU->getValue();
750       
751 #ifdef PROFILE_STRUCTURE_FIELDS
752       if (ProfileStructureFields) {
753         // Do accounting for this field...
754         std::vector<unsigned> &OfC = FieldAccessCounts[STy];
755         if (OfC.size() == 0) OfC.resize(STy->getElementTypes().size());
756         OfC[Index]++;
757       }
758 #endif
759       
760       Total += SLO->MemberOffsets[Index];
761       Ty = STy->getElementTypes()[Index];
762     } else if (const SequentialType *ST = cast<SequentialType>(Ty)) {
763
764       // Get the index number for the array... which must be long type...
765       assert((*I)->getType() == Type::LongTy);
766       unsigned Idx = getOperandValue(*I, SF).LongVal;
767       if (const ArrayType *AT = dyn_cast<ArrayType>(ST))
768         if (Idx >= AT->getNumElements() && ArrayChecksEnabled) {
769           std::cerr << "Out of range memory access to element #" << Idx
770                     << " of a " << AT->getNumElements() << " element array."
771                     << " Subscript #" << *I << "\n";
772           // Get outta here!!!
773           siglongjmp(SignalRecoverBuffer, SIGTRAP);
774         }
775
776       Ty = ST->getElementType();
777       unsigned Size = TD.getTypeSize(Ty);
778       Total += Size*Idx;
779     }  
780   }
781
782   GenericValue Result;
783   Result.PointerVal = getOperandValue(Ptr, SF).PointerVal + Total;
784   return Result;
785 }
786
787 static void executeGEPInst(GetElementPtrInst &I, ExecutionContext &SF) {
788   SetValue(&I, TheEE->executeGEPOperation(I.getPointerOperand(),
789                                    I.idx_begin(), I.idx_end(), SF), SF);
790 }
791
792 void Interpreter::executeLoadInst(LoadInst &I, ExecutionContext &SF) {
793   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
794   GenericValue *Ptr = (GenericValue*)GVTOP(SRC);
795   GenericValue Result = LoadValueFromMemory(Ptr, I.getType());
796   SetValue(&I, Result, SF);
797 }
798
799 void Interpreter::executeStoreInst(StoreInst &I, ExecutionContext &SF) {
800   GenericValue Val = getOperandValue(I.getOperand(0), SF);
801   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
802   StoreValueToMemory(Val, (GenericValue *)GVTOP(SRC),
803                      I.getOperand(0)->getType());
804 }
805
806
807
808 //===----------------------------------------------------------------------===//
809 //                 Miscellaneous Instruction Implementations
810 //===----------------------------------------------------------------------===//
811
812 void Interpreter::executeCallInst(CallInst &I, ExecutionContext &SF) {
813   ECStack.back().Caller = &I;
814   std::vector<GenericValue> ArgVals;
815   ArgVals.reserve(I.getNumOperands()-1);
816   for (unsigned i = 1; i < I.getNumOperands(); ++i) {
817     ArgVals.push_back(getOperandValue(I.getOperand(i), SF));
818     // Promote all integral types whose size is < sizeof(int) into ints.  We do
819     // this by zero or sign extending the value as appropriate according to the
820     // source type.
821     if (I.getOperand(i)->getType()->isIntegral() &&
822         I.getOperand(i)->getType()->getPrimitiveSize() < 4) {
823       const Type *Ty = I.getOperand(i)->getType();
824       if (Ty == Type::ShortTy)
825         ArgVals.back().IntVal = ArgVals.back().ShortVal;
826       else if (Ty == Type::UShortTy)
827         ArgVals.back().UIntVal = ArgVals.back().UShortVal;
828       else if (Ty == Type::SByteTy)
829         ArgVals.back().IntVal = ArgVals.back().SByteVal;
830       else if (Ty == Type::UByteTy)
831         ArgVals.back().UIntVal = ArgVals.back().UByteVal;
832       else if (Ty == Type::BoolTy)
833         ArgVals.back().UIntVal = ArgVals.back().BoolVal;
834       else
835         assert(0 && "Unknown type!");
836     }
837   }
838
839   // To handle indirect calls, we must get the pointer value from the argument 
840   // and treat it as a function pointer.
841   GenericValue SRC = getOperandValue(I.getCalledValue(), SF);
842   
843   callFunction((Function*)GVTOP(SRC), ArgVals);
844 }
845
846 #define IMPLEMENT_SHIFT(OP, TY) \
847    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
848
849 static void executeShlInst(ShiftInst &I, ExecutionContext &SF) {
850   const Type *Ty    = I.getOperand(0)->getType();
851   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
852   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
853   GenericValue Dest;
854
855   switch (Ty->getPrimitiveID()) {
856     IMPLEMENT_SHIFT(<<, UByte);
857     IMPLEMENT_SHIFT(<<, SByte);
858     IMPLEMENT_SHIFT(<<, UShort);
859     IMPLEMENT_SHIFT(<<, Short);
860     IMPLEMENT_SHIFT(<<, UInt);
861     IMPLEMENT_SHIFT(<<, Int);
862     IMPLEMENT_SHIFT(<<, ULong);
863     IMPLEMENT_SHIFT(<<, Long);
864   default:
865     std::cout << "Unhandled type for Shl instruction: " << *Ty << "\n";
866   }
867   SetValue(&I, Dest, SF);
868 }
869
870 static void executeShrInst(ShiftInst &I, ExecutionContext &SF) {
871   const Type *Ty    = I.getOperand(0)->getType();
872   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
873   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
874   GenericValue Dest;
875
876   switch (Ty->getPrimitiveID()) {
877     IMPLEMENT_SHIFT(>>, UByte);
878     IMPLEMENT_SHIFT(>>, SByte);
879     IMPLEMENT_SHIFT(>>, UShort);
880     IMPLEMENT_SHIFT(>>, Short);
881     IMPLEMENT_SHIFT(>>, UInt);
882     IMPLEMENT_SHIFT(>>, Int);
883     IMPLEMENT_SHIFT(>>, ULong);
884     IMPLEMENT_SHIFT(>>, Long);
885   default:
886     std::cout << "Unhandled type for Shr instruction: " << *Ty << "\n";
887     abort();
888   }
889   SetValue(&I, Dest, SF);
890 }
891
892 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
893    case Type::STY##TyID: Dest.DTY##Val = DCTY Src.STY##Val; break;
894
895 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY)    \
896   case Type::DESTTY##TyID:                      \
897     switch (SrcTy->getPrimitiveID()) {          \
898       IMPLEMENT_CAST(DESTTY, DESTCTY, Bool);    \
899       IMPLEMENT_CAST(DESTTY, DESTCTY, UByte);   \
900       IMPLEMENT_CAST(DESTTY, DESTCTY, SByte);   \
901       IMPLEMENT_CAST(DESTTY, DESTCTY, UShort);  \
902       IMPLEMENT_CAST(DESTTY, DESTCTY, Short);   \
903       IMPLEMENT_CAST(DESTTY, DESTCTY, UInt);    \
904       IMPLEMENT_CAST(DESTTY, DESTCTY, Int);     \
905       IMPLEMENT_CAST(DESTTY, DESTCTY, ULong);   \
906       IMPLEMENT_CAST(DESTTY, DESTCTY, Long);    \
907       IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
908
909 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
910       IMPLEMENT_CAST(DESTTY, DESTCTY, Float);   \
911       IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
912
913 #define IMPLEMENT_CAST_CASE_END()    \
914     default: std::cout << "Unhandled cast: " << SrcTy << " to " << Ty << "\n"; \
915       abort();                                  \
916     }                                           \
917     break
918
919 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
920    IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY);   \
921    IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
922    IMPLEMENT_CAST_CASE_END()
923
924 static GenericValue executeCastOperation(Value *SrcVal, const Type *Ty,
925                                          ExecutionContext &SF) {
926   const Type *SrcTy = SrcVal->getType();
927   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
928
929   switch (Ty->getPrimitiveID()) {
930     IMPLEMENT_CAST_CASE(UByte  , (unsigned char));
931     IMPLEMENT_CAST_CASE(SByte  , (  signed char));
932     IMPLEMENT_CAST_CASE(UShort , (unsigned short));
933     IMPLEMENT_CAST_CASE(Short  , (  signed short));
934     IMPLEMENT_CAST_CASE(UInt   , (unsigned int ));
935     IMPLEMENT_CAST_CASE(Int    , (  signed int ));
936     IMPLEMENT_CAST_CASE(ULong  , (uint64_t));
937     IMPLEMENT_CAST_CASE(Long   , ( int64_t));
938     IMPLEMENT_CAST_CASE(Pointer, (PointerTy));
939     IMPLEMENT_CAST_CASE(Float  , (float));
940     IMPLEMENT_CAST_CASE(Double , (double));
941     IMPLEMENT_CAST_CASE(Bool   , (bool));
942   default:
943     std::cout << "Unhandled dest type for cast instruction: " << *Ty << "\n";
944     abort();
945   }
946
947   return Dest;
948 }
949
950
951 static void executeCastInst(CastInst &I, ExecutionContext &SF) {
952   SetValue(&I, executeCastOperation(I.getOperand(0), I.getType(), SF), SF);
953 }
954
955 static void executeVarArgInst(VarArgInst &I, ExecutionContext &SF) {
956   // Get the pointer to the valist element.  LLI treats the valist in memory as
957   // an integer.
958   GenericValue VAListPtr = getOperandValue(I.getOperand(0), SF);
959
960   // Load the pointer
961   GenericValue VAList = 
962     TheEE->LoadValueFromMemory((GenericValue *)GVTOP(VAListPtr), Type::UIntTy);
963
964   unsigned Argument = VAList.IntVal++;
965
966   // Update the valist to point to the next argument...
967   TheEE->StoreValueToMemory(VAList, (GenericValue *)GVTOP(VAListPtr),
968                             Type::UIntTy);
969
970   // Set the value...
971   assert(Argument < SF.VarArgs.size() &&
972          "Accessing past the last vararg argument!");
973   SetValue(&I, SF.VarArgs[Argument], SF);
974 }
975
976 //===----------------------------------------------------------------------===//
977 //                        Dispatch and Execution Code
978 //===----------------------------------------------------------------------===//
979
980 FunctionInfo::FunctionInfo(Function *F) : Annotation(FunctionInfoAID) {
981   // Assign slot numbers to the function arguments...
982   for (Function::const_aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
983     AI->addAnnotation(new SlotNumber(getValueSlot(AI)));
984
985   // Iterate over all of the instructions...
986   unsigned InstNum = 0;
987   for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
988     for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II)
989       // For each instruction... Add Annote
990       II->addAnnotation(new InstNumber(++InstNum, getValueSlot(II)));
991 }
992
993 unsigned FunctionInfo::getValueSlot(const Value *V) {
994   unsigned Plane = V->getType()->getUniqueID();
995   if (Plane >= NumPlaneElements.size())
996     NumPlaneElements.resize(Plane+1, 0);
997   return NumPlaneElements[Plane]++;
998 }
999
1000
1001 //===----------------------------------------------------------------------===//
1002 // callFunction - Execute the specified function...
1003 //
1004 void Interpreter::callFunction(Function *F,
1005                                const std::vector<GenericValue> &ArgVals) {
1006   assert((ECStack.empty() || ECStack.back().Caller == 0 || 
1007           ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
1008          "Incorrect number of arguments passed into function call!");
1009   if (F->isExternal()) {
1010     GenericValue Result = callExternalFunction(F, ArgVals);
1011     const Type *RetTy = F->getReturnType();
1012
1013     // Copy the result back into the result variable if we are not returning
1014     // void.
1015     if (RetTy != Type::VoidTy) {
1016       if (!ECStack.empty() && ECStack.back().Caller) {
1017         ExecutionContext &SF = ECStack.back();
1018         SetValue(SF.Caller, Result, SF);
1019       
1020         SF.Caller = 0;          // We returned from the call...
1021       } else if (!QuietMode) {
1022         // print it.
1023         CW << "Function " << F->getType() << " \"" << F->getName()
1024            << "\" returned ";
1025         print(RetTy, Result); 
1026         std::cout << "\n";
1027         
1028         if (RetTy->isIntegral())
1029           ExitCode = Result.IntVal;   // Capture the exit code of the program
1030       }
1031     }
1032
1033     return;
1034   }
1035
1036   // Process the function, assigning instruction numbers to the instructions in
1037   // the function.  Also calculate the number of values for each type slot
1038   // active.
1039   //
1040   FunctionInfo *FuncInfo =
1041     (FunctionInfo*)F->getOrCreateAnnotation(FunctionInfoAID);
1042   ECStack.push_back(ExecutionContext());         // Make a new stack frame...
1043
1044   ExecutionContext &StackFrame = ECStack.back(); // Fill it in...
1045   StackFrame.CurFunction = F;
1046   StackFrame.CurBB     = F->begin();
1047   StackFrame.CurInst   = StackFrame.CurBB->begin();
1048   StackFrame.FuncInfo  = FuncInfo;
1049
1050   // Initialize the values to nothing...
1051   StackFrame.Values.resize(FuncInfo->NumPlaneElements.size());
1052   for (unsigned i = 0; i < FuncInfo->NumPlaneElements.size(); ++i) {
1053     StackFrame.Values[i].resize(FuncInfo->NumPlaneElements[i]);
1054
1055     // Taint the initial values of stuff
1056     memset(&StackFrame.Values[i][0], 42,
1057            FuncInfo->NumPlaneElements[i]*sizeof(GenericValue));
1058   }
1059
1060
1061   // Run through the function arguments and initialize their values...
1062   assert((ArgVals.size() == F->asize() ||
1063          (ArgVals.size() > F->asize() && F->getFunctionType()->isVarArg())) &&
1064          "Invalid number of values passed to function invocation!");
1065
1066   // Handle non-varargs arguments...
1067   unsigned i = 0;
1068   for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI, ++i)
1069     SetValue(AI, ArgVals[i], StackFrame);
1070
1071   // Handle varargs arguments...
1072   StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
1073 }
1074
1075 // executeInstruction - Interpret a single instruction, increment the "PC", and
1076 // return true if the next instruction is a breakpoint...
1077 //
1078 bool Interpreter::executeInstruction() {
1079   assert(!ECStack.empty() && "No program running, cannot execute inst!");
1080
1081   ExecutionContext &SF = ECStack.back();  // Current stack frame
1082   Instruction &I = *SF.CurInst++;         // Increment before execute
1083
1084   if (Trace)
1085     CW << "Run:" << I;
1086
1087   // Track the number of dynamic instructions executed.
1088   ++NumDynamicInsts;
1089
1090   // Set a sigsetjmp buffer so that we can recover if an error happens during
1091   // instruction execution...
1092   //
1093   if (int SigNo = sigsetjmp(SignalRecoverBuffer, 1)) {
1094     --SF.CurInst;   // Back up to erroring instruction
1095     if (SigNo != SIGINT) {
1096       std::cout << "EXCEPTION OCCURRED [" << strsignal(SigNo) << "]:\n";
1097       printStackTrace();
1098       // If -abort-on-exception was specified, terminate LLI instead of trying
1099       // to debug it.
1100       //
1101       if (AbortOnExceptions) exit(1);
1102     } else if (SigNo == SIGINT) {
1103       std::cout << "CTRL-C Detected, execution halted.\n";
1104     }
1105     InInstruction = false;
1106     return true;
1107   }
1108
1109   InInstruction = true;
1110   if (I.isBinaryOp()) {
1111     executeBinaryInst(cast<BinaryOperator>(I), SF);
1112   } else {
1113     switch (I.getOpcode()) {
1114       // Terminators
1115     case Instruction::Ret:     executeRetInst  (cast<ReturnInst>(I), SF); break;
1116     case Instruction::Br:      executeBrInst   (cast<BranchInst>(I), SF); break;
1117     case Instruction::Switch:  executeSwitchInst(cast<SwitchInst>(I), SF);break;
1118       // Invoke not handled!
1119
1120       // Memory Instructions
1121     case Instruction::Alloca:
1122     case Instruction::Malloc:  executeAllocInst((AllocationInst&)I, SF); break;
1123     case Instruction::Free:    executeFreeInst (cast<FreeInst> (I), SF); break;
1124     case Instruction::Load:    executeLoadInst (cast<LoadInst> (I), SF); break;
1125     case Instruction::Store:   executeStoreInst(cast<StoreInst>(I), SF); break;
1126     case Instruction::GetElementPtr:
1127                           executeGEPInst(cast<GetElementPtrInst>(I), SF); break;
1128
1129       // Miscellaneous Instructions
1130     case Instruction::Call:    executeCallInst (cast<CallInst> (I), SF); break;
1131     case Instruction::PHINode: assert(0 && "PHI nodes already handled!");
1132     case Instruction::Cast:    executeCastInst (cast<CastInst> (I), SF); break;
1133     case Instruction::Shl:     executeShlInst  (cast<ShiftInst>(I), SF); break;
1134     case Instruction::Shr:     executeShrInst  (cast<ShiftInst>(I), SF); break;
1135     case Instruction::VarArg:  executeVarArgInst(cast<VarArgInst>(I),SF); break;
1136     default:
1137       std::cout << "Don't know how to execute this instruction!\n-->" << I;
1138       abort();
1139     }
1140   }
1141   InInstruction = false;
1142   
1143   // Reset the current frame location to the top of stack
1144   CurFrame = ECStack.size()-1;
1145
1146   if (CurFrame == -1) return false;  // No breakpoint if no code
1147
1148   // Return true if there is a breakpoint annotation on the instruction...
1149   return ECStack[CurFrame].CurInst->getAnnotation(BreakpointAID) != 0;
1150 }
1151
1152 void Interpreter::stepInstruction() {  // Do the 'step' command
1153   if (ECStack.empty()) {
1154     std::cout << "Error: no program running, cannot step!\n";
1155     return;
1156   }
1157
1158   // Run an instruction...
1159   executeInstruction();
1160
1161   // Print the next instruction to execute...
1162   printCurrentInstruction();
1163 }
1164
1165 // --- UI Stuff...
1166 void Interpreter::nextInstruction() {  // Do the 'next' command
1167   if (ECStack.empty()) {
1168     std::cout << "Error: no program running, cannot 'next'!\n";
1169     return;
1170   }
1171
1172   // If this is a call instruction, step over the call instruction...
1173   // TODO: ICALL, CALL WITH, ...
1174   if (ECStack.back().CurInst->getOpcode() == Instruction::Call) {
1175     unsigned StackSize = ECStack.size();
1176     // Step into the function...
1177     if (executeInstruction()) {
1178       // Hit a breakpoint, print current instruction, then return to user...
1179       std::cout << "Breakpoint hit!\n";
1180       printCurrentInstruction();
1181       return;
1182     }
1183
1184     // If we we able to step into the function, finish it now.  We might not be
1185     // able the step into a function, if it's external for example.
1186     if (ECStack.size() != StackSize)
1187       finish(); // Finish executing the function...
1188     else
1189       printCurrentInstruction();
1190
1191   } else {
1192     // Normal instruction, just step...
1193     stepInstruction();
1194   }
1195 }
1196
1197 void Interpreter::run() {
1198   if (ECStack.empty()) {
1199     std::cout << "Error: no program running, cannot run!\n";
1200     return;
1201   }
1202
1203   bool HitBreakpoint = false;
1204   while (!ECStack.empty() && !HitBreakpoint) {
1205     // Run an instruction...
1206     HitBreakpoint = executeInstruction();
1207   }
1208
1209   if (HitBreakpoint)
1210     std::cout << "Breakpoint hit!\n";
1211
1212   // Print the next instruction to execute...
1213   printCurrentInstruction();
1214 }
1215
1216 void Interpreter::finish() {
1217   if (ECStack.empty()) {
1218     std::cout << "Error: no program running, cannot run!\n";
1219     return;
1220   }
1221
1222   unsigned StackSize = ECStack.size();
1223   bool HitBreakpoint = false;
1224   while (ECStack.size() >= StackSize && !HitBreakpoint) {
1225     // Run an instruction...
1226     HitBreakpoint = executeInstruction();
1227   }
1228
1229   if (HitBreakpoint)
1230     std::cout << "Breakpoint hit!\n";
1231
1232   // Print the next instruction to execute...
1233   printCurrentInstruction();
1234 }
1235
1236
1237
1238 // printCurrentInstruction - Print out the instruction that the virtual PC is
1239 // at, or fail silently if no program is running.
1240 //
1241 void Interpreter::printCurrentInstruction() {
1242   if (!ECStack.empty()) {
1243     if (ECStack.back().CurBB->begin() == ECStack.back().CurInst)  // print label
1244       WriteAsOperand(std::cout, ECStack.back().CurBB) << ":\n";
1245
1246     Instruction &I = *ECStack.back().CurInst;
1247     InstNumber *IN = (InstNumber*)I.getAnnotation(SlotNumberAID);
1248     assert(IN && "Instruction has no numbering annotation!");
1249     std::cout << "#" << IN->InstNum << I;
1250   }
1251 }
1252
1253 void Interpreter::printValue(const Type *Ty, GenericValue V) {
1254   switch (Ty->getPrimitiveID()) {
1255   case Type::BoolTyID:   std::cout << (V.BoolVal?"true":"false"); break;
1256   case Type::SByteTyID:
1257     std::cout << (int)V.SByteVal << " '" << V.SByteVal << "'";  break;
1258   case Type::UByteTyID:
1259     std::cout << (unsigned)V.UByteVal << " '" << V.UByteVal << "'";  break;
1260   case Type::ShortTyID:  std::cout << V.ShortVal;  break;
1261   case Type::UShortTyID: std::cout << V.UShortVal; break;
1262   case Type::IntTyID:    std::cout << V.IntVal;    break;
1263   case Type::UIntTyID:   std::cout << V.UIntVal;   break;
1264   case Type::LongTyID:   std::cout << (long)V.LongVal;   break;
1265   case Type::ULongTyID:  std::cout << (unsigned long)V.ULongVal;  break;
1266   case Type::FloatTyID:  std::cout << V.FloatVal;  break;
1267   case Type::DoubleTyID: std::cout << V.DoubleVal; break;
1268   case Type::PointerTyID:std::cout << (void*)GVTOP(V); break;
1269   default:
1270     std::cout << "- Don't know how to print value of this type!";
1271     break;
1272   }
1273 }
1274
1275 void Interpreter::print(const Type *Ty, GenericValue V) {
1276   CW << Ty << " ";
1277   printValue(Ty, V);
1278 }
1279
1280 void Interpreter::print(const std::string &Name) {
1281   Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1282   if (!PickedVal) return;
1283
1284   if (const Function *F = dyn_cast<const Function>(PickedVal)) {
1285     CW << F;  // Print the function
1286   } else if (const Type *Ty = dyn_cast<const Type>(PickedVal)) {
1287     CW << "type %" << Name << " = " << Ty->getDescription() << "\n";
1288   } else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(PickedVal)) {
1289     CW << BB;   // Print the basic block
1290   } else {      // Otherwise there should be an annotation for the slot#
1291     print(PickedVal->getType(), 
1292           getOperandValue(PickedVal, ECStack[CurFrame]));
1293     std::cout << "\n";
1294   }
1295 }
1296
1297 void Interpreter::infoValue(const std::string &Name) {
1298   Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1299   if (!PickedVal) return;
1300
1301   std::cout << "Value: ";
1302   print(PickedVal->getType(), 
1303         getOperandValue(PickedVal, ECStack[CurFrame]));
1304   std::cout << "\n";
1305   printOperandInfo(PickedVal, ECStack[CurFrame]);
1306 }
1307
1308 // printStackFrame - Print information about the specified stack frame, or -1
1309 // for the default one.
1310 //
1311 void Interpreter::printStackFrame(int FrameNo) {
1312   if (FrameNo == -1) FrameNo = CurFrame;
1313   Function *F = ECStack[FrameNo].CurFunction;
1314   const Type *RetTy = F->getReturnType();
1315
1316   CW << ((FrameNo == CurFrame) ? '>' : '-') << "#" << FrameNo << ". "
1317      << (Value*)RetTy << " \"" << F->getName() << "\"(";
1318   
1319   unsigned i = 0;
1320   for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++i) {
1321     if (i != 0) std::cout << ", ";
1322     CW << *I << "=";
1323     
1324     printValue(I->getType(), getOperandValue(I, ECStack[FrameNo]));
1325   }
1326
1327   std::cout << ")\n";
1328
1329   if (FrameNo != int(ECStack.size()-1)) {
1330     BasicBlock::iterator I = ECStack[FrameNo].CurInst;
1331     CW << --I;
1332   } else {
1333     CW << *ECStack[FrameNo].CurInst;
1334   }
1335 }
1336