a26c755ee76a6434e5ed487da54401096739c118
[oota-llvm.git] / include / llvm / ExecutionEngine / ExecutionEngine.h
1 //===- ExecutionEngine.h - Abstract Execution Engine Interface --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the abstract interface that implements execution support
11 // for LLVM.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_EXECUTION_ENGINE_H
16 #define LLVM_EXECUTION_ENGINE_H
17
18 #include <vector>
19 #include <map>
20 #include <string>
21 #include "llvm/System/Mutex.h"
22 #include "llvm/ADT/SmallVector.h"
23
24 namespace llvm {
25
26 struct GenericValue;
27 class Constant;
28 class Function;
29 class GlobalVariable;
30 class GlobalValue;
31 class Module;
32 class ModuleProvider;
33 class TargetData;
34 class Type;
35 class MutexGuard;
36 class JITMemoryManager;
37
38 class ExecutionEngineState {
39 private:
40   /// GlobalAddressMap - A mapping between LLVM global values and their
41   /// actualized version...
42   std::map<const GlobalValue*, void *> GlobalAddressMap;
43
44   /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
45   /// used to convert raw addresses into the LLVM global value that is emitted
46   /// at the address.  This map is not computed unless getGlobalValueAtAddress
47   /// is called at some point.
48   std::map<void *, const GlobalValue*> GlobalAddressReverseMap;
49
50 public:
51   std::map<const GlobalValue*, void *> &
52   getGlobalAddressMap(const MutexGuard &) {
53     return GlobalAddressMap;
54   }
55
56   std::map<void*, const GlobalValue*> & 
57   getGlobalAddressReverseMap(const MutexGuard &) {
58     return GlobalAddressReverseMap;
59   }
60 };
61
62
63 class ExecutionEngine {
64   const TargetData *TD;
65   ExecutionEngineState state;
66   bool LazyCompilationDisabled;
67   bool GVCompilationDisabled;
68   bool SymbolSearchingDisabled;
69
70 protected:
71   /// Modules - This is a list of ModuleProvider's that we are JIT'ing from.  We
72   /// use a smallvector to optimize for the case where there is only one module.
73   SmallVector<ModuleProvider*, 1> Modules;
74   
75   void setTargetData(const TargetData *td) {
76     TD = td;
77   }
78   
79   /// getMemoryforGV - Allocate memory for a global variable.
80   virtual char* getMemoryForGV(const GlobalVariable* GV);
81
82   // To avoid having libexecutionengine depend on the JIT and interpreter
83   // libraries, the JIT and Interpreter set these functions to ctor pointers
84   // at startup time if they are linked in.
85   typedef ExecutionEngine *(*EECtorFn)(ModuleProvider*, std::string*,
86                                        bool Fast);
87   static EECtorFn JITCtor, InterpCtor;
88
89   /// LazyFunctionCreator - If an unknown function is needed, this function
90   /// pointer is invoked to create it. If this returns null, the JIT will abort.
91   void* (*LazyFunctionCreator)(const std::string &);
92   
93   /// ExceptionTableRegister - If Exception Handling is set, the JIT will 
94   /// register dwarf tables with this function
95   typedef void (*EERegisterFn)(void*);
96   static EERegisterFn ExceptionTableRegister;
97
98 public:
99   /// lock - This lock is protects the ExecutionEngine, JIT, JITResolver and
100   /// JITEmitter classes.  It must be held while changing the internal state of
101   /// any of those classes.
102   sys::Mutex lock; // Used to make this class and subclasses thread-safe
103
104   //===--------------------------------------------------------------------===//
105   //  ExecutionEngine Startup
106   //===--------------------------------------------------------------------===//
107
108   virtual ~ExecutionEngine();
109
110   /// create - This is the factory method for creating an execution engine which
111   /// is appropriate for the current machine.  This takes ownership of the
112   /// module provider.
113   static ExecutionEngine *create(ModuleProvider *MP,
114                                  bool ForceInterpreter = false,
115                                  std::string *ErrorStr = 0,
116                                  bool Fast = false);
117   
118   /// create - This is the factory method for creating an execution engine which
119   /// is appropriate for the current machine.  This takes ownership of the
120   /// module.
121   static ExecutionEngine *create(Module *M);
122
123   /// createJIT - This is the factory method for creating a JIT for the current
124   /// machine, it does not fall back to the interpreter.  This takes ownership
125   /// of the ModuleProvider and JITMemoryManager if successful.
126   static ExecutionEngine *createJIT(ModuleProvider *MP,
127                                     std::string *ErrorStr = 0,
128                                     JITMemoryManager *JMM = 0,
129                                     bool Fast = false);
130   
131   
132   
133   /// addModuleProvider - Add a ModuleProvider to the list of modules that we
134   /// can JIT from.  Note that this takes ownership of the ModuleProvider: when
135   /// the ExecutionEngine is destroyed, it destroys the MP as well.
136   virtual void addModuleProvider(ModuleProvider *P) {
137     Modules.push_back(P);
138   }
139   
140   //===----------------------------------------------------------------------===//
141
142   const TargetData *getTargetData() const { return TD; }
143
144
145   /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
146   /// Release module from ModuleProvider.
147   virtual Module* removeModuleProvider(ModuleProvider *P,
148                                        std::string *ErrInfo = 0);
149
150   /// FindFunctionNamed - Search all of the active modules to find the one that
151   /// defines FnName.  This is very slow operation and shouldn't be used for
152   /// general code.
153   Function *FindFunctionNamed(const char *FnName);
154   
155   /// runFunction - Execute the specified function with the specified arguments,
156   /// and return the result.
157   ///
158   virtual GenericValue runFunction(Function *F,
159                                 const std::vector<GenericValue> &ArgValues) = 0;
160
161   /// runStaticConstructorsDestructors - This method is used to execute all of
162   /// the static constructors or destructors for a program, depending on the
163   /// value of isDtors.
164   void runStaticConstructorsDestructors(bool isDtors);
165   /// runStaticConstructorsDestructors - This method is used to execute all of
166   /// the static constructors or destructors for a module, depending on the
167   /// value of isDtors.
168   void runStaticConstructorsDestructors(Module *module, bool isDtors);
169   
170   
171   /// runFunctionAsMain - This is a helper function which wraps runFunction to
172   /// handle the common task of starting up main with the specified argc, argv,
173   /// and envp parameters.
174   int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
175                         const char * const * envp);
176
177
178   /// addGlobalMapping - Tell the execution engine that the specified global is
179   /// at the specified location.  This is used internally as functions are JIT'd
180   /// and as global variables are laid out in memory.  It can and should also be
181   /// used by clients of the EE that want to have an LLVM global overlay
182   /// existing data in memory.
183   void addGlobalMapping(const GlobalValue *GV, void *Addr);
184   
185   /// clearAllGlobalMappings - Clear all global mappings and start over again
186   /// use in dynamic compilation scenarios when you want to move globals
187   void clearAllGlobalMappings();
188   
189   /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
190   /// particular module, because it has been removed from the JIT.
191   void clearGlobalMappingsFromModule(Module *M);
192   
193   /// updateGlobalMapping - Replace an existing mapping for GV with a new
194   /// address.  This updates both maps as required.  If "Addr" is null, the
195   /// entry for the global is removed from the mappings.  This returns the old
196   /// value of the pointer, or null if it was not in the map.
197   void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
198   
199   /// getPointerToGlobalIfAvailable - This returns the address of the specified
200   /// global value if it is has already been codegen'd, otherwise it returns
201   /// null.
202   ///
203   void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
204
205   /// getPointerToGlobal - This returns the address of the specified global
206   /// value.  This may involve code generation if it's a function.
207   ///
208   void *getPointerToGlobal(const GlobalValue *GV);
209
210   /// getPointerToFunction - The different EE's represent function bodies in
211   /// different ways.  They should each implement this to say what a function
212   /// pointer should look like.
213   ///
214   virtual void *getPointerToFunction(Function *F) = 0;
215
216   /// getPointerToFunctionOrStub - If the specified function has been
217   /// code-gen'd, return a pointer to the function.  If not, compile it, or use
218   /// a stub to implement lazy compilation if available.
219   ///
220   virtual void *getPointerToFunctionOrStub(Function *F) {
221     // Default implementation, just codegen the function.
222     return getPointerToFunction(F);
223   }
224
225   /// getGlobalValueAtAddress - Return the LLVM global value object that starts
226   /// at the specified address.
227   ///
228   const GlobalValue *getGlobalValueAtAddress(void *Addr);
229
230
231   void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
232                           const Type *Ty);
233   void InitializeMemory(const Constant *Init, void *Addr);
234
235   /// recompileAndRelinkFunction - This method is used to force a function
236   /// which has already been compiled to be compiled again, possibly
237   /// after it has been modified. Then the entry to the old copy is overwritten
238   /// with a branch to the new copy. If there was no old copy, this acts
239   /// just like VM::getPointerToFunction().
240   ///
241   virtual void *recompileAndRelinkFunction(Function *F) = 0;
242
243   /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
244   /// corresponding to the machine code emitted to execute this function, useful
245   /// for garbage-collecting generated code.
246   ///
247   virtual void freeMachineCodeForFunction(Function *F) = 0;
248
249   /// getOrEmitGlobalVariable - Return the address of the specified global
250   /// variable, possibly emitting it to memory if needed.  This is used by the
251   /// Emitter.
252   virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
253     return getPointerToGlobal((GlobalValue*)GV);
254   }
255   
256   /// DisableLazyCompilation - If called, the JIT will abort if lazy compilation
257   /// is ever attempted.
258   void DisableLazyCompilation(bool Disabled = true) {
259     LazyCompilationDisabled = Disabled;
260   }
261   bool isLazyCompilationDisabled() const {
262     return LazyCompilationDisabled;
263   }
264
265   /// DisableGVCompilation - If called, the JIT will abort if it's asked to
266   /// allocate space and populate a GlobalVariable that is not internal to
267   /// the module.
268   void DisableGVCompilation(bool Disabled = true) {
269     GVCompilationDisabled = Disabled;
270   }
271   bool isGVCompilationDisabled() const {
272     return GVCompilationDisabled;
273   }
274
275   /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
276   /// symbols with dlsym.  A client can still use InstallLazyFunctionCreator to
277   /// resolve symbols in a custom way.
278   void DisableSymbolSearching(bool Disabled = true) {
279     SymbolSearchingDisabled = Disabled;
280   }
281   bool isSymbolSearchingDisabled() const {
282     return SymbolSearchingDisabled;
283   }
284   
285   
286   /// InstallLazyFunctionCreator - If an unknown function is needed, the
287   /// specified function pointer is invoked to create it.  If it returns null,
288   /// the JIT will abort.
289   void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
290     LazyFunctionCreator = P;
291   }
292   
293   /// InstallExceptionTableRegister - The JIT will use the given function
294   /// to register the exception tables it generates.
295   static void InstallExceptionTableRegister(void (*F)(void*)) {
296     ExceptionTableRegister = F;
297   }
298   
299   /// RegisterTable - Registers the given pointer as an exception table. It uses
300   /// the ExceptionTableRegister function.
301   static void RegisterTable(void* res) {
302     if (ExceptionTableRegister)
303       ExceptionTableRegister(res);
304   }
305
306 protected:
307   explicit ExecutionEngine(ModuleProvider *P);
308
309   void emitGlobals();
310
311   // EmitGlobalVariable - This method emits the specified global variable to the
312   // address specified in GlobalAddresses, or allocates new memory if it's not
313   // already in the map.
314   void EmitGlobalVariable(const GlobalVariable *GV);
315
316   GenericValue getConstantValue(const Constant *C);
317   void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr, 
318                            const Type *Ty);
319 };
320
321 } // End llvm namespace
322
323 #endif