Make getOperandValue and executeCastOperation methods of Interpreter.
[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
36 // Create a TargetData structure to handle memory addressing and size/alignment
37 // computations
38 //
39 CachedWriter CW;     // Object to accelerate printing of LLVM
40
41 sigjmp_buf SignalRecoverBuffer;
42 static bool InInstruction = false;
43
44 extern "C" {
45 static void SigHandler(int Signal) {
46   if (InInstruction)
47     siglongjmp(SignalRecoverBuffer, Signal);
48 }
49 }
50
51 static void initializeSignalHandlers() {
52   struct sigaction Action;
53   Action.sa_handler = SigHandler;
54   Action.sa_flags   = SA_SIGINFO;
55   sigemptyset(&Action.sa_mask);
56   sigaction(SIGSEGV, &Action, 0);
57   sigaction(SIGBUS, &Action, 0);
58   sigaction(SIGINT, &Action, 0);
59   sigaction(SIGFPE, &Action, 0);
60 }
61
62
63 //===----------------------------------------------------------------------===//
64 //                     Value Manipulation code
65 //===----------------------------------------------------------------------===//
66
67 static unsigned getOperandSlot(Value *V) {
68   SlotNumber *SN = (SlotNumber*)V->getAnnotation(SlotNumberAID);
69   assert(SN && "Operand does not have a slot number annotation!");
70   return SN->SlotNum;
71 }
72
73 // Operations used by constant expr implementations...
74 static GenericValue executeCastOperation(Value *Src, const Type *DestTy,
75                                          ExecutionContext &SF);
76 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2, 
77                                    const Type *Ty);
78
79
80 GenericValue Interpreter::getOperandValue(Value *V, ExecutionContext &SF) {
81   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
82     switch (CE->getOpcode()) {
83     case Instruction::Cast:
84       return executeCastOperation(CE->getOperand(0), CE->getType(), SF);
85     case Instruction::GetElementPtr:
86       return TheEE->executeGEPOperation(CE->getOperand(0), CE->op_begin()+1,
87                                         CE->op_end(), SF);
88     case Instruction::Add:
89       return executeAddInst(getOperandValue(CE->getOperand(0), SF),
90                             getOperandValue(CE->getOperand(1), SF),
91                             CE->getType());
92     default:
93       std::cerr << "Unhandled ConstantExpr: " << CE << "\n";
94       abort();
95       return GenericValue();
96     }
97   } else if (Constant *CPV = dyn_cast<Constant>(V)) {
98     return TheEE->getConstantValue(CPV);
99   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
100     return PTOGV(TheEE->getPointerToGlobal(GV));
101   } else {
102     unsigned TyP = V->getType()->getUniqueID();   // TypePlane for value
103     unsigned OpSlot = getOperandSlot(V);
104     assert(TyP < SF.Values.size() && 
105            OpSlot < SF.Values[TyP].size() && "Value out of range!");
106     return SF.Values[TyP][getOperandSlot(V)];
107   }
108 }
109
110 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
111   unsigned TyP = V->getType()->getUniqueID();   // TypePlane for value
112
113   //std::cout << "Setting value: " << &SF.Values[TyP][getOperandSlot(V)]<< "\n";
114   SF.Values[TyP][getOperandSlot(V)] = Val;
115 }
116
117 //===----------------------------------------------------------------------===//
118 //                    Annotation Wrangling code
119 //===----------------------------------------------------------------------===//
120
121 void Interpreter::initializeExecutionEngine() {
122   TheEE = this;
123   AnnotationManager::registerAnnotationFactory(FunctionInfoAID,
124                                                &FunctionInfo::Create);
125   initializeSignalHandlers();
126 }
127
128 //===----------------------------------------------------------------------===//
129 //                    Binary Instruction Implementations
130 //===----------------------------------------------------------------------===//
131
132 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
133    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
134
135 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2, 
136                                    const Type *Ty) {
137   GenericValue Dest;
138   switch (Ty->getPrimitiveID()) {
139     IMPLEMENT_BINARY_OPERATOR(+, UByte);
140     IMPLEMENT_BINARY_OPERATOR(+, SByte);
141     IMPLEMENT_BINARY_OPERATOR(+, UShort);
142     IMPLEMENT_BINARY_OPERATOR(+, Short);
143     IMPLEMENT_BINARY_OPERATOR(+, UInt);
144     IMPLEMENT_BINARY_OPERATOR(+, Int);
145     IMPLEMENT_BINARY_OPERATOR(+, ULong);
146     IMPLEMENT_BINARY_OPERATOR(+, Long);
147     IMPLEMENT_BINARY_OPERATOR(+, Float);
148     IMPLEMENT_BINARY_OPERATOR(+, Double);
149   default:
150     std::cout << "Unhandled type for Add instruction: " << *Ty << "\n";
151     abort();
152   }
153   return Dest;
154 }
155
156 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2, 
157                                    const Type *Ty) {
158   GenericValue Dest;
159   switch (Ty->getPrimitiveID()) {
160     IMPLEMENT_BINARY_OPERATOR(-, UByte);
161     IMPLEMENT_BINARY_OPERATOR(-, SByte);
162     IMPLEMENT_BINARY_OPERATOR(-, UShort);
163     IMPLEMENT_BINARY_OPERATOR(-, Short);
164     IMPLEMENT_BINARY_OPERATOR(-, UInt);
165     IMPLEMENT_BINARY_OPERATOR(-, Int);
166     IMPLEMENT_BINARY_OPERATOR(-, ULong);
167     IMPLEMENT_BINARY_OPERATOR(-, Long);
168     IMPLEMENT_BINARY_OPERATOR(-, Float);
169     IMPLEMENT_BINARY_OPERATOR(-, Double);
170   default:
171     std::cout << "Unhandled type for Sub instruction: " << *Ty << "\n";
172     abort();
173   }
174   return Dest;
175 }
176
177 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2, 
178                                    const Type *Ty) {
179   GenericValue Dest;
180   switch (Ty->getPrimitiveID()) {
181     IMPLEMENT_BINARY_OPERATOR(*, UByte);
182     IMPLEMENT_BINARY_OPERATOR(*, SByte);
183     IMPLEMENT_BINARY_OPERATOR(*, UShort);
184     IMPLEMENT_BINARY_OPERATOR(*, Short);
185     IMPLEMENT_BINARY_OPERATOR(*, UInt);
186     IMPLEMENT_BINARY_OPERATOR(*, Int);
187     IMPLEMENT_BINARY_OPERATOR(*, ULong);
188     IMPLEMENT_BINARY_OPERATOR(*, Long);
189     IMPLEMENT_BINARY_OPERATOR(*, Float);
190     IMPLEMENT_BINARY_OPERATOR(*, Double);
191   default:
192     std::cout << "Unhandled type for Mul instruction: " << Ty << "\n";
193     abort();
194   }
195   return Dest;
196 }
197
198 static GenericValue executeDivInst(GenericValue Src1, GenericValue Src2, 
199                                    const Type *Ty) {
200   GenericValue Dest;
201   switch (Ty->getPrimitiveID()) {
202     IMPLEMENT_BINARY_OPERATOR(/, UByte);
203     IMPLEMENT_BINARY_OPERATOR(/, SByte);
204     IMPLEMENT_BINARY_OPERATOR(/, UShort);
205     IMPLEMENT_BINARY_OPERATOR(/, Short);
206     IMPLEMENT_BINARY_OPERATOR(/, UInt);
207     IMPLEMENT_BINARY_OPERATOR(/, Int);
208     IMPLEMENT_BINARY_OPERATOR(/, ULong);
209     IMPLEMENT_BINARY_OPERATOR(/, Long);
210     IMPLEMENT_BINARY_OPERATOR(/, Float);
211     IMPLEMENT_BINARY_OPERATOR(/, Double);
212   default:
213     std::cout << "Unhandled type for Div instruction: " << *Ty << "\n";
214     abort();
215   }
216   return Dest;
217 }
218
219 static GenericValue executeRemInst(GenericValue Src1, GenericValue Src2, 
220                                    const Type *Ty) {
221   GenericValue Dest;
222   switch (Ty->getPrimitiveID()) {
223     IMPLEMENT_BINARY_OPERATOR(%, UByte);
224     IMPLEMENT_BINARY_OPERATOR(%, SByte);
225     IMPLEMENT_BINARY_OPERATOR(%, UShort);
226     IMPLEMENT_BINARY_OPERATOR(%, Short);
227     IMPLEMENT_BINARY_OPERATOR(%, UInt);
228     IMPLEMENT_BINARY_OPERATOR(%, Int);
229     IMPLEMENT_BINARY_OPERATOR(%, ULong);
230     IMPLEMENT_BINARY_OPERATOR(%, Long);
231   case Type::FloatTyID:
232     Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
233     break;
234   case Type::DoubleTyID:
235     Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
236     break;
237   default:
238     std::cout << "Unhandled type for Rem instruction: " << *Ty << "\n";
239     abort();
240   }
241   return Dest;
242 }
243
244 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2, 
245                                    const Type *Ty) {
246   GenericValue Dest;
247   switch (Ty->getPrimitiveID()) {
248     IMPLEMENT_BINARY_OPERATOR(&, Bool);
249     IMPLEMENT_BINARY_OPERATOR(&, UByte);
250     IMPLEMENT_BINARY_OPERATOR(&, SByte);
251     IMPLEMENT_BINARY_OPERATOR(&, UShort);
252     IMPLEMENT_BINARY_OPERATOR(&, Short);
253     IMPLEMENT_BINARY_OPERATOR(&, UInt);
254     IMPLEMENT_BINARY_OPERATOR(&, Int);
255     IMPLEMENT_BINARY_OPERATOR(&, ULong);
256     IMPLEMENT_BINARY_OPERATOR(&, Long);
257   default:
258     std::cout << "Unhandled type for And instruction: " << *Ty << "\n";
259     abort();
260   }
261   return Dest;
262 }
263
264
265 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2, 
266                                   const Type *Ty) {
267   GenericValue Dest;
268   switch (Ty->getPrimitiveID()) {
269     IMPLEMENT_BINARY_OPERATOR(|, Bool);
270     IMPLEMENT_BINARY_OPERATOR(|, UByte);
271     IMPLEMENT_BINARY_OPERATOR(|, SByte);
272     IMPLEMENT_BINARY_OPERATOR(|, UShort);
273     IMPLEMENT_BINARY_OPERATOR(|, Short);
274     IMPLEMENT_BINARY_OPERATOR(|, UInt);
275     IMPLEMENT_BINARY_OPERATOR(|, Int);
276     IMPLEMENT_BINARY_OPERATOR(|, ULong);
277     IMPLEMENT_BINARY_OPERATOR(|, Long);
278   default:
279     std::cout << "Unhandled type for Or instruction: " << *Ty << "\n";
280     abort();
281   }
282   return Dest;
283 }
284
285
286 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2, 
287                                    const Type *Ty) {
288   GenericValue Dest;
289   switch (Ty->getPrimitiveID()) {
290     IMPLEMENT_BINARY_OPERATOR(^, Bool);
291     IMPLEMENT_BINARY_OPERATOR(^, UByte);
292     IMPLEMENT_BINARY_OPERATOR(^, SByte);
293     IMPLEMENT_BINARY_OPERATOR(^, UShort);
294     IMPLEMENT_BINARY_OPERATOR(^, Short);
295     IMPLEMENT_BINARY_OPERATOR(^, UInt);
296     IMPLEMENT_BINARY_OPERATOR(^, Int);
297     IMPLEMENT_BINARY_OPERATOR(^, ULong);
298     IMPLEMENT_BINARY_OPERATOR(^, Long);
299   default:
300     std::cout << "Unhandled type for Xor instruction: " << *Ty << "\n";
301     abort();
302   }
303   return Dest;
304 }
305
306
307 #define IMPLEMENT_SETCC(OP, TY) \
308    case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
309
310 // Handle pointers specially because they must be compared with only as much
311 // width as the host has.  We _do not_ want to be comparing 64 bit values when
312 // running on a 32-bit target, otherwise the upper 32 bits might mess up
313 // comparisons if they contain garbage.
314 #define IMPLEMENT_POINTERSETCC(OP) \
315    case Type::PointerTyID: \
316         Dest.BoolVal = (void*)(intptr_t)Src1.PointerVal OP \
317                        (void*)(intptr_t)Src2.PointerVal; break
318
319 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2, 
320                                      const Type *Ty) {
321   GenericValue Dest;
322   switch (Ty->getPrimitiveID()) {
323     IMPLEMENT_SETCC(==, UByte);
324     IMPLEMENT_SETCC(==, SByte);
325     IMPLEMENT_SETCC(==, UShort);
326     IMPLEMENT_SETCC(==, Short);
327     IMPLEMENT_SETCC(==, UInt);
328     IMPLEMENT_SETCC(==, Int);
329     IMPLEMENT_SETCC(==, ULong);
330     IMPLEMENT_SETCC(==, Long);
331     IMPLEMENT_SETCC(==, Float);
332     IMPLEMENT_SETCC(==, Double);
333     IMPLEMENT_POINTERSETCC(==);
334   default:
335     std::cout << "Unhandled type for SetEQ instruction: " << *Ty << "\n";
336     abort();
337   }
338   return Dest;
339 }
340
341 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2, 
342                                      const Type *Ty) {
343   GenericValue Dest;
344   switch (Ty->getPrimitiveID()) {
345     IMPLEMENT_SETCC(!=, UByte);
346     IMPLEMENT_SETCC(!=, SByte);
347     IMPLEMENT_SETCC(!=, UShort);
348     IMPLEMENT_SETCC(!=, Short);
349     IMPLEMENT_SETCC(!=, UInt);
350     IMPLEMENT_SETCC(!=, Int);
351     IMPLEMENT_SETCC(!=, ULong);
352     IMPLEMENT_SETCC(!=, Long);
353     IMPLEMENT_SETCC(!=, Float);
354     IMPLEMENT_SETCC(!=, Double);
355     IMPLEMENT_POINTERSETCC(!=);
356
357   default:
358     std::cout << "Unhandled type for SetNE instruction: " << *Ty << "\n";
359     abort();
360   }
361   return Dest;
362 }
363
364 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2, 
365                                      const Type *Ty) {
366   GenericValue Dest;
367   switch (Ty->getPrimitiveID()) {
368     IMPLEMENT_SETCC(<=, UByte);
369     IMPLEMENT_SETCC(<=, SByte);
370     IMPLEMENT_SETCC(<=, UShort);
371     IMPLEMENT_SETCC(<=, Short);
372     IMPLEMENT_SETCC(<=, UInt);
373     IMPLEMENT_SETCC(<=, Int);
374     IMPLEMENT_SETCC(<=, ULong);
375     IMPLEMENT_SETCC(<=, Long);
376     IMPLEMENT_SETCC(<=, Float);
377     IMPLEMENT_SETCC(<=, Double);
378     IMPLEMENT_POINTERSETCC(<=);
379   default:
380     std::cout << "Unhandled type for SetLE instruction: " << Ty << "\n";
381     abort();
382   }
383   return Dest;
384 }
385
386 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2, 
387                                      const Type *Ty) {
388   GenericValue Dest;
389   switch (Ty->getPrimitiveID()) {
390     IMPLEMENT_SETCC(>=, UByte);
391     IMPLEMENT_SETCC(>=, SByte);
392     IMPLEMENT_SETCC(>=, UShort);
393     IMPLEMENT_SETCC(>=, Short);
394     IMPLEMENT_SETCC(>=, UInt);
395     IMPLEMENT_SETCC(>=, Int);
396     IMPLEMENT_SETCC(>=, ULong);
397     IMPLEMENT_SETCC(>=, Long);
398     IMPLEMENT_SETCC(>=, Float);
399     IMPLEMENT_SETCC(>=, Double);
400     IMPLEMENT_POINTERSETCC(>=);
401   default:
402     std::cout << "Unhandled type for SetGE instruction: " << *Ty << "\n";
403     abort();
404   }
405   return Dest;
406 }
407
408 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2, 
409                                      const Type *Ty) {
410   GenericValue Dest;
411   switch (Ty->getPrimitiveID()) {
412     IMPLEMENT_SETCC(<, UByte);
413     IMPLEMENT_SETCC(<, SByte);
414     IMPLEMENT_SETCC(<, UShort);
415     IMPLEMENT_SETCC(<, Short);
416     IMPLEMENT_SETCC(<, UInt);
417     IMPLEMENT_SETCC(<, Int);
418     IMPLEMENT_SETCC(<, ULong);
419     IMPLEMENT_SETCC(<, Long);
420     IMPLEMENT_SETCC(<, Float);
421     IMPLEMENT_SETCC(<, Double);
422     IMPLEMENT_POINTERSETCC(<);
423   default:
424     std::cout << "Unhandled type for SetLT instruction: " << *Ty << "\n";
425     abort();
426   }
427   return Dest;
428 }
429
430 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2, 
431                                      const Type *Ty) {
432   GenericValue Dest;
433   switch (Ty->getPrimitiveID()) {
434     IMPLEMENT_SETCC(>, UByte);
435     IMPLEMENT_SETCC(>, SByte);
436     IMPLEMENT_SETCC(>, UShort);
437     IMPLEMENT_SETCC(>, Short);
438     IMPLEMENT_SETCC(>, UInt);
439     IMPLEMENT_SETCC(>, Int);
440     IMPLEMENT_SETCC(>, ULong);
441     IMPLEMENT_SETCC(>, Long);
442     IMPLEMENT_SETCC(>, Float);
443     IMPLEMENT_SETCC(>, Double);
444     IMPLEMENT_POINTERSETCC(>);
445   default:
446     std::cout << "Unhandled type for SetGT instruction: " << *Ty << "\n";
447     abort();
448   }
449   return Dest;
450 }
451
452 void Interpreter::visitBinaryOperator(BinaryOperator &I) {
453   ExecutionContext &SF = ECStack.back();
454   const Type *Ty    = I.getOperand(0)->getType();
455   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
456   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
457   GenericValue R;   // Result
458
459   switch (I.getOpcode()) {
460   case Instruction::Add:   R = executeAddInst  (Src1, Src2, Ty); break;
461   case Instruction::Sub:   R = executeSubInst  (Src1, Src2, Ty); break;
462   case Instruction::Mul:   R = executeMulInst  (Src1, Src2, Ty); break;
463   case Instruction::Div:   R = executeDivInst  (Src1, Src2, Ty); break;
464   case Instruction::Rem:   R = executeRemInst  (Src1, Src2, Ty); break;
465   case Instruction::And:   R = executeAndInst  (Src1, Src2, Ty); break;
466   case Instruction::Or:    R = executeOrInst   (Src1, Src2, Ty); break;
467   case Instruction::Xor:   R = executeXorInst  (Src1, Src2, Ty); break;
468   case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty); break;
469   case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty); break;
470   case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty); break;
471   case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty); break;
472   case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty); break;
473   case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty); break;
474   default:
475     std::cout << "Don't know how to handle this binary operator!\n-->" << I;
476     abort();
477   }
478
479   SetValue(&I, R, SF);
480 }
481
482 //===----------------------------------------------------------------------===//
483 //                     Terminator Instruction Implementations
484 //===----------------------------------------------------------------------===//
485
486 void Interpreter::exitCalled(GenericValue GV) {
487   if (!QuietMode) {
488     std::cout << "Program returned ";
489     print(Type::IntTy, GV);
490     std::cout << " via 'void exit(int)'\n";
491   }
492
493   ExitCode = GV.SByteVal;
494   ECStack.clear();
495 }
496
497 void Interpreter::visitReturnInst(ReturnInst &I) {
498   ExecutionContext &SF = ECStack.back();
499   const Type *RetTy = 0;
500   GenericValue Result;
501
502   // Save away the return value... (if we are not 'ret void')
503   if (I.getNumOperands()) {
504     RetTy  = I.getReturnValue()->getType();
505     Result = getOperandValue(I.getReturnValue(), SF);
506   }
507
508   // Save previously executing meth
509   const Function *M = ECStack.back().CurFunction;
510
511   // Pop the current stack frame... this invalidates SF
512   ECStack.pop_back();
513
514   if (ECStack.empty()) {  // Finished main.  Put result into exit code...
515     if (RetTy) {          // Nonvoid return type?
516       if (!QuietMode) {
517         CW << "Function " << M->getType() << " \"" << M->getName()
518            << "\" returned ";
519         print(RetTy, Result);
520         std::cout << "\n";
521       }
522
523       if (RetTy->isIntegral())
524         ExitCode = Result.IntVal;   // Capture the exit code of the program
525     } else {
526       ExitCode = 0;
527     }
528     return;
529   }
530
531   // If we have a previous stack frame, and we have a previous call, fill in
532   // the return value...
533   //
534   ExecutionContext &NewSF = ECStack.back();
535   if (NewSF.Caller) {
536     if (NewSF.Caller->getType() != Type::VoidTy)             // Save result...
537       SetValue(NewSF.Caller, Result, NewSF);
538
539     NewSF.Caller = 0;          // We returned from the call...
540   } else if (!QuietMode) {
541     // This must be a function that is executing because of a user 'call'
542     // instruction.
543     CW << "Function " << M->getType() << " \"" << M->getName()
544        << "\" returned ";
545     print(RetTy, Result);
546     std::cout << "\n";
547   }
548 }
549
550 void Interpreter::visitBranchInst(BranchInst &I) {
551   ExecutionContext &SF = ECStack.back();
552   BasicBlock *Dest;
553
554   Dest = I.getSuccessor(0);          // Uncond branches have a fixed dest...
555   if (!I.isUnconditional()) {
556     Value *Cond = I.getCondition();
557     if (getOperandValue(Cond, SF).BoolVal == 0) // If false cond...
558       Dest = I.getSuccessor(1);    
559   }
560   SwitchToNewBasicBlock(Dest, SF);
561 }
562
563 void Interpreter::visitSwitchInst(SwitchInst &I) {
564   ExecutionContext &SF = ECStack.back();
565   GenericValue CondVal = getOperandValue(I.getOperand(0), SF);
566   const Type *ElTy = I.getOperand(0)->getType();
567
568   // Check to see if any of the cases match...
569   BasicBlock *Dest = 0;
570   for (unsigned i = 2, e = I.getNumOperands(); i != e; i += 2)
571     if (executeSetEQInst(CondVal,
572                          getOperandValue(I.getOperand(i), SF), ElTy).BoolVal) {
573       Dest = cast<BasicBlock>(I.getOperand(i+1));
574       break;
575     }
576   
577   if (!Dest) Dest = I.getDefaultDest();   // No cases matched: use default
578   SwitchToNewBasicBlock(Dest, SF);
579 }
580
581 // SwitchToNewBasicBlock - This method is used to jump to a new basic block.
582 // This function handles the actual updating of block and instruction iterators
583 // as well as execution of all of the PHI nodes in the destination block.
584 //
585 // This method does this because all of the PHI nodes must be executed
586 // atomically, reading their inputs before any of the results are updated.  Not
587 // doing this can cause problems if the PHI nodes depend on other PHI nodes for
588 // their inputs.  If the input PHI node is updated before it is read, incorrect
589 // results can happen.  Thus we use a two phase approach.
590 //
591 void Interpreter::SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF){
592   BasicBlock *PrevBB = SF.CurBB;      // Remember where we came from...
593   SF.CurBB   = Dest;                  // Update CurBB to branch destination
594   SF.CurInst = SF.CurBB->begin();     // Update new instruction ptr...
595
596   if (!isa<PHINode>(SF.CurInst)) return;  // Nothing fancy to do
597
598   // Loop over all of the PHI nodes in the current block, reading their inputs.
599   std::vector<GenericValue> ResultValues;
600
601   for (; PHINode *PN = dyn_cast<PHINode>(SF.CurInst); ++SF.CurInst) {
602     if (Trace) CW << "Run:" << PN;
603
604     // Search for the value corresponding to this previous bb...
605     int i = PN->getBasicBlockIndex(PrevBB);
606     assert(i != -1 && "PHINode doesn't contain entry for predecessor??");
607     Value *IncomingValue = PN->getIncomingValue(i);
608     
609     // Save the incoming value for this PHI node...
610     ResultValues.push_back(getOperandValue(IncomingValue, SF));
611   }
612
613   // Now loop over all of the PHI nodes setting their values...
614   SF.CurInst = SF.CurBB->begin();
615   for (unsigned i = 0; PHINode *PN = dyn_cast<PHINode>(SF.CurInst);
616        ++SF.CurInst, ++i)
617     SetValue(PN, ResultValues[i], SF);
618 }
619
620
621 //===----------------------------------------------------------------------===//
622 //                     Memory Instruction Implementations
623 //===----------------------------------------------------------------------===//
624
625 void Interpreter::visitAllocationInst(AllocationInst &I) {
626   ExecutionContext &SF = ECStack.back();
627
628   const Type *Ty = I.getType()->getElementType();  // Type to be allocated
629
630   // Get the number of elements being allocated by the array...
631   unsigned NumElements = getOperandValue(I.getOperand(0), SF).UIntVal;
632
633   // Allocate enough memory to hold the type...
634   // FIXME: Don't use CALLOC, use a tainted malloc.
635   void *Memory = calloc(NumElements, TD.getTypeSize(Ty));
636
637   GenericValue Result = PTOGV(Memory);
638   assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
639   SetValue(&I, Result, SF);
640
641   if (I.getOpcode() == Instruction::Alloca)
642     ECStack.back().Allocas.add(Memory);
643 }
644
645 void Interpreter::visitFreeInst(FreeInst &I) {
646   ExecutionContext &SF = ECStack.back();
647   assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
648   GenericValue Value = getOperandValue(I.getOperand(0), SF);
649   // TODO: Check to make sure memory is allocated
650   free(GVTOP(Value));   // Free memory
651 }
652
653
654 // getElementOffset - The workhorse for getelementptr.
655 //
656 GenericValue Interpreter::executeGEPOperation(Value *Ptr, User::op_iterator I,
657                                               User::op_iterator E,
658                                               ExecutionContext &SF) {
659   assert(isa<PointerType>(Ptr->getType()) &&
660          "Cannot getElementOffset of a nonpointer type!");
661
662   PointerTy Total = 0;
663   const Type *Ty = Ptr->getType();
664
665   for (; I != E; ++I) {
666     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
667       const StructLayout *SLO = TD.getStructLayout(STy);
668       
669       // Indicies must be ubyte constants...
670       const ConstantUInt *CPU = cast<ConstantUInt>(*I);
671       assert(CPU->getType() == Type::UByteTy);
672       unsigned Index = CPU->getValue();
673       
674       Total += SLO->MemberOffsets[Index];
675       Ty = STy->getElementTypes()[Index];
676     } else if (const SequentialType *ST = cast<SequentialType>(Ty)) {
677
678       // Get the index number for the array... which must be long type...
679       assert((*I)->getType() == Type::LongTy);
680       unsigned Idx = getOperandValue(*I, SF).LongVal;
681       if (const ArrayType *AT = dyn_cast<ArrayType>(ST))
682         if (Idx >= AT->getNumElements() && ArrayChecksEnabled) {
683           std::cerr << "Out of range memory access to element #" << Idx
684                     << " of a " << AT->getNumElements() << " element array."
685                     << " Subscript #" << *I << "\n";
686           // Get outta here!!!
687           siglongjmp(SignalRecoverBuffer, SIGTRAP);
688         }
689
690       Ty = ST->getElementType();
691       unsigned Size = TD.getTypeSize(Ty);
692       Total += Size*Idx;
693     }  
694   }
695
696   GenericValue Result;
697   Result.PointerVal = getOperandValue(Ptr, SF).PointerVal + Total;
698   return Result;
699 }
700
701 void Interpreter::visitGetElementPtrInst(GetElementPtrInst &I) {
702   ExecutionContext &SF = ECStack.back();
703   SetValue(&I, TheEE->executeGEPOperation(I.getPointerOperand(),
704                                    I.idx_begin(), I.idx_end(), SF), SF);
705 }
706
707 void Interpreter::visitLoadInst(LoadInst &I) {
708   ExecutionContext &SF = ECStack.back();
709   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
710   GenericValue *Ptr = (GenericValue*)GVTOP(SRC);
711   GenericValue Result = LoadValueFromMemory(Ptr, I.getType());
712   SetValue(&I, Result, SF);
713 }
714
715 void Interpreter::visitStoreInst(StoreInst &I) {
716   ExecutionContext &SF = ECStack.back();
717   GenericValue Val = getOperandValue(I.getOperand(0), SF);
718   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
719   StoreValueToMemory(Val, (GenericValue *)GVTOP(SRC),
720                      I.getOperand(0)->getType());
721 }
722
723
724
725 //===----------------------------------------------------------------------===//
726 //                 Miscellaneous Instruction Implementations
727 //===----------------------------------------------------------------------===//
728
729 void Interpreter::visitCallInst(CallInst &I) {
730   ExecutionContext &SF = ECStack.back();
731   SF.Caller = &I;
732   std::vector<GenericValue> ArgVals;
733   ArgVals.reserve(I.getNumOperands()-1);
734   for (unsigned i = 1; i < I.getNumOperands(); ++i) {
735     ArgVals.push_back(getOperandValue(I.getOperand(i), SF));
736     // Promote all integral types whose size is < sizeof(int) into ints.  We do
737     // this by zero or sign extending the value as appropriate according to the
738     // source type.
739     if (I.getOperand(i)->getType()->isIntegral() &&
740         I.getOperand(i)->getType()->getPrimitiveSize() < 4) {
741       const Type *Ty = I.getOperand(i)->getType();
742       if (Ty == Type::ShortTy)
743         ArgVals.back().IntVal = ArgVals.back().ShortVal;
744       else if (Ty == Type::UShortTy)
745         ArgVals.back().UIntVal = ArgVals.back().UShortVal;
746       else if (Ty == Type::SByteTy)
747         ArgVals.back().IntVal = ArgVals.back().SByteVal;
748       else if (Ty == Type::UByteTy)
749         ArgVals.back().UIntVal = ArgVals.back().UByteVal;
750       else if (Ty == Type::BoolTy)
751         ArgVals.back().UIntVal = ArgVals.back().BoolVal;
752       else
753         assert(0 && "Unknown type!");
754     }
755   }
756
757   // To handle indirect calls, we must get the pointer value from the argument 
758   // and treat it as a function pointer.
759   GenericValue SRC = getOperandValue(I.getCalledValue(), SF);  
760   callFunction((Function*)GVTOP(SRC), ArgVals);
761 }
762
763 #define IMPLEMENT_SHIFT(OP, TY) \
764    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
765
766 void Interpreter::visitShl(ShiftInst &I) {
767   ExecutionContext &SF = ECStack.back();
768   const Type *Ty    = I.getOperand(0)->getType();
769   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
770   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
771   GenericValue Dest;
772
773   switch (Ty->getPrimitiveID()) {
774     IMPLEMENT_SHIFT(<<, UByte);
775     IMPLEMENT_SHIFT(<<, SByte);
776     IMPLEMENT_SHIFT(<<, UShort);
777     IMPLEMENT_SHIFT(<<, Short);
778     IMPLEMENT_SHIFT(<<, UInt);
779     IMPLEMENT_SHIFT(<<, Int);
780     IMPLEMENT_SHIFT(<<, ULong);
781     IMPLEMENT_SHIFT(<<, Long);
782   default:
783     std::cout << "Unhandled type for Shl instruction: " << *Ty << "\n";
784   }
785   SetValue(&I, Dest, SF);
786 }
787
788 void Interpreter::visitShr(ShiftInst &I) {
789   ExecutionContext &SF = ECStack.back();
790   const Type *Ty    = I.getOperand(0)->getType();
791   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
792   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
793   GenericValue Dest;
794
795   switch (Ty->getPrimitiveID()) {
796     IMPLEMENT_SHIFT(>>, UByte);
797     IMPLEMENT_SHIFT(>>, SByte);
798     IMPLEMENT_SHIFT(>>, UShort);
799     IMPLEMENT_SHIFT(>>, Short);
800     IMPLEMENT_SHIFT(>>, UInt);
801     IMPLEMENT_SHIFT(>>, Int);
802     IMPLEMENT_SHIFT(>>, ULong);
803     IMPLEMENT_SHIFT(>>, Long);
804   default:
805     std::cout << "Unhandled type for Shr instruction: " << *Ty << "\n";
806     abort();
807   }
808   SetValue(&I, Dest, SF);
809 }
810
811 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
812    case Type::STY##TyID: Dest.DTY##Val = DCTY Src.STY##Val; break;
813
814 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY)    \
815   case Type::DESTTY##TyID:                      \
816     switch (SrcTy->getPrimitiveID()) {          \
817       IMPLEMENT_CAST(DESTTY, DESTCTY, Bool);    \
818       IMPLEMENT_CAST(DESTTY, DESTCTY, UByte);   \
819       IMPLEMENT_CAST(DESTTY, DESTCTY, SByte);   \
820       IMPLEMENT_CAST(DESTTY, DESTCTY, UShort);  \
821       IMPLEMENT_CAST(DESTTY, DESTCTY, Short);   \
822       IMPLEMENT_CAST(DESTTY, DESTCTY, UInt);    \
823       IMPLEMENT_CAST(DESTTY, DESTCTY, Int);     \
824       IMPLEMENT_CAST(DESTTY, DESTCTY, ULong);   \
825       IMPLEMENT_CAST(DESTTY, DESTCTY, Long);    \
826       IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
827
828 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
829       IMPLEMENT_CAST(DESTTY, DESTCTY, Float);   \
830       IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
831
832 #define IMPLEMENT_CAST_CASE_END()    \
833     default: std::cout << "Unhandled cast: " << SrcTy << " to " << Ty << "\n"; \
834       abort();                                  \
835     }                                           \
836     break
837
838 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
839    IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY);   \
840    IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
841    IMPLEMENT_CAST_CASE_END()
842
843 GenericValue Interpreter::executeCastOperation(Value *SrcVal, const Type *Ty,
844                                                ExecutionContext &SF) {
845   const Type *SrcTy = SrcVal->getType();
846   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
847
848   switch (Ty->getPrimitiveID()) {
849     IMPLEMENT_CAST_CASE(UByte  , (unsigned char));
850     IMPLEMENT_CAST_CASE(SByte  , (  signed char));
851     IMPLEMENT_CAST_CASE(UShort , (unsigned short));
852     IMPLEMENT_CAST_CASE(Short  , (  signed short));
853     IMPLEMENT_CAST_CASE(UInt   , (unsigned int ));
854     IMPLEMENT_CAST_CASE(Int    , (  signed int ));
855     IMPLEMENT_CAST_CASE(ULong  , (uint64_t));
856     IMPLEMENT_CAST_CASE(Long   , ( int64_t));
857     IMPLEMENT_CAST_CASE(Pointer, (PointerTy));
858     IMPLEMENT_CAST_CASE(Float  , (float));
859     IMPLEMENT_CAST_CASE(Double , (double));
860     IMPLEMENT_CAST_CASE(Bool   , (bool));
861   default:
862     std::cout << "Unhandled dest type for cast instruction: " << *Ty << "\n";
863     abort();
864   }
865
866   return Dest;
867 }
868
869
870 void Interpreter::visitCastInst(CastInst &I) {
871   ExecutionContext &SF = ECStack.back();
872   SetValue(&I, executeCastOperation(I.getOperand(0), I.getType(), SF), SF);
873 }
874
875 void Interpreter::visitVarArgInst(VarArgInst &I) {
876   ExecutionContext &SF = ECStack.back();
877
878   // Get the pointer to the valist element.  LLI treats the valist in memory as
879   // an integer.
880   GenericValue VAListPtr = getOperandValue(I.getOperand(0), SF);
881
882   // Load the pointer
883   GenericValue VAList = 
884     TheEE->LoadValueFromMemory((GenericValue *)GVTOP(VAListPtr), Type::UIntTy);
885
886   unsigned Argument = VAList.IntVal++;
887
888   // Update the valist to point to the next argument...
889   TheEE->StoreValueToMemory(VAList, (GenericValue *)GVTOP(VAListPtr),
890                             Type::UIntTy);
891
892   // Set the value...
893   assert(Argument < SF.VarArgs.size() &&
894          "Accessing past the last vararg argument!");
895   SetValue(&I, SF.VarArgs[Argument], SF);
896 }
897
898 //===----------------------------------------------------------------------===//
899 //                        Dispatch and Execution Code
900 //===----------------------------------------------------------------------===//
901
902 FunctionInfo::FunctionInfo(Function *F) : Annotation(FunctionInfoAID) {
903   // Assign slot numbers to the function arguments...
904   for (Function::const_aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
905     AI->addAnnotation(new SlotNumber(getValueSlot(AI)));
906
907   // Iterate over all of the instructions...
908   unsigned InstNum = 0;
909   for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
910     for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II)
911       // For each instruction... Add Annote
912       II->addAnnotation(new InstNumber(++InstNum, getValueSlot(II)));
913 }
914
915 unsigned FunctionInfo::getValueSlot(const Value *V) {
916   unsigned Plane = V->getType()->getUniqueID();
917   if (Plane >= NumPlaneElements.size())
918     NumPlaneElements.resize(Plane+1, 0);
919   return NumPlaneElements[Plane]++;
920 }
921
922
923 //===----------------------------------------------------------------------===//
924 // callFunction - Execute the specified function...
925 //
926 void Interpreter::callFunction(Function *F,
927                                const std::vector<GenericValue> &ArgVals) {
928   assert((ECStack.empty() || ECStack.back().Caller == 0 || 
929           ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
930          "Incorrect number of arguments passed into function call!");
931   if (F->isExternal()) {
932     GenericValue Result = callExternalFunction(F, ArgVals);
933     const Type *RetTy = F->getReturnType();
934
935     // Copy the result back into the result variable if we are not returning
936     // void.
937     if (RetTy != Type::VoidTy) {
938       if (!ECStack.empty() && ECStack.back().Caller) {
939         ExecutionContext &SF = ECStack.back();
940         SetValue(SF.Caller, Result, SF);
941       
942         SF.Caller = 0;          // We returned from the call...
943       } else if (!QuietMode) {
944         // print it.
945         CW << "Function " << F->getType() << " \"" << F->getName()
946            << "\" returned ";
947         print(RetTy, Result); 
948         std::cout << "\n";
949         
950         if (RetTy->isIntegral())
951           ExitCode = Result.IntVal;   // Capture the exit code of the program
952       }
953     }
954
955     return;
956   }
957
958   // Process the function, assigning instruction numbers to the instructions in
959   // the function.  Also calculate the number of values for each type slot
960   // active.
961   //
962   FunctionInfo *FuncInfo =
963     (FunctionInfo*)F->getOrCreateAnnotation(FunctionInfoAID);
964   ECStack.push_back(ExecutionContext());         // Make a new stack frame...
965
966   ExecutionContext &StackFrame = ECStack.back(); // Fill it in...
967   StackFrame.CurFunction = F;
968   StackFrame.CurBB     = F->begin();
969   StackFrame.CurInst   = StackFrame.CurBB->begin();
970   StackFrame.FuncInfo  = FuncInfo;
971
972   // Initialize the values to nothing...
973   StackFrame.Values.resize(FuncInfo->NumPlaneElements.size());
974   for (unsigned i = 0; i < FuncInfo->NumPlaneElements.size(); ++i) {
975     StackFrame.Values[i].resize(FuncInfo->NumPlaneElements[i]);
976
977     // Taint the initial values of stuff
978     memset(&StackFrame.Values[i][0], 42,
979            FuncInfo->NumPlaneElements[i]*sizeof(GenericValue));
980   }
981
982
983   // Run through the function arguments and initialize their values...
984   assert((ArgVals.size() == F->asize() ||
985          (ArgVals.size() > F->asize() && F->getFunctionType()->isVarArg())) &&
986          "Invalid number of values passed to function invocation!");
987
988   // Handle non-varargs arguments...
989   unsigned i = 0;
990   for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI, ++i)
991     SetValue(AI, ArgVals[i], StackFrame);
992
993   // Handle varargs arguments...
994   StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
995 }
996
997 // executeInstruction - Interpret a single instruction & increment the "PC".
998 //
999 void Interpreter::executeInstruction() {
1000   assert(!ECStack.empty() && "No program running, cannot execute inst!");
1001
1002   ExecutionContext &SF = ECStack.back();  // Current stack frame
1003   Instruction &I = *SF.CurInst++;         // Increment before execute
1004
1005   if (Trace) CW << "Run:" << I;
1006
1007   // Track the number of dynamic instructions executed.
1008   ++NumDynamicInsts;
1009
1010   // Set a sigsetjmp buffer so that we can recover if an error happens during
1011   // instruction execution...
1012   //
1013   if (int SigNo = sigsetjmp(SignalRecoverBuffer, 1)) {
1014     std::cout << "EXCEPTION OCCURRED [" << strsignal(SigNo) << "]\n";
1015     exit(1);
1016   }
1017
1018   InInstruction = true;
1019   visit(I);   // Dispatch to one of the visit* methods...
1020   InInstruction = false;
1021   
1022   // Reset the current frame location to the top of stack
1023   CurFrame = ECStack.size()-1;
1024 }
1025
1026 void Interpreter::run() {
1027   while (!ECStack.empty()) {
1028     // Run an instruction...
1029     executeInstruction();
1030   }
1031 }
1032
1033 void Interpreter::printValue(const Type *Ty, GenericValue V) {
1034   switch (Ty->getPrimitiveID()) {
1035   case Type::BoolTyID:   std::cout << (V.BoolVal?"true":"false"); break;
1036   case Type::SByteTyID:
1037     std::cout << (int)V.SByteVal << " '" << V.SByteVal << "'";  break;
1038   case Type::UByteTyID:
1039     std::cout << (unsigned)V.UByteVal << " '" << V.UByteVal << "'";  break;
1040   case Type::ShortTyID:  std::cout << V.ShortVal;  break;
1041   case Type::UShortTyID: std::cout << V.UShortVal; break;
1042   case Type::IntTyID:    std::cout << V.IntVal;    break;
1043   case Type::UIntTyID:   std::cout << V.UIntVal;   break;
1044   case Type::LongTyID:   std::cout << (long)V.LongVal;   break;
1045   case Type::ULongTyID:  std::cout << (unsigned long)V.ULongVal;  break;
1046   case Type::FloatTyID:  std::cout << V.FloatVal;  break;
1047   case Type::DoubleTyID: std::cout << V.DoubleVal; break;
1048   case Type::PointerTyID:std::cout << (void*)GVTOP(V); break;
1049   default:
1050     std::cout << "- Don't know how to print value of this type!";
1051     break;
1052   }
1053 }
1054
1055 void Interpreter::print(const Type *Ty, GenericValue V) {
1056   CW << Ty << " ";
1057   printValue(Ty, V);
1058 }