Get rid of unnecessary global variables.
[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 is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file contains the actual instruction interpreter.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "interpreter"
15 #include "Interpreter.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/CodeGen/IntrinsicLowering.h"
20 #include "llvm/Support/GetElementPtrTypeIterator.h"
21 #include "llvm/ADT/APInt.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/MathExtras.h"
26 #include <algorithm>
27 #include <cmath>
28 #include <cstring>
29 using namespace llvm;
30
31 STATISTIC(NumDynamicInsts, "Number of dynamic instructions executed");
32
33 static cl::opt<bool> PrintVolatile("interpreter-print-volatile", cl::Hidden,
34           cl::desc("make the interpreter print every volatile load and store"));
35
36 //===----------------------------------------------------------------------===//
37 //                     Various Helper Functions
38 //===----------------------------------------------------------------------===//
39
40 static inline uint64_t doSignExtension(uint64_t Val, const IntegerType* ITy) {
41   // Determine if the value is signed or not
42   bool isSigned = (Val & (1 << (ITy->getBitWidth()-1))) != 0;
43   // If its signed, extend the sign bits
44   if (isSigned)
45     Val |= ~ITy->getBitMask();
46   return Val;
47 }
48
49 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
50   SF.Values[V] = Val;
51 }
52
53 //===----------------------------------------------------------------------===//
54 //                    Binary Instruction Implementations
55 //===----------------------------------------------------------------------===//
56
57 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
58    case Type::TY##TyID: \
59      Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; \
60      break
61
62 static void executeFAddInst(GenericValue &Dest, GenericValue Src1,
63                             GenericValue Src2, const Type *Ty) {
64   switch (Ty->getTypeID()) {
65     IMPLEMENT_BINARY_OPERATOR(+, Float);
66     IMPLEMENT_BINARY_OPERATOR(+, Double);
67   default:
68     cerr << "Unhandled type for FAdd instruction: " << *Ty << "\n";
69     abort();
70   }
71 }
72
73 static void executeFSubInst(GenericValue &Dest, GenericValue Src1,
74                             GenericValue Src2, const Type *Ty) {
75   switch (Ty->getTypeID()) {
76     IMPLEMENT_BINARY_OPERATOR(-, Float);
77     IMPLEMENT_BINARY_OPERATOR(-, Double);
78   default:
79     cerr << "Unhandled type for FSub instruction: " << *Ty << "\n";
80     abort();
81   }
82 }
83
84 static void executeFMulInst(GenericValue &Dest, GenericValue Src1,
85                             GenericValue Src2, const Type *Ty) {
86   switch (Ty->getTypeID()) {
87     IMPLEMENT_BINARY_OPERATOR(*, Float);
88     IMPLEMENT_BINARY_OPERATOR(*, Double);
89   default:
90     cerr << "Unhandled type for FMul instruction: " << *Ty << "\n";
91     abort();
92   }
93 }
94
95 static void executeFDivInst(GenericValue &Dest, GenericValue Src1, 
96                             GenericValue Src2, const Type *Ty) {
97   switch (Ty->getTypeID()) {
98     IMPLEMENT_BINARY_OPERATOR(/, Float);
99     IMPLEMENT_BINARY_OPERATOR(/, Double);
100   default:
101     cerr << "Unhandled type for FDiv instruction: " << *Ty << "\n";
102     abort();
103   }
104 }
105
106 static void executeFRemInst(GenericValue &Dest, GenericValue Src1, 
107                             GenericValue Src2, const Type *Ty) {
108   switch (Ty->getTypeID()) {
109   case Type::FloatTyID:
110     Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
111     break;
112   case Type::DoubleTyID:
113     Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
114     break;
115   default:
116     cerr << "Unhandled type for Rem instruction: " << *Ty << "\n";
117     abort();
118   }
119 }
120
121 #define IMPLEMENT_INTEGER_ICMP(OP, TY) \
122    case Type::IntegerTyID:  \
123       Dest.IntVal = APInt(1,Src1.IntVal.OP(Src2.IntVal)); \
124       break;
125
126 // Handle pointers specially because they must be compared with only as much
127 // width as the host has.  We _do not_ want to be comparing 64 bit values when
128 // running on a 32-bit target, otherwise the upper 32 bits might mess up
129 // comparisons if they contain garbage.
130 #define IMPLEMENT_POINTER_ICMP(OP) \
131    case Type::PointerTyID: \
132       Dest.IntVal = APInt(1,(void*)(intptr_t)Src1.PointerVal OP \
133                             (void*)(intptr_t)Src2.PointerVal); \
134       break;
135
136 static GenericValue executeICMP_EQ(GenericValue Src1, GenericValue Src2,
137                                    const Type *Ty) {
138   GenericValue Dest;
139   switch (Ty->getTypeID()) {
140     IMPLEMENT_INTEGER_ICMP(eq,Ty);
141     IMPLEMENT_POINTER_ICMP(==);
142   default:
143     cerr << "Unhandled type for ICMP_EQ predicate: " << *Ty << "\n";
144     abort();
145   }
146   return Dest;
147 }
148
149 static GenericValue executeICMP_NE(GenericValue Src1, GenericValue Src2,
150                                    const Type *Ty) {
151   GenericValue Dest;
152   switch (Ty->getTypeID()) {
153     IMPLEMENT_INTEGER_ICMP(ne,Ty);
154     IMPLEMENT_POINTER_ICMP(!=);
155   default:
156     cerr << "Unhandled type for ICMP_NE predicate: " << *Ty << "\n";
157     abort();
158   }
159   return Dest;
160 }
161
162 static GenericValue executeICMP_ULT(GenericValue Src1, GenericValue Src2,
163                                     const Type *Ty) {
164   GenericValue Dest;
165   switch (Ty->getTypeID()) {
166     IMPLEMENT_INTEGER_ICMP(ult,Ty);
167     IMPLEMENT_POINTER_ICMP(<);
168   default:
169     cerr << "Unhandled type for ICMP_ULT predicate: " << *Ty << "\n";
170     abort();
171   }
172   return Dest;
173 }
174
175 static GenericValue executeICMP_SLT(GenericValue Src1, GenericValue Src2,
176                                     const Type *Ty) {
177   GenericValue Dest;
178   switch (Ty->getTypeID()) {
179     IMPLEMENT_INTEGER_ICMP(slt,Ty);
180     IMPLEMENT_POINTER_ICMP(<);
181   default:
182     cerr << "Unhandled type for ICMP_SLT predicate: " << *Ty << "\n";
183     abort();
184   }
185   return Dest;
186 }
187
188 static GenericValue executeICMP_UGT(GenericValue Src1, GenericValue Src2,
189                                     const Type *Ty) {
190   GenericValue Dest;
191   switch (Ty->getTypeID()) {
192     IMPLEMENT_INTEGER_ICMP(ugt,Ty);
193     IMPLEMENT_POINTER_ICMP(>);
194   default:
195     cerr << "Unhandled type for ICMP_UGT predicate: " << *Ty << "\n";
196     abort();
197   }
198   return Dest;
199 }
200
201 static GenericValue executeICMP_SGT(GenericValue Src1, GenericValue Src2,
202                                     const Type *Ty) {
203   GenericValue Dest;
204   switch (Ty->getTypeID()) {
205     IMPLEMENT_INTEGER_ICMP(sgt,Ty);
206     IMPLEMENT_POINTER_ICMP(>);
207   default:
208     cerr << "Unhandled type for ICMP_SGT predicate: " << *Ty << "\n";
209     abort();
210   }
211   return Dest;
212 }
213
214 static GenericValue executeICMP_ULE(GenericValue Src1, GenericValue Src2,
215                                     const Type *Ty) {
216   GenericValue Dest;
217   switch (Ty->getTypeID()) {
218     IMPLEMENT_INTEGER_ICMP(ule,Ty);
219     IMPLEMENT_POINTER_ICMP(<=);
220   default:
221     cerr << "Unhandled type for ICMP_ULE predicate: " << *Ty << "\n";
222     abort();
223   }
224   return Dest;
225 }
226
227 static GenericValue executeICMP_SLE(GenericValue Src1, GenericValue Src2,
228                                     const Type *Ty) {
229   GenericValue Dest;
230   switch (Ty->getTypeID()) {
231     IMPLEMENT_INTEGER_ICMP(sle,Ty);
232     IMPLEMENT_POINTER_ICMP(<=);
233   default:
234     cerr << "Unhandled type for ICMP_SLE predicate: " << *Ty << "\n";
235     abort();
236   }
237   return Dest;
238 }
239
240 static GenericValue executeICMP_UGE(GenericValue Src1, GenericValue Src2,
241                                     const Type *Ty) {
242   GenericValue Dest;
243   switch (Ty->getTypeID()) {
244     IMPLEMENT_INTEGER_ICMP(uge,Ty);
245     IMPLEMENT_POINTER_ICMP(>=);
246   default:
247     cerr << "Unhandled type for ICMP_UGE predicate: " << *Ty << "\n";
248     abort();
249   }
250   return Dest;
251 }
252
253 static GenericValue executeICMP_SGE(GenericValue Src1, GenericValue Src2,
254                                     const Type *Ty) {
255   GenericValue Dest;
256   switch (Ty->getTypeID()) {
257     IMPLEMENT_INTEGER_ICMP(sge,Ty);
258     IMPLEMENT_POINTER_ICMP(>=);
259   default:
260     cerr << "Unhandled type for ICMP_SGE predicate: " << *Ty << "\n";
261     abort();
262   }
263   return Dest;
264 }
265
266 void Interpreter::visitICmpInst(ICmpInst &I) {
267   ExecutionContext &SF = ECStack.back();
268   const Type *Ty    = I.getOperand(0)->getType();
269   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
270   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
271   GenericValue R;   // Result
272   
273   switch (I.getPredicate()) {
274   case ICmpInst::ICMP_EQ:  R = executeICMP_EQ(Src1,  Src2, Ty); break;
275   case ICmpInst::ICMP_NE:  R = executeICMP_NE(Src1,  Src2, Ty); break;
276   case ICmpInst::ICMP_ULT: R = executeICMP_ULT(Src1, Src2, Ty); break;
277   case ICmpInst::ICMP_SLT: R = executeICMP_SLT(Src1, Src2, Ty); break;
278   case ICmpInst::ICMP_UGT: R = executeICMP_UGT(Src1, Src2, Ty); break;
279   case ICmpInst::ICMP_SGT: R = executeICMP_SGT(Src1, Src2, Ty); break;
280   case ICmpInst::ICMP_ULE: R = executeICMP_ULE(Src1, Src2, Ty); break;
281   case ICmpInst::ICMP_SLE: R = executeICMP_SLE(Src1, Src2, Ty); break;
282   case ICmpInst::ICMP_UGE: R = executeICMP_UGE(Src1, Src2, Ty); break;
283   case ICmpInst::ICMP_SGE: R = executeICMP_SGE(Src1, Src2, Ty); break;
284   default:
285     cerr << "Don't know how to handle this ICmp predicate!\n-->" << I;
286     abort();
287   }
288  
289   SetValue(&I, R, SF);
290 }
291
292 #define IMPLEMENT_FCMP(OP, TY) \
293    case Type::TY##TyID: \
294      Dest.IntVal = APInt(1,Src1.TY##Val OP Src2.TY##Val); \
295      break
296
297 static GenericValue executeFCMP_OEQ(GenericValue Src1, GenericValue Src2,
298                                    const Type *Ty) {
299   GenericValue Dest;
300   switch (Ty->getTypeID()) {
301     IMPLEMENT_FCMP(==, Float);
302     IMPLEMENT_FCMP(==, Double);
303   default:
304     cerr << "Unhandled type for FCmp EQ instruction: " << *Ty << "\n";
305     abort();
306   }
307   return Dest;
308 }
309
310 static GenericValue executeFCMP_ONE(GenericValue Src1, GenericValue Src2,
311                                    const Type *Ty) {
312   GenericValue Dest;
313   switch (Ty->getTypeID()) {
314     IMPLEMENT_FCMP(!=, Float);
315     IMPLEMENT_FCMP(!=, Double);
316
317   default:
318     cerr << "Unhandled type for FCmp NE instruction: " << *Ty << "\n";
319     abort();
320   }
321   return Dest;
322 }
323
324 static GenericValue executeFCMP_OLE(GenericValue Src1, GenericValue Src2,
325                                    const Type *Ty) {
326   GenericValue Dest;
327   switch (Ty->getTypeID()) {
328     IMPLEMENT_FCMP(<=, Float);
329     IMPLEMENT_FCMP(<=, Double);
330   default:
331     cerr << "Unhandled type for FCmp LE instruction: " << *Ty << "\n";
332     abort();
333   }
334   return Dest;
335 }
336
337 static GenericValue executeFCMP_OGE(GenericValue Src1, GenericValue Src2,
338                                    const Type *Ty) {
339   GenericValue Dest;
340   switch (Ty->getTypeID()) {
341     IMPLEMENT_FCMP(>=, Float);
342     IMPLEMENT_FCMP(>=, Double);
343   default:
344     cerr << "Unhandled type for FCmp GE instruction: " << *Ty << "\n";
345     abort();
346   }
347   return Dest;
348 }
349
350 static GenericValue executeFCMP_OLT(GenericValue Src1, GenericValue Src2,
351                                    const Type *Ty) {
352   GenericValue Dest;
353   switch (Ty->getTypeID()) {
354     IMPLEMENT_FCMP(<, Float);
355     IMPLEMENT_FCMP(<, Double);
356   default:
357     cerr << "Unhandled type for FCmp LT instruction: " << *Ty << "\n";
358     abort();
359   }
360   return Dest;
361 }
362
363 static GenericValue executeFCMP_OGT(GenericValue Src1, GenericValue Src2,
364                                      const Type *Ty) {
365   GenericValue Dest;
366   switch (Ty->getTypeID()) {
367     IMPLEMENT_FCMP(>, Float);
368     IMPLEMENT_FCMP(>, Double);
369   default:
370     cerr << "Unhandled type for FCmp GT instruction: " << *Ty << "\n";
371     abort();
372   }
373   return Dest;
374 }
375
376 #define IMPLEMENT_UNORDERED(TY, X,Y)                                     \
377   if (TY == Type::FloatTy) {                                             \
378     if (X.FloatVal != X.FloatVal || Y.FloatVal != Y.FloatVal) {          \
379       Dest.IntVal = APInt(1,true);                                       \
380       return Dest;                                                       \
381     }                                                                    \
382   } else if (X.DoubleVal != X.DoubleVal || Y.DoubleVal != Y.DoubleVal) { \
383     Dest.IntVal = APInt(1,true);                                         \
384     return Dest;                                                         \
385   }
386
387
388 static GenericValue executeFCMP_UEQ(GenericValue Src1, GenericValue Src2,
389                                    const Type *Ty) {
390   GenericValue Dest;
391   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
392   return executeFCMP_OEQ(Src1, Src2, Ty);
393 }
394
395 static GenericValue executeFCMP_UNE(GenericValue Src1, GenericValue Src2,
396                                    const Type *Ty) {
397   GenericValue Dest;
398   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
399   return executeFCMP_ONE(Src1, Src2, Ty);
400 }
401
402 static GenericValue executeFCMP_ULE(GenericValue Src1, GenericValue Src2,
403                                    const Type *Ty) {
404   GenericValue Dest;
405   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
406   return executeFCMP_OLE(Src1, Src2, Ty);
407 }
408
409 static GenericValue executeFCMP_UGE(GenericValue Src1, GenericValue Src2,
410                                    const Type *Ty) {
411   GenericValue Dest;
412   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
413   return executeFCMP_OGE(Src1, Src2, Ty);
414 }
415
416 static GenericValue executeFCMP_ULT(GenericValue Src1, GenericValue Src2,
417                                    const Type *Ty) {
418   GenericValue Dest;
419   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
420   return executeFCMP_OLT(Src1, Src2, Ty);
421 }
422
423 static GenericValue executeFCMP_UGT(GenericValue Src1, GenericValue Src2,
424                                      const Type *Ty) {
425   GenericValue Dest;
426   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
427   return executeFCMP_OGT(Src1, Src2, Ty);
428 }
429
430 static GenericValue executeFCMP_ORD(GenericValue Src1, GenericValue Src2,
431                                      const Type *Ty) {
432   GenericValue Dest;
433   if (Ty == Type::FloatTy)
434     Dest.IntVal = APInt(1,(Src1.FloatVal == Src1.FloatVal && 
435                            Src2.FloatVal == Src2.FloatVal));
436   else
437     Dest.IntVal = APInt(1,(Src1.DoubleVal == Src1.DoubleVal && 
438                            Src2.DoubleVal == Src2.DoubleVal));
439   return Dest;
440 }
441
442 static GenericValue executeFCMP_UNO(GenericValue Src1, GenericValue Src2,
443                                      const Type *Ty) {
444   GenericValue Dest;
445   if (Ty == Type::FloatTy)
446     Dest.IntVal = APInt(1,(Src1.FloatVal != Src1.FloatVal || 
447                            Src2.FloatVal != Src2.FloatVal));
448   else
449     Dest.IntVal = APInt(1,(Src1.DoubleVal != Src1.DoubleVal || 
450                            Src2.DoubleVal != Src2.DoubleVal));
451   return Dest;
452 }
453
454 void Interpreter::visitFCmpInst(FCmpInst &I) {
455   ExecutionContext &SF = ECStack.back();
456   const Type *Ty    = I.getOperand(0)->getType();
457   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
458   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
459   GenericValue R;   // Result
460   
461   switch (I.getPredicate()) {
462   case FCmpInst::FCMP_FALSE: R.IntVal = APInt(1,false); break;
463   case FCmpInst::FCMP_TRUE:  R.IntVal = APInt(1,true); break;
464   case FCmpInst::FCMP_ORD:   R = executeFCMP_ORD(Src1, Src2, Ty); break;
465   case FCmpInst::FCMP_UNO:   R = executeFCMP_UNO(Src1, Src2, Ty); break;
466   case FCmpInst::FCMP_UEQ:   R = executeFCMP_UEQ(Src1, Src2, Ty); break;
467   case FCmpInst::FCMP_OEQ:   R = executeFCMP_OEQ(Src1, Src2, Ty); break;
468   case FCmpInst::FCMP_UNE:   R = executeFCMP_UNE(Src1, Src2, Ty); break;
469   case FCmpInst::FCMP_ONE:   R = executeFCMP_ONE(Src1, Src2, Ty); break;
470   case FCmpInst::FCMP_ULT:   R = executeFCMP_ULT(Src1, Src2, Ty); break;
471   case FCmpInst::FCMP_OLT:   R = executeFCMP_OLT(Src1, Src2, Ty); break;
472   case FCmpInst::FCMP_UGT:   R = executeFCMP_UGT(Src1, Src2, Ty); break;
473   case FCmpInst::FCMP_OGT:   R = executeFCMP_OGT(Src1, Src2, Ty); break;
474   case FCmpInst::FCMP_ULE:   R = executeFCMP_ULE(Src1, Src2, Ty); break;
475   case FCmpInst::FCMP_OLE:   R = executeFCMP_OLE(Src1, Src2, Ty); break;
476   case FCmpInst::FCMP_UGE:   R = executeFCMP_UGE(Src1, Src2, Ty); break;
477   case FCmpInst::FCMP_OGE:   R = executeFCMP_OGE(Src1, Src2, Ty); break;
478   default:
479     cerr << "Don't know how to handle this FCmp predicate!\n-->" << I;
480     abort();
481   }
482  
483   SetValue(&I, R, SF);
484 }
485
486 static GenericValue executeCmpInst(unsigned predicate, GenericValue Src1, 
487                                    GenericValue Src2, const Type *Ty) {
488   GenericValue Result;
489   switch (predicate) {
490   case ICmpInst::ICMP_EQ:    return executeICMP_EQ(Src1, Src2, Ty);
491   case ICmpInst::ICMP_NE:    return executeICMP_NE(Src1, Src2, Ty);
492   case ICmpInst::ICMP_UGT:   return executeICMP_UGT(Src1, Src2, Ty);
493   case ICmpInst::ICMP_SGT:   return executeICMP_SGT(Src1, Src2, Ty);
494   case ICmpInst::ICMP_ULT:   return executeICMP_ULT(Src1, Src2, Ty);
495   case ICmpInst::ICMP_SLT:   return executeICMP_SLT(Src1, Src2, Ty);
496   case ICmpInst::ICMP_UGE:   return executeICMP_UGE(Src1, Src2, Ty);
497   case ICmpInst::ICMP_SGE:   return executeICMP_SGE(Src1, Src2, Ty);
498   case ICmpInst::ICMP_ULE:   return executeICMP_ULE(Src1, Src2, Ty);
499   case ICmpInst::ICMP_SLE:   return executeICMP_SLE(Src1, Src2, Ty);
500   case FCmpInst::FCMP_ORD:   return executeFCMP_ORD(Src1, Src2, Ty);
501   case FCmpInst::FCMP_UNO:   return executeFCMP_UNO(Src1, Src2, Ty);
502   case FCmpInst::FCMP_OEQ:   return executeFCMP_OEQ(Src1, Src2, Ty);
503   case FCmpInst::FCMP_UEQ:   return executeFCMP_UEQ(Src1, Src2, Ty);
504   case FCmpInst::FCMP_ONE:   return executeFCMP_ONE(Src1, Src2, Ty);
505   case FCmpInst::FCMP_UNE:   return executeFCMP_UNE(Src1, Src2, Ty);
506   case FCmpInst::FCMP_OLT:   return executeFCMP_OLT(Src1, Src2, Ty);
507   case FCmpInst::FCMP_ULT:   return executeFCMP_ULT(Src1, Src2, Ty);
508   case FCmpInst::FCMP_OGT:   return executeFCMP_OGT(Src1, Src2, Ty);
509   case FCmpInst::FCMP_UGT:   return executeFCMP_UGT(Src1, Src2, Ty);
510   case FCmpInst::FCMP_OLE:   return executeFCMP_OLE(Src1, Src2, Ty);
511   case FCmpInst::FCMP_ULE:   return executeFCMP_ULE(Src1, Src2, Ty);
512   case FCmpInst::FCMP_OGE:   return executeFCMP_OGE(Src1, Src2, Ty);
513   case FCmpInst::FCMP_UGE:   return executeFCMP_UGE(Src1, Src2, Ty);
514   case FCmpInst::FCMP_FALSE: { 
515     GenericValue Result;
516     Result.IntVal = APInt(1, false);
517     return Result;
518   }
519   case FCmpInst::FCMP_TRUE: {
520     GenericValue Result;
521     Result.IntVal = APInt(1, true);
522     return Result;
523   }
524   default:
525     cerr << "Unhandled Cmp predicate\n";
526     abort();
527   }
528 }
529
530 void Interpreter::visitBinaryOperator(BinaryOperator &I) {
531   ExecutionContext &SF = ECStack.back();
532   const Type *Ty    = I.getOperand(0)->getType();
533   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
534   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
535   GenericValue R;   // Result
536
537   switch (I.getOpcode()) {
538   case Instruction::Add:   R.IntVal = Src1.IntVal + Src2.IntVal; break;
539   case Instruction::Sub:   R.IntVal = Src1.IntVal - Src2.IntVal; break;
540   case Instruction::Mul:   R.IntVal = Src1.IntVal * Src2.IntVal; break;
541   case Instruction::FAdd:  executeFAddInst(R, Src1, Src2, Ty); break;
542   case Instruction::FSub:  executeFSubInst(R, Src1, Src2, Ty); break;
543   case Instruction::FMul:  executeFMulInst(R, Src1, Src2, Ty); break;
544   case Instruction::FDiv:  executeFDivInst(R, Src1, Src2, Ty); break;
545   case Instruction::FRem:  executeFRemInst(R, Src1, Src2, Ty); break;
546   case Instruction::UDiv:  R.IntVal = Src1.IntVal.udiv(Src2.IntVal); break;
547   case Instruction::SDiv:  R.IntVal = Src1.IntVal.sdiv(Src2.IntVal); break;
548   case Instruction::URem:  R.IntVal = Src1.IntVal.urem(Src2.IntVal); break;
549   case Instruction::SRem:  R.IntVal = Src1.IntVal.srem(Src2.IntVal); break;
550   case Instruction::And:   R.IntVal = Src1.IntVal & Src2.IntVal; break;
551   case Instruction::Or:    R.IntVal = Src1.IntVal | Src2.IntVal; break;
552   case Instruction::Xor:   R.IntVal = Src1.IntVal ^ Src2.IntVal; break;
553   default:
554     cerr << "Don't know how to handle this binary operator!\n-->" << I;
555     abort();
556   }
557
558   SetValue(&I, R, SF);
559 }
560
561 static GenericValue executeSelectInst(GenericValue Src1, GenericValue Src2,
562                                       GenericValue Src3) {
563   return Src1.IntVal == 0 ? Src3 : Src2;
564 }
565
566 void Interpreter::visitSelectInst(SelectInst &I) {
567   ExecutionContext &SF = ECStack.back();
568   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
569   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
570   GenericValue Src3 = getOperandValue(I.getOperand(2), SF);
571   GenericValue R = executeSelectInst(Src1, Src2, Src3);
572   SetValue(&I, R, SF);
573 }
574
575
576 //===----------------------------------------------------------------------===//
577 //                     Terminator Instruction Implementations
578 //===----------------------------------------------------------------------===//
579
580 void Interpreter::exitCalled(GenericValue GV) {
581   // runAtExitHandlers() assumes there are no stack frames, but
582   // if exit() was called, then it had a stack frame. Blow away
583   // the stack before interpreting atexit handlers.
584   ECStack.clear ();
585   runAtExitHandlers ();
586   exit (GV.IntVal.zextOrTrunc(32).getZExtValue());
587 }
588
589 /// Pop the last stack frame off of ECStack and then copy the result
590 /// back into the result variable if we are not returning void. The
591 /// result variable may be the ExitValue, or the Value of the calling
592 /// CallInst if there was a previous stack frame. This method may
593 /// invalidate any ECStack iterators you have. This method also takes
594 /// care of switching to the normal destination BB, if we are returning
595 /// from an invoke.
596 ///
597 void Interpreter::popStackAndReturnValueToCaller (const Type *RetTy,
598                                                   GenericValue Result) {
599   // Pop the current stack frame.
600   ECStack.pop_back();
601
602   if (ECStack.empty()) {  // Finished main.  Put result into exit code...
603     if (RetTy && RetTy->isInteger()) {          // Nonvoid return type?
604       ExitValue = Result;   // Capture the exit value of the program
605     } else {
606       memset(&ExitValue.Untyped, 0, sizeof(ExitValue.Untyped));
607     }
608   } else {
609     // If we have a previous stack frame, and we have a previous call,
610     // fill in the return value...
611     ExecutionContext &CallingSF = ECStack.back();
612     if (Instruction *I = CallingSF.Caller.getInstruction()) {
613       if (CallingSF.Caller.getType() != Type::VoidTy)      // Save result...
614         SetValue(I, Result, CallingSF);
615       if (InvokeInst *II = dyn_cast<InvokeInst> (I))
616         SwitchToNewBasicBlock (II->getNormalDest (), CallingSF);
617       CallingSF.Caller = CallSite();          // We returned from the call...
618     }
619   }
620 }
621
622 void Interpreter::visitReturnInst(ReturnInst &I) {
623   ExecutionContext &SF = ECStack.back();
624   const Type *RetTy = Type::VoidTy;
625   GenericValue Result;
626
627   // Save away the return value... (if we are not 'ret void')
628   if (I.getNumOperands()) {
629     RetTy  = I.getReturnValue()->getType();
630     Result = getOperandValue(I.getReturnValue(), SF);
631   }
632
633   popStackAndReturnValueToCaller(RetTy, Result);
634 }
635
636 void Interpreter::visitUnwindInst(UnwindInst &I) {
637   // Unwind stack
638   Instruction *Inst;
639   do {
640     ECStack.pop_back ();
641     if (ECStack.empty ())
642       abort ();
643     Inst = ECStack.back ().Caller.getInstruction ();
644   } while (!(Inst && isa<InvokeInst> (Inst)));
645
646   // Return from invoke
647   ExecutionContext &InvokingSF = ECStack.back ();
648   InvokingSF.Caller = CallSite ();
649
650   // Go to exceptional destination BB of invoke instruction
651   SwitchToNewBasicBlock(cast<InvokeInst>(Inst)->getUnwindDest(), InvokingSF);
652 }
653
654 void Interpreter::visitUnreachableInst(UnreachableInst &I) {
655   cerr << "ERROR: Program executed an 'unreachable' instruction!\n";
656   abort();
657 }
658
659 void Interpreter::visitBranchInst(BranchInst &I) {
660   ExecutionContext &SF = ECStack.back();
661   BasicBlock *Dest;
662
663   Dest = I.getSuccessor(0);          // Uncond branches have a fixed dest...
664   if (!I.isUnconditional()) {
665     Value *Cond = I.getCondition();
666     if (getOperandValue(Cond, SF).IntVal == 0) // If false cond...
667       Dest = I.getSuccessor(1);
668   }
669   SwitchToNewBasicBlock(Dest, SF);
670 }
671
672 void Interpreter::visitSwitchInst(SwitchInst &I) {
673   ExecutionContext &SF = ECStack.back();
674   GenericValue CondVal = getOperandValue(I.getOperand(0), SF);
675   const Type *ElTy = I.getOperand(0)->getType();
676
677   // Check to see if any of the cases match...
678   BasicBlock *Dest = 0;
679   for (unsigned i = 2, e = I.getNumOperands(); i != e; i += 2)
680     if (executeICMP_EQ(CondVal, getOperandValue(I.getOperand(i), SF), ElTy)
681         .IntVal != 0) {
682       Dest = cast<BasicBlock>(I.getOperand(i+1));
683       break;
684     }
685
686   if (!Dest) Dest = I.getDefaultDest();   // No cases matched: use default
687   SwitchToNewBasicBlock(Dest, SF);
688 }
689
690 // SwitchToNewBasicBlock - This method is used to jump to a new basic block.
691 // This function handles the actual updating of block and instruction iterators
692 // as well as execution of all of the PHI nodes in the destination block.
693 //
694 // This method does this because all of the PHI nodes must be executed
695 // atomically, reading their inputs before any of the results are updated.  Not
696 // doing this can cause problems if the PHI nodes depend on other PHI nodes for
697 // their inputs.  If the input PHI node is updated before it is read, incorrect
698 // results can happen.  Thus we use a two phase approach.
699 //
700 void Interpreter::SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF){
701   BasicBlock *PrevBB = SF.CurBB;      // Remember where we came from...
702   SF.CurBB   = Dest;                  // Update CurBB to branch destination
703   SF.CurInst = SF.CurBB->begin();     // Update new instruction ptr...
704
705   if (!isa<PHINode>(SF.CurInst)) return;  // Nothing fancy to do
706
707   // Loop over all of the PHI nodes in the current block, reading their inputs.
708   std::vector<GenericValue> ResultValues;
709
710   for (; PHINode *PN = dyn_cast<PHINode>(SF.CurInst); ++SF.CurInst) {
711     // Search for the value corresponding to this previous bb...
712     int i = PN->getBasicBlockIndex(PrevBB);
713     assert(i != -1 && "PHINode doesn't contain entry for predecessor??");
714     Value *IncomingValue = PN->getIncomingValue(i);
715
716     // Save the incoming value for this PHI node...
717     ResultValues.push_back(getOperandValue(IncomingValue, SF));
718   }
719
720   // Now loop over all of the PHI nodes setting their values...
721   SF.CurInst = SF.CurBB->begin();
722   for (unsigned i = 0; isa<PHINode>(SF.CurInst); ++SF.CurInst, ++i) {
723     PHINode *PN = cast<PHINode>(SF.CurInst);
724     SetValue(PN, ResultValues[i], SF);
725   }
726 }
727
728 //===----------------------------------------------------------------------===//
729 //                     Memory Instruction Implementations
730 //===----------------------------------------------------------------------===//
731
732 void Interpreter::visitAllocationInst(AllocationInst &I) {
733   ExecutionContext &SF = ECStack.back();
734
735   const Type *Ty = I.getType()->getElementType();  // Type to be allocated
736
737   // Get the number of elements being allocated by the array...
738   unsigned NumElements = 
739     getOperandValue(I.getOperand(0), SF).IntVal.getZExtValue();
740
741   unsigned TypeSize = (size_t)TD.getTypeAllocSize(Ty);
742
743   // Avoid malloc-ing zero bytes, use max()...
744   unsigned MemToAlloc = std::max(1U, NumElements * TypeSize);
745
746   // Allocate enough memory to hold the type...
747   void *Memory = malloc(MemToAlloc);
748
749   DOUT << "Allocated Type: " << *Ty << " (" << TypeSize << " bytes) x " 
750        << NumElements << " (Total: " << MemToAlloc << ") at "
751        << uintptr_t(Memory) << '\n';
752
753   GenericValue Result = PTOGV(Memory);
754   assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
755   SetValue(&I, Result, SF);
756
757   if (I.getOpcode() == Instruction::Alloca)
758     ECStack.back().Allocas.add(Memory);
759 }
760
761 void Interpreter::visitFreeInst(FreeInst &I) {
762   ExecutionContext &SF = ECStack.back();
763   assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
764   GenericValue Value = getOperandValue(I.getOperand(0), SF);
765   // TODO: Check to make sure memory is allocated
766   free(GVTOP(Value));   // Free memory
767 }
768
769 // getElementOffset - The workhorse for getelementptr.
770 //
771 GenericValue Interpreter::executeGEPOperation(Value *Ptr, gep_type_iterator I,
772                                               gep_type_iterator E,
773                                               ExecutionContext &SF) {
774   assert(isa<PointerType>(Ptr->getType()) &&
775          "Cannot getElementOffset of a nonpointer type!");
776
777   uint64_t Total = 0;
778
779   for (; I != E; ++I) {
780     if (const StructType *STy = dyn_cast<StructType>(*I)) {
781       const StructLayout *SLO = TD.getStructLayout(STy);
782
783       const ConstantInt *CPU = cast<ConstantInt>(I.getOperand());
784       unsigned Index = unsigned(CPU->getZExtValue());
785
786       Total += SLO->getElementOffset(Index);
787     } else {
788       const SequentialType *ST = cast<SequentialType>(*I);
789       // Get the index number for the array... which must be long type...
790       GenericValue IdxGV = getOperandValue(I.getOperand(), SF);
791
792       int64_t Idx;
793       unsigned BitWidth = 
794         cast<IntegerType>(I.getOperand()->getType())->getBitWidth();
795       if (BitWidth == 32)
796         Idx = (int64_t)(int32_t)IdxGV.IntVal.getZExtValue();
797       else {
798         assert(BitWidth == 64 && "Invalid index type for getelementptr");
799         Idx = (int64_t)IdxGV.IntVal.getZExtValue();
800       }
801       Total += TD.getTypeAllocSize(ST->getElementType())*Idx;
802     }
803   }
804
805   GenericValue Result;
806   Result.PointerVal = ((char*)getOperandValue(Ptr, SF).PointerVal) + Total;
807   DOUT << "GEP Index " << Total << " bytes.\n";
808   return Result;
809 }
810
811 void Interpreter::visitGetElementPtrInst(GetElementPtrInst &I) {
812   ExecutionContext &SF = ECStack.back();
813   SetValue(&I, executeGEPOperation(I.getPointerOperand(),
814                                    gep_type_begin(I), gep_type_end(I), SF), SF);
815 }
816
817 void Interpreter::visitLoadInst(LoadInst &I) {
818   ExecutionContext &SF = ECStack.back();
819   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
820   GenericValue *Ptr = (GenericValue*)GVTOP(SRC);
821   GenericValue Result;
822   LoadValueFromMemory(Result, Ptr, I.getType());
823   SetValue(&I, Result, SF);
824   if (I.isVolatile() && PrintVolatile)
825     cerr << "Volatile load " << I;
826 }
827
828 void Interpreter::visitStoreInst(StoreInst &I) {
829   ExecutionContext &SF = ECStack.back();
830   GenericValue Val = getOperandValue(I.getOperand(0), SF);
831   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
832   StoreValueToMemory(Val, (GenericValue *)GVTOP(SRC),
833                      I.getOperand(0)->getType());
834   if (I.isVolatile() && PrintVolatile)
835     cerr << "Volatile store: " << I;
836 }
837
838 //===----------------------------------------------------------------------===//
839 //                 Miscellaneous Instruction Implementations
840 //===----------------------------------------------------------------------===//
841
842 void Interpreter::visitCallSite(CallSite CS) {
843   ExecutionContext &SF = ECStack.back();
844
845   // Check to see if this is an intrinsic function call...
846   Function *F = CS.getCalledFunction();
847   if (F && F->isDeclaration ())
848     switch (F->getIntrinsicID()) {
849     case Intrinsic::not_intrinsic:
850       break;
851     case Intrinsic::vastart: { // va_start
852       GenericValue ArgIndex;
853       ArgIndex.UIntPairVal.first = ECStack.size() - 1;
854       ArgIndex.UIntPairVal.second = 0;
855       SetValue(CS.getInstruction(), ArgIndex, SF);
856       return;
857     }
858     case Intrinsic::vaend:    // va_end is a noop for the interpreter
859       return;
860     case Intrinsic::vacopy:   // va_copy: dest = src
861       SetValue(CS.getInstruction(), getOperandValue(*CS.arg_begin(), SF), SF);
862       return;
863     default:
864       // If it is an unknown intrinsic function, use the intrinsic lowering
865       // class to transform it into hopefully tasty LLVM code.
866       //
867       BasicBlock::iterator me(CS.getInstruction());
868       BasicBlock *Parent = CS.getInstruction()->getParent();
869       bool atBegin(Parent->begin() == me);
870       if (!atBegin)
871         --me;
872       IL->LowerIntrinsicCall(cast<CallInst>(CS.getInstruction()));
873
874       // Restore the CurInst pointer to the first instruction newly inserted, if
875       // any.
876       if (atBegin) {
877         SF.CurInst = Parent->begin();
878       } else {
879         SF.CurInst = me;
880         ++SF.CurInst;
881       }
882       return;
883     }
884
885
886   SF.Caller = CS;
887   std::vector<GenericValue> ArgVals;
888   const unsigned NumArgs = SF.Caller.arg_size();
889   ArgVals.reserve(NumArgs);
890   uint16_t pNum = 1;
891   for (CallSite::arg_iterator i = SF.Caller.arg_begin(),
892          e = SF.Caller.arg_end(); i != e; ++i, ++pNum) {
893     Value *V = *i;
894     ArgVals.push_back(getOperandValue(V, SF));
895     // Promote all integral types whose size is < sizeof(i32) into i32.
896     // We do this by zero or sign extending the value as appropriate
897     // according to the parameter attributes
898     const Type *Ty = V->getType();
899     if (Ty->isInteger() && (ArgVals.back().IntVal.getBitWidth() < 32)) {
900       if (CS.paramHasAttr(pNum, Attribute::ZExt))
901         ArgVals.back().IntVal = ArgVals.back().IntVal.zext(32);
902       else if (CS.paramHasAttr(pNum, Attribute::SExt))
903         ArgVals.back().IntVal = ArgVals.back().IntVal.sext(32);
904     }
905   }
906
907   // To handle indirect calls, we must get the pointer value from the argument
908   // and treat it as a function pointer.
909   GenericValue SRC = getOperandValue(SF.Caller.getCalledValue(), SF);
910   callFunction((Function*)GVTOP(SRC), ArgVals);
911 }
912
913 void Interpreter::visitShl(BinaryOperator &I) {
914   ExecutionContext &SF = ECStack.back();
915   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
916   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
917   GenericValue Dest;
918   if (Src2.IntVal.getZExtValue() < Src1.IntVal.getBitWidth())
919     Dest.IntVal = Src1.IntVal.shl(Src2.IntVal.getZExtValue());
920   else
921     Dest.IntVal = Src1.IntVal;
922   
923   SetValue(&I, Dest, SF);
924 }
925
926 void Interpreter::visitLShr(BinaryOperator &I) {
927   ExecutionContext &SF = ECStack.back();
928   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
929   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
930   GenericValue Dest;
931   if (Src2.IntVal.getZExtValue() < Src1.IntVal.getBitWidth())
932     Dest.IntVal = Src1.IntVal.lshr(Src2.IntVal.getZExtValue());
933   else
934     Dest.IntVal = Src1.IntVal;
935   
936   SetValue(&I, Dest, SF);
937 }
938
939 void Interpreter::visitAShr(BinaryOperator &I) {
940   ExecutionContext &SF = ECStack.back();
941   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
942   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
943   GenericValue Dest;
944   if (Src2.IntVal.getZExtValue() < Src1.IntVal.getBitWidth())
945     Dest.IntVal = Src1.IntVal.ashr(Src2.IntVal.getZExtValue());
946   else
947     Dest.IntVal = Src1.IntVal;
948   
949   SetValue(&I, Dest, SF);
950 }
951
952 GenericValue Interpreter::executeTruncInst(Value *SrcVal, const Type *DstTy,
953                                            ExecutionContext &SF) {
954   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
955   const IntegerType *DITy = cast<IntegerType>(DstTy);
956   unsigned DBitWidth = DITy->getBitWidth();
957   Dest.IntVal = Src.IntVal.trunc(DBitWidth);
958   return Dest;
959 }
960
961 GenericValue Interpreter::executeSExtInst(Value *SrcVal, const Type *DstTy,
962                                           ExecutionContext &SF) {
963   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
964   const IntegerType *DITy = cast<IntegerType>(DstTy);
965   unsigned DBitWidth = DITy->getBitWidth();
966   Dest.IntVal = Src.IntVal.sext(DBitWidth);
967   return Dest;
968 }
969
970 GenericValue Interpreter::executeZExtInst(Value *SrcVal, const Type *DstTy,
971                                           ExecutionContext &SF) {
972   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
973   const IntegerType *DITy = cast<IntegerType>(DstTy);
974   unsigned DBitWidth = DITy->getBitWidth();
975   Dest.IntVal = Src.IntVal.zext(DBitWidth);
976   return Dest;
977 }
978
979 GenericValue Interpreter::executeFPTruncInst(Value *SrcVal, const Type *DstTy,
980                                              ExecutionContext &SF) {
981   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
982   assert(SrcVal->getType() == Type::DoubleTy && DstTy == Type::FloatTy &&
983          "Invalid FPTrunc instruction");
984   Dest.FloatVal = (float) Src.DoubleVal;
985   return Dest;
986 }
987
988 GenericValue Interpreter::executeFPExtInst(Value *SrcVal, const Type *DstTy,
989                                            ExecutionContext &SF) {
990   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
991   assert(SrcVal->getType() == Type::FloatTy && DstTy == Type::DoubleTy &&
992          "Invalid FPTrunc instruction");
993   Dest.DoubleVal = (double) Src.FloatVal;
994   return Dest;
995 }
996
997 GenericValue Interpreter::executeFPToUIInst(Value *SrcVal, const Type *DstTy,
998                                             ExecutionContext &SF) {
999   const Type *SrcTy = SrcVal->getType();
1000   uint32_t DBitWidth = cast<IntegerType>(DstTy)->getBitWidth();
1001   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1002   assert(SrcTy->isFloatingPoint() && "Invalid FPToUI instruction");
1003
1004   if (SrcTy->getTypeID() == Type::FloatTyID)
1005     Dest.IntVal = APIntOps::RoundFloatToAPInt(Src.FloatVal, DBitWidth);
1006   else
1007     Dest.IntVal = APIntOps::RoundDoubleToAPInt(Src.DoubleVal, DBitWidth);
1008   return Dest;
1009 }
1010
1011 GenericValue Interpreter::executeFPToSIInst(Value *SrcVal, const Type *DstTy,
1012                                             ExecutionContext &SF) {
1013   const Type *SrcTy = SrcVal->getType();
1014   uint32_t DBitWidth = cast<IntegerType>(DstTy)->getBitWidth();
1015   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1016   assert(SrcTy->isFloatingPoint() && "Invalid FPToSI instruction");
1017
1018   if (SrcTy->getTypeID() == Type::FloatTyID)
1019     Dest.IntVal = APIntOps::RoundFloatToAPInt(Src.FloatVal, DBitWidth);
1020   else
1021     Dest.IntVal = APIntOps::RoundDoubleToAPInt(Src.DoubleVal, DBitWidth);
1022   return Dest;
1023 }
1024
1025 GenericValue Interpreter::executeUIToFPInst(Value *SrcVal, const Type *DstTy,
1026                                             ExecutionContext &SF) {
1027   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1028   assert(DstTy->isFloatingPoint() && "Invalid UIToFP instruction");
1029
1030   if (DstTy->getTypeID() == Type::FloatTyID)
1031     Dest.FloatVal = APIntOps::RoundAPIntToFloat(Src.IntVal);
1032   else
1033     Dest.DoubleVal = APIntOps::RoundAPIntToDouble(Src.IntVal);
1034   return Dest;
1035 }
1036
1037 GenericValue Interpreter::executeSIToFPInst(Value *SrcVal, const Type *DstTy,
1038                                             ExecutionContext &SF) {
1039   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1040   assert(DstTy->isFloatingPoint() && "Invalid SIToFP instruction");
1041
1042   if (DstTy->getTypeID() == Type::FloatTyID)
1043     Dest.FloatVal = APIntOps::RoundSignedAPIntToFloat(Src.IntVal);
1044   else
1045     Dest.DoubleVal = APIntOps::RoundSignedAPIntToDouble(Src.IntVal);
1046   return Dest;
1047
1048 }
1049
1050 GenericValue Interpreter::executePtrToIntInst(Value *SrcVal, const Type *DstTy,
1051                                               ExecutionContext &SF) {
1052   uint32_t DBitWidth = cast<IntegerType>(DstTy)->getBitWidth();
1053   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1054   assert(isa<PointerType>(SrcVal->getType()) && "Invalid PtrToInt instruction");
1055
1056   Dest.IntVal = APInt(DBitWidth, (intptr_t) Src.PointerVal);
1057   return Dest;
1058 }
1059
1060 GenericValue Interpreter::executeIntToPtrInst(Value *SrcVal, const Type *DstTy,
1061                                               ExecutionContext &SF) {
1062   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1063   assert(isa<PointerType>(DstTy) && "Invalid PtrToInt instruction");
1064
1065   uint32_t PtrSize = TD.getPointerSizeInBits();
1066   if (PtrSize != Src.IntVal.getBitWidth())
1067     Src.IntVal = Src.IntVal.zextOrTrunc(PtrSize);
1068
1069   Dest.PointerVal = PointerTy(intptr_t(Src.IntVal.getZExtValue()));
1070   return Dest;
1071 }
1072
1073 GenericValue Interpreter::executeBitCastInst(Value *SrcVal, const Type *DstTy,
1074                                              ExecutionContext &SF) {
1075   
1076   const Type *SrcTy = SrcVal->getType();
1077   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1078   if (isa<PointerType>(DstTy)) {
1079     assert(isa<PointerType>(SrcTy) && "Invalid BitCast");
1080     Dest.PointerVal = Src.PointerVal;
1081   } else if (DstTy->isInteger()) {
1082     if (SrcTy == Type::FloatTy) {
1083       Dest.IntVal.zext(sizeof(Src.FloatVal) * CHAR_BIT);
1084       Dest.IntVal.floatToBits(Src.FloatVal);
1085     } else if (SrcTy == Type::DoubleTy) {
1086       Dest.IntVal.zext(sizeof(Src.DoubleVal) * CHAR_BIT);
1087       Dest.IntVal.doubleToBits(Src.DoubleVal);
1088     } else if (SrcTy->isInteger()) {
1089       Dest.IntVal = Src.IntVal;
1090     } else 
1091       assert(0 && "Invalid BitCast");
1092   } else if (DstTy == Type::FloatTy) {
1093     if (SrcTy->isInteger())
1094       Dest.FloatVal = Src.IntVal.bitsToFloat();
1095     else
1096       Dest.FloatVal = Src.FloatVal;
1097   } else if (DstTy == Type::DoubleTy) {
1098     if (SrcTy->isInteger())
1099       Dest.DoubleVal = Src.IntVal.bitsToDouble();
1100     else
1101       Dest.DoubleVal = Src.DoubleVal;
1102   } else
1103     assert(0 && "Invalid Bitcast");
1104
1105   return Dest;
1106 }
1107
1108 void Interpreter::visitTruncInst(TruncInst &I) {
1109   ExecutionContext &SF = ECStack.back();
1110   SetValue(&I, executeTruncInst(I.getOperand(0), I.getType(), SF), SF);
1111 }
1112
1113 void Interpreter::visitSExtInst(SExtInst &I) {
1114   ExecutionContext &SF = ECStack.back();
1115   SetValue(&I, executeSExtInst(I.getOperand(0), I.getType(), SF), SF);
1116 }
1117
1118 void Interpreter::visitZExtInst(ZExtInst &I) {
1119   ExecutionContext &SF = ECStack.back();
1120   SetValue(&I, executeZExtInst(I.getOperand(0), I.getType(), SF), SF);
1121 }
1122
1123 void Interpreter::visitFPTruncInst(FPTruncInst &I) {
1124   ExecutionContext &SF = ECStack.back();
1125   SetValue(&I, executeFPTruncInst(I.getOperand(0), I.getType(), SF), SF);
1126 }
1127
1128 void Interpreter::visitFPExtInst(FPExtInst &I) {
1129   ExecutionContext &SF = ECStack.back();
1130   SetValue(&I, executeFPExtInst(I.getOperand(0), I.getType(), SF), SF);
1131 }
1132
1133 void Interpreter::visitUIToFPInst(UIToFPInst &I) {
1134   ExecutionContext &SF = ECStack.back();
1135   SetValue(&I, executeUIToFPInst(I.getOperand(0), I.getType(), SF), SF);
1136 }
1137
1138 void Interpreter::visitSIToFPInst(SIToFPInst &I) {
1139   ExecutionContext &SF = ECStack.back();
1140   SetValue(&I, executeSIToFPInst(I.getOperand(0), I.getType(), SF), SF);
1141 }
1142
1143 void Interpreter::visitFPToUIInst(FPToUIInst &I) {
1144   ExecutionContext &SF = ECStack.back();
1145   SetValue(&I, executeFPToUIInst(I.getOperand(0), I.getType(), SF), SF);
1146 }
1147
1148 void Interpreter::visitFPToSIInst(FPToSIInst &I) {
1149   ExecutionContext &SF = ECStack.back();
1150   SetValue(&I, executeFPToSIInst(I.getOperand(0), I.getType(), SF), SF);
1151 }
1152
1153 void Interpreter::visitPtrToIntInst(PtrToIntInst &I) {
1154   ExecutionContext &SF = ECStack.back();
1155   SetValue(&I, executePtrToIntInst(I.getOperand(0), I.getType(), SF), SF);
1156 }
1157
1158 void Interpreter::visitIntToPtrInst(IntToPtrInst &I) {
1159   ExecutionContext &SF = ECStack.back();
1160   SetValue(&I, executeIntToPtrInst(I.getOperand(0), I.getType(), SF), SF);
1161 }
1162
1163 void Interpreter::visitBitCastInst(BitCastInst &I) {
1164   ExecutionContext &SF = ECStack.back();
1165   SetValue(&I, executeBitCastInst(I.getOperand(0), I.getType(), SF), SF);
1166 }
1167
1168 #define IMPLEMENT_VAARG(TY) \
1169    case Type::TY##TyID: Dest.TY##Val = Src.TY##Val; break
1170
1171 void Interpreter::visitVAArgInst(VAArgInst &I) {
1172   ExecutionContext &SF = ECStack.back();
1173
1174   // Get the incoming valist parameter.  LLI treats the valist as a
1175   // (ec-stack-depth var-arg-index) pair.
1176   GenericValue VAList = getOperandValue(I.getOperand(0), SF);
1177   GenericValue Dest;
1178   GenericValue Src = ECStack[VAList.UIntPairVal.first]
1179                       .VarArgs[VAList.UIntPairVal.second];
1180   const Type *Ty = I.getType();
1181   switch (Ty->getTypeID()) {
1182     case Type::IntegerTyID: Dest.IntVal = Src.IntVal;
1183     IMPLEMENT_VAARG(Pointer);
1184     IMPLEMENT_VAARG(Float);
1185     IMPLEMENT_VAARG(Double);
1186   default:
1187     cerr << "Unhandled dest type for vaarg instruction: " << *Ty << "\n";
1188     abort();
1189   }
1190
1191   // Set the Value of this Instruction.
1192   SetValue(&I, Dest, SF);
1193
1194   // Move the pointer to the next vararg.
1195   ++VAList.UIntPairVal.second;
1196 }
1197
1198 GenericValue Interpreter::getConstantExprValue (ConstantExpr *CE,
1199                                                 ExecutionContext &SF) {
1200   switch (CE->getOpcode()) {
1201   case Instruction::Trunc:   
1202       return executeTruncInst(CE->getOperand(0), CE->getType(), SF);
1203   case Instruction::ZExt:
1204       return executeZExtInst(CE->getOperand(0), CE->getType(), SF);
1205   case Instruction::SExt:
1206       return executeSExtInst(CE->getOperand(0), CE->getType(), SF);
1207   case Instruction::FPTrunc:
1208       return executeFPTruncInst(CE->getOperand(0), CE->getType(), SF);
1209   case Instruction::FPExt:
1210       return executeFPExtInst(CE->getOperand(0), CE->getType(), SF);
1211   case Instruction::UIToFP:
1212       return executeUIToFPInst(CE->getOperand(0), CE->getType(), SF);
1213   case Instruction::SIToFP:
1214       return executeSIToFPInst(CE->getOperand(0), CE->getType(), SF);
1215   case Instruction::FPToUI:
1216       return executeFPToUIInst(CE->getOperand(0), CE->getType(), SF);
1217   case Instruction::FPToSI:
1218       return executeFPToSIInst(CE->getOperand(0), CE->getType(), SF);
1219   case Instruction::PtrToInt:
1220       return executePtrToIntInst(CE->getOperand(0), CE->getType(), SF);
1221   case Instruction::IntToPtr:
1222       return executeIntToPtrInst(CE->getOperand(0), CE->getType(), SF);
1223   case Instruction::BitCast:
1224       return executeBitCastInst(CE->getOperand(0), CE->getType(), SF);
1225   case Instruction::GetElementPtr:
1226     return executeGEPOperation(CE->getOperand(0), gep_type_begin(CE),
1227                                gep_type_end(CE), SF);
1228   case Instruction::FCmp:
1229   case Instruction::ICmp:
1230     return executeCmpInst(CE->getPredicate(),
1231                           getOperandValue(CE->getOperand(0), SF),
1232                           getOperandValue(CE->getOperand(1), SF),
1233                           CE->getOperand(0)->getType());
1234   case Instruction::Select:
1235     return executeSelectInst(getOperandValue(CE->getOperand(0), SF),
1236                              getOperandValue(CE->getOperand(1), SF),
1237                              getOperandValue(CE->getOperand(2), SF));
1238   default :
1239     break;
1240   }
1241
1242   // The cases below here require a GenericValue parameter for the result
1243   // so we initialize one, compute it and then return it.
1244   GenericValue Op0 = getOperandValue(CE->getOperand(0), SF);
1245   GenericValue Op1 = getOperandValue(CE->getOperand(1), SF);
1246   GenericValue Dest;
1247   const Type * Ty = CE->getOperand(0)->getType();
1248   switch (CE->getOpcode()) {
1249   case Instruction::Add:  Dest.IntVal = Op0.IntVal + Op1.IntVal; break;
1250   case Instruction::Sub:  Dest.IntVal = Op0.IntVal - Op1.IntVal; break;
1251   case Instruction::Mul:  Dest.IntVal = Op0.IntVal * Op1.IntVal; break;
1252   case Instruction::FAdd: executeFAddInst(Dest, Op0, Op1, Ty); break;
1253   case Instruction::FSub: executeFSubInst(Dest, Op0, Op1, Ty); break;
1254   case Instruction::FMul: executeFMulInst(Dest, Op0, Op1, Ty); break;
1255   case Instruction::FDiv: executeFDivInst(Dest, Op0, Op1, Ty); break;
1256   case Instruction::FRem: executeFRemInst(Dest, Op0, Op1, Ty); break;
1257   case Instruction::SDiv: Dest.IntVal = Op0.IntVal.sdiv(Op1.IntVal); break;
1258   case Instruction::UDiv: Dest.IntVal = Op0.IntVal.udiv(Op1.IntVal); break;
1259   case Instruction::URem: Dest.IntVal = Op0.IntVal.urem(Op1.IntVal); break;
1260   case Instruction::SRem: Dest.IntVal = Op0.IntVal.srem(Op1.IntVal); break;
1261   case Instruction::And:  Dest.IntVal = Op0.IntVal & Op1.IntVal; break;
1262   case Instruction::Or:   Dest.IntVal = Op0.IntVal | Op1.IntVal; break;
1263   case Instruction::Xor:  Dest.IntVal = Op0.IntVal ^ Op1.IntVal; break;
1264   case Instruction::Shl:  
1265     Dest.IntVal = Op0.IntVal.shl(Op1.IntVal.getZExtValue());
1266     break;
1267   case Instruction::LShr: 
1268     Dest.IntVal = Op0.IntVal.lshr(Op1.IntVal.getZExtValue());
1269     break;
1270   case Instruction::AShr: 
1271     Dest.IntVal = Op0.IntVal.ashr(Op1.IntVal.getZExtValue());
1272     break;
1273   default:
1274     cerr << "Unhandled ConstantExpr: " << *CE << "\n";
1275     abort();
1276     return GenericValue();
1277   }
1278   return Dest;
1279 }
1280
1281 GenericValue Interpreter::getOperandValue(Value *V, ExecutionContext &SF) {
1282   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1283     return getConstantExprValue(CE, SF);
1284   } else if (Constant *CPV = dyn_cast<Constant>(V)) {
1285     return getConstantValue(CPV);
1286   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1287     return PTOGV(getPointerToGlobal(GV));
1288   } else {
1289     return SF.Values[V];
1290   }
1291 }
1292
1293 //===----------------------------------------------------------------------===//
1294 //                        Dispatch and Execution Code
1295 //===----------------------------------------------------------------------===//
1296
1297 //===----------------------------------------------------------------------===//
1298 // callFunction - Execute the specified function...
1299 //
1300 void Interpreter::callFunction(Function *F,
1301                                const std::vector<GenericValue> &ArgVals) {
1302   assert((ECStack.empty() || ECStack.back().Caller.getInstruction() == 0 ||
1303           ECStack.back().Caller.arg_size() == ArgVals.size()) &&
1304          "Incorrect number of arguments passed into function call!");
1305   // Make a new stack frame... and fill it in.
1306   ECStack.push_back(ExecutionContext());
1307   ExecutionContext &StackFrame = ECStack.back();
1308   StackFrame.CurFunction = F;
1309
1310   // Special handling for external functions.
1311   if (F->isDeclaration()) {
1312     GenericValue Result = callExternalFunction (F, ArgVals);
1313     // Simulate a 'ret' instruction of the appropriate type.
1314     popStackAndReturnValueToCaller (F->getReturnType (), Result);
1315     return;
1316   }
1317
1318   // Get pointers to first LLVM BB & Instruction in function.
1319   StackFrame.CurBB     = F->begin();
1320   StackFrame.CurInst   = StackFrame.CurBB->begin();
1321
1322   // Run through the function arguments and initialize their values...
1323   assert((ArgVals.size() == F->arg_size() ||
1324          (ArgVals.size() > F->arg_size() && F->getFunctionType()->isVarArg()))&&
1325          "Invalid number of values passed to function invocation!");
1326
1327   // Handle non-varargs arguments...
1328   unsigned i = 0;
1329   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 
1330        AI != E; ++AI, ++i)
1331     SetValue(AI, ArgVals[i], StackFrame);
1332
1333   // Handle varargs arguments...
1334   StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
1335 }
1336
1337
1338 void Interpreter::run() {
1339   while (!ECStack.empty()) {
1340     // Interpret a single instruction & increment the "PC".
1341     ExecutionContext &SF = ECStack.back();  // Current stack frame
1342     Instruction &I = *SF.CurInst++;         // Increment before execute
1343
1344     // Track the number of dynamic instructions executed.
1345     ++NumDynamicInsts;
1346
1347     DOUT << "About to interpret: " << I;
1348     visit(I);   // Dispatch to one of the visit* methods...
1349 #if 0
1350     // This is not safe, as visiting the instruction could lower it and free I.
1351 #ifndef NDEBUG
1352     if (!isa<CallInst>(I) && !isa<InvokeInst>(I) && 
1353         I.getType() != Type::VoidTy) {
1354       DOUT << "  --> ";
1355       const GenericValue &Val = SF.Values[&I];
1356       switch (I.getType()->getTypeID()) {
1357       default: assert(0 && "Invalid GenericValue Type");
1358       case Type::VoidTyID:    DOUT << "void"; break;
1359       case Type::FloatTyID:   DOUT << "float " << Val.FloatVal; break;
1360       case Type::DoubleTyID:  DOUT << "double " << Val.DoubleVal; break;
1361       case Type::PointerTyID: DOUT << "void* " << intptr_t(Val.PointerVal);
1362         break;
1363       case Type::IntegerTyID: 
1364         DOUT << "i" << Val.IntVal.getBitWidth() << " "
1365         << Val.IntVal.toStringUnsigned(10)
1366         << " (0x" << Val.IntVal.toStringUnsigned(16) << ")\n";
1367         break;
1368       }
1369     }
1370 #endif
1371 #endif
1372   }
1373 }