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