Do not depend on structure elements being of type UByteTy
[oota-llvm.git] / lib / ExecutionEngine / Interpreter / Execution.cpp
1 //===-- Execution.cpp - Implement code to simulate the program ------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 // 
10 //  This file contains the actual instruction interpreter.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Interpreter.h"
15 #include "llvm/Instructions.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Support/GetElementPtrTypeIterator.h"
19 #include "Support/Statistic.h"
20 #include <cmath>  // For fmod
21 using namespace llvm;
22
23 namespace {
24   Statistic<> NumDynamicInsts("lli", "Number of dynamic instructions executed");
25 }
26
27 namespace llvm {
28   Interpreter *TheEE = 0;
29 }
30
31 //===----------------------------------------------------------------------===//
32 //                     Value Manipulation code
33 //===----------------------------------------------------------------------===//
34
35 // Operations used by constant expr implementations...
36 static GenericValue executeCastOperation(Value *Src, const Type *DestTy,
37                                          ExecutionContext &SF);
38 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2, 
39                                    const Type *Ty);
40
41 GenericValue Interpreter::getOperandValue(Value *V, ExecutionContext &SF) {
42   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
43     switch (CE->getOpcode()) {
44     case Instruction::Cast:
45       return executeCastOperation(CE->getOperand(0), CE->getType(), SF);
46     case Instruction::GetElementPtr:
47       return TheEE->executeGEPOperation(CE->getOperand(0), gep_type_begin(CE),
48                                         gep_type_end(CE), SF);
49     case Instruction::Add:
50       return executeAddInst(getOperandValue(CE->getOperand(0), SF),
51                             getOperandValue(CE->getOperand(1), SF),
52                             CE->getType());
53     default:
54       std::cerr << "Unhandled ConstantExpr: " << CE << "\n";
55       abort();
56       return GenericValue();
57     }
58   } else if (Constant *CPV = dyn_cast<Constant>(V)) {
59     return TheEE->getConstantValue(CPV);
60   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
61     return PTOGV(TheEE->getPointerToGlobal(GV));
62   } else {
63     return SF.Values[V];
64   }
65 }
66
67 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
68   SF.Values[V] = Val;
69 }
70
71 //===----------------------------------------------------------------------===//
72 //                    Annotation Wrangling code
73 //===----------------------------------------------------------------------===//
74
75 void Interpreter::initializeExecutionEngine() {
76   TheEE = this;
77 }
78
79 //===----------------------------------------------------------------------===//
80 //                    Binary Instruction Implementations
81 //===----------------------------------------------------------------------===//
82
83 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
84    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
85
86 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2, 
87                                    const Type *Ty) {
88   GenericValue Dest;
89   switch (Ty->getPrimitiveID()) {
90     IMPLEMENT_BINARY_OPERATOR(+, UByte);
91     IMPLEMENT_BINARY_OPERATOR(+, SByte);
92     IMPLEMENT_BINARY_OPERATOR(+, UShort);
93     IMPLEMENT_BINARY_OPERATOR(+, Short);
94     IMPLEMENT_BINARY_OPERATOR(+, UInt);
95     IMPLEMENT_BINARY_OPERATOR(+, Int);
96     IMPLEMENT_BINARY_OPERATOR(+, ULong);
97     IMPLEMENT_BINARY_OPERATOR(+, Long);
98     IMPLEMENT_BINARY_OPERATOR(+, Float);
99     IMPLEMENT_BINARY_OPERATOR(+, Double);
100   default:
101     std::cout << "Unhandled type for Add instruction: " << *Ty << "\n";
102     abort();
103   }
104   return Dest;
105 }
106
107 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2, 
108                                    const Type *Ty) {
109   GenericValue Dest;
110   switch (Ty->getPrimitiveID()) {
111     IMPLEMENT_BINARY_OPERATOR(-, UByte);
112     IMPLEMENT_BINARY_OPERATOR(-, SByte);
113     IMPLEMENT_BINARY_OPERATOR(-, UShort);
114     IMPLEMENT_BINARY_OPERATOR(-, Short);
115     IMPLEMENT_BINARY_OPERATOR(-, UInt);
116     IMPLEMENT_BINARY_OPERATOR(-, Int);
117     IMPLEMENT_BINARY_OPERATOR(-, ULong);
118     IMPLEMENT_BINARY_OPERATOR(-, Long);
119     IMPLEMENT_BINARY_OPERATOR(-, Float);
120     IMPLEMENT_BINARY_OPERATOR(-, Double);
121   default:
122     std::cout << "Unhandled type for Sub instruction: " << *Ty << "\n";
123     abort();
124   }
125   return Dest;
126 }
127
128 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2, 
129                                    const Type *Ty) {
130   GenericValue Dest;
131   switch (Ty->getPrimitiveID()) {
132     IMPLEMENT_BINARY_OPERATOR(*, UByte);
133     IMPLEMENT_BINARY_OPERATOR(*, SByte);
134     IMPLEMENT_BINARY_OPERATOR(*, UShort);
135     IMPLEMENT_BINARY_OPERATOR(*, Short);
136     IMPLEMENT_BINARY_OPERATOR(*, UInt);
137     IMPLEMENT_BINARY_OPERATOR(*, Int);
138     IMPLEMENT_BINARY_OPERATOR(*, ULong);
139     IMPLEMENT_BINARY_OPERATOR(*, Long);
140     IMPLEMENT_BINARY_OPERATOR(*, Float);
141     IMPLEMENT_BINARY_OPERATOR(*, Double);
142   default:
143     std::cout << "Unhandled type for Mul instruction: " << Ty << "\n";
144     abort();
145   }
146   return Dest;
147 }
148
149 static GenericValue executeDivInst(GenericValue Src1, GenericValue Src2, 
150                                    const Type *Ty) {
151   GenericValue Dest;
152   switch (Ty->getPrimitiveID()) {
153     IMPLEMENT_BINARY_OPERATOR(/, UByte);
154     IMPLEMENT_BINARY_OPERATOR(/, SByte);
155     IMPLEMENT_BINARY_OPERATOR(/, UShort);
156     IMPLEMENT_BINARY_OPERATOR(/, Short);
157     IMPLEMENT_BINARY_OPERATOR(/, UInt);
158     IMPLEMENT_BINARY_OPERATOR(/, Int);
159     IMPLEMENT_BINARY_OPERATOR(/, ULong);
160     IMPLEMENT_BINARY_OPERATOR(/, Long);
161     IMPLEMENT_BINARY_OPERATOR(/, Float);
162     IMPLEMENT_BINARY_OPERATOR(/, Double);
163   default:
164     std::cout << "Unhandled type for Div instruction: " << *Ty << "\n";
165     abort();
166   }
167   return Dest;
168 }
169
170 static GenericValue executeRemInst(GenericValue Src1, GenericValue Src2, 
171                                    const Type *Ty) {
172   GenericValue Dest;
173   switch (Ty->getPrimitiveID()) {
174     IMPLEMENT_BINARY_OPERATOR(%, UByte);
175     IMPLEMENT_BINARY_OPERATOR(%, SByte);
176     IMPLEMENT_BINARY_OPERATOR(%, UShort);
177     IMPLEMENT_BINARY_OPERATOR(%, Short);
178     IMPLEMENT_BINARY_OPERATOR(%, UInt);
179     IMPLEMENT_BINARY_OPERATOR(%, Int);
180     IMPLEMENT_BINARY_OPERATOR(%, ULong);
181     IMPLEMENT_BINARY_OPERATOR(%, Long);
182   case Type::FloatTyID:
183     Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
184     break;
185   case Type::DoubleTyID:
186     Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
187     break;
188   default:
189     std::cout << "Unhandled type for Rem instruction: " << *Ty << "\n";
190     abort();
191   }
192   return Dest;
193 }
194
195 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2, 
196                                    const Type *Ty) {
197   GenericValue Dest;
198   switch (Ty->getPrimitiveID()) {
199     IMPLEMENT_BINARY_OPERATOR(&, Bool);
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   default:
209     std::cout << "Unhandled type for And instruction: " << *Ty << "\n";
210     abort();
211   }
212   return Dest;
213 }
214
215 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2, 
216                                   const Type *Ty) {
217   GenericValue Dest;
218   switch (Ty->getPrimitiveID()) {
219     IMPLEMENT_BINARY_OPERATOR(|, Bool);
220     IMPLEMENT_BINARY_OPERATOR(|, UByte);
221     IMPLEMENT_BINARY_OPERATOR(|, SByte);
222     IMPLEMENT_BINARY_OPERATOR(|, UShort);
223     IMPLEMENT_BINARY_OPERATOR(|, Short);
224     IMPLEMENT_BINARY_OPERATOR(|, UInt);
225     IMPLEMENT_BINARY_OPERATOR(|, Int);
226     IMPLEMENT_BINARY_OPERATOR(|, ULong);
227     IMPLEMENT_BINARY_OPERATOR(|, Long);
228   default:
229     std::cout << "Unhandled type for Or instruction: " << *Ty << "\n";
230     abort();
231   }
232   return Dest;
233 }
234
235 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2, 
236                                    const Type *Ty) {
237   GenericValue Dest;
238   switch (Ty->getPrimitiveID()) {
239     IMPLEMENT_BINARY_OPERATOR(^, Bool);
240     IMPLEMENT_BINARY_OPERATOR(^, UByte);
241     IMPLEMENT_BINARY_OPERATOR(^, SByte);
242     IMPLEMENT_BINARY_OPERATOR(^, UShort);
243     IMPLEMENT_BINARY_OPERATOR(^, Short);
244     IMPLEMENT_BINARY_OPERATOR(^, UInt);
245     IMPLEMENT_BINARY_OPERATOR(^, Int);
246     IMPLEMENT_BINARY_OPERATOR(^, ULong);
247     IMPLEMENT_BINARY_OPERATOR(^, Long);
248   default:
249     std::cout << "Unhandled type for Xor instruction: " << *Ty << "\n";
250     abort();
251   }
252   return Dest;
253 }
254
255 #define IMPLEMENT_SETCC(OP, TY) \
256    case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
257
258 // Handle pointers specially because they must be compared with only as much
259 // width as the host has.  We _do not_ want to be comparing 64 bit values when
260 // running on a 32-bit target, otherwise the upper 32 bits might mess up
261 // comparisons if they contain garbage.
262 #define IMPLEMENT_POINTERSETCC(OP) \
263    case Type::PointerTyID: \
264         Dest.BoolVal = (void*)(intptr_t)Src1.PointerVal OP \
265                        (void*)(intptr_t)Src2.PointerVal; break
266
267 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2, 
268                                      const Type *Ty) {
269   GenericValue Dest;
270   switch (Ty->getPrimitiveID()) {
271     IMPLEMENT_SETCC(==, UByte);
272     IMPLEMENT_SETCC(==, SByte);
273     IMPLEMENT_SETCC(==, UShort);
274     IMPLEMENT_SETCC(==, Short);
275     IMPLEMENT_SETCC(==, UInt);
276     IMPLEMENT_SETCC(==, Int);
277     IMPLEMENT_SETCC(==, ULong);
278     IMPLEMENT_SETCC(==, Long);
279     IMPLEMENT_SETCC(==, Float);
280     IMPLEMENT_SETCC(==, Double);
281     IMPLEMENT_POINTERSETCC(==);
282   default:
283     std::cout << "Unhandled type for SetEQ instruction: " << *Ty << "\n";
284     abort();
285   }
286   return Dest;
287 }
288
289 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2, 
290                                      const Type *Ty) {
291   GenericValue Dest;
292   switch (Ty->getPrimitiveID()) {
293     IMPLEMENT_SETCC(!=, UByte);
294     IMPLEMENT_SETCC(!=, SByte);
295     IMPLEMENT_SETCC(!=, UShort);
296     IMPLEMENT_SETCC(!=, Short);
297     IMPLEMENT_SETCC(!=, UInt);
298     IMPLEMENT_SETCC(!=, Int);
299     IMPLEMENT_SETCC(!=, ULong);
300     IMPLEMENT_SETCC(!=, Long);
301     IMPLEMENT_SETCC(!=, Float);
302     IMPLEMENT_SETCC(!=, Double);
303     IMPLEMENT_POINTERSETCC(!=);
304
305   default:
306     std::cout << "Unhandled type for SetNE instruction: " << *Ty << "\n";
307     abort();
308   }
309   return Dest;
310 }
311
312 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2, 
313                                      const Type *Ty) {
314   GenericValue Dest;
315   switch (Ty->getPrimitiveID()) {
316     IMPLEMENT_SETCC(<=, UByte);
317     IMPLEMENT_SETCC(<=, SByte);
318     IMPLEMENT_SETCC(<=, UShort);
319     IMPLEMENT_SETCC(<=, Short);
320     IMPLEMENT_SETCC(<=, UInt);
321     IMPLEMENT_SETCC(<=, Int);
322     IMPLEMENT_SETCC(<=, ULong);
323     IMPLEMENT_SETCC(<=, Long);
324     IMPLEMENT_SETCC(<=, Float);
325     IMPLEMENT_SETCC(<=, Double);
326     IMPLEMENT_POINTERSETCC(<=);
327   default:
328     std::cout << "Unhandled type for SetLE instruction: " << Ty << "\n";
329     abort();
330   }
331   return Dest;
332 }
333
334 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2, 
335                                      const Type *Ty) {
336   GenericValue Dest;
337   switch (Ty->getPrimitiveID()) {
338     IMPLEMENT_SETCC(>=, UByte);
339     IMPLEMENT_SETCC(>=, SByte);
340     IMPLEMENT_SETCC(>=, UShort);
341     IMPLEMENT_SETCC(>=, Short);
342     IMPLEMENT_SETCC(>=, UInt);
343     IMPLEMENT_SETCC(>=, Int);
344     IMPLEMENT_SETCC(>=, ULong);
345     IMPLEMENT_SETCC(>=, Long);
346     IMPLEMENT_SETCC(>=, Float);
347     IMPLEMENT_SETCC(>=, Double);
348     IMPLEMENT_POINTERSETCC(>=);
349   default:
350     std::cout << "Unhandled type for SetGE instruction: " << *Ty << "\n";
351     abort();
352   }
353   return Dest;
354 }
355
356 static GenericValue executeSetLTInst(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 SetLT instruction: " << *Ty << "\n";
373     abort();
374   }
375   return Dest;
376 }
377
378 static GenericValue executeSetGTInst(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   default:
394     std::cout << "Unhandled type for SetGT instruction: " << *Ty << "\n";
395     abort();
396   }
397   return Dest;
398 }
399
400 void Interpreter::visitBinaryOperator(BinaryOperator &I) {
401   ExecutionContext &SF = ECStack.back();
402   const Type *Ty    = I.getOperand(0)->getType();
403   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
404   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
405   GenericValue R;   // Result
406
407   switch (I.getOpcode()) {
408   case Instruction::Add:   R = executeAddInst  (Src1, Src2, Ty); break;
409   case Instruction::Sub:   R = executeSubInst  (Src1, Src2, Ty); break;
410   case Instruction::Mul:   R = executeMulInst  (Src1, Src2, Ty); break;
411   case Instruction::Div:   R = executeDivInst  (Src1, Src2, Ty); break;
412   case Instruction::Rem:   R = executeRemInst  (Src1, Src2, Ty); break;
413   case Instruction::And:   R = executeAndInst  (Src1, Src2, Ty); break;
414   case Instruction::Or:    R = executeOrInst   (Src1, Src2, Ty); break;
415   case Instruction::Xor:   R = executeXorInst  (Src1, Src2, Ty); break;
416   case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty); break;
417   case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty); break;
418   case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty); break;
419   case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty); break;
420   case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty); break;
421   case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty); break;
422   default:
423     std::cout << "Don't know how to handle this binary operator!\n-->" << I;
424     abort();
425   }
426
427   SetValue(&I, R, SF);
428 }
429
430 //===----------------------------------------------------------------------===//
431 //                     Terminator Instruction Implementations
432 //===----------------------------------------------------------------------===//
433
434 void Interpreter::exitCalled(GenericValue GV) {
435   ExitCode = GV.SByteVal;
436   ECStack.clear();
437 }
438
439 /// Pop the last stack frame off of ECStack and then copy the result
440 /// back into the result variable if we are not returning void. The
441 /// result variable may be the ExitCode, or the Value of the calling
442 /// CallInst if there was a previous stack frame. This method may
443 /// invalidate any ECStack iterators you have. This method also takes
444 /// care of switching to the normal destination BB, if we are returning
445 /// from an invoke.
446 ///
447 void Interpreter::popStackAndReturnValueToCaller (const Type *RetTy,
448                                                   GenericValue Result) {
449   // Pop the current stack frame.
450   ECStack.pop_back();
451
452   if (ECStack.empty()) {  // Finished main.  Put result into exit code... 
453     if (RetTy && RetTy->isIntegral()) {          // Nonvoid return type?       
454       ExitCode = Result.IntVal;   // Capture the exit code of the program 
455     } else { 
456       ExitCode = 0; 
457     } 
458   } else { 
459     // If we have a previous stack frame, and we have a previous call, 
460     // fill in the return value... 
461     ExecutionContext &CallingSF = ECStack.back();
462     if (Instruction *I = CallingSF.Caller.getInstruction()) {
463       if (CallingSF.Caller.getType() != Type::VoidTy)      // Save result...
464         SetValue(I, Result, CallingSF);
465       if (InvokeInst *II = dyn_cast<InvokeInst> (I))
466         SwitchToNewBasicBlock (II->getNormalDest (), CallingSF);
467       CallingSF.Caller = CallSite();          // We returned from the call...
468     }
469   }
470 }
471
472 void Interpreter::visitReturnInst(ReturnInst &I) {
473   ExecutionContext &SF = ECStack.back();
474   const Type *RetTy = Type::VoidTy;
475   GenericValue Result;
476
477   // Save away the return value... (if we are not 'ret void')
478   if (I.getNumOperands()) {
479     RetTy  = I.getReturnValue()->getType();
480     Result = getOperandValue(I.getReturnValue(), SF);
481   }
482
483   popStackAndReturnValueToCaller(RetTy, Result);
484 }
485
486 void Interpreter::visitUnwindInst(UnwindInst &I) {
487   // Unwind stack
488   Instruction *Inst;
489   do {
490     ECStack.pop_back ();
491     if (ECStack.empty ())
492       abort ();
493     Inst = ECStack.back ().Caller.getInstruction ();
494   } while (!(Inst && isa<InvokeInst> (Inst)));
495
496   // Return from invoke
497   ExecutionContext &InvokingSF = ECStack.back ();
498   InvokingSF.Caller = CallSite ();
499
500   // Go to exceptional destination BB of invoke instruction
501   SwitchToNewBasicBlock (cast<InvokeInst> (Inst)->getExceptionalDest (),
502                          InvokingSF);
503 }
504
505 void Interpreter::visitBranchInst(BranchInst &I) {
506   ExecutionContext &SF = ECStack.back();
507   BasicBlock *Dest;
508
509   Dest = I.getSuccessor(0);          // Uncond branches have a fixed dest...
510   if (!I.isUnconditional()) {
511     Value *Cond = I.getCondition();
512     if (getOperandValue(Cond, SF).BoolVal == 0) // If false cond...
513       Dest = I.getSuccessor(1);    
514   }
515   SwitchToNewBasicBlock(Dest, SF);
516 }
517
518 void Interpreter::visitSwitchInst(SwitchInst &I) {
519   ExecutionContext &SF = ECStack.back();
520   GenericValue CondVal = getOperandValue(I.getOperand(0), SF);
521   const Type *ElTy = I.getOperand(0)->getType();
522
523   // Check to see if any of the cases match...
524   BasicBlock *Dest = 0;
525   for (unsigned i = 2, e = I.getNumOperands(); i != e; i += 2)
526     if (executeSetEQInst(CondVal,
527                          getOperandValue(I.getOperand(i), SF), ElTy).BoolVal) {
528       Dest = cast<BasicBlock>(I.getOperand(i+1));
529       break;
530     }
531   
532   if (!Dest) Dest = I.getDefaultDest();   // No cases matched: use default
533   SwitchToNewBasicBlock(Dest, SF);
534 }
535
536 // SwitchToNewBasicBlock - This method is used to jump to a new basic block.
537 // This function handles the actual updating of block and instruction iterators
538 // as well as execution of all of the PHI nodes in the destination block.
539 //
540 // This method does this because all of the PHI nodes must be executed
541 // atomically, reading their inputs before any of the results are updated.  Not
542 // doing this can cause problems if the PHI nodes depend on other PHI nodes for
543 // their inputs.  If the input PHI node is updated before it is read, incorrect
544 // results can happen.  Thus we use a two phase approach.
545 //
546 void Interpreter::SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF){
547   BasicBlock *PrevBB = SF.CurBB;      // Remember where we came from...
548   SF.CurBB   = Dest;                  // Update CurBB to branch destination
549   SF.CurInst = SF.CurBB->begin();     // Update new instruction ptr...
550
551   if (!isa<PHINode>(SF.CurInst)) return;  // Nothing fancy to do
552
553   // Loop over all of the PHI nodes in the current block, reading their inputs.
554   std::vector<GenericValue> ResultValues;
555
556   for (; PHINode *PN = dyn_cast<PHINode>(SF.CurInst); ++SF.CurInst) {
557     // Search for the value corresponding to this previous bb...
558     int i = PN->getBasicBlockIndex(PrevBB);
559     assert(i != -1 && "PHINode doesn't contain entry for predecessor??");
560     Value *IncomingValue = PN->getIncomingValue(i);
561     
562     // Save the incoming value for this PHI node...
563     ResultValues.push_back(getOperandValue(IncomingValue, SF));
564   }
565
566   // Now loop over all of the PHI nodes setting their values...
567   SF.CurInst = SF.CurBB->begin();
568   for (unsigned i = 0; PHINode *PN = dyn_cast<PHINode>(SF.CurInst);
569        ++SF.CurInst, ++i)
570     SetValue(PN, ResultValues[i], SF);
571 }
572
573 //===----------------------------------------------------------------------===//
574 //                     Memory Instruction Implementations
575 //===----------------------------------------------------------------------===//
576
577 void Interpreter::visitAllocationInst(AllocationInst &I) {
578   ExecutionContext &SF = ECStack.back();
579
580   const Type *Ty = I.getType()->getElementType();  // Type to be allocated
581
582   // Get the number of elements being allocated by the array...
583   unsigned NumElements = getOperandValue(I.getOperand(0), SF).UIntVal;
584
585   // Allocate enough memory to hold the type...
586   void *Memory = malloc(NumElements * TD.getTypeSize(Ty));
587
588   GenericValue Result = PTOGV(Memory);
589   assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
590   SetValue(&I, Result, SF);
591
592   if (I.getOpcode() == Instruction::Alloca)
593     ECStack.back().Allocas.add(Memory);
594 }
595
596 void Interpreter::visitFreeInst(FreeInst &I) {
597   ExecutionContext &SF = ECStack.back();
598   assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
599   GenericValue Value = getOperandValue(I.getOperand(0), SF);
600   // TODO: Check to make sure memory is allocated
601   free(GVTOP(Value));   // Free memory
602 }
603
604 // getElementOffset - The workhorse for getelementptr.
605 //
606 GenericValue Interpreter::executeGEPOperation(Value *Ptr, gep_type_iterator I,
607                                               gep_type_iterator E,
608                                               ExecutionContext &SF) {
609   assert(isa<PointerType>(Ptr->getType()) &&
610          "Cannot getElementOffset of a nonpointer type!");
611
612   PointerTy Total = 0;
613
614   for (; I != E; ++I) {
615     if (const StructType *STy = dyn_cast<StructType>(*I)) {
616       const StructLayout *SLO = TD.getStructLayout(STy);
617       
618       // Indices must be ubyte constants...
619       const ConstantUInt *CPU = cast<ConstantUInt>(*I);
620       unsigned Index = CPU->getValue();
621       
622       Total += SLO->MemberOffsets[Index];
623     } else {
624       const SequentialType *ST = cast<SequentialType>(*I);
625       // Get the index number for the array... which must be long type...
626       GenericValue IdxGV = getOperandValue(I.getOperand(), SF);
627
628       uint64_t Idx;
629       switch (I.getOperand()->getType()->getPrimitiveID()) {
630       default: assert(0 && "Illegal getelementptr index for sequential type!");
631       case Type::SByteTyID:  Idx = IdxGV.SByteVal; break;
632       case Type::ShortTyID:  Idx = IdxGV.ShortVal; break;
633       case Type::IntTyID:    Idx = IdxGV.IntVal; break;
634       case Type::LongTyID:   Idx = IdxGV.LongVal; break;
635       case Type::UByteTyID:  Idx = IdxGV.UByteVal; break;
636       case Type::UShortTyID: Idx = IdxGV.UShortVal; break;
637       case Type::UIntTyID:   Idx = IdxGV.UIntVal; break;
638       case Type::ULongTyID:  Idx = IdxGV.ULongVal; break;
639       }
640       Total += TD.getTypeSize(ST->getElementType())*Idx;
641     }
642   }
643
644   GenericValue Result;
645   Result.PointerVal = getOperandValue(Ptr, SF).PointerVal + Total;
646   return Result;
647 }
648
649 void Interpreter::visitGetElementPtrInst(GetElementPtrInst &I) {
650   ExecutionContext &SF = ECStack.back();
651   SetValue(&I, TheEE->executeGEPOperation(I.getPointerOperand(),
652                                    gep_type_begin(I), gep_type_end(I), SF), SF);
653 }
654
655 void Interpreter::visitLoadInst(LoadInst &I) {
656   ExecutionContext &SF = ECStack.back();
657   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
658   GenericValue *Ptr = (GenericValue*)GVTOP(SRC);
659   GenericValue Result = LoadValueFromMemory(Ptr, I.getType());
660   SetValue(&I, Result, SF);
661 }
662
663 void Interpreter::visitStoreInst(StoreInst &I) {
664   ExecutionContext &SF = ECStack.back();
665   GenericValue Val = getOperandValue(I.getOperand(0), SF);
666   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
667   StoreValueToMemory(Val, (GenericValue *)GVTOP(SRC),
668                      I.getOperand(0)->getType());
669 }
670
671 //===----------------------------------------------------------------------===//
672 //                 Miscellaneous Instruction Implementations
673 //===----------------------------------------------------------------------===//
674
675 void Interpreter::visitCallSite(CallSite CS) {
676   ExecutionContext &SF = ECStack.back();
677   SF.Caller = CS;
678   std::vector<GenericValue> ArgVals;
679   const unsigned NumArgs = SF.Caller.arg_size();
680   ArgVals.reserve(NumArgs);
681   for (CallSite::arg_iterator i = SF.Caller.arg_begin(),
682          e = SF.Caller.arg_end(); i != e; ++i) {
683     Value *V = *i;
684     ArgVals.push_back(getOperandValue(V, SF));
685     // Promote all integral types whose size is < sizeof(int) into ints.  We do
686     // this by zero or sign extending the value as appropriate according to the
687     // source type.
688     const Type *Ty = V->getType();
689     if (Ty->isIntegral() && Ty->getPrimitiveSize() < 4) {
690       if (Ty == Type::ShortTy)
691         ArgVals.back().IntVal = ArgVals.back().ShortVal;
692       else if (Ty == Type::UShortTy)
693         ArgVals.back().UIntVal = ArgVals.back().UShortVal;
694       else if (Ty == Type::SByteTy)
695         ArgVals.back().IntVal = ArgVals.back().SByteVal;
696       else if (Ty == Type::UByteTy)
697         ArgVals.back().UIntVal = ArgVals.back().UByteVal;
698       else if (Ty == Type::BoolTy)
699         ArgVals.back().UIntVal = ArgVals.back().BoolVal;
700       else
701         assert(0 && "Unknown type!");
702     }
703   }
704
705   // To handle indirect calls, we must get the pointer value from the argument 
706   // and treat it as a function pointer.
707   GenericValue SRC = getOperandValue(SF.Caller.getCalledValue(), SF);  
708   callFunction((Function*)GVTOP(SRC), ArgVals);
709 }
710
711 #define IMPLEMENT_SHIFT(OP, TY) \
712    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
713
714 void Interpreter::visitShl(ShiftInst &I) {
715   ExecutionContext &SF = ECStack.back();
716   const Type *Ty    = I.getOperand(0)->getType();
717   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
718   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
719   GenericValue Dest;
720
721   switch (Ty->getPrimitiveID()) {
722     IMPLEMENT_SHIFT(<<, UByte);
723     IMPLEMENT_SHIFT(<<, SByte);
724     IMPLEMENT_SHIFT(<<, UShort);
725     IMPLEMENT_SHIFT(<<, Short);
726     IMPLEMENT_SHIFT(<<, UInt);
727     IMPLEMENT_SHIFT(<<, Int);
728     IMPLEMENT_SHIFT(<<, ULong);
729     IMPLEMENT_SHIFT(<<, Long);
730   default:
731     std::cout << "Unhandled type for Shl instruction: " << *Ty << "\n";
732   }
733   SetValue(&I, Dest, SF);
734 }
735
736 void Interpreter::visitShr(ShiftInst &I) {
737   ExecutionContext &SF = ECStack.back();
738   const Type *Ty    = I.getOperand(0)->getType();
739   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
740   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
741   GenericValue Dest;
742
743   switch (Ty->getPrimitiveID()) {
744     IMPLEMENT_SHIFT(>>, UByte);
745     IMPLEMENT_SHIFT(>>, SByte);
746     IMPLEMENT_SHIFT(>>, UShort);
747     IMPLEMENT_SHIFT(>>, Short);
748     IMPLEMENT_SHIFT(>>, UInt);
749     IMPLEMENT_SHIFT(>>, Int);
750     IMPLEMENT_SHIFT(>>, ULong);
751     IMPLEMENT_SHIFT(>>, Long);
752   default:
753     std::cout << "Unhandled type for Shr instruction: " << *Ty << "\n";
754     abort();
755   }
756   SetValue(&I, Dest, SF);
757 }
758
759 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
760    case Type::STY##TyID: Dest.DTY##Val = DCTY Src.STY##Val; break;
761
762 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY)    \
763   case Type::DESTTY##TyID:                      \
764     switch (SrcTy->getPrimitiveID()) {          \
765       IMPLEMENT_CAST(DESTTY, DESTCTY, Bool);    \
766       IMPLEMENT_CAST(DESTTY, DESTCTY, UByte);   \
767       IMPLEMENT_CAST(DESTTY, DESTCTY, SByte);   \
768       IMPLEMENT_CAST(DESTTY, DESTCTY, UShort);  \
769       IMPLEMENT_CAST(DESTTY, DESTCTY, Short);   \
770       IMPLEMENT_CAST(DESTTY, DESTCTY, UInt);    \
771       IMPLEMENT_CAST(DESTTY, DESTCTY, Int);     \
772       IMPLEMENT_CAST(DESTTY, DESTCTY, ULong);   \
773       IMPLEMENT_CAST(DESTTY, DESTCTY, Long);    \
774       IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
775
776 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
777       IMPLEMENT_CAST(DESTTY, DESTCTY, Float);   \
778       IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
779
780 #define IMPLEMENT_CAST_CASE_END()    \
781     default: std::cout << "Unhandled cast: " << SrcTy << " to " << Ty << "\n"; \
782       abort();                                  \
783     }                                           \
784     break
785
786 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
787    IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY);   \
788    IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
789    IMPLEMENT_CAST_CASE_END()
790
791 GenericValue Interpreter::executeCastOperation(Value *SrcVal, const Type *Ty,
792                                                ExecutionContext &SF) {
793   const Type *SrcTy = SrcVal->getType();
794   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
795
796   switch (Ty->getPrimitiveID()) {
797     IMPLEMENT_CAST_CASE(UByte  , (unsigned char));
798     IMPLEMENT_CAST_CASE(SByte  , (  signed char));
799     IMPLEMENT_CAST_CASE(UShort , (unsigned short));
800     IMPLEMENT_CAST_CASE(Short  , (  signed short));
801     IMPLEMENT_CAST_CASE(UInt   , (unsigned int ));
802     IMPLEMENT_CAST_CASE(Int    , (  signed int ));
803     IMPLEMENT_CAST_CASE(ULong  , (uint64_t));
804     IMPLEMENT_CAST_CASE(Long   , ( int64_t));
805     IMPLEMENT_CAST_CASE(Pointer, (PointerTy));
806     IMPLEMENT_CAST_CASE(Float  , (float));
807     IMPLEMENT_CAST_CASE(Double , (double));
808     IMPLEMENT_CAST_CASE(Bool   , (bool));
809   default:
810     std::cout << "Unhandled dest type for cast instruction: " << *Ty << "\n";
811     abort();
812   }
813
814   return Dest;
815 }
816
817 void Interpreter::visitCastInst(CastInst &I) {
818   ExecutionContext &SF = ECStack.back();
819   SetValue(&I, executeCastOperation(I.getOperand(0), I.getType(), SF), SF);
820 }
821
822 void Interpreter::visitVANextInst(VANextInst &I) {
823   ExecutionContext &SF = ECStack.back();
824
825   // Get the incoming valist parameter.  LLI treats the valist as a pointer 
826   // to the next argument.
827   GenericValue VAList = getOperandValue(I.getOperand(0), SF);
828   
829   // Move the pointer to the next vararg.
830   GenericValue *ArgPtr = (GenericValue *) GVTOP (VAList);
831   ++ArgPtr;
832   VAList = PTOGV (ArgPtr);
833   SetValue(&I, VAList, SF);
834 }
835
836 #define IMPLEMENT_VAARG(TY) \
837    case Type::TY##TyID: Dest.TY##Val = Src.TY##Val; break
838
839 void Interpreter::visitVAArgInst(VAArgInst &I) {
840   ExecutionContext &SF = ECStack.back();
841
842   // Get the incoming valist parameter.  LLI treats the valist as a pointer 
843   // to the next argument.
844   GenericValue VAList = getOperandValue(I.getOperand(0), SF);
845   assert (GVTOP (VAList) != 0 && "VAList was null in vaarg instruction");
846   GenericValue Dest, Src = *(GenericValue *) GVTOP (VAList);
847   const Type *Ty = I.getType();
848   switch (Ty->getPrimitiveID()) {
849     IMPLEMENT_VAARG(UByte);
850     IMPLEMENT_VAARG(SByte);
851     IMPLEMENT_VAARG(UShort);
852     IMPLEMENT_VAARG(Short);
853     IMPLEMENT_VAARG(UInt);
854     IMPLEMENT_VAARG(Int);
855     IMPLEMENT_VAARG(ULong);
856     IMPLEMENT_VAARG(Long);
857     IMPLEMENT_VAARG(Pointer);
858     IMPLEMENT_VAARG(Float);
859     IMPLEMENT_VAARG(Double);
860     IMPLEMENT_VAARG(Bool);
861   default:
862     std::cout << "Unhandled dest type for vaarg instruction: " << *Ty << "\n";
863     abort();
864   }
865   
866   // Set the Value of this Instruction.
867   SetValue(&I, Dest, SF);
868 }
869
870 //===----------------------------------------------------------------------===//
871 //                        Dispatch and Execution Code
872 //===----------------------------------------------------------------------===//
873
874 //===----------------------------------------------------------------------===//
875 // callFunction - Execute the specified function...
876 //
877 void Interpreter::callFunction(Function *F,
878                                const std::vector<GenericValue> &ArgVals) {
879   assert((ECStack.empty() || ECStack.back().Caller.getInstruction() == 0 || 
880           ECStack.back().Caller.arg_size() == ArgVals.size()) &&
881          "Incorrect number of arguments passed into function call!");
882   // Make a new stack frame... and fill it in.
883   ECStack.push_back(ExecutionContext());
884   ExecutionContext &StackFrame = ECStack.back();
885   StackFrame.CurFunction = F;
886
887   // Special handling for external functions.
888   if (F->isExternal()) {
889     GenericValue Result = callExternalFunction (F, ArgVals);
890     // Simulate a 'ret' instruction of the appropriate type.
891     popStackAndReturnValueToCaller (F->getReturnType (), Result);
892     return;
893   }
894
895   // Get pointers to first LLVM BB & Instruction in function.
896   StackFrame.CurBB     = F->begin();
897   StackFrame.CurInst   = StackFrame.CurBB->begin();
898
899   // Run through the function arguments and initialize their values...
900   assert((ArgVals.size() == F->asize() ||
901          (ArgVals.size() > F->asize() && F->getFunctionType()->isVarArg())) &&
902          "Invalid number of values passed to function invocation!");
903
904   // Handle non-varargs arguments...
905   unsigned i = 0;
906   for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI, ++i)
907     SetValue(AI, ArgVals[i], StackFrame);
908
909   // Handle varargs arguments...
910   StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
911 }
912
913 void Interpreter::run() {
914   while (!ECStack.empty()) {
915     // Interpret a single instruction & increment the "PC".
916     ExecutionContext &SF = ECStack.back();  // Current stack frame
917     Instruction &I = *SF.CurInst++;         // Increment before execute
918     
919     // Track the number of dynamic instructions executed.
920     ++NumDynamicInsts;
921
922     visit(I);   // Dispatch to one of the visit* methods...
923   }
924 }