For PR950:
[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 <cmath>  // For fmod
24 using namespace llvm;
25
26 namespace {
27   Statistic<> NumDynamicInsts("lli", "Number of dynamic instructions executed");
28
29   Interpreter *TheEE = 0;
30 }
31
32
33 //===----------------------------------------------------------------------===//
34 //                     Value Manipulation code
35 //===----------------------------------------------------------------------===//
36
37 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
38                                    const Type *Ty);
39 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
40                                    const Type *Ty);
41 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2,
42                                    const Type *Ty);
43 static GenericValue executeRemInst(GenericValue Src1, GenericValue Src2,
44                                    const Type *Ty);
45 static GenericValue executeUDivInst(GenericValue Src1, GenericValue Src2,
46                                     const Type *Ty);
47 static GenericValue executeSDivInst(GenericValue Src1, GenericValue Src2,
48                                     const Type *Ty);
49 static GenericValue executeFDivInst(GenericValue Src1, GenericValue Src2,
50                                     const Type *Ty);
51 static GenericValue executeURemInst(GenericValue Src1, GenericValue Src2,
52                                     const Type *Ty);
53 static GenericValue executeSRemInst(GenericValue Src1, GenericValue Src2,
54                                     const Type *Ty);
55 static GenericValue executeFRemInst(GenericValue Src1, GenericValue Src2,
56                                     const Type *Ty);
57 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2,
58                                    const Type *Ty);
59 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2,
60                                    const Type *Ty);
61 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2,
62                                    const Type *Ty);
63 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2,
64                                    const Type *Ty);
65 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2,
66                                    const Type *Ty);
67 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2,
68                                    const Type *Ty);
69 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2,
70                                    const Type *Ty);
71 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2,
72                                    const Type *Ty);
73 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2,
74                                    const Type *Ty);
75 static GenericValue executeShlInst(GenericValue Src1, GenericValue Src2,
76                                    const Type *Ty);
77 static GenericValue executeShrInst(GenericValue Src1, GenericValue Src2,
78                                    const Type *Ty);
79 static GenericValue executeSelectInst(GenericValue Src1, GenericValue Src2,
80                                       GenericValue Src3);
81
82 GenericValue Interpreter::getConstantExprValue (ConstantExpr *CE,
83                                                 ExecutionContext &SF) {
84   switch (CE->getOpcode()) {
85   case Instruction::Cast:
86     return executeCastOperation(CE->getOperand(0), CE->getType(), SF);
87   case Instruction::GetElementPtr:
88     return executeGEPOperation(CE->getOperand(0), gep_type_begin(CE),
89                                gep_type_end(CE), SF);
90   case Instruction::Add:
91     return executeAddInst(getOperandValue(CE->getOperand(0), SF),
92                           getOperandValue(CE->getOperand(1), SF),
93                           CE->getOperand(0)->getType());
94   case Instruction::Sub:
95     return executeSubInst(getOperandValue(CE->getOperand(0), SF),
96                           getOperandValue(CE->getOperand(1), SF),
97                           CE->getOperand(0)->getType());
98   case Instruction::Mul:
99     return executeMulInst(getOperandValue(CE->getOperand(0), SF),
100                           getOperandValue(CE->getOperand(1), SF),
101                           CE->getOperand(0)->getType());
102   case Instruction::SDiv:
103     return executeSDivInst(getOperandValue(CE->getOperand(0), SF),
104                            getOperandValue(CE->getOperand(1), SF),
105                            CE->getOperand(0)->getType());
106   case Instruction::UDiv:
107     return executeUDivInst(getOperandValue(CE->getOperand(0), SF),
108                            getOperandValue(CE->getOperand(1), SF),
109                            CE->getOperand(0)->getType());
110   case Instruction::FDiv:
111     return executeFDivInst(getOperandValue(CE->getOperand(0), SF),
112                            getOperandValue(CE->getOperand(1), SF),
113                            CE->getOperand(0)->getType());
114   case Instruction::URem:
115     return executeURemInst(getOperandValue(CE->getOperand(0), SF),
116                           getOperandValue(CE->getOperand(1), SF),
117                           CE->getOperand(0)->getType());
118   case Instruction::SRem:
119     return executeSRemInst(getOperandValue(CE->getOperand(0), SF),
120                           getOperandValue(CE->getOperand(1), SF),
121                           CE->getOperand(0)->getType());
122   case Instruction::FRem:
123     return executeFRemInst(getOperandValue(CE->getOperand(0), SF),
124                            getOperandValue(CE->getOperand(1), SF),
125                            CE->getOperand(0)->getType());
126   case Instruction::And:
127     return executeAndInst(getOperandValue(CE->getOperand(0), SF),
128                           getOperandValue(CE->getOperand(1), SF),
129                           CE->getOperand(0)->getType());
130   case Instruction::Or:
131     return executeOrInst(getOperandValue(CE->getOperand(0), SF),
132                          getOperandValue(CE->getOperand(1), SF),
133                          CE->getOperand(0)->getType());
134   case Instruction::Xor:
135     return executeXorInst(getOperandValue(CE->getOperand(0), SF),
136                           getOperandValue(CE->getOperand(1), SF),
137                           CE->getOperand(0)->getType());
138   case Instruction::SetEQ:
139     return executeSetEQInst(getOperandValue(CE->getOperand(0), SF),
140                             getOperandValue(CE->getOperand(1), SF),
141                             CE->getOperand(0)->getType());
142   case Instruction::SetNE:
143     return executeSetNEInst(getOperandValue(CE->getOperand(0), SF),
144                             getOperandValue(CE->getOperand(1), SF),
145                             CE->getOperand(0)->getType());
146   case Instruction::SetLE:
147     return executeSetLEInst(getOperandValue(CE->getOperand(0), SF),
148                             getOperandValue(CE->getOperand(1), SF),
149                             CE->getOperand(0)->getType());
150   case Instruction::SetGE:
151     return executeSetGEInst(getOperandValue(CE->getOperand(0), SF),
152                             getOperandValue(CE->getOperand(1), SF),
153                             CE->getOperand(0)->getType());
154   case Instruction::SetLT:
155     return executeSetLTInst(getOperandValue(CE->getOperand(0), SF),
156                             getOperandValue(CE->getOperand(1), SF),
157                             CE->getOperand(0)->getType());
158   case Instruction::SetGT:
159     return executeSetGTInst(getOperandValue(CE->getOperand(0), SF),
160                             getOperandValue(CE->getOperand(1), SF),
161                             CE->getOperand(0)->getType());
162   case Instruction::Shl:
163     return executeShlInst(getOperandValue(CE->getOperand(0), SF),
164                           getOperandValue(CE->getOperand(1), SF),
165                           CE->getOperand(0)->getType());
166   case Instruction::Shr:
167     return executeShrInst(getOperandValue(CE->getOperand(0), SF),
168                           getOperandValue(CE->getOperand(1), SF),
169                           CE->getOperand(0)->getType());
170   case Instruction::Select:
171     return executeSelectInst(getOperandValue(CE->getOperand(0), SF),
172                              getOperandValue(CE->getOperand(1), SF),
173                              getOperandValue(CE->getOperand(2), SF));
174   default:
175     std::cerr << "Unhandled ConstantExpr: " << *CE << "\n";
176     abort();
177     return GenericValue();
178   }
179 }
180
181 GenericValue Interpreter::getOperandValue(Value *V, ExecutionContext &SF) {
182   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
183     return getConstantExprValue(CE, SF);
184   } else if (Constant *CPV = dyn_cast<Constant>(V)) {
185     return getConstantValue(CPV);
186   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
187     return PTOGV(getPointerToGlobal(GV));
188   } else {
189     return SF.Values[V];
190   }
191 }
192
193 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
194   SF.Values[V] = Val;
195 }
196
197 void Interpreter::initializeExecutionEngine() {
198   TheEE = this;
199 }
200
201 //===----------------------------------------------------------------------===//
202 //                    Binary Instruction Implementations
203 //===----------------------------------------------------------------------===//
204
205 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
206    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
207
208 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
209                                    const Type *Ty) {
210   GenericValue Dest;
211   switch (Ty->getTypeID()) {
212     IMPLEMENT_BINARY_OPERATOR(+, UByte);
213     IMPLEMENT_BINARY_OPERATOR(+, SByte);
214     IMPLEMENT_BINARY_OPERATOR(+, UShort);
215     IMPLEMENT_BINARY_OPERATOR(+, Short);
216     IMPLEMENT_BINARY_OPERATOR(+, UInt);
217     IMPLEMENT_BINARY_OPERATOR(+, Int);
218     IMPLEMENT_BINARY_OPERATOR(+, ULong);
219     IMPLEMENT_BINARY_OPERATOR(+, Long);
220     IMPLEMENT_BINARY_OPERATOR(+, Float);
221     IMPLEMENT_BINARY_OPERATOR(+, Double);
222   default:
223     std::cout << "Unhandled type for Add instruction: " << *Ty << "\n";
224     abort();
225   }
226   return Dest;
227 }
228
229 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
230                                    const Type *Ty) {
231   GenericValue Dest;
232   switch (Ty->getTypeID()) {
233     IMPLEMENT_BINARY_OPERATOR(-, UByte);
234     IMPLEMENT_BINARY_OPERATOR(-, SByte);
235     IMPLEMENT_BINARY_OPERATOR(-, UShort);
236     IMPLEMENT_BINARY_OPERATOR(-, Short);
237     IMPLEMENT_BINARY_OPERATOR(-, UInt);
238     IMPLEMENT_BINARY_OPERATOR(-, Int);
239     IMPLEMENT_BINARY_OPERATOR(-, ULong);
240     IMPLEMENT_BINARY_OPERATOR(-, Long);
241     IMPLEMENT_BINARY_OPERATOR(-, Float);
242     IMPLEMENT_BINARY_OPERATOR(-, Double);
243   default:
244     std::cout << "Unhandled type for Sub instruction: " << *Ty << "\n";
245     abort();
246   }
247   return Dest;
248 }
249
250 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2,
251                                    const Type *Ty) {
252   GenericValue Dest;
253   switch (Ty->getTypeID()) {
254     IMPLEMENT_BINARY_OPERATOR(*, UByte);
255     IMPLEMENT_BINARY_OPERATOR(*, SByte);
256     IMPLEMENT_BINARY_OPERATOR(*, UShort);
257     IMPLEMENT_BINARY_OPERATOR(*, Short);
258     IMPLEMENT_BINARY_OPERATOR(*, UInt);
259     IMPLEMENT_BINARY_OPERATOR(*, Int);
260     IMPLEMENT_BINARY_OPERATOR(*, ULong);
261     IMPLEMENT_BINARY_OPERATOR(*, Long);
262     IMPLEMENT_BINARY_OPERATOR(*, Float);
263     IMPLEMENT_BINARY_OPERATOR(*, Double);
264   default:
265     std::cout << "Unhandled type for Mul instruction: " << *Ty << "\n";
266     abort();
267   }
268   return Dest;
269 }
270
271 #define IMPLEMENT_SIGNLESS_BINOP(OP, TY1, TY2) \
272    case Type::TY2##TyID: IMPLEMENT_BINARY_OPERATOR(OP, TY1)
273
274 static GenericValue executeUDivInst(GenericValue Src1, GenericValue Src2,
275                                    const Type *Ty) {
276   GenericValue Dest;
277   switch (Ty->getTypeID()) {
278     IMPLEMENT_SIGNLESS_BINOP(/, UByte,  SByte);
279     IMPLEMENT_SIGNLESS_BINOP(/, UShort, Short);
280     IMPLEMENT_SIGNLESS_BINOP(/, UInt,   Int);
281     IMPLEMENT_SIGNLESS_BINOP(/, ULong,  Long);
282   default:
283     std::cout << "Unhandled type for UDiv instruction: " << *Ty << "\n";
284     abort();
285   }
286   return Dest;
287 }
288
289 static GenericValue executeSDivInst(GenericValue Src1, GenericValue Src2,
290                                    const Type *Ty) {
291   GenericValue Dest;
292   switch (Ty->getTypeID()) {
293     IMPLEMENT_SIGNLESS_BINOP(/, SByte, UByte);
294     IMPLEMENT_SIGNLESS_BINOP(/, Short, UShort);
295     IMPLEMENT_SIGNLESS_BINOP(/, Int,   UInt);
296     IMPLEMENT_SIGNLESS_BINOP(/, Long,  ULong);
297   default:
298     std::cout << "Unhandled type for SDiv instruction: " << *Ty << "\n";
299     abort();
300   }
301   return Dest;
302 }
303
304 static GenericValue executeFDivInst(GenericValue Src1, GenericValue Src2,
305                                    const Type *Ty) {
306   GenericValue Dest;
307   switch (Ty->getTypeID()) {
308     IMPLEMENT_BINARY_OPERATOR(/, Float);
309     IMPLEMENT_BINARY_OPERATOR(/, Double);
310   default:
311     std::cout << "Unhandled type for Div instruction: " << *Ty << "\n";
312     abort();
313   }
314   return Dest;
315 }
316
317 static GenericValue executeURemInst(GenericValue Src1, GenericValue Src2,
318                                    const Type *Ty) {
319   GenericValue Dest;
320   switch (Ty->getTypeID()) {
321     IMPLEMENT_SIGNLESS_BINOP(%, UByte,  SByte);
322     IMPLEMENT_SIGNLESS_BINOP(%, UShort, Short);
323     IMPLEMENT_SIGNLESS_BINOP(%, UInt,   Int);
324     IMPLEMENT_SIGNLESS_BINOP(%, ULong,  Long);
325   default:
326     std::cout << "Unhandled type for URem instruction: " << *Ty << "\n";
327     abort();
328   }
329   return Dest;
330 }
331
332 static GenericValue executeSRemInst(GenericValue Src1, GenericValue Src2,
333                                    const Type *Ty) {
334   GenericValue Dest;
335   switch (Ty->getTypeID()) {
336     IMPLEMENT_SIGNLESS_BINOP(%, SByte, UByte);
337     IMPLEMENT_SIGNLESS_BINOP(%, Short, UShort);
338     IMPLEMENT_SIGNLESS_BINOP(%, Int,   UInt);
339     IMPLEMENT_SIGNLESS_BINOP(%, Long,  ULong);
340   default:
341     std::cout << "Unhandled type for Rem instruction: " << *Ty << "\n";
342     abort();
343   }
344   return Dest;
345 }
346
347 static GenericValue executeFRemInst(GenericValue Src1, GenericValue Src2,
348                                    const Type *Ty) {
349   GenericValue Dest;
350   switch (Ty->getTypeID()) {
351   case Type::FloatTyID:
352     Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
353     break;
354   case Type::DoubleTyID:
355     Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
356     break;
357   default:
358     std::cout << "Unhandled type for Rem instruction: " << *Ty << "\n";
359     abort();
360   }
361   return Dest;
362 }
363
364 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2,
365                                    const Type *Ty) {
366   GenericValue Dest;
367   switch (Ty->getTypeID()) {
368     IMPLEMENT_BINARY_OPERATOR(&, Bool);
369     IMPLEMENT_BINARY_OPERATOR(&, UByte);
370     IMPLEMENT_BINARY_OPERATOR(&, SByte);
371     IMPLEMENT_BINARY_OPERATOR(&, UShort);
372     IMPLEMENT_BINARY_OPERATOR(&, Short);
373     IMPLEMENT_BINARY_OPERATOR(&, UInt);
374     IMPLEMENT_BINARY_OPERATOR(&, Int);
375     IMPLEMENT_BINARY_OPERATOR(&, ULong);
376     IMPLEMENT_BINARY_OPERATOR(&, Long);
377   default:
378     std::cout << "Unhandled type for And instruction: " << *Ty << "\n";
379     abort();
380   }
381   return Dest;
382 }
383
384 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2,
385                                   const Type *Ty) {
386   GenericValue Dest;
387   switch (Ty->getTypeID()) {
388     IMPLEMENT_BINARY_OPERATOR(|, Bool);
389     IMPLEMENT_BINARY_OPERATOR(|, UByte);
390     IMPLEMENT_BINARY_OPERATOR(|, SByte);
391     IMPLEMENT_BINARY_OPERATOR(|, UShort);
392     IMPLEMENT_BINARY_OPERATOR(|, Short);
393     IMPLEMENT_BINARY_OPERATOR(|, UInt);
394     IMPLEMENT_BINARY_OPERATOR(|, Int);
395     IMPLEMENT_BINARY_OPERATOR(|, ULong);
396     IMPLEMENT_BINARY_OPERATOR(|, Long);
397   default:
398     std::cout << "Unhandled type for Or instruction: " << *Ty << "\n";
399     abort();
400   }
401   return Dest;
402 }
403
404 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2,
405                                    const Type *Ty) {
406   GenericValue Dest;
407   switch (Ty->getTypeID()) {
408     IMPLEMENT_BINARY_OPERATOR(^, Bool);
409     IMPLEMENT_BINARY_OPERATOR(^, UByte);
410     IMPLEMENT_BINARY_OPERATOR(^, SByte);
411     IMPLEMENT_BINARY_OPERATOR(^, UShort);
412     IMPLEMENT_BINARY_OPERATOR(^, Short);
413     IMPLEMENT_BINARY_OPERATOR(^, UInt);
414     IMPLEMENT_BINARY_OPERATOR(^, Int);
415     IMPLEMENT_BINARY_OPERATOR(^, ULong);
416     IMPLEMENT_BINARY_OPERATOR(^, Long);
417   default:
418     std::cout << "Unhandled type for Xor instruction: " << *Ty << "\n";
419     abort();
420   }
421   return Dest;
422 }
423
424 #define IMPLEMENT_SETCC(OP, TY) \
425    case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
426
427 // Handle pointers specially because they must be compared with only as much
428 // width as the host has.  We _do not_ want to be comparing 64 bit values when
429 // running on a 32-bit target, otherwise the upper 32 bits might mess up
430 // comparisons if they contain garbage.
431 #define IMPLEMENT_POINTERSETCC(OP) \
432    case Type::PointerTyID: \
433         Dest.BoolVal = (void*)(intptr_t)Src1.PointerVal OP \
434                        (void*)(intptr_t)Src2.PointerVal; break
435
436 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2,
437                                      const Type *Ty) {
438   GenericValue Dest;
439   switch (Ty->getTypeID()) {
440     IMPLEMENT_SETCC(==, UByte);
441     IMPLEMENT_SETCC(==, SByte);
442     IMPLEMENT_SETCC(==, UShort);
443     IMPLEMENT_SETCC(==, Short);
444     IMPLEMENT_SETCC(==, UInt);
445     IMPLEMENT_SETCC(==, Int);
446     IMPLEMENT_SETCC(==, ULong);
447     IMPLEMENT_SETCC(==, Long);
448     IMPLEMENT_SETCC(==, Float);
449     IMPLEMENT_SETCC(==, Double);
450     IMPLEMENT_POINTERSETCC(==);
451   default:
452     std::cout << "Unhandled type for SetEQ instruction: " << *Ty << "\n";
453     abort();
454   }
455   return Dest;
456 }
457
458 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2,
459                                      const Type *Ty) {
460   GenericValue Dest;
461   switch (Ty->getTypeID()) {
462     IMPLEMENT_SETCC(!=, UByte);
463     IMPLEMENT_SETCC(!=, SByte);
464     IMPLEMENT_SETCC(!=, UShort);
465     IMPLEMENT_SETCC(!=, Short);
466     IMPLEMENT_SETCC(!=, UInt);
467     IMPLEMENT_SETCC(!=, Int);
468     IMPLEMENT_SETCC(!=, ULong);
469     IMPLEMENT_SETCC(!=, Long);
470     IMPLEMENT_SETCC(!=, Float);
471     IMPLEMENT_SETCC(!=, Double);
472     IMPLEMENT_POINTERSETCC(!=);
473
474   default:
475     std::cout << "Unhandled type for SetNE instruction: " << *Ty << "\n";
476     abort();
477   }
478   return Dest;
479 }
480
481 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2,
482                                      const Type *Ty) {
483   GenericValue Dest;
484   switch (Ty->getTypeID()) {
485     IMPLEMENT_SETCC(<=, UByte);
486     IMPLEMENT_SETCC(<=, SByte);
487     IMPLEMENT_SETCC(<=, UShort);
488     IMPLEMENT_SETCC(<=, Short);
489     IMPLEMENT_SETCC(<=, UInt);
490     IMPLEMENT_SETCC(<=, Int);
491     IMPLEMENT_SETCC(<=, ULong);
492     IMPLEMENT_SETCC(<=, Long);
493     IMPLEMENT_SETCC(<=, Float);
494     IMPLEMENT_SETCC(<=, Double);
495     IMPLEMENT_POINTERSETCC(<=);
496   default:
497     std::cout << "Unhandled type for SetLE instruction: " << *Ty << "\n";
498     abort();
499   }
500   return Dest;
501 }
502
503 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2,
504                                      const Type *Ty) {
505   GenericValue Dest;
506   switch (Ty->getTypeID()) {
507     IMPLEMENT_SETCC(>=, UByte);
508     IMPLEMENT_SETCC(>=, SByte);
509     IMPLEMENT_SETCC(>=, UShort);
510     IMPLEMENT_SETCC(>=, Short);
511     IMPLEMENT_SETCC(>=, UInt);
512     IMPLEMENT_SETCC(>=, Int);
513     IMPLEMENT_SETCC(>=, ULong);
514     IMPLEMENT_SETCC(>=, Long);
515     IMPLEMENT_SETCC(>=, Float);
516     IMPLEMENT_SETCC(>=, Double);
517     IMPLEMENT_POINTERSETCC(>=);
518   default:
519     std::cout << "Unhandled type for SetGE instruction: " << *Ty << "\n";
520     abort();
521   }
522   return Dest;
523 }
524
525 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2,
526                                      const Type *Ty) {
527   GenericValue Dest;
528   switch (Ty->getTypeID()) {
529     IMPLEMENT_SETCC(<, UByte);
530     IMPLEMENT_SETCC(<, SByte);
531     IMPLEMENT_SETCC(<, UShort);
532     IMPLEMENT_SETCC(<, Short);
533     IMPLEMENT_SETCC(<, UInt);
534     IMPLEMENT_SETCC(<, Int);
535     IMPLEMENT_SETCC(<, ULong);
536     IMPLEMENT_SETCC(<, Long);
537     IMPLEMENT_SETCC(<, Float);
538     IMPLEMENT_SETCC(<, Double);
539     IMPLEMENT_POINTERSETCC(<);
540   default:
541     std::cout << "Unhandled type for SetLT instruction: " << *Ty << "\n";
542     abort();
543   }
544   return Dest;
545 }
546
547 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2,
548                                      const Type *Ty) {
549   GenericValue Dest;
550   switch (Ty->getTypeID()) {
551     IMPLEMENT_SETCC(>, UByte);
552     IMPLEMENT_SETCC(>, SByte);
553     IMPLEMENT_SETCC(>, UShort);
554     IMPLEMENT_SETCC(>, Short);
555     IMPLEMENT_SETCC(>, UInt);
556     IMPLEMENT_SETCC(>, Int);
557     IMPLEMENT_SETCC(>, ULong);
558     IMPLEMENT_SETCC(>, Long);
559     IMPLEMENT_SETCC(>, Float);
560     IMPLEMENT_SETCC(>, Double);
561     IMPLEMENT_POINTERSETCC(>);
562   default:
563     std::cout << "Unhandled type for SetGT instruction: " << *Ty << "\n";
564     abort();
565   }
566   return Dest;
567 }
568
569 void Interpreter::visitBinaryOperator(BinaryOperator &I) {
570   ExecutionContext &SF = ECStack.back();
571   const Type *Ty    = I.getOperand(0)->getType();
572   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
573   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
574   GenericValue R;   // Result
575
576   switch (I.getOpcode()) {
577   case Instruction::Add:   R = executeAddInst  (Src1, Src2, Ty); break;
578   case Instruction::Sub:   R = executeSubInst  (Src1, Src2, Ty); break;
579   case Instruction::Mul:   R = executeMulInst  (Src1, Src2, Ty); break;
580   case Instruction::UDiv:  R = executeUDivInst (Src1, Src2, Ty); break;
581   case Instruction::SDiv:  R = executeSDivInst (Src1, Src2, Ty); break;
582   case Instruction::FDiv:  R = executeFDivInst (Src1, Src2, Ty); break;
583   case Instruction::URem:  R = executeURemInst (Src1, Src2, Ty); break;
584   case Instruction::SRem:  R = executeSRemInst (Src1, Src2, Ty); break;
585   case Instruction::FRem:  R = executeFRemInst (Src1, Src2, Ty); break;
586   case Instruction::And:   R = executeAndInst  (Src1, Src2, Ty); break;
587   case Instruction::Or:    R = executeOrInst   (Src1, Src2, Ty); break;
588   case Instruction::Xor:   R = executeXorInst  (Src1, Src2, Ty); break;
589   case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty); break;
590   case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty); break;
591   case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty); break;
592   case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty); break;
593   case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty); break;
594   case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty); break;
595   default:
596     std::cout << "Don't know how to handle this binary operator!\n-->" << I;
597     abort();
598   }
599
600   SetValue(&I, R, SF);
601 }
602
603 static GenericValue executeSelectInst(GenericValue Src1, GenericValue Src2,
604                                       GenericValue Src3) {
605   return Src1.BoolVal ? Src2 : Src3;
606 }
607
608 void Interpreter::visitSelectInst(SelectInst &I) {
609   ExecutionContext &SF = ECStack.back();
610   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
611   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
612   GenericValue Src3 = getOperandValue(I.getOperand(2), SF);
613   GenericValue R = executeSelectInst(Src1, Src2, Src3);
614   SetValue(&I, R, SF);
615 }
616
617
618 //===----------------------------------------------------------------------===//
619 //                     Terminator Instruction Implementations
620 //===----------------------------------------------------------------------===//
621
622 void Interpreter::exitCalled(GenericValue GV) {
623   // runAtExitHandlers() assumes there are no stack frames, but
624   // if exit() was called, then it had a stack frame. Blow away
625   // the stack before interpreting atexit handlers.
626   ECStack.clear ();
627   runAtExitHandlers ();
628   exit (GV.IntVal);
629 }
630
631 /// Pop the last stack frame off of ECStack and then copy the result
632 /// back into the result variable if we are not returning void. The
633 /// result variable may be the ExitValue, or the Value of the calling
634 /// CallInst if there was a previous stack frame. This method may
635 /// invalidate any ECStack iterators you have. This method also takes
636 /// care of switching to the normal destination BB, if we are returning
637 /// from an invoke.
638 ///
639 void Interpreter::popStackAndReturnValueToCaller (const Type *RetTy,
640                                                   GenericValue Result) {
641   // Pop the current stack frame.
642   ECStack.pop_back();
643
644   if (ECStack.empty()) {  // Finished main.  Put result into exit code...
645     if (RetTy && RetTy->isIntegral()) {          // Nonvoid return type?
646       ExitValue = Result;   // Capture the exit value of the program
647     } else {
648       memset(&ExitValue, 0, sizeof(ExitValue));
649     }
650   } else {
651     // If we have a previous stack frame, and we have a previous call,
652     // fill in the return value...
653     ExecutionContext &CallingSF = ECStack.back();
654     if (Instruction *I = CallingSF.Caller.getInstruction()) {
655       if (CallingSF.Caller.getType() != Type::VoidTy)      // Save result...
656         SetValue(I, Result, CallingSF);
657       if (InvokeInst *II = dyn_cast<InvokeInst> (I))
658         SwitchToNewBasicBlock (II->getNormalDest (), CallingSF);
659       CallingSF.Caller = CallSite();          // We returned from the call...
660     }
661   }
662 }
663
664 void Interpreter::visitReturnInst(ReturnInst &I) {
665   ExecutionContext &SF = ECStack.back();
666   const Type *RetTy = Type::VoidTy;
667   GenericValue Result;
668
669   // Save away the return value... (if we are not 'ret void')
670   if (I.getNumOperands()) {
671     RetTy  = I.getReturnValue()->getType();
672     Result = getOperandValue(I.getReturnValue(), SF);
673   }
674
675   popStackAndReturnValueToCaller(RetTy, Result);
676 }
677
678 void Interpreter::visitUnwindInst(UnwindInst &I) {
679   // Unwind stack
680   Instruction *Inst;
681   do {
682     ECStack.pop_back ();
683     if (ECStack.empty ())
684       abort ();
685     Inst = ECStack.back ().Caller.getInstruction ();
686   } while (!(Inst && isa<InvokeInst> (Inst)));
687
688   // Return from invoke
689   ExecutionContext &InvokingSF = ECStack.back ();
690   InvokingSF.Caller = CallSite ();
691
692   // Go to exceptional destination BB of invoke instruction
693   SwitchToNewBasicBlock(cast<InvokeInst>(Inst)->getUnwindDest(), InvokingSF);
694 }
695
696 void Interpreter::visitUnreachableInst(UnreachableInst &I) {
697   std::cerr << "ERROR: Program executed an 'unreachable' instruction!\n";
698   abort();
699 }
700
701 void Interpreter::visitBranchInst(BranchInst &I) {
702   ExecutionContext &SF = ECStack.back();
703   BasicBlock *Dest;
704
705   Dest = I.getSuccessor(0);          // Uncond branches have a fixed dest...
706   if (!I.isUnconditional()) {
707     Value *Cond = I.getCondition();
708     if (getOperandValue(Cond, SF).BoolVal == 0) // If false cond...
709       Dest = I.getSuccessor(1);
710   }
711   SwitchToNewBasicBlock(Dest, SF);
712 }
713
714 void Interpreter::visitSwitchInst(SwitchInst &I) {
715   ExecutionContext &SF = ECStack.back();
716   GenericValue CondVal = getOperandValue(I.getOperand(0), SF);
717   const Type *ElTy = I.getOperand(0)->getType();
718
719   // Check to see if any of the cases match...
720   BasicBlock *Dest = 0;
721   for (unsigned i = 2, e = I.getNumOperands(); i != e; i += 2)
722     if (executeSetEQInst(CondVal,
723                          getOperandValue(I.getOperand(i), SF), ElTy).BoolVal) {
724       Dest = cast<BasicBlock>(I.getOperand(i+1));
725       break;
726     }
727
728   if (!Dest) Dest = I.getDefaultDest();   // No cases matched: use default
729   SwitchToNewBasicBlock(Dest, SF);
730 }
731
732 // SwitchToNewBasicBlock - This method is used to jump to a new basic block.
733 // This function handles the actual updating of block and instruction iterators
734 // as well as execution of all of the PHI nodes in the destination block.
735 //
736 // This method does this because all of the PHI nodes must be executed
737 // atomically, reading their inputs before any of the results are updated.  Not
738 // doing this can cause problems if the PHI nodes depend on other PHI nodes for
739 // their inputs.  If the input PHI node is updated before it is read, incorrect
740 // results can happen.  Thus we use a two phase approach.
741 //
742 void Interpreter::SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF){
743   BasicBlock *PrevBB = SF.CurBB;      // Remember where we came from...
744   SF.CurBB   = Dest;                  // Update CurBB to branch destination
745   SF.CurInst = SF.CurBB->begin();     // Update new instruction ptr...
746
747   if (!isa<PHINode>(SF.CurInst)) return;  // Nothing fancy to do
748
749   // Loop over all of the PHI nodes in the current block, reading their inputs.
750   std::vector<GenericValue> ResultValues;
751
752   for (; PHINode *PN = dyn_cast<PHINode>(SF.CurInst); ++SF.CurInst) {
753     // Search for the value corresponding to this previous bb...
754     int i = PN->getBasicBlockIndex(PrevBB);
755     assert(i != -1 && "PHINode doesn't contain entry for predecessor??");
756     Value *IncomingValue = PN->getIncomingValue(i);
757
758     // Save the incoming value for this PHI node...
759     ResultValues.push_back(getOperandValue(IncomingValue, SF));
760   }
761
762   // Now loop over all of the PHI nodes setting their values...
763   SF.CurInst = SF.CurBB->begin();
764   for (unsigned i = 0; isa<PHINode>(SF.CurInst); ++SF.CurInst, ++i) {
765     PHINode *PN = cast<PHINode>(SF.CurInst);
766     SetValue(PN, ResultValues[i], SF);
767   }
768 }
769
770 //===----------------------------------------------------------------------===//
771 //                     Memory Instruction Implementations
772 //===----------------------------------------------------------------------===//
773
774 void Interpreter::visitAllocationInst(AllocationInst &I) {
775   ExecutionContext &SF = ECStack.back();
776
777   const Type *Ty = I.getType()->getElementType();  // Type to be allocated
778
779   // Get the number of elements being allocated by the array...
780   unsigned NumElements = getOperandValue(I.getOperand(0), SF).UIntVal;
781
782   // Allocate enough memory to hold the type...
783   void *Memory = malloc(NumElements * (size_t)TD.getTypeSize(Ty));
784
785   GenericValue Result = PTOGV(Memory);
786   assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
787   SetValue(&I, Result, SF);
788
789   if (I.getOpcode() == Instruction::Alloca)
790     ECStack.back().Allocas.add(Memory);
791 }
792
793 void Interpreter::visitFreeInst(FreeInst &I) {
794   ExecutionContext &SF = ECStack.back();
795   assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
796   GenericValue Value = getOperandValue(I.getOperand(0), SF);
797   // TODO: Check to make sure memory is allocated
798   free(GVTOP(Value));   // Free memory
799 }
800
801 // getElementOffset - The workhorse for getelementptr.
802 //
803 GenericValue Interpreter::executeGEPOperation(Value *Ptr, gep_type_iterator I,
804                                               gep_type_iterator E,
805                                               ExecutionContext &SF) {
806   assert(isa<PointerType>(Ptr->getType()) &&
807          "Cannot getElementOffset of a nonpointer type!");
808
809   PointerTy Total = 0;
810
811   for (; I != E; ++I) {
812     if (const StructType *STy = dyn_cast<StructType>(*I)) {
813       const StructLayout *SLO = TD.getStructLayout(STy);
814
815       const ConstantInt *CPU = cast<ConstantInt>(I.getOperand());
816       unsigned Index = unsigned(CPU->getZExtValue());
817
818       Total += (PointerTy)SLO->MemberOffsets[Index];
819     } else {
820       const SequentialType *ST = cast<SequentialType>(*I);
821       // Get the index number for the array... which must be long type...
822       GenericValue IdxGV = getOperandValue(I.getOperand(), SF);
823
824       uint64_t Idx;
825       switch (I.getOperand()->getType()->getTypeID()) {
826       default: assert(0 && "Illegal getelementptr index for sequential type!");
827       case Type::SByteTyID:  Idx = IdxGV.SByteVal; break;
828       case Type::ShortTyID:  Idx = IdxGV.ShortVal; break;
829       case Type::IntTyID:    Idx = IdxGV.IntVal; break;
830       case Type::LongTyID:   Idx = IdxGV.LongVal; break;
831       case Type::UByteTyID:  Idx = IdxGV.UByteVal; break;
832       case Type::UShortTyID: Idx = IdxGV.UShortVal; break;
833       case Type::UIntTyID:   Idx = IdxGV.UIntVal; break;
834       case Type::ULongTyID:  Idx = IdxGV.ULongVal; break;
835       }
836       Total += PointerTy(TD.getTypeSize(ST->getElementType())*Idx);
837     }
838   }
839
840   GenericValue Result;
841   Result.PointerVal = getOperandValue(Ptr, SF).PointerVal + Total;
842   return Result;
843 }
844
845 void Interpreter::visitGetElementPtrInst(GetElementPtrInst &I) {
846   ExecutionContext &SF = ECStack.back();
847   SetValue(&I, TheEE->executeGEPOperation(I.getPointerOperand(),
848                                    gep_type_begin(I), gep_type_end(I), SF), SF);
849 }
850
851 void Interpreter::visitLoadInst(LoadInst &I) {
852   ExecutionContext &SF = ECStack.back();
853   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
854   GenericValue *Ptr = (GenericValue*)GVTOP(SRC);
855   GenericValue Result = LoadValueFromMemory(Ptr, I.getType());
856   SetValue(&I, Result, SF);
857 }
858
859 void Interpreter::visitStoreInst(StoreInst &I) {
860   ExecutionContext &SF = ECStack.back();
861   GenericValue Val = getOperandValue(I.getOperand(0), SF);
862   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
863   StoreValueToMemory(Val, (GenericValue *)GVTOP(SRC),
864                      I.getOperand(0)->getType());
865 }
866
867 //===----------------------------------------------------------------------===//
868 //                 Miscellaneous Instruction Implementations
869 //===----------------------------------------------------------------------===//
870
871 void Interpreter::visitCallSite(CallSite CS) {
872   ExecutionContext &SF = ECStack.back();
873
874   // Check to see if this is an intrinsic function call...
875   if (Function *F = CS.getCalledFunction())
876    if (F->isExternal ())
877     switch (F->getIntrinsicID()) {
878     case Intrinsic::not_intrinsic:
879       break;
880     case Intrinsic::vastart: { // va_start
881       GenericValue ArgIndex;
882       ArgIndex.UIntPairVal.first = ECStack.size() - 1;
883       ArgIndex.UIntPairVal.second = 0;
884       SetValue(CS.getInstruction(), ArgIndex, SF);
885       return;
886     }
887     case Intrinsic::vaend:    // va_end is a noop for the interpreter
888       return;
889     case Intrinsic::vacopy:   // va_copy: dest = src
890       SetValue(CS.getInstruction(), getOperandValue(*CS.arg_begin(), SF), SF);
891       return;
892     default:
893       // If it is an unknown intrinsic function, use the intrinsic lowering
894       // class to transform it into hopefully tasty LLVM code.
895       //
896       Instruction *Prev = CS.getInstruction()->getPrev();
897       BasicBlock *Parent = CS.getInstruction()->getParent();
898       IL->LowerIntrinsicCall(cast<CallInst>(CS.getInstruction()));
899
900       // Restore the CurInst pointer to the first instruction newly inserted, if
901       // any.
902       if (!Prev) {
903         SF.CurInst = Parent->begin();
904       } else {
905         SF.CurInst = Prev;
906         ++SF.CurInst;
907       }
908       return;
909     }
910
911   SF.Caller = CS;
912   std::vector<GenericValue> ArgVals;
913   const unsigned NumArgs = SF.Caller.arg_size();
914   ArgVals.reserve(NumArgs);
915   for (CallSite::arg_iterator i = SF.Caller.arg_begin(),
916          e = SF.Caller.arg_end(); i != e; ++i) {
917     Value *V = *i;
918     ArgVals.push_back(getOperandValue(V, SF));
919     // Promote all integral types whose size is < sizeof(int) into ints.  We do
920     // this by zero or sign extending the value as appropriate according to the
921     // source type.
922     const Type *Ty = V->getType();
923     if (Ty->isIntegral() && Ty->getPrimitiveSize() < 4) {
924       if (Ty == Type::ShortTy)
925         ArgVals.back().IntVal = ArgVals.back().ShortVal;
926       else if (Ty == Type::UShortTy)
927         ArgVals.back().UIntVal = ArgVals.back().UShortVal;
928       else if (Ty == Type::SByteTy)
929         ArgVals.back().IntVal = ArgVals.back().SByteVal;
930       else if (Ty == Type::UByteTy)
931         ArgVals.back().UIntVal = ArgVals.back().UByteVal;
932       else if (Ty == Type::BoolTy)
933         ArgVals.back().UIntVal = ArgVals.back().BoolVal;
934       else
935         assert(0 && "Unknown type!");
936     }
937   }
938
939   // To handle indirect calls, we must get the pointer value from the argument
940   // and treat it as a function pointer.
941   GenericValue SRC = getOperandValue(SF.Caller.getCalledValue(), SF);
942   callFunction((Function*)GVTOP(SRC), ArgVals);
943 }
944
945 #define IMPLEMENT_SHIFT(OP, TY) \
946    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
947
948 static GenericValue executeShlInst(GenericValue Src1, GenericValue Src2,
949                                    const Type *Ty) {
950   GenericValue Dest;
951   switch (Ty->getTypeID()) {
952     IMPLEMENT_SHIFT(<<, UByte);
953     IMPLEMENT_SHIFT(<<, SByte);
954     IMPLEMENT_SHIFT(<<, UShort);
955     IMPLEMENT_SHIFT(<<, Short);
956     IMPLEMENT_SHIFT(<<, UInt);
957     IMPLEMENT_SHIFT(<<, Int);
958     IMPLEMENT_SHIFT(<<, ULong);
959     IMPLEMENT_SHIFT(<<, Long);
960   default:
961     std::cout << "Unhandled type for Shl instruction: " << *Ty << "\n";
962   }
963   return Dest;
964 }
965
966 static GenericValue executeShrInst(GenericValue Src1, GenericValue Src2,
967                                    const Type *Ty) {
968   GenericValue Dest;
969   switch (Ty->getTypeID()) {
970     IMPLEMENT_SHIFT(>>, UByte);
971     IMPLEMENT_SHIFT(>>, SByte);
972     IMPLEMENT_SHIFT(>>, UShort);
973     IMPLEMENT_SHIFT(>>, Short);
974     IMPLEMENT_SHIFT(>>, UInt);
975     IMPLEMENT_SHIFT(>>, Int);
976     IMPLEMENT_SHIFT(>>, ULong);
977     IMPLEMENT_SHIFT(>>, Long);
978   default:
979     std::cout << "Unhandled type for Shr instruction: " << *Ty << "\n";
980     abort();
981   }
982   return Dest;
983 }
984
985 void Interpreter::visitShl(ShiftInst &I) {
986   ExecutionContext &SF = ECStack.back();
987   const Type *Ty    = I.getOperand(0)->getType();
988   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
989   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
990   GenericValue Dest;
991   Dest = executeShlInst (Src1, Src2, Ty);
992   SetValue(&I, Dest, SF);
993 }
994
995 void Interpreter::visitShr(ShiftInst &I) {
996   ExecutionContext &SF = ECStack.back();
997   const Type *Ty    = I.getOperand(0)->getType();
998   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
999   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
1000   GenericValue Dest;
1001   Dest = executeShrInst (Src1, Src2, Ty);
1002   SetValue(&I, Dest, SF);
1003 }
1004
1005 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
1006    case Type::STY##TyID: Dest.DTY##Val = DCTY Src.STY##Val; break;
1007
1008 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY)    \
1009   case Type::DESTTY##TyID:                      \
1010     switch (SrcTy->getTypeID()) {          \
1011       IMPLEMENT_CAST(DESTTY, DESTCTY, Bool);    \
1012       IMPLEMENT_CAST(DESTTY, DESTCTY, UByte);   \
1013       IMPLEMENT_CAST(DESTTY, DESTCTY, SByte);   \
1014       IMPLEMENT_CAST(DESTTY, DESTCTY, UShort);  \
1015       IMPLEMENT_CAST(DESTTY, DESTCTY, Short);   \
1016       IMPLEMENT_CAST(DESTTY, DESTCTY, UInt);    \
1017       IMPLEMENT_CAST(DESTTY, DESTCTY, Int);     \
1018       IMPLEMENT_CAST(DESTTY, DESTCTY, ULong);   \
1019       IMPLEMENT_CAST(DESTTY, DESTCTY, Long);    \
1020       IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
1021
1022 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
1023       IMPLEMENT_CAST(DESTTY, DESTCTY, Float);   \
1024       IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
1025
1026 #define IMPLEMENT_CAST_CASE_END()    \
1027     default: std::cout << "Unhandled cast: " << *SrcTy << " to " << *Ty << "\n"; \
1028       abort();                                  \
1029     }                                           \
1030     break
1031
1032 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
1033    IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY);   \
1034    IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
1035    IMPLEMENT_CAST_CASE_END()
1036
1037 GenericValue Interpreter::executeCastOperation(Value *SrcVal, const Type *Ty,
1038                                                ExecutionContext &SF) {
1039   const Type *SrcTy = SrcVal->getType();
1040   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1041
1042   switch (Ty->getTypeID()) {
1043     IMPLEMENT_CAST_CASE(UByte  , (unsigned char));
1044     IMPLEMENT_CAST_CASE(SByte  , (  signed char));
1045     IMPLEMENT_CAST_CASE(UShort , (unsigned short));
1046     IMPLEMENT_CAST_CASE(Short  , (  signed short));
1047     IMPLEMENT_CAST_CASE(UInt   , (unsigned int ));
1048     IMPLEMENT_CAST_CASE(Int    , (  signed int ));
1049     IMPLEMENT_CAST_CASE(ULong  , (uint64_t));
1050     IMPLEMENT_CAST_CASE(Long   , ( int64_t));
1051     IMPLEMENT_CAST_CASE(Pointer, (PointerTy));
1052     IMPLEMENT_CAST_CASE(Float  , (float));
1053     IMPLEMENT_CAST_CASE(Double , (double));
1054     IMPLEMENT_CAST_CASE(Bool   , (bool));
1055   default:
1056     std::cout << "Unhandled dest type for cast instruction: " << *Ty << "\n";
1057     abort();
1058   }
1059
1060   return Dest;
1061 }
1062
1063 void Interpreter::visitCastInst(CastInst &I) {
1064   ExecutionContext &SF = ECStack.back();
1065   SetValue(&I, executeCastOperation(I.getOperand(0), I.getType(), SF), SF);
1066 }
1067
1068 #define IMPLEMENT_VAARG(TY) \
1069    case Type::TY##TyID: Dest.TY##Val = Src.TY##Val; break
1070
1071 void Interpreter::visitVAArgInst(VAArgInst &I) {
1072   ExecutionContext &SF = ECStack.back();
1073
1074   // Get the incoming valist parameter.  LLI treats the valist as a
1075   // (ec-stack-depth var-arg-index) pair.
1076   GenericValue VAList = getOperandValue(I.getOperand(0), SF);
1077   GenericValue Dest;
1078   GenericValue Src = ECStack[VAList.UIntPairVal.first]
1079    .VarArgs[VAList.UIntPairVal.second];
1080   const Type *Ty = I.getType();
1081   switch (Ty->getTypeID()) {
1082     IMPLEMENT_VAARG(UByte);
1083     IMPLEMENT_VAARG(SByte);
1084     IMPLEMENT_VAARG(UShort);
1085     IMPLEMENT_VAARG(Short);
1086     IMPLEMENT_VAARG(UInt);
1087     IMPLEMENT_VAARG(Int);
1088     IMPLEMENT_VAARG(ULong);
1089     IMPLEMENT_VAARG(Long);
1090     IMPLEMENT_VAARG(Pointer);
1091     IMPLEMENT_VAARG(Float);
1092     IMPLEMENT_VAARG(Double);
1093     IMPLEMENT_VAARG(Bool);
1094   default:
1095     std::cout << "Unhandled dest type for vaarg instruction: " << *Ty << "\n";
1096     abort();
1097   }
1098
1099   // Set the Value of this Instruction.
1100   SetValue(&I, Dest, SF);
1101
1102   // Move the pointer to the next vararg.
1103   ++VAList.UIntPairVal.second;
1104 }
1105
1106 //===----------------------------------------------------------------------===//
1107 //                        Dispatch and Execution Code
1108 //===----------------------------------------------------------------------===//
1109
1110 //===----------------------------------------------------------------------===//
1111 // callFunction - Execute the specified function...
1112 //
1113 void Interpreter::callFunction(Function *F,
1114                                const std::vector<GenericValue> &ArgVals) {
1115   assert((ECStack.empty() || ECStack.back().Caller.getInstruction() == 0 ||
1116           ECStack.back().Caller.arg_size() == ArgVals.size()) &&
1117          "Incorrect number of arguments passed into function call!");
1118   // Make a new stack frame... and fill it in.
1119   ECStack.push_back(ExecutionContext());
1120   ExecutionContext &StackFrame = ECStack.back();
1121   StackFrame.CurFunction = F;
1122
1123   // Special handling for external functions.
1124   if (F->isExternal()) {
1125     GenericValue Result = callExternalFunction (F, ArgVals);
1126     // Simulate a 'ret' instruction of the appropriate type.
1127     popStackAndReturnValueToCaller (F->getReturnType (), Result);
1128     return;
1129   }
1130
1131   // Get pointers to first LLVM BB & Instruction in function.
1132   StackFrame.CurBB     = F->begin();
1133   StackFrame.CurInst   = StackFrame.CurBB->begin();
1134
1135   // Run through the function arguments and initialize their values...
1136   assert((ArgVals.size() == F->arg_size() ||
1137          (ArgVals.size() > F->arg_size() && F->getFunctionType()->isVarArg()))&&
1138          "Invalid number of values passed to function invocation!");
1139
1140   // Handle non-varargs arguments...
1141   unsigned i = 0;
1142   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E; ++AI, ++i)
1143     SetValue(AI, ArgVals[i], StackFrame);
1144
1145   // Handle varargs arguments...
1146   StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
1147 }
1148
1149 void Interpreter::run() {
1150   while (!ECStack.empty()) {
1151     // Interpret a single instruction & increment the "PC".
1152     ExecutionContext &SF = ECStack.back();  // Current stack frame
1153     Instruction &I = *SF.CurInst++;         // Increment before execute
1154
1155     // Track the number of dynamic instructions executed.
1156     ++NumDynamicInsts;
1157
1158     DEBUG(std::cerr << "About to interpret: " << I);
1159     visit(I);   // Dispatch to one of the visit* methods...
1160   }
1161 }