Implement bit-accurate sext instruction.
[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 #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/Statistic.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/MathExtras.h"
24 #include <cmath>
25 using namespace llvm;
26
27 STATISTIC(NumDynamicInsts, "Number of dynamic instructions executed");
28 static Interpreter *TheEE = 0;
29
30
31 //===----------------------------------------------------------------------===//
32 //                     Value Manipulation code
33 //===----------------------------------------------------------------------===//
34
35 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
36                                    const Type *Ty);
37 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
38                                    const Type *Ty);
39 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2,
40                                    const Type *Ty);
41 static GenericValue executeUDivInst(GenericValue Src1, GenericValue Src2,
42                                     const Type *Ty);
43 static GenericValue executeSDivInst(GenericValue Src1, GenericValue Src2,
44                                     const Type *Ty);
45 static GenericValue executeFDivInst(GenericValue Src1, GenericValue Src2,
46                                     const Type *Ty);
47 static GenericValue executeURemInst(GenericValue Src1, GenericValue Src2,
48                                     const Type *Ty);
49 static GenericValue executeSRemInst(GenericValue Src1, GenericValue Src2,
50                                     const Type *Ty);
51 static GenericValue executeFRemInst(GenericValue Src1, GenericValue Src2,
52                                     const Type *Ty);
53 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2,
54                                    const Type *Ty);
55 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2,
56                                    const Type *Ty);
57 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2,
58                                    const Type *Ty);
59 static GenericValue executeCmpInst(unsigned predicate, GenericValue Src1, 
60                                    GenericValue Src2, const Type *Ty);
61 static GenericValue executeShlInst(GenericValue Src1, GenericValue Src2,
62                                    const Type *Ty);
63 static GenericValue executeLShrInst(GenericValue Src1, GenericValue Src2,
64                                     const Type *Ty);
65 static GenericValue executeAShrInst(GenericValue Src1, GenericValue Src2,
66                                     const Type *Ty);
67 static GenericValue executeSelectInst(GenericValue Src1, GenericValue Src2,
68                                       GenericValue Src3);
69
70 GenericValue Interpreter::getConstantExprValue (ConstantExpr *CE,
71                                                 ExecutionContext &SF) {
72   switch (CE->getOpcode()) {
73   case Instruction::Trunc:   
74       return executeTruncInst(CE->getOperand(0), CE->getType(), SF);
75   case Instruction::ZExt:
76       return executeZExtInst(CE->getOperand(0), CE->getType(), SF);
77   case Instruction::SExt:
78       return executeSExtInst(CE->getOperand(0), CE->getType(), SF);
79   case Instruction::FPTrunc:
80       return executeFPTruncInst(CE->getOperand(0), CE->getType(), SF);
81   case Instruction::FPExt:
82       return executeFPExtInst(CE->getOperand(0), CE->getType(), SF);
83   case Instruction::UIToFP:
84       return executeUIToFPInst(CE->getOperand(0), CE->getType(), SF);
85   case Instruction::SIToFP:
86       return executeSIToFPInst(CE->getOperand(0), CE->getType(), SF);
87   case Instruction::FPToUI:
88       return executeFPToUIInst(CE->getOperand(0), CE->getType(), SF);
89   case Instruction::FPToSI:
90       return executeFPToSIInst(CE->getOperand(0), CE->getType(), SF);
91   case Instruction::PtrToInt:
92       return executePtrToIntInst(CE->getOperand(0), CE->getType(), SF);
93   case Instruction::IntToPtr:
94       return executeIntToPtrInst(CE->getOperand(0), CE->getType(), SF);
95   case Instruction::BitCast:
96       return executeBitCastInst(CE->getOperand(0), CE->getType(), SF);
97   case Instruction::GetElementPtr:
98     return executeGEPOperation(CE->getOperand(0), gep_type_begin(CE),
99                                gep_type_end(CE), SF);
100   case Instruction::Add:
101     return executeAddInst(getOperandValue(CE->getOperand(0), SF),
102                           getOperandValue(CE->getOperand(1), SF),
103                           CE->getOperand(0)->getType());
104   case Instruction::Sub:
105     return executeSubInst(getOperandValue(CE->getOperand(0), SF),
106                           getOperandValue(CE->getOperand(1), SF),
107                           CE->getOperand(0)->getType());
108   case Instruction::Mul:
109     return executeMulInst(getOperandValue(CE->getOperand(0), SF),
110                           getOperandValue(CE->getOperand(1), SF),
111                           CE->getOperand(0)->getType());
112   case Instruction::SDiv:
113     return executeSDivInst(getOperandValue(CE->getOperand(0), SF),
114                            getOperandValue(CE->getOperand(1), SF),
115                            CE->getOperand(0)->getType());
116   case Instruction::UDiv:
117     return executeUDivInst(getOperandValue(CE->getOperand(0), SF),
118                            getOperandValue(CE->getOperand(1), SF),
119                            CE->getOperand(0)->getType());
120   case Instruction::FDiv:
121     return executeFDivInst(getOperandValue(CE->getOperand(0), SF),
122                            getOperandValue(CE->getOperand(1), SF),
123                            CE->getOperand(0)->getType());
124   case Instruction::URem:
125     return executeURemInst(getOperandValue(CE->getOperand(0), SF),
126                           getOperandValue(CE->getOperand(1), SF),
127                           CE->getOperand(0)->getType());
128   case Instruction::SRem:
129     return executeSRemInst(getOperandValue(CE->getOperand(0), SF),
130                           getOperandValue(CE->getOperand(1), SF),
131                           CE->getOperand(0)->getType());
132   case Instruction::FRem:
133     return executeFRemInst(getOperandValue(CE->getOperand(0), SF),
134                            getOperandValue(CE->getOperand(1), SF),
135                            CE->getOperand(0)->getType());
136   case Instruction::And:
137     return executeAndInst(getOperandValue(CE->getOperand(0), SF),
138                           getOperandValue(CE->getOperand(1), SF),
139                           CE->getOperand(0)->getType());
140   case Instruction::Or:
141     return executeOrInst(getOperandValue(CE->getOperand(0), SF),
142                          getOperandValue(CE->getOperand(1), SF),
143                          CE->getOperand(0)->getType());
144   case Instruction::Xor:
145     return executeXorInst(getOperandValue(CE->getOperand(0), SF),
146                           getOperandValue(CE->getOperand(1), SF),
147                           CE->getOperand(0)->getType());
148   case Instruction::FCmp:
149   case Instruction::ICmp:
150     return executeCmpInst(CE->getPredicate(),
151                           getOperandValue(CE->getOperand(0), SF),
152                           getOperandValue(CE->getOperand(1), SF),
153                           CE->getOperand(0)->getType());
154   case Instruction::Shl:
155     return executeShlInst(getOperandValue(CE->getOperand(0), SF),
156                           getOperandValue(CE->getOperand(1), SF),
157                           CE->getOperand(0)->getType());
158   case Instruction::LShr:
159     return executeLShrInst(getOperandValue(CE->getOperand(0), SF),
160                            getOperandValue(CE->getOperand(1), SF),
161                            CE->getOperand(0)->getType());
162   case Instruction::AShr:
163     return executeAShrInst(getOperandValue(CE->getOperand(0), SF),
164                            getOperandValue(CE->getOperand(1), SF),
165                            CE->getOperand(0)->getType());
166   case Instruction::Select:
167     return executeSelectInst(getOperandValue(CE->getOperand(0), SF),
168                              getOperandValue(CE->getOperand(1), SF),
169                              getOperandValue(CE->getOperand(2), SF));
170   default:
171     cerr << "Unhandled ConstantExpr: " << *CE << "\n";
172     abort();
173     return GenericValue();
174   }
175 }
176
177 GenericValue Interpreter::getOperandValue(Value *V, ExecutionContext &SF) {
178   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
179     return getConstantExprValue(CE, SF);
180   } else if (Constant *CPV = dyn_cast<Constant>(V)) {
181     return getConstantValue(CPV);
182   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
183     return PTOGV(getPointerToGlobal(GV));
184   } else {
185     return SF.Values[V];
186   }
187 }
188
189 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
190   SF.Values[V] = Val;
191 }
192
193 void Interpreter::initializeExecutionEngine() {
194   TheEE = this;
195 }
196
197 //===----------------------------------------------------------------------===//
198 //                    Binary Instruction Implementations
199 //===----------------------------------------------------------------------===//
200
201 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
202    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
203
204 #define IMPLEMENT_INTEGER_BINOP(OP, TY) \
205    case Type::IntegerTyID: { \
206      unsigned BitWidth = cast<IntegerType>(TY)->getBitWidth(); \
207      if (BitWidth == 1) \
208        Dest.Int1Val = Src1.Int1Val OP Src2.Int1Val; \
209      else if (BitWidth <= 8) \
210        Dest.Int8Val = Src1.Int8Val OP Src2.Int8Val; \
211      else if (BitWidth <= 16) \
212        Dest.Int16Val = Src1.Int16Val OP Src2.Int16Val; \
213      else if (BitWidth <= 32) \
214        Dest.Int32Val = Src1.Int32Val OP Src2.Int32Val; \
215      else if (BitWidth <= 64) \
216        Dest.Int64Val = Src1.Int64Val OP Src2.Int64Val; \
217      else \
218       cerr << "Integer types > 64 bits not supported: " << *Ty << "\n"; \
219      maskToBitWidth(Dest, BitWidth); \
220      break; \
221    }
222
223 #define IMPLEMENT_SIGNED_BINOP(OP, TY) \
224    if (const IntegerType *ITy = dyn_cast<IntegerType>(TY)) { \
225      unsigned BitWidth = ITy->getBitWidth(); \
226      if (BitWidth <= 8) \
227        Dest.Int8Val  = ((int8_t)Src1.Int8Val)   OP ((int8_t)Src2.Int8Val); \
228      else if (BitWidth <= 16) \
229        Dest.Int16Val = ((int16_t)Src1.Int16Val) OP ((int16_t)Src2.Int16Val); \
230      else if (BitWidth <= 32) \
231        Dest.Int32Val = ((int32_t)Src1.Int32Val) OP ((int32_t)Src2.Int32Val); \
232      else if (BitWidth <= 64) \
233        Dest.Int64Val = ((int64_t)Src1.Int64Val) OP ((int64_t)Src2.Int64Val); \
234      else { \
235       cerr << "Integer types > 64 bits not supported: " << *Ty << "\n"; \
236        abort(); \
237      } \
238      maskToBitWidth(Dest, BitWidth); \
239    } else { \
240     cerr << "Unhandled type for " #OP " operator: " << *Ty << "\n"; \
241     abort(); \
242    }
243
244 #define IMPLEMENT_UNSIGNED_BINOP(OP, TY) \
245    if (const IntegerType *ITy = dyn_cast<IntegerType>(TY)) { \
246      unsigned BitWidth = ITy->getBitWidth(); \
247      if (BitWidth <= 8) \
248        Dest.Int8Val  = ((uint8_t)Src1.Int8Val)   OP ((uint8_t)Src2.Int8Val); \
249      else if (BitWidth <= 16) \
250        Dest.Int16Val = ((uint16_t)Src1.Int16Val) OP ((uint16_t)Src2.Int16Val); \
251      else if (BitWidth <= 32) \
252        Dest.Int32Val = ((uint32_t)Src1.Int32Val) OP ((uint32_t)Src2.Int32Val); \
253      else if (BitWidth <= 64) \
254        Dest.Int64Val = ((uint64_t)Src1.Int64Val) OP ((uint64_t)Src2.Int64Val); \
255      else { \
256       cerr << "Integer types > 64 bits not supported: " << *Ty << "\n"; \
257        abort(); \
258      } \
259      maskToBitWidth(Dest, BitWidth); \
260    } else { \
261     cerr << "Unhandled type for " #OP " operator: " << *Ty << "\n"; \
262     abort(); \
263   }
264
265 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
266                                    const Type *Ty) {
267   GenericValue Dest;
268   switch (Ty->getTypeID()) {
269     IMPLEMENT_INTEGER_BINOP(+, Ty);
270     IMPLEMENT_BINARY_OPERATOR(+, Float);
271     IMPLEMENT_BINARY_OPERATOR(+, Double);
272   default:
273     cerr << "Unhandled type for Add instruction: " << *Ty << "\n";
274     abort();
275   }
276   return Dest;
277 }
278
279 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
280                                    const Type *Ty) {
281   GenericValue Dest;
282   switch (Ty->getTypeID()) {
283     IMPLEMENT_INTEGER_BINOP(-, Ty);
284     IMPLEMENT_BINARY_OPERATOR(-, Float);
285     IMPLEMENT_BINARY_OPERATOR(-, Double);
286   default:
287     cerr << "Unhandled type for Sub instruction: " << *Ty << "\n";
288     abort();
289   }
290   return Dest;
291 }
292
293 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2,
294                                    const Type *Ty) {
295   GenericValue Dest;
296   switch (Ty->getTypeID()) {
297     IMPLEMENT_INTEGER_BINOP(*, Ty);
298     IMPLEMENT_BINARY_OPERATOR(*, Float);
299     IMPLEMENT_BINARY_OPERATOR(*, Double);
300   default:
301     cerr << "Unhandled type for Mul instruction: " << *Ty << "\n";
302     abort();
303   }
304   return Dest;
305 }
306
307 static GenericValue executeUDivInst(GenericValue Src1, GenericValue Src2,
308                                    const Type *Ty) {
309   GenericValue Dest;
310   IMPLEMENT_UNSIGNED_BINOP(/,Ty)
311   return Dest;
312 }
313
314 static GenericValue executeSDivInst(GenericValue Src1, GenericValue Src2,
315                                    const Type *Ty) {
316   GenericValue Dest;
317   IMPLEMENT_SIGNED_BINOP(/,Ty)
318   return Dest;
319 }
320
321 static GenericValue executeFDivInst(GenericValue Src1, GenericValue Src2,
322                                    const Type *Ty) {
323   GenericValue Dest;
324   switch (Ty->getTypeID()) {
325     IMPLEMENT_BINARY_OPERATOR(/, Float);
326     IMPLEMENT_BINARY_OPERATOR(/, Double);
327   default:
328     cerr << "Unhandled type for FDiv instruction: " << *Ty << "\n";
329     abort();
330   }
331   return Dest;
332 }
333
334 static GenericValue executeURemInst(GenericValue Src1, GenericValue Src2,
335                                    const Type *Ty) {
336   GenericValue Dest;
337   IMPLEMENT_UNSIGNED_BINOP(%, Ty)
338   return Dest;
339 }
340
341 static GenericValue executeSRemInst(GenericValue Src1, GenericValue Src2,
342                                    const Type *Ty) {
343   GenericValue Dest;
344   IMPLEMENT_SIGNED_BINOP(%, Ty)
345   return Dest;
346 }
347
348 static GenericValue executeFRemInst(GenericValue Src1, GenericValue Src2,
349                                    const Type *Ty) {
350   GenericValue Dest;
351   switch (Ty->getTypeID()) {
352   case Type::FloatTyID:
353     Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
354     break;
355   case Type::DoubleTyID:
356     Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
357     break;
358   default:
359     cerr << "Unhandled type for Rem instruction: " << *Ty << "\n";
360     abort();
361   }
362   return Dest;
363 }
364
365 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2,
366                                    const Type *Ty) {
367   GenericValue Dest;
368   IMPLEMENT_UNSIGNED_BINOP(&, Ty)
369   return Dest;
370 }
371
372 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2,
373                                   const Type *Ty) {
374   GenericValue Dest;
375   IMPLEMENT_UNSIGNED_BINOP(|, Ty)
376   return Dest;
377 }
378
379 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2,
380                                    const Type *Ty) {
381   GenericValue Dest;
382   IMPLEMENT_UNSIGNED_BINOP(^, Ty)
383   return Dest;
384 }
385
386 #define IMPLEMENT_SIGNED_ICMP(OP, TY) \
387    case Type::IntegerTyID: {  \
388      unsigned BitWidth = cast<IntegerType>(TY)->getBitWidth(); \
389      if (BitWidth == 1) \
390        Dest.Int1Val = ((int8_t)Src1.Int1Val)   OP ((int8_t)Src2.Int1Val); \
391      else if (BitWidth <= 8) \
392        Dest.Int1Val = ((int8_t)Src1.Int8Val)   OP ((int8_t)Src2.Int8Val); \
393      else if (BitWidth <= 16) \
394        Dest.Int1Val = ((int16_t)Src1.Int16Val) OP ((int16_t)Src2.Int16Val); \
395      else if (BitWidth <= 32) \
396        Dest.Int1Val = ((int32_t)Src1.Int32Val) OP ((int32_t)Src2.Int32Val); \
397      else if (BitWidth <= 64) \
398        Dest.Int1Val = ((int64_t)Src1.Int64Val) OP ((int64_t)Src2.Int64Val); \
399      else { \
400       cerr << "Integer types > 64 bits not supported: " << *Ty << "\n"; \
401        abort(); \
402      } \
403      maskToBitWidth(Dest, BitWidth); \
404      break; \
405    }
406
407 #define IMPLEMENT_UNSIGNED_ICMP(OP, TY) \
408    case Type::IntegerTyID: { \
409      unsigned BitWidth = cast<IntegerType>(TY)->getBitWidth(); \
410      if (BitWidth == 1) \
411        Dest.Int1Val = ((uint8_t)Src1.Int1Val)   OP ((uint8_t)Src2.Int1Val); \
412      else if (BitWidth <= 8) \
413        Dest.Int1Val = ((uint8_t)Src1.Int8Val)   OP ((uint8_t)Src2.Int8Val); \
414      else if (BitWidth <= 16) \
415        Dest.Int1Val = ((uint16_t)Src1.Int16Val) OP ((uint16_t)Src2.Int16Val); \
416      else if (BitWidth <= 32) \
417        Dest.Int1Val = ((uint32_t)Src1.Int32Val) OP ((uint32_t)Src2.Int32Val); \
418      else if (BitWidth <= 64) \
419        Dest.Int1Val = ((uint64_t)Src1.Int64Val) OP ((uint64_t)Src2.Int64Val); \
420      else { \
421       cerr << "Integer types > 64 bits not supported: " << *Ty << "\n"; \
422        abort(); \
423      } \
424      maskToBitWidth(Dest, BitWidth); \
425      break; \
426    }
427
428 // Handle pointers specially because they must be compared with only as much
429 // width as the host has.  We _do not_ want to be comparing 64 bit values when
430 // running on a 32-bit target, otherwise the upper 32 bits might mess up
431 // comparisons if they contain garbage.
432 #define IMPLEMENT_POINTER_ICMP(OP) \
433    case Type::PointerTyID: \
434         Dest.Int1Val = (void*)(intptr_t)Src1.PointerVal OP \
435                        (void*)(intptr_t)Src2.PointerVal; break
436
437 static GenericValue executeICMP_EQ(GenericValue Src1, GenericValue Src2,
438                                    const Type *Ty) {
439   GenericValue Dest;
440   switch (Ty->getTypeID()) {
441     IMPLEMENT_UNSIGNED_ICMP(==, Ty);
442     IMPLEMENT_POINTER_ICMP(==);
443   default:
444     cerr << "Unhandled type for ICMP_EQ predicate: " << *Ty << "\n";
445     abort();
446   }
447   return Dest;
448 }
449
450 static GenericValue executeICMP_NE(GenericValue Src1, GenericValue Src2,
451                                    const Type *Ty) {
452   GenericValue Dest;
453   switch (Ty->getTypeID()) {
454     IMPLEMENT_UNSIGNED_ICMP(!=, Ty);
455     IMPLEMENT_POINTER_ICMP(!=);
456   default:
457     cerr << "Unhandled type for ICMP_NE predicate: " << *Ty << "\n";
458     abort();
459   }
460   return Dest;
461 }
462
463 static GenericValue executeICMP_ULT(GenericValue Src1, GenericValue Src2,
464                                     const Type *Ty) {
465   GenericValue Dest;
466   switch (Ty->getTypeID()) {
467     IMPLEMENT_UNSIGNED_ICMP(<, Ty);
468     IMPLEMENT_POINTER_ICMP(<);
469   default:
470     cerr << "Unhandled type for ICMP_ULT predicate: " << *Ty << "\n";
471     abort();
472   }
473   return Dest;
474 }
475
476 static GenericValue executeICMP_SLT(GenericValue Src1, GenericValue Src2,
477                                     const Type *Ty) {
478   GenericValue Dest;
479   switch (Ty->getTypeID()) {
480     IMPLEMENT_SIGNED_ICMP(<, Ty);
481     IMPLEMENT_POINTER_ICMP(<);
482   default:
483     cerr << "Unhandled type for ICMP_SLT predicate: " << *Ty << "\n";
484     abort();
485   }
486   return Dest;
487 }
488
489 static GenericValue executeICMP_UGT(GenericValue Src1, GenericValue Src2,
490                                     const Type *Ty) {
491   GenericValue Dest;
492   switch (Ty->getTypeID()) {
493     IMPLEMENT_UNSIGNED_ICMP(>, Ty);
494     IMPLEMENT_POINTER_ICMP(>);
495   default:
496     cerr << "Unhandled type for ICMP_UGT predicate: " << *Ty << "\n";
497     abort();
498   }
499   return Dest;
500 }
501
502 static GenericValue executeICMP_SGT(GenericValue Src1, GenericValue Src2,
503                                     const Type *Ty) {
504   GenericValue Dest;
505   switch (Ty->getTypeID()) {
506     IMPLEMENT_SIGNED_ICMP(>, Ty);
507     IMPLEMENT_POINTER_ICMP(>);
508   default:
509     cerr << "Unhandled type for ICMP_SGT predicate: " << *Ty << "\n";
510     abort();
511   }
512   return Dest;
513 }
514
515 static GenericValue executeICMP_ULE(GenericValue Src1, GenericValue Src2,
516                                     const Type *Ty) {
517   GenericValue Dest;
518   switch (Ty->getTypeID()) {
519     IMPLEMENT_UNSIGNED_ICMP(<=, Ty);
520     IMPLEMENT_POINTER_ICMP(<=);
521   default:
522     cerr << "Unhandled type for ICMP_ULE predicate: " << *Ty << "\n";
523     abort();
524   }
525   return Dest;
526 }
527
528 static GenericValue executeICMP_SLE(GenericValue Src1, GenericValue Src2,
529                                     const Type *Ty) {
530   GenericValue Dest;
531   switch (Ty->getTypeID()) {
532     IMPLEMENT_SIGNED_ICMP(<=, Ty);
533     IMPLEMENT_POINTER_ICMP(<=);
534   default:
535     cerr << "Unhandled type for ICMP_SLE predicate: " << *Ty << "\n";
536     abort();
537   }
538   return Dest;
539 }
540
541 static GenericValue executeICMP_UGE(GenericValue Src1, GenericValue Src2,
542                                     const Type *Ty) {
543   GenericValue Dest;
544   switch (Ty->getTypeID()) {
545     IMPLEMENT_UNSIGNED_ICMP(>=,Ty);
546     IMPLEMENT_POINTER_ICMP(>=);
547   default:
548     cerr << "Unhandled type for ICMP_UGE predicate: " << *Ty << "\n";
549     abort();
550   }
551   return Dest;
552 }
553
554 static GenericValue executeICMP_SGE(GenericValue Src1, GenericValue Src2,
555                                     const Type *Ty) {
556   GenericValue Dest;
557   switch (Ty->getTypeID()) {
558     IMPLEMENT_SIGNED_ICMP(>=, Ty);
559     IMPLEMENT_POINTER_ICMP(>=);
560   default:
561     cerr << "Unhandled type for ICMP_SGE predicate: " << *Ty << "\n";
562     abort();
563   }
564   return Dest;
565 }
566
567 void Interpreter::visitICmpInst(ICmpInst &I) {
568   ExecutionContext &SF = ECStack.back();
569   const Type *Ty    = I.getOperand(0)->getType();
570   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
571   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
572   GenericValue R;   // Result
573   
574   switch (I.getPredicate()) {
575   case ICmpInst::ICMP_EQ:  R = executeICMP_EQ(Src1,  Src2, Ty); break;
576   case ICmpInst::ICMP_NE:  R = executeICMP_NE(Src1,  Src2, Ty); break;
577   case ICmpInst::ICMP_ULT: R = executeICMP_ULT(Src1, Src2, Ty); break;
578   case ICmpInst::ICMP_SLT: R = executeICMP_SLT(Src1, Src2, Ty); break;
579   case ICmpInst::ICMP_UGT: R = executeICMP_UGT(Src1, Src2, Ty); break;
580   case ICmpInst::ICMP_SGT: R = executeICMP_SGT(Src1, Src2, Ty); break;
581   case ICmpInst::ICMP_ULE: R = executeICMP_ULE(Src1, Src2, Ty); break;
582   case ICmpInst::ICMP_SLE: R = executeICMP_SLE(Src1, Src2, Ty); break;
583   case ICmpInst::ICMP_UGE: R = executeICMP_UGE(Src1, Src2, Ty); break;
584   case ICmpInst::ICMP_SGE: R = executeICMP_SGE(Src1, Src2, Ty); break;
585   default:
586     cerr << "Don't know how to handle this ICmp predicate!\n-->" << I;
587     abort();
588   }
589  
590   SetValue(&I, R, SF);
591 }
592
593 #define IMPLEMENT_FCMP(OP, TY) \
594    case Type::TY##TyID: Dest.Int1Val = Src1.TY##Val OP Src2.TY##Val; break
595
596 static GenericValue executeFCMP_OEQ(GenericValue Src1, GenericValue Src2,
597                                    const Type *Ty) {
598   GenericValue Dest;
599   switch (Ty->getTypeID()) {
600     IMPLEMENT_FCMP(==, Float);
601     IMPLEMENT_FCMP(==, Double);
602   default:
603     cerr << "Unhandled type for FCmp EQ instruction: " << *Ty << "\n";
604     abort();
605   }
606   return Dest;
607 }
608
609 static GenericValue executeFCMP_ONE(GenericValue Src1, GenericValue Src2,
610                                    const Type *Ty) {
611   GenericValue Dest;
612   switch (Ty->getTypeID()) {
613     IMPLEMENT_FCMP(!=, Float);
614     IMPLEMENT_FCMP(!=, Double);
615
616   default:
617     cerr << "Unhandled type for FCmp NE instruction: " << *Ty << "\n";
618     abort();
619   }
620   return Dest;
621 }
622
623 static GenericValue executeFCMP_OLE(GenericValue Src1, GenericValue Src2,
624                                    const Type *Ty) {
625   GenericValue Dest;
626   switch (Ty->getTypeID()) {
627     IMPLEMENT_FCMP(<=, Float);
628     IMPLEMENT_FCMP(<=, Double);
629   default:
630     cerr << "Unhandled type for FCmp LE instruction: " << *Ty << "\n";
631     abort();
632   }
633   return Dest;
634 }
635
636 static GenericValue executeFCMP_OGE(GenericValue Src1, GenericValue Src2,
637                                    const Type *Ty) {
638   GenericValue Dest;
639   switch (Ty->getTypeID()) {
640     IMPLEMENT_FCMP(>=, Float);
641     IMPLEMENT_FCMP(>=, Double);
642   default:
643     cerr << "Unhandled type for FCmp GE instruction: " << *Ty << "\n";
644     abort();
645   }
646   return Dest;
647 }
648
649 static GenericValue executeFCMP_OLT(GenericValue Src1, GenericValue Src2,
650                                    const Type *Ty) {
651   GenericValue Dest;
652   switch (Ty->getTypeID()) {
653     IMPLEMENT_FCMP(<, Float);
654     IMPLEMENT_FCMP(<, Double);
655   default:
656     cerr << "Unhandled type for FCmp LT instruction: " << *Ty << "\n";
657     abort();
658   }
659   return Dest;
660 }
661
662 static GenericValue executeFCMP_OGT(GenericValue Src1, GenericValue Src2,
663                                      const Type *Ty) {
664   GenericValue Dest;
665   switch (Ty->getTypeID()) {
666     IMPLEMENT_FCMP(>, Float);
667     IMPLEMENT_FCMP(>, Double);
668   default:
669     cerr << "Unhandled type for FCmp GT instruction: " << *Ty << "\n";
670     abort();
671   }
672   return Dest;
673 }
674
675 #define IMPLEMENT_UNORDERED(TY, X,Y) \
676    if (TY == Type::FloatTy) \
677      if (X.FloatVal != X.FloatVal || Y.FloatVal != Y.FloatVal) { \
678        Dest.Int1Val = true; \
679        return Dest; \
680      } \
681    else if (X.DoubleVal != X.DoubleVal || Y.DoubleVal != Y.DoubleVal) { \
682      Dest.Int1Val = true; \
683      return Dest; \
684    }
685
686
687 static GenericValue executeFCMP_UEQ(GenericValue Src1, GenericValue Src2,
688                                    const Type *Ty) {
689   GenericValue Dest;
690   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
691   return executeFCMP_OEQ(Src1, Src2, Ty);
692 }
693
694 static GenericValue executeFCMP_UNE(GenericValue Src1, GenericValue Src2,
695                                    const Type *Ty) {
696   GenericValue Dest;
697   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
698   return executeFCMP_ONE(Src1, Src2, Ty);
699 }
700
701 static GenericValue executeFCMP_ULE(GenericValue Src1, GenericValue Src2,
702                                    const Type *Ty) {
703   GenericValue Dest;
704   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
705   return executeFCMP_OLE(Src1, Src2, Ty);
706 }
707
708 static GenericValue executeFCMP_UGE(GenericValue Src1, GenericValue Src2,
709                                    const Type *Ty) {
710   GenericValue Dest;
711   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
712   return executeFCMP_OGE(Src1, Src2, Ty);
713 }
714
715 static GenericValue executeFCMP_ULT(GenericValue Src1, GenericValue Src2,
716                                    const Type *Ty) {
717   GenericValue Dest;
718   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
719   return executeFCMP_OLT(Src1, Src2, Ty);
720 }
721
722 static GenericValue executeFCMP_UGT(GenericValue Src1, GenericValue Src2,
723                                      const Type *Ty) {
724   GenericValue Dest;
725   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
726   return executeFCMP_OGT(Src1, Src2, Ty);
727 }
728
729 static GenericValue executeFCMP_ORD(GenericValue Src1, GenericValue Src2,
730                                      const Type *Ty) {
731   GenericValue Dest;
732   if (Ty == Type::FloatTy)
733     Dest.Int1Val = (Src1.FloatVal == Src1.FloatVal && 
734                     Src2.FloatVal == Src2.FloatVal);
735   else
736     Dest.Int1Val = (Src1.DoubleVal == Src1.DoubleVal && 
737                     Src2.DoubleVal == Src2.DoubleVal);
738   return Dest;
739 }
740
741 static GenericValue executeFCMP_UNO(GenericValue Src1, GenericValue Src2,
742                                      const Type *Ty) {
743   GenericValue Dest;
744   if (Ty == Type::FloatTy)
745     Dest.Int1Val = (Src1.FloatVal != Src1.FloatVal || 
746                     Src2.FloatVal != Src2.FloatVal);
747   else
748     Dest.Int1Val = (Src1.DoubleVal != Src1.DoubleVal || 
749                     Src2.DoubleVal != Src2.DoubleVal);
750   return Dest;
751 }
752
753 void Interpreter::visitFCmpInst(FCmpInst &I) {
754   ExecutionContext &SF = ECStack.back();
755   const Type *Ty    = I.getOperand(0)->getType();
756   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
757   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
758   GenericValue R;   // Result
759   
760   switch (I.getPredicate()) {
761   case FCmpInst::FCMP_FALSE: R.Int1Val = false; break;
762   case FCmpInst::FCMP_TRUE:  R.Int1Val = true; break;
763   case FCmpInst::FCMP_ORD:   R = executeFCMP_ORD(Src1, Src2, Ty); break;
764   case FCmpInst::FCMP_UNO:   R = executeFCMP_UNO(Src1, Src2, Ty); break;
765   case FCmpInst::FCMP_UEQ:   R = executeFCMP_UEQ(Src1, Src2, Ty); break;
766   case FCmpInst::FCMP_OEQ:   R = executeFCMP_OEQ(Src1, Src2, Ty); break;
767   case FCmpInst::FCMP_UNE:   R = executeFCMP_UNE(Src1, Src2, Ty); break;
768   case FCmpInst::FCMP_ONE:   R = executeFCMP_ONE(Src1, Src2, Ty); break;
769   case FCmpInst::FCMP_ULT:   R = executeFCMP_ULT(Src1, Src2, Ty); break;
770   case FCmpInst::FCMP_OLT:   R = executeFCMP_OLT(Src1, Src2, Ty); break;
771   case FCmpInst::FCMP_UGT:   R = executeFCMP_UGT(Src1, Src2, Ty); break;
772   case FCmpInst::FCMP_OGT:   R = executeFCMP_OGT(Src1, Src2, Ty); break;
773   case FCmpInst::FCMP_ULE:   R = executeFCMP_ULE(Src1, Src2, Ty); break;
774   case FCmpInst::FCMP_OLE:   R = executeFCMP_OLE(Src1, Src2, Ty); break;
775   case FCmpInst::FCMP_UGE:   R = executeFCMP_UGE(Src1, Src2, Ty); break;
776   case FCmpInst::FCMP_OGE:   R = executeFCMP_OGE(Src1, Src2, Ty); break;
777   default:
778     cerr << "Don't know how to handle this FCmp predicate!\n-->" << I;
779     abort();
780   }
781  
782   SetValue(&I, R, SF);
783 }
784
785 static GenericValue executeCmpInst(unsigned predicate, GenericValue Src1, 
786                                    GenericValue Src2, const Type *Ty) {
787   GenericValue Result;
788   switch (predicate) {
789   case ICmpInst::ICMP_EQ:    return executeICMP_EQ(Src1, Src2, Ty);
790   case ICmpInst::ICMP_NE:    return executeICMP_NE(Src1, Src2, Ty);
791   case ICmpInst::ICMP_UGT:   return executeICMP_UGT(Src1, Src2, Ty);
792   case ICmpInst::ICMP_SGT:   return executeICMP_SGT(Src1, Src2, Ty);
793   case ICmpInst::ICMP_ULT:   return executeICMP_ULT(Src1, Src2, Ty);
794   case ICmpInst::ICMP_SLT:   return executeICMP_SLT(Src1, Src2, Ty);
795   case ICmpInst::ICMP_UGE:   return executeICMP_UGE(Src1, Src2, Ty);
796   case ICmpInst::ICMP_SGE:   return executeICMP_SGE(Src1, Src2, Ty);
797   case ICmpInst::ICMP_ULE:   return executeICMP_ULE(Src1, Src2, Ty);
798   case ICmpInst::ICMP_SLE:   return executeICMP_SLE(Src1, Src2, Ty);
799   case FCmpInst::FCMP_ORD:   return executeFCMP_ORD(Src1, Src2, Ty);
800   case FCmpInst::FCMP_UNO:   return executeFCMP_UNO(Src1, Src2, Ty);
801   case FCmpInst::FCMP_OEQ:   return executeFCMP_OEQ(Src1, Src2, Ty);
802   case FCmpInst::FCMP_UEQ:   return executeFCMP_UEQ(Src1, Src2, Ty);
803   case FCmpInst::FCMP_ONE:   return executeFCMP_ONE(Src1, Src2, Ty);
804   case FCmpInst::FCMP_UNE:   return executeFCMP_UNE(Src1, Src2, Ty);
805   case FCmpInst::FCMP_OLT:   return executeFCMP_OLT(Src1, Src2, Ty);
806   case FCmpInst::FCMP_ULT:   return executeFCMP_ULT(Src1, Src2, Ty);
807   case FCmpInst::FCMP_OGT:   return executeFCMP_OGT(Src1, Src2, Ty);
808   case FCmpInst::FCMP_UGT:   return executeFCMP_UGT(Src1, Src2, Ty);
809   case FCmpInst::FCMP_OLE:   return executeFCMP_OLE(Src1, Src2, Ty);
810   case FCmpInst::FCMP_ULE:   return executeFCMP_ULE(Src1, Src2, Ty);
811   case FCmpInst::FCMP_OGE:   return executeFCMP_OGE(Src1, Src2, Ty);
812   case FCmpInst::FCMP_UGE:   return executeFCMP_UGE(Src1, Src2, Ty);
813   case FCmpInst::FCMP_FALSE: { 
814     GenericValue Result;
815     Result.Int1Val = false; 
816     return Result;
817   }
818   case FCmpInst::FCMP_TRUE: {
819     GenericValue Result;
820     Result.Int1Val = true;
821     return Result;
822   }
823   default:
824     cerr << "Unhandled Cmp predicate\n";
825     abort();
826   }
827 }
828
829 void Interpreter::visitBinaryOperator(BinaryOperator &I) {
830   ExecutionContext &SF = ECStack.back();
831   const Type *Ty    = I.getOperand(0)->getType();
832   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
833   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
834   GenericValue R;   // Result
835
836   switch (I.getOpcode()) {
837   case Instruction::Add:   R = executeAddInst  (Src1, Src2, Ty); break;
838   case Instruction::Sub:   R = executeSubInst  (Src1, Src2, Ty); break;
839   case Instruction::Mul:   R = executeMulInst  (Src1, Src2, Ty); break;
840   case Instruction::UDiv:  R = executeUDivInst (Src1, Src2, Ty); break;
841   case Instruction::SDiv:  R = executeSDivInst (Src1, Src2, Ty); break;
842   case Instruction::FDiv:  R = executeFDivInst (Src1, Src2, Ty); break;
843   case Instruction::URem:  R = executeURemInst (Src1, Src2, Ty); break;
844   case Instruction::SRem:  R = executeSRemInst (Src1, Src2, Ty); break;
845   case Instruction::FRem:  R = executeFRemInst (Src1, Src2, Ty); break;
846   case Instruction::And:   R = executeAndInst  (Src1, Src2, Ty); break;
847   case Instruction::Or:    R = executeOrInst   (Src1, Src2, Ty); break;
848   case Instruction::Xor:   R = executeXorInst  (Src1, Src2, Ty); break;
849   default:
850     cerr << "Don't know how to handle this binary operator!\n-->" << I;
851     abort();
852   }
853
854   SetValue(&I, R, SF);
855 }
856
857 static GenericValue executeSelectInst(GenericValue Src1, GenericValue Src2,
858                                       GenericValue Src3) {
859   return Src1.Int1Val ? Src2 : Src3;
860 }
861
862 void Interpreter::visitSelectInst(SelectInst &I) {
863   ExecutionContext &SF = ECStack.back();
864   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
865   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
866   GenericValue Src3 = getOperandValue(I.getOperand(2), SF);
867   GenericValue R = executeSelectInst(Src1, Src2, Src3);
868   SetValue(&I, R, SF);
869 }
870
871
872 //===----------------------------------------------------------------------===//
873 //                     Terminator Instruction Implementations
874 //===----------------------------------------------------------------------===//
875
876 void Interpreter::exitCalled(GenericValue GV) {
877   // runAtExitHandlers() assumes there are no stack frames, but
878   // if exit() was called, then it had a stack frame. Blow away
879   // the stack before interpreting atexit handlers.
880   ECStack.clear ();
881   runAtExitHandlers ();
882   exit (GV.Int32Val);
883 }
884
885 /// Pop the last stack frame off of ECStack and then copy the result
886 /// back into the result variable if we are not returning void. The
887 /// result variable may be the ExitValue, or the Value of the calling
888 /// CallInst if there was a previous stack frame. This method may
889 /// invalidate any ECStack iterators you have. This method also takes
890 /// care of switching to the normal destination BB, if we are returning
891 /// from an invoke.
892 ///
893 void Interpreter::popStackAndReturnValueToCaller (const Type *RetTy,
894                                                   GenericValue Result) {
895   // Pop the current stack frame.
896   ECStack.pop_back();
897
898   if (ECStack.empty()) {  // Finished main.  Put result into exit code...
899     if (RetTy && RetTy->isInteger()) {          // Nonvoid return type?
900       ExitValue = Result;   // Capture the exit value of the program
901     } else {
902       memset(&ExitValue, 0, sizeof(ExitValue));
903     }
904   } else {
905     // If we have a previous stack frame, and we have a previous call,
906     // fill in the return value...
907     ExecutionContext &CallingSF = ECStack.back();
908     if (Instruction *I = CallingSF.Caller.getInstruction()) {
909       if (CallingSF.Caller.getType() != Type::VoidTy)      // Save result...
910         SetValue(I, Result, CallingSF);
911       if (InvokeInst *II = dyn_cast<InvokeInst> (I))
912         SwitchToNewBasicBlock (II->getNormalDest (), CallingSF);
913       CallingSF.Caller = CallSite();          // We returned from the call...
914     }
915   }
916 }
917
918 void Interpreter::visitReturnInst(ReturnInst &I) {
919   ExecutionContext &SF = ECStack.back();
920   const Type *RetTy = Type::VoidTy;
921   GenericValue Result;
922
923   // Save away the return value... (if we are not 'ret void')
924   if (I.getNumOperands()) {
925     RetTy  = I.getReturnValue()->getType();
926     Result = getOperandValue(I.getReturnValue(), SF);
927   }
928
929   popStackAndReturnValueToCaller(RetTy, Result);
930 }
931
932 void Interpreter::visitUnwindInst(UnwindInst &I) {
933   // Unwind stack
934   Instruction *Inst;
935   do {
936     ECStack.pop_back ();
937     if (ECStack.empty ())
938       abort ();
939     Inst = ECStack.back ().Caller.getInstruction ();
940   } while (!(Inst && isa<InvokeInst> (Inst)));
941
942   // Return from invoke
943   ExecutionContext &InvokingSF = ECStack.back ();
944   InvokingSF.Caller = CallSite ();
945
946   // Go to exceptional destination BB of invoke instruction
947   SwitchToNewBasicBlock(cast<InvokeInst>(Inst)->getUnwindDest(), InvokingSF);
948 }
949
950 void Interpreter::visitUnreachableInst(UnreachableInst &I) {
951   cerr << "ERROR: Program executed an 'unreachable' instruction!\n";
952   abort();
953 }
954
955 void Interpreter::visitBranchInst(BranchInst &I) {
956   ExecutionContext &SF = ECStack.back();
957   BasicBlock *Dest;
958
959   Dest = I.getSuccessor(0);          // Uncond branches have a fixed dest...
960   if (!I.isUnconditional()) {
961     Value *Cond = I.getCondition();
962     if (getOperandValue(Cond, SF).Int1Val == 0) // If false cond...
963       Dest = I.getSuccessor(1);
964   }
965   SwitchToNewBasicBlock(Dest, SF);
966 }
967
968 void Interpreter::visitSwitchInst(SwitchInst &I) {
969   ExecutionContext &SF = ECStack.back();
970   GenericValue CondVal = getOperandValue(I.getOperand(0), SF);
971   const Type *ElTy = I.getOperand(0)->getType();
972
973   // Check to see if any of the cases match...
974   BasicBlock *Dest = 0;
975   for (unsigned i = 2, e = I.getNumOperands(); i != e; i += 2)
976     if (executeICMP_EQ(CondVal,
977                        getOperandValue(I.getOperand(i), SF), ElTy).Int1Val) {
978       Dest = cast<BasicBlock>(I.getOperand(i+1));
979       break;
980     }
981
982   if (!Dest) Dest = I.getDefaultDest();   // No cases matched: use default
983   SwitchToNewBasicBlock(Dest, SF);
984 }
985
986 // SwitchToNewBasicBlock - This method is used to jump to a new basic block.
987 // This function handles the actual updating of block and instruction iterators
988 // as well as execution of all of the PHI nodes in the destination block.
989 //
990 // This method does this because all of the PHI nodes must be executed
991 // atomically, reading their inputs before any of the results are updated.  Not
992 // doing this can cause problems if the PHI nodes depend on other PHI nodes for
993 // their inputs.  If the input PHI node is updated before it is read, incorrect
994 // results can happen.  Thus we use a two phase approach.
995 //
996 void Interpreter::SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF){
997   BasicBlock *PrevBB = SF.CurBB;      // Remember where we came from...
998   SF.CurBB   = Dest;                  // Update CurBB to branch destination
999   SF.CurInst = SF.CurBB->begin();     // Update new instruction ptr...
1000
1001   if (!isa<PHINode>(SF.CurInst)) return;  // Nothing fancy to do
1002
1003   // Loop over all of the PHI nodes in the current block, reading their inputs.
1004   std::vector<GenericValue> ResultValues;
1005
1006   for (; PHINode *PN = dyn_cast<PHINode>(SF.CurInst); ++SF.CurInst) {
1007     // Search for the value corresponding to this previous bb...
1008     int i = PN->getBasicBlockIndex(PrevBB);
1009     assert(i != -1 && "PHINode doesn't contain entry for predecessor??");
1010     Value *IncomingValue = PN->getIncomingValue(i);
1011
1012     // Save the incoming value for this PHI node...
1013     ResultValues.push_back(getOperandValue(IncomingValue, SF));
1014   }
1015
1016   // Now loop over all of the PHI nodes setting their values...
1017   SF.CurInst = SF.CurBB->begin();
1018   for (unsigned i = 0; isa<PHINode>(SF.CurInst); ++SF.CurInst, ++i) {
1019     PHINode *PN = cast<PHINode>(SF.CurInst);
1020     SetValue(PN, ResultValues[i], SF);
1021   }
1022 }
1023
1024 //===----------------------------------------------------------------------===//
1025 //                     Memory Instruction Implementations
1026 //===----------------------------------------------------------------------===//
1027
1028 void Interpreter::visitAllocationInst(AllocationInst &I) {
1029   ExecutionContext &SF = ECStack.back();
1030
1031   const Type *Ty = I.getType()->getElementType();  // Type to be allocated
1032
1033   // Get the number of elements being allocated by the array...
1034   unsigned NumElements = getOperandValue(I.getOperand(0), SF).Int32Val;
1035
1036   // Allocate enough memory to hold the type...
1037   void *Memory = malloc(NumElements * (size_t)TD.getTypeSize(Ty));
1038
1039   GenericValue Result = PTOGV(Memory);
1040   assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
1041   SetValue(&I, Result, SF);
1042
1043   if (I.getOpcode() == Instruction::Alloca)
1044     ECStack.back().Allocas.add(Memory);
1045 }
1046
1047 void Interpreter::visitFreeInst(FreeInst &I) {
1048   ExecutionContext &SF = ECStack.back();
1049   assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
1050   GenericValue Value = getOperandValue(I.getOperand(0), SF);
1051   // TODO: Check to make sure memory is allocated
1052   free(GVTOP(Value));   // Free memory
1053 }
1054
1055 // getElementOffset - The workhorse for getelementptr.
1056 //
1057 GenericValue Interpreter::executeGEPOperation(Value *Ptr, gep_type_iterator I,
1058                                               gep_type_iterator E,
1059                                               ExecutionContext &SF) {
1060   assert(isa<PointerType>(Ptr->getType()) &&
1061          "Cannot getElementOffset of a nonpointer type!");
1062
1063   PointerTy Total = 0;
1064
1065   for (; I != E; ++I) {
1066     if (const StructType *STy = dyn_cast<StructType>(*I)) {
1067       const StructLayout *SLO = TD.getStructLayout(STy);
1068
1069       const ConstantInt *CPU = cast<ConstantInt>(I.getOperand());
1070       unsigned Index = unsigned(CPU->getZExtValue());
1071
1072       Total += (PointerTy)SLO->MemberOffsets[Index];
1073     } else {
1074       const SequentialType *ST = cast<SequentialType>(*I);
1075       // Get the index number for the array... which must be long type...
1076       GenericValue IdxGV = getOperandValue(I.getOperand(), SF);
1077
1078       int64_t Idx;
1079       unsigned BitWidth = 
1080         cast<IntegerType>(I.getOperand()->getType())->getBitWidth();
1081       if (BitWidth == 32)
1082         Idx = (int64_t)(int32_t)IdxGV.Int32Val;
1083       else if (BitWidth == 64)
1084         Idx = (int64_t)IdxGV.Int64Val;
1085       else 
1086         assert(0 && "Invalid index type for getelementptr");
1087       Total += PointerTy(TD.getTypeSize(ST->getElementType())*Idx);
1088     }
1089   }
1090
1091   GenericValue Result;
1092   Result.PointerVal = getOperandValue(Ptr, SF).PointerVal + Total;
1093   return Result;
1094 }
1095
1096 void Interpreter::visitGetElementPtrInst(GetElementPtrInst &I) {
1097   ExecutionContext &SF = ECStack.back();
1098   SetValue(&I, TheEE->executeGEPOperation(I.getPointerOperand(),
1099                                    gep_type_begin(I), gep_type_end(I), SF), SF);
1100 }
1101
1102 void Interpreter::visitLoadInst(LoadInst &I) {
1103   ExecutionContext &SF = ECStack.back();
1104   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
1105   GenericValue *Ptr = (GenericValue*)GVTOP(SRC);
1106   GenericValue Result = LoadValueFromMemory(Ptr, I.getType());
1107   SetValue(&I, Result, SF);
1108 }
1109
1110 void Interpreter::visitStoreInst(StoreInst &I) {
1111   ExecutionContext &SF = ECStack.back();
1112   GenericValue Val = getOperandValue(I.getOperand(0), SF);
1113   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
1114   StoreValueToMemory(Val, (GenericValue *)GVTOP(SRC),
1115                      I.getOperand(0)->getType());
1116 }
1117
1118 //===----------------------------------------------------------------------===//
1119 //                 Miscellaneous Instruction Implementations
1120 //===----------------------------------------------------------------------===//
1121
1122 void Interpreter::visitCallSite(CallSite CS) {
1123   ExecutionContext &SF = ECStack.back();
1124
1125   // Check to see if this is an intrinsic function call...
1126   if (Function *F = CS.getCalledFunction())
1127    if (F->isExternal ())
1128     switch (F->getIntrinsicID()) {
1129     case Intrinsic::not_intrinsic:
1130       break;
1131     case Intrinsic::vastart: { // va_start
1132       GenericValue ArgIndex;
1133       ArgIndex.UIntPairVal.first = ECStack.size() - 1;
1134       ArgIndex.UIntPairVal.second = 0;
1135       SetValue(CS.getInstruction(), ArgIndex, SF);
1136       return;
1137     }
1138     case Intrinsic::vaend:    // va_end is a noop for the interpreter
1139       return;
1140     case Intrinsic::vacopy:   // va_copy: dest = src
1141       SetValue(CS.getInstruction(), getOperandValue(*CS.arg_begin(), SF), SF);
1142       return;
1143     default:
1144       // If it is an unknown intrinsic function, use the intrinsic lowering
1145       // class to transform it into hopefully tasty LLVM code.
1146       //
1147       Instruction *Prev = CS.getInstruction()->getPrev();
1148       BasicBlock *Parent = CS.getInstruction()->getParent();
1149       IL->LowerIntrinsicCall(cast<CallInst>(CS.getInstruction()));
1150
1151       // Restore the CurInst pointer to the first instruction newly inserted, if
1152       // any.
1153       if (!Prev) {
1154         SF.CurInst = Parent->begin();
1155       } else {
1156         SF.CurInst = Prev;
1157         ++SF.CurInst;
1158       }
1159       return;
1160     }
1161
1162   SF.Caller = CS;
1163   std::vector<GenericValue> ArgVals;
1164   const unsigned NumArgs = SF.Caller.arg_size();
1165   ArgVals.reserve(NumArgs);
1166   for (CallSite::arg_iterator i = SF.Caller.arg_begin(),
1167          e = SF.Caller.arg_end(); i != e; ++i) {
1168     Value *V = *i;
1169     ArgVals.push_back(getOperandValue(V, SF));
1170     // Promote all integral types whose size is < sizeof(int) into ints.  We do
1171     // this by zero or sign extending the value as appropriate according to the
1172     // source type.
1173     const Type *Ty = V->getType();
1174     if (Ty->isInteger()) {
1175       if (Ty->getPrimitiveSizeInBits() == 1)
1176         ArgVals.back().Int32Val = ArgVals.back().Int1Val;
1177       else if (Ty->getPrimitiveSizeInBits() <= 8)
1178         ArgVals.back().Int32Val = ArgVals.back().Int8Val;
1179       else if (Ty->getPrimitiveSizeInBits() <= 16)
1180         ArgVals.back().Int32Val = ArgVals.back().Int16Val;
1181     }
1182   }
1183
1184   // To handle indirect calls, we must get the pointer value from the argument
1185   // and treat it as a function pointer.
1186   GenericValue SRC = getOperandValue(SF.Caller.getCalledValue(), SF);
1187   callFunction((Function*)GVTOP(SRC), ArgVals);
1188 }
1189
1190 static GenericValue executeShlInst(GenericValue Src1, GenericValue Src2,
1191                                    const Type *Ty) {
1192   GenericValue Dest;
1193   if (const IntegerType *ITy = cast<IntegerType>(Ty)) {
1194     unsigned BitWidth = ITy->getBitWidth();
1195     if (BitWidth <= 8)
1196       Dest.Int8Val  = ((uint8_t)Src1.Int8Val)   << ((uint32_t)Src2.Int8Val);
1197     else if (BitWidth <= 16)
1198       Dest.Int16Val = ((uint16_t)Src1.Int16Val) << ((uint32_t)Src2.Int8Val);
1199     else if (BitWidth <= 32)
1200       Dest.Int32Val = ((uint32_t)Src1.Int32Val) << ((uint32_t)Src2.Int8Val);
1201     else if (BitWidth <= 64)
1202       Dest.Int64Val = ((uint64_t)Src1.Int64Val) << ((uint32_t)Src2.Int8Val);
1203     else {
1204       cerr << "Integer types > 64 bits not supported: " << *Ty << "\n";
1205       abort();
1206     }
1207     maskToBitWidth(Dest, BitWidth);
1208   } else {
1209     cerr << "Unhandled type for Shl instruction: " << *Ty << "\n";
1210     abort();
1211   }
1212   return Dest;
1213 }
1214
1215 static GenericValue executeLShrInst(GenericValue Src1, GenericValue Src2,
1216                                     const Type *Ty) {
1217   GenericValue Dest;
1218   if (const IntegerType *ITy = cast<IntegerType>(Ty)) {
1219     unsigned BitWidth = ITy->getBitWidth();
1220     if (BitWidth <= 8)
1221       Dest.Int8Val = ((uint8_t)Src1.Int8Val)   >> ((uint32_t)Src2.Int8Val);
1222     else if (BitWidth <= 16)
1223       Dest.Int16Val = ((uint16_t)Src1.Int16Val) >> ((uint32_t)Src2.Int8Val);
1224     else if (BitWidth <= 32)
1225       Dest.Int32Val = ((uint32_t)Src1.Int32Val) >> ((uint32_t)Src2.Int8Val);
1226     else if (BitWidth <= 64)
1227       Dest.Int64Val = ((uint64_t)Src1.Int64Val) >> ((uint32_t)Src2.Int8Val);
1228     else {
1229       cerr << "Integer types > 64 bits not supported: " << *Ty << "\n";
1230       abort();
1231     }
1232     maskToBitWidth(Dest, BitWidth);
1233   } else {
1234     cerr << "Unhandled type for LShr instruction: " << *Ty << "\n";
1235     abort();
1236   }
1237   return Dest;
1238 }
1239
1240 static GenericValue executeAShrInst(GenericValue Src1, GenericValue Src2,
1241                                     const Type *Ty) {
1242   GenericValue Dest;
1243   if (const IntegerType *ITy = cast<IntegerType>(Ty)) {
1244     unsigned BitWidth = ITy->getBitWidth();
1245     if (BitWidth <= 8)
1246       Dest.Int8Val  = ((int8_t)Src1.Int8Val)   >> ((int32_t)Src2.Int8Val);
1247     else if (BitWidth <= 16)
1248       Dest.Int16Val = ((int16_t)Src1.Int16Val) >> ((int32_t)Src2.Int8Val);
1249     else if (BitWidth <= 32)
1250       Dest.Int32Val = ((int32_t)Src1.Int32Val) >> ((int32_t)Src2.Int8Val);
1251     else if (BitWidth <= 64)
1252       Dest.Int64Val = ((int64_t)Src1.Int64Val) >> ((int32_t)Src2.Int8Val);
1253     else {
1254       cerr << "Integer types > 64 bits not supported: " << *Ty << "\n"; \
1255       abort();
1256     } 
1257     maskToBitWidth(Dest, BitWidth);
1258   } else { 
1259     cerr << "Unhandled type for AShr instruction: " << *Ty << "\n";
1260     abort();
1261   }
1262   return Dest;
1263 }
1264
1265 void Interpreter::visitShl(ShiftInst &I) {
1266   ExecutionContext &SF = ECStack.back();
1267   const Type *Ty    = I.getOperand(0)->getType();
1268   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
1269   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
1270   GenericValue Dest;
1271   Dest = executeShlInst (Src1, Src2, Ty);
1272   SetValue(&I, Dest, SF);
1273 }
1274
1275 void Interpreter::visitLShr(ShiftInst &I) {
1276   ExecutionContext &SF = ECStack.back();
1277   const Type *Ty    = I.getOperand(0)->getType();
1278   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
1279   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
1280   GenericValue Dest;
1281   Dest = executeLShrInst (Src1, Src2, Ty);
1282   SetValue(&I, Dest, SF);
1283 }
1284
1285 void Interpreter::visitAShr(ShiftInst &I) {
1286   ExecutionContext &SF = ECStack.back();
1287   const Type *Ty    = I.getOperand(0)->getType();
1288   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
1289   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
1290   GenericValue Dest;
1291   Dest = executeAShrInst (Src1, Src2, Ty);
1292   SetValue(&I, Dest, SF);
1293 }
1294
1295 #define INTEGER_ASSIGN(DEST, BITWIDTH, VAL)     \
1296   {                                             \
1297     uint64_t Mask = (1ull << BITWIDTH) - 1;     \
1298     if (BITWIDTH == 1) {                        \
1299       Dest.Int1Val = (bool) (VAL & Mask);       \
1300     } else if (BITWIDTH <= 8) {                 \
1301       Dest.Int8Val = (uint8_t) (VAL & Mask);    \
1302     } else if (BITWIDTH <= 16) {                \
1303       Dest.Int16Val = (uint16_t) (VAL & Mask);  \
1304     } else if (BITWIDTH <= 32) {                \
1305       Dest.Int32Val = (uint32_t) (VAL & Mask);  \
1306     } else                                      \
1307       Dest.Int64Val = (uint64_t) (VAL & Mask);  \
1308   }
1309
1310 GenericValue Interpreter::executeTruncInst(Value *SrcVal, const Type *DstTy,
1311                                            ExecutionContext &SF) {
1312   const Type *SrcTy = SrcVal->getType();
1313   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1314   const IntegerType *DITy = cast<IntegerType>(DstTy);
1315   const IntegerType *SITy = cast<IntegerType>(SrcTy);
1316   unsigned DBitWidth = DITy->getBitWidth();
1317   unsigned SBitWidth = SITy->getBitWidth();
1318   assert(SBitWidth <= 64 && DBitWidth <= 64  && 
1319          "Integer types > 64 bits not supported");
1320   assert(SBitWidth > DBitWidth && "Invalid truncate");
1321
1322   // Mask the source value to its actual bit width. This ensures that any
1323   // high order bits are cleared.
1324   uint64_t Mask = (1ULL << DBitWidth) - 1;
1325   uint64_t MaskedVal = 0;
1326   if (SBitWidth <= 8)
1327     MaskedVal = Src.Int8Val  & Mask;
1328   else if (SBitWidth <= 16)
1329     MaskedVal = Src.Int16Val & Mask;
1330   else if (SBitWidth <= 32)
1331     MaskedVal = Src.Int32Val & Mask;
1332   else 
1333     MaskedVal = Src.Int64Val & Mask;
1334
1335   INTEGER_ASSIGN(Dest, DBitWidth, MaskedVal);
1336   return Dest;
1337 }
1338
1339 GenericValue Interpreter::executeSExtInst(Value *SrcVal, const Type *DstTy,
1340                                           ExecutionContext &SF) {
1341   const Type *SrcTy = SrcVal->getType();
1342   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1343   const IntegerType *DITy = cast<IntegerType>(DstTy);
1344   const IntegerType *SITy = cast<IntegerType>(SrcTy);
1345   unsigned DBitWidth = DITy->getBitWidth();
1346   unsigned SBitWidth = SITy->getBitWidth();
1347   assert(SBitWidth <= 64 && DBitWidth <= 64  && 
1348          "Integer types > 64 bits not supported");
1349   assert(SBitWidth < DBitWidth && "Invalid sign extend");
1350
1351   // Normalize to a 64-bit value.
1352   uint64_t Normalized = 0;
1353   if (SBitWidth <= 8)
1354     Normalized = Src.Int8Val;
1355   else if (SBitWidth <= 16)
1356     Normalized = Src.Int16Val;
1357   else if (SBitWidth <= 32)
1358     Normalized = Src.Int32Val;
1359   else 
1360     Normalized = Src.Int64Val;
1361
1362   // Now do the bit-accurate sign extension manually.
1363   bool isSigned = (Normalized & (1 << (SBitWidth-1))) != 0;
1364   if (isSigned)
1365     Normalized |= ~SITy->getBitMask();
1366
1367   // Now that we have a sign extended value, assign it to the destination
1368   INTEGER_ASSIGN(Dest, DBitWidth, Normalized);
1369   return Dest;
1370 }
1371
1372 GenericValue Interpreter::executeZExtInst(Value *SrcVal, const Type *DstTy,
1373                                           ExecutionContext &SF) {
1374   const Type *SrcTy = SrcVal->getType();
1375   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1376   const IntegerType *DITy = cast<IntegerType>(DstTy);
1377   const IntegerType *SITy = cast<IntegerType>(SrcTy);
1378   unsigned DBitWidth = DITy->getBitWidth();
1379   unsigned SBitWidth = SITy->getBitWidth();
1380   assert(SBitWidth <= 64 && DBitWidth <= 64  && 
1381          "Integer types > 64 bits not supported");
1382   assert(SBitWidth < DBitWidth && "Invalid sign extend");
1383   uint64_t Extended = 0;
1384   if (SBitWidth == 1)
1385     // For sign extension from bool, we must extend the source bits.
1386     Extended = (uint64_t) (Src.Int1Val & 1);
1387   else if (SBitWidth <= 8)
1388     Extended = (uint64_t) (uint8_t)Src.Int8Val;
1389   else if (SBitWidth <= 16)
1390     Extended = (uint64_t) (uint16_t)Src.Int16Val;
1391   else if (SBitWidth <= 32)
1392     Extended = (uint64_t) (uint32_t)Src.Int32Val;
1393   else 
1394     Extended = (uint64_t) Src.Int64Val;
1395
1396   // Now that we have a sign extended value, assign it to the destination
1397   INTEGER_ASSIGN(Dest, DBitWidth, Extended);
1398   return Dest;
1399 }
1400
1401 GenericValue Interpreter::executeFPTruncInst(Value *SrcVal, const Type *DstTy,
1402                                              ExecutionContext &SF) {
1403   const Type *SrcTy = SrcVal->getType();
1404   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1405   assert(SrcTy == Type::DoubleTy && DstTy == Type::FloatTy &&
1406          "Invalid FPTrunc instruction");
1407   Dest.FloatVal = (float) Src.DoubleVal;
1408   return Dest;
1409 }
1410
1411 GenericValue Interpreter::executeFPExtInst(Value *SrcVal, const Type *DstTy,
1412                                            ExecutionContext &SF) {
1413   const Type *SrcTy = SrcVal->getType();
1414   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1415   assert(SrcTy == Type::FloatTy && DstTy == Type::DoubleTy &&
1416          "Invalid FPTrunc instruction");
1417   Dest.DoubleVal = (double) Src.FloatVal;
1418   return Dest;
1419 }
1420
1421 GenericValue Interpreter::executeFPToUIInst(Value *SrcVal, const Type *DstTy,
1422                                             ExecutionContext &SF) {
1423   const Type *SrcTy = SrcVal->getType();
1424   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1425   const IntegerType *DITy = cast<IntegerType>(DstTy);
1426   unsigned DBitWidth = DITy->getBitWidth();
1427   assert(DBitWidth <= 64  && "Integer types > 64 bits not supported");
1428   assert(SrcTy->isFloatingPoint() && "Invalid FPToUI instruction");
1429   uint64_t Converted = 0;
1430   if (SrcTy->getTypeID() == Type::FloatTyID)
1431     Converted = (uint64_t) Src.FloatVal;
1432   else
1433     Converted = (uint64_t) Src.DoubleVal;
1434
1435   INTEGER_ASSIGN(Dest, DBitWidth, Converted);
1436   return Dest;
1437 }
1438
1439 GenericValue Interpreter::executeFPToSIInst(Value *SrcVal, const Type *DstTy,
1440                                             ExecutionContext &SF) {
1441   const Type *SrcTy = SrcVal->getType();
1442   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1443   const IntegerType *DITy = cast<IntegerType>(DstTy);
1444   unsigned DBitWidth = DITy->getBitWidth();
1445   assert(DBitWidth <= 64  && "Integer types > 64 bits not supported");
1446   assert(SrcTy->isFloatingPoint() && "Invalid FPToSI instruction");
1447   int64_t Converted = 0;
1448   if (SrcTy->getTypeID() == Type::FloatTyID)
1449     Converted = (int64_t) Src.FloatVal;
1450   else
1451     Converted = (int64_t) Src.DoubleVal;
1452
1453   INTEGER_ASSIGN(Dest, DBitWidth, Converted);
1454   return Dest;
1455 }
1456
1457 GenericValue Interpreter::executeUIToFPInst(Value *SrcVal, const Type *DstTy,
1458                                             ExecutionContext &SF) {
1459   const Type *SrcTy = SrcVal->getType();
1460   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1461   const IntegerType *SITy = cast<IntegerType>(SrcTy);
1462   unsigned SBitWidth = SITy->getBitWidth();
1463   assert(SBitWidth <= 64  && "Integer types > 64 bits not supported");
1464   assert(DstTy->isFloatingPoint() && "Invalid UIToFP instruction");
1465   uint64_t Converted = 0;
1466   if (SBitWidth == 1)
1467     Converted = (uint64_t) Src.Int1Val;
1468   else if (SBitWidth <= 8)
1469     Converted = (uint64_t) Src.Int8Val;
1470   else if (SBitWidth <= 16)
1471     Converted = (uint64_t) Src.Int16Val;
1472   else if (SBitWidth <= 32)
1473     Converted = (uint64_t) Src.Int32Val;
1474   else 
1475     Converted = (uint64_t) Src.Int64Val;
1476
1477   if (DstTy->getTypeID() == Type::FloatTyID)
1478     Dest.FloatVal = (float) Converted;
1479   else
1480     Dest.DoubleVal = (double) Converted;
1481   return Dest;
1482 }
1483
1484 GenericValue Interpreter::executeSIToFPInst(Value *SrcVal, const Type *DstTy,
1485                                             ExecutionContext &SF) {
1486   const Type *SrcTy = SrcVal->getType();
1487   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1488   const IntegerType *SITy = cast<IntegerType>(SrcTy);
1489   unsigned SBitWidth = SITy->getBitWidth();
1490   assert(SBitWidth <= 64  && "Integer types > 64 bits not supported");
1491   assert(DstTy->isFloatingPoint() && "Invalid UIToFP instruction");
1492   int64_t Converted = 0;
1493   if (SBitWidth == 1)
1494     Converted = 0LL - Src.Int1Val;
1495   else if (SBitWidth <= 8)
1496     Converted = (int64_t) (int8_t)Src.Int8Val;
1497   else if (SBitWidth <= 16)
1498     Converted = (int64_t) (int16_t)Src.Int16Val;
1499   else if (SBitWidth <= 32)
1500     Converted = (int64_t) (int32_t)Src.Int32Val;
1501   else 
1502     Converted = (int64_t) Src.Int64Val;
1503
1504   if (DstTy->getTypeID() == Type::FloatTyID)
1505     Dest.FloatVal = (float) Converted;
1506   else
1507     Dest.DoubleVal = (double) Converted;
1508   return Dest;
1509 }
1510
1511 GenericValue Interpreter::executePtrToIntInst(Value *SrcVal, const Type *DstTy,
1512                                               ExecutionContext &SF) {
1513   const Type *SrcTy = SrcVal->getType();
1514   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1515   const IntegerType *DITy = cast<IntegerType>(DstTy);
1516   unsigned DBitWidth = DITy->getBitWidth();
1517   assert(DBitWidth <= 64  && "Integer types > 64 bits not supported");
1518   assert(isa<PointerType>(SrcTy) && "Invalid PtrToInt instruction");
1519   INTEGER_ASSIGN(Dest, DBitWidth, (intptr_t) Src.PointerVal);
1520   return Dest;
1521 }
1522
1523 GenericValue Interpreter::executeIntToPtrInst(Value *SrcVal, const Type *DstTy,
1524                                               ExecutionContext &SF) {
1525   const Type *SrcTy = SrcVal->getType();
1526   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1527   const IntegerType *SITy = cast<IntegerType>(SrcTy);
1528   unsigned SBitWidth = SITy->getBitWidth();
1529   assert(SBitWidth <= 64  && "Integer types > 64 bits not supported");
1530   assert(isa<PointerType>(DstTy) && "Invalid PtrToInt instruction");
1531   uint64_t Converted = 0;
1532   if (SBitWidth == 1)
1533     Converted = (uint64_t) Src.Int1Val;
1534   else if (SBitWidth <= 8)
1535     Converted = (uint64_t) Src.Int8Val;
1536   else if (SBitWidth <= 16)
1537     Converted = (uint64_t) Src.Int16Val;
1538   else if (SBitWidth <= 32)
1539     Converted = (uint64_t) Src.Int32Val;
1540   else 
1541     Converted = (uint64_t) Src.Int64Val;
1542
1543   Dest.PointerVal = (PointerTy) Converted;
1544   return Dest;
1545 }
1546
1547 GenericValue Interpreter::executeBitCastInst(Value *SrcVal, const Type *DstTy,
1548                                              ExecutionContext &SF) {
1549   
1550   const Type *SrcTy = SrcVal->getType();
1551   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1552   if (isa<PointerType>(DstTy)) {
1553     assert(isa<PointerType>(SrcTy) && "Invalid BitCast");
1554     Dest.PointerVal = Src.PointerVal;
1555   } else if (DstTy->isInteger()) {
1556     const IntegerType *DITy = cast<IntegerType>(DstTy);
1557     unsigned DBitWidth = DITy->getBitWidth();
1558     if (SrcTy == Type::FloatTy) {
1559       Dest.Int32Val = FloatToBits(Src.FloatVal);
1560     } else if (SrcTy == Type::DoubleTy) {
1561       Dest.Int64Val = DoubleToBits(Src.DoubleVal);
1562     } else if (SrcTy->isInteger()) {
1563       const IntegerType *SITy = cast<IntegerType>(SrcTy);
1564       unsigned SBitWidth = SITy->getBitWidth();
1565       assert(SBitWidth <= 64  && "Integer types > 64 bits not supported");
1566       assert(SBitWidth == DBitWidth && "Invalid BitCast");
1567       if (SBitWidth == 1)
1568         Dest.Int1Val = Src.Int1Val;
1569       else if (SBitWidth <= 8)
1570         Dest.Int8Val =  Src.Int8Val;
1571       else if (SBitWidth <= 16)
1572         Dest.Int16Val = Src.Int16Val;
1573       else if (SBitWidth <= 32)
1574         Dest.Int32Val = Src.Int32Val;
1575       else 
1576         Dest.Int64Val = Src.Int64Val;
1577       maskToBitWidth(Dest, DBitWidth);
1578     } else 
1579       assert(0 && "Invalid BitCast");
1580   } else if (DstTy == Type::FloatTy) {
1581     if (SrcTy->isInteger())
1582       Dest.FloatVal = BitsToFloat(Src.Int32Val);
1583     else
1584       Dest.FloatVal = Src.FloatVal;
1585   } else if (DstTy == Type::DoubleTy) {
1586     if (SrcTy->isInteger())
1587       Dest.DoubleVal = BitsToDouble(Src.Int64Val);
1588     else
1589       Dest.DoubleVal = Src.DoubleVal;
1590   } else
1591     assert(0 && "Invalid Bitcast");
1592
1593   return Dest;
1594 }
1595
1596 void Interpreter::visitTruncInst(TruncInst &I) {
1597   ExecutionContext &SF = ECStack.back();
1598   SetValue(&I, executeTruncInst(I.getOperand(0), I.getType(), SF), SF);
1599 }
1600
1601 void Interpreter::visitSExtInst(SExtInst &I) {
1602   ExecutionContext &SF = ECStack.back();
1603   SetValue(&I, executeSExtInst(I.getOperand(0), I.getType(), SF), SF);
1604 }
1605
1606 void Interpreter::visitZExtInst(ZExtInst &I) {
1607   ExecutionContext &SF = ECStack.back();
1608   SetValue(&I, executeZExtInst(I.getOperand(0), I.getType(), SF), SF);
1609 }
1610
1611 void Interpreter::visitFPTruncInst(FPTruncInst &I) {
1612   ExecutionContext &SF = ECStack.back();
1613   SetValue(&I, executeFPTruncInst(I.getOperand(0), I.getType(), SF), SF);
1614 }
1615
1616 void Interpreter::visitFPExtInst(FPExtInst &I) {
1617   ExecutionContext &SF = ECStack.back();
1618   SetValue(&I, executeFPExtInst(I.getOperand(0), I.getType(), SF), SF);
1619 }
1620
1621 void Interpreter::visitUIToFPInst(UIToFPInst &I) {
1622   ExecutionContext &SF = ECStack.back();
1623   SetValue(&I, executeUIToFPInst(I.getOperand(0), I.getType(), SF), SF);
1624 }
1625
1626 void Interpreter::visitSIToFPInst(SIToFPInst &I) {
1627   ExecutionContext &SF = ECStack.back();
1628   SetValue(&I, executeSIToFPInst(I.getOperand(0), I.getType(), SF), SF);
1629 }
1630
1631 void Interpreter::visitFPToUIInst(FPToUIInst &I) {
1632   ExecutionContext &SF = ECStack.back();
1633   SetValue(&I, executeFPToUIInst(I.getOperand(0), I.getType(), SF), SF);
1634 }
1635
1636 void Interpreter::visitFPToSIInst(FPToSIInst &I) {
1637   ExecutionContext &SF = ECStack.back();
1638   SetValue(&I, executeFPToSIInst(I.getOperand(0), I.getType(), SF), SF);
1639 }
1640
1641 void Interpreter::visitPtrToIntInst(PtrToIntInst &I) {
1642   ExecutionContext &SF = ECStack.back();
1643   SetValue(&I, executePtrToIntInst(I.getOperand(0), I.getType(), SF), SF);
1644 }
1645
1646 void Interpreter::visitIntToPtrInst(IntToPtrInst &I) {
1647   ExecutionContext &SF = ECStack.back();
1648   SetValue(&I, executeIntToPtrInst(I.getOperand(0), I.getType(), SF), SF);
1649 }
1650
1651 void Interpreter::visitBitCastInst(BitCastInst &I) {
1652   ExecutionContext &SF = ECStack.back();
1653   SetValue(&I, executeBitCastInst(I.getOperand(0), I.getType(), SF), SF);
1654 }
1655
1656 #define IMPLEMENT_VAARG(TY) \
1657    case Type::TY##TyID: Dest.TY##Val = Src.TY##Val; break
1658
1659 void Interpreter::visitVAArgInst(VAArgInst &I) {
1660   ExecutionContext &SF = ECStack.back();
1661
1662   // Get the incoming valist parameter.  LLI treats the valist as a
1663   // (ec-stack-depth var-arg-index) pair.
1664   GenericValue VAList = getOperandValue(I.getOperand(0), SF);
1665   GenericValue Dest;
1666   GenericValue Src = ECStack[VAList.UIntPairVal.first]
1667    .VarArgs[VAList.UIntPairVal.second];
1668   const Type *Ty = I.getType();
1669   switch (Ty->getTypeID()) {
1670     case Type::IntegerTyID: {
1671       unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1672       if (BitWidth == 1)
1673         Dest.Int1Val = Src.Int1Val;
1674       else if (BitWidth <= 8)
1675         Dest.Int8Val = Src.Int8Val;
1676       else if (BitWidth <= 16)
1677         Dest.Int16Val = Src.Int16Val;
1678       else if (BitWidth <= 32)
1679         Dest.Int32Val = Src.Int32Val;
1680       else if (BitWidth <= 64)
1681         Dest.Int64Val = Src.Int64Val;
1682       else
1683         assert("Integer types > 64 bits not supported");
1684       maskToBitWidth(Dest, BitWidth);
1685     }
1686     IMPLEMENT_VAARG(Pointer);
1687     IMPLEMENT_VAARG(Float);
1688     IMPLEMENT_VAARG(Double);
1689   default:
1690     cerr << "Unhandled dest type for vaarg instruction: " << *Ty << "\n";
1691     abort();
1692   }
1693
1694   // Set the Value of this Instruction.
1695   SetValue(&I, Dest, SF);
1696
1697   // Move the pointer to the next vararg.
1698   ++VAList.UIntPairVal.second;
1699 }
1700
1701 //===----------------------------------------------------------------------===//
1702 //                        Dispatch and Execution Code
1703 //===----------------------------------------------------------------------===//
1704
1705 //===----------------------------------------------------------------------===//
1706 // callFunction - Execute the specified function...
1707 //
1708 void Interpreter::callFunction(Function *F,
1709                                const std::vector<GenericValue> &ArgVals) {
1710   assert((ECStack.empty() || ECStack.back().Caller.getInstruction() == 0 ||
1711           ECStack.back().Caller.arg_size() == ArgVals.size()) &&
1712          "Incorrect number of arguments passed into function call!");
1713   // Make a new stack frame... and fill it in.
1714   ECStack.push_back(ExecutionContext());
1715   ExecutionContext &StackFrame = ECStack.back();
1716   StackFrame.CurFunction = F;
1717
1718   // Special handling for external functions.
1719   if (F->isExternal()) {
1720     GenericValue Result = callExternalFunction (F, ArgVals);
1721     // Simulate a 'ret' instruction of the appropriate type.
1722     popStackAndReturnValueToCaller (F->getReturnType (), Result);
1723     return;
1724   }
1725
1726   // Get pointers to first LLVM BB & Instruction in function.
1727   StackFrame.CurBB     = F->begin();
1728   StackFrame.CurInst   = StackFrame.CurBB->begin();
1729
1730   // Run through the function arguments and initialize their values...
1731   assert((ArgVals.size() == F->arg_size() ||
1732          (ArgVals.size() > F->arg_size() && F->getFunctionType()->isVarArg()))&&
1733          "Invalid number of values passed to function invocation!");
1734
1735   // Handle non-varargs arguments...
1736   unsigned i = 0;
1737   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E; ++AI, ++i)
1738     SetValue(AI, ArgVals[i], StackFrame);
1739
1740   // Handle varargs arguments...
1741   StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
1742 }
1743
1744 void Interpreter::run() {
1745   while (!ECStack.empty()) {
1746     // Interpret a single instruction & increment the "PC".
1747     ExecutionContext &SF = ECStack.back();  // Current stack frame
1748     Instruction &I = *SF.CurInst++;         // Increment before execute
1749
1750     // Track the number of dynamic instructions executed.
1751     ++NumDynamicInsts;
1752
1753     DOUT << "About to interpret: " << I;
1754     visit(I);   // Dispatch to one of the visit* methods...
1755   }
1756 }