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