Deal with error handling better.
[oota-llvm.git] / lib / ExecutionEngine / Interpreter / Interpreter.h
1 //===-- Interpreter.h ------------------------------------------*- C++ -*--===//
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 header file defines the interpreter structure
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLI_INTERPRETER_H
15 #define LLI_INTERPRETER_H
16
17 #include "llvm/Function.h"
18 #include "llvm/ExecutionEngine/ExecutionEngine.h"
19 #include "llvm/ExecutionEngine/GenericValue.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/Support/InstVisitor.h"
22 #include "llvm/Support/CallSite.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Support/DataTypes.h"
25
26 namespace llvm {
27
28 class IntrinsicLowering;
29 struct FunctionInfo;
30 template<typename T> class generic_gep_type_iterator;
31 class ConstantExpr;
32 typedef generic_gep_type_iterator<User::const_op_iterator> gep_type_iterator;
33
34
35 // AllocaHolder - Object to track all of the blocks of memory allocated by
36 // alloca.  When the function returns, this object is popped off the execution
37 // stack, which causes the dtor to be run, which frees all the alloca'd memory.
38 //
39 class AllocaHolder {
40   friend class AllocaHolderHandle;
41   std::vector<void*> Allocations;
42   unsigned RefCnt;
43 public:
44   AllocaHolder() : RefCnt(0) {}
45   void add(void *mem) { Allocations.push_back(mem); }
46   ~AllocaHolder() {
47     for (unsigned i = 0; i < Allocations.size(); ++i)
48       free(Allocations[i]);
49   }
50 };
51
52 // AllocaHolderHandle gives AllocaHolder value semantics so we can stick it into
53 // a vector...
54 //
55 class AllocaHolderHandle {
56   AllocaHolder *H;
57 public:
58   AllocaHolderHandle() : H(new AllocaHolder()) { H->RefCnt++; }
59   AllocaHolderHandle(const AllocaHolderHandle &AH) : H(AH.H) { H->RefCnt++; }
60   ~AllocaHolderHandle() { if (--H->RefCnt == 0) delete H; }
61
62   void add(void *mem) { H->add(mem); }
63 };
64
65 typedef std::vector<GenericValue> ValuePlaneTy;
66
67 // ExecutionContext struct - This struct represents one stack frame currently
68 // executing.
69 //
70 struct ExecutionContext {
71   Function             *CurFunction;// The currently executing function
72   BasicBlock           *CurBB;      // The currently executing BB
73   BasicBlock::iterator  CurInst;    // The next instruction to execute
74   std::map<Value *, GenericValue> Values; // LLVM values used in this invocation
75   std::vector<GenericValue>  VarArgs; // Values passed through an ellipsis
76   CallSite             Caller;     // Holds the call that called subframes.
77                                    // NULL if main func or debugger invoked fn
78   AllocaHolderHandle    Allocas;    // Track memory allocated by alloca
79   std::vector<APInt*>   APInts;     // Track memory allocated for APInts
80   APInt* getAPInt(uint32_t BitWidth) {
81     APInt* Result = new APInt(BitWidth, 0);
82     APInts.push_back(Result);
83     return Result;
84   }
85   ~ExecutionContext() {
86     while (!APInts.empty()) {
87       delete APInts.back();
88       APInts.pop_back();
89     }
90   }
91 };
92
93 // Interpreter - This class represents the entirety of the interpreter.
94 //
95 class Interpreter : public ExecutionEngine, public InstVisitor<Interpreter> {
96   GenericValue ExitValue;          // The return value of the called function
97   TargetData TD;
98   IntrinsicLowering *IL;
99
100   // The runtime stack of executing code.  The top of the stack is the current
101   // function record.
102   std::vector<ExecutionContext> ECStack;
103
104   // AtExitHandlers - List of functions to call when the program exits,
105   // registered with the atexit() library function.
106   std::vector<Function*> AtExitHandlers;
107
108 public:
109   Interpreter(Module *M);
110   ~Interpreter();
111
112   /// runAtExitHandlers - Run any functions registered by the program's calls to
113   /// atexit(3), which we intercept and store in AtExitHandlers.
114   ///
115   void runAtExitHandlers();
116
117   static void Register() {
118     InterpCtor = create;
119   }
120   
121   /// create - Create an interpreter ExecutionEngine. This can never fail.
122   ///
123   static ExecutionEngine *create(ModuleProvider *M, std::string *ErrorStr = 0);
124
125   /// run - Start execution with the specified function and arguments.
126   ///
127   virtual GenericValue runFunction(Function *F,
128                                    const std::vector<GenericValue> &ArgValues);
129
130   /// recompileAndRelinkFunction - For the interpreter, functions are always
131   /// up-to-date.
132   ///
133   virtual void *recompileAndRelinkFunction(Function *F) {
134     return getPointerToFunction(F);
135   }
136
137   /// freeMachineCodeForFunction - The interpreter does not generate any code.
138   ///
139   void freeMachineCodeForFunction(Function *F) { }
140
141   // Methods used to execute code:
142   // Place a call on the stack
143   void callFunction(Function *F, const std::vector<GenericValue> &ArgVals);
144   void run();                // Execute instructions until nothing left to do
145
146   // Opcode Implementations
147   void visitReturnInst(ReturnInst &I);
148   void visitBranchInst(BranchInst &I);
149   void visitSwitchInst(SwitchInst &I);
150
151   void visitBinaryOperator(BinaryOperator &I);
152   void visitICmpInst(ICmpInst &I);
153   void visitFCmpInst(FCmpInst &I);
154   void visitAllocationInst(AllocationInst &I);
155   void visitFreeInst(FreeInst &I);
156   void visitLoadInst(LoadInst &I);
157   void visitStoreInst(StoreInst &I);
158   void visitGetElementPtrInst(GetElementPtrInst &I);
159   void visitPHINode(PHINode &PN) { assert(0 && "PHI nodes already handled!"); }
160   void visitTruncInst(TruncInst &I);
161   void visitZExtInst(ZExtInst &I);
162   void visitSExtInst(SExtInst &I);
163   void visitFPTruncInst(FPTruncInst &I);
164   void visitFPExtInst(FPExtInst &I);
165   void visitUIToFPInst(UIToFPInst &I);
166   void visitSIToFPInst(SIToFPInst &I);
167   void visitFPToUIInst(FPToUIInst &I);
168   void visitFPToSIInst(FPToSIInst &I);
169   void visitPtrToIntInst(PtrToIntInst &I);
170   void visitIntToPtrInst(IntToPtrInst &I);
171   void visitBitCastInst(BitCastInst &I);
172   void visitSelectInst(SelectInst &I);
173
174
175   void visitCallSite(CallSite CS);
176   void visitCallInst(CallInst &I) { visitCallSite (CallSite (&I)); }
177   void visitInvokeInst(InvokeInst &I) { visitCallSite (CallSite (&I)); }
178   void visitUnwindInst(UnwindInst &I);
179   void visitUnreachableInst(UnreachableInst &I);
180
181   void visitShl(BinaryOperator &I);
182   void visitLShr(BinaryOperator &I);
183   void visitAShr(BinaryOperator &I);
184
185   void visitVAArgInst(VAArgInst &I);
186   void visitInstruction(Instruction &I) {
187     cerr << I;
188     assert(0 && "Instruction not interpretable yet!");
189   }
190
191   GenericValue callExternalFunction(Function *F,
192                                     const std::vector<GenericValue> &ArgVals);
193   void exitCalled(GenericValue GV);
194
195   void addAtExitHandler(Function *F) {
196     AtExitHandlers.push_back(F);
197   }
198
199   GenericValue *getFirstVarArg () {
200     return &(ECStack.back ().VarArgs[0]);
201   }
202
203   //FIXME: private:
204 public:
205   GenericValue executeGEPOperation(Value *Ptr, gep_type_iterator I,
206                                    gep_type_iterator E, ExecutionContext &SF);
207
208 private:  // Helper functions
209   // SwitchToNewBasicBlock - Start execution in a new basic block and run any
210   // PHI nodes in the top of the block.  This is used for intraprocedural
211   // control flow.
212   //
213   void SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF);
214
215   void *getPointerToFunction(Function *F) { return (void*)F; }
216
217   void initializeExecutionEngine();
218   void initializeExternalFunctions();
219   GenericValue getConstantExprValue(ConstantExpr *CE, ExecutionContext &SF);
220   GenericValue getOperandValue(Value *V, ExecutionContext &SF);
221   GenericValue executeTruncInst(Value *SrcVal, const Type *DstTy,
222                                 ExecutionContext &SF);
223   GenericValue executeSExtInst(Value *SrcVal, const Type *DstTy,
224                                ExecutionContext &SF);
225   GenericValue executeZExtInst(Value *SrcVal, const Type *DstTy,
226                                ExecutionContext &SF);
227   GenericValue executeFPTruncInst(Value *SrcVal, const Type *DstTy,
228                                   ExecutionContext &SF);
229   GenericValue executeFPExtInst(Value *SrcVal, const Type *DstTy,
230                                 ExecutionContext &SF);
231   GenericValue executeFPToUIInst(Value *SrcVal, const Type *DstTy,
232                                  ExecutionContext &SF);
233   GenericValue executeFPToSIInst(Value *SrcVal, const Type *DstTy,
234                                  ExecutionContext &SF);
235   GenericValue executeUIToFPInst(Value *SrcVal, const Type *DstTy,
236                                  ExecutionContext &SF);
237   GenericValue executeSIToFPInst(Value *SrcVal, const Type *DstTy,
238                                  ExecutionContext &SF);
239   GenericValue executePtrToIntInst(Value *SrcVal, const Type *DstTy,
240                                    ExecutionContext &SF);
241   GenericValue executeIntToPtrInst(Value *SrcVal, const Type *DstTy,
242                                    ExecutionContext &SF);
243   GenericValue executeBitCastInst(Value *SrcVal, const Type *DstTy,
244                                   ExecutionContext &SF);
245   GenericValue executeCastOperation(Instruction::CastOps opcode, Value *SrcVal, 
246                                     const Type *Ty, ExecutionContext &SF);
247   void popStackAndReturnValueToCaller(const Type *RetTy, GenericValue Result);
248
249 };
250
251 } // End llvm namespace
252
253 #endif