3559ede31c34ed37fc509f8b06e63a7375c6816c
[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   /// Relases the Module from the ModuleProvider, materializing it in the
147   /// process, and returns the materialized Module.
148   virtual Module* removeModuleProvider(ModuleProvider *P,
149                                        std::string *ErrInfo = 0);
150
151   /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
152   /// and deletes the ModuleProvider and owned Module.  Avoids materializing 
153   /// the underlying module.
154   virtual void deleteModuleProvider(ModuleProvider *P,std::string *ErrInfo = 0);
155
156   /// FindFunctionNamed - Search all of the active modules to find the one that
157   /// defines FnName.  This is very slow operation and shouldn't be used for
158   /// general code.
159   Function *FindFunctionNamed(const char *FnName);
160   
161   /// runFunction - Execute the specified function with the specified arguments,
162   /// and return the result.
163   ///
164   virtual GenericValue runFunction(Function *F,
165                                 const std::vector<GenericValue> &ArgValues) = 0;
166
167   /// runStaticConstructorsDestructors - This method is used to execute all of
168   /// the static constructors or destructors for a program, depending on the
169   /// value of isDtors.
170   void runStaticConstructorsDestructors(bool isDtors);
171   /// runStaticConstructorsDestructors - This method is used to execute all of
172   /// the static constructors or destructors for a module, depending on the
173   /// value of isDtors.
174   void runStaticConstructorsDestructors(Module *module, bool isDtors);
175   
176   
177   /// runFunctionAsMain - This is a helper function which wraps runFunction to
178   /// handle the common task of starting up main with the specified argc, argv,
179   /// and envp parameters.
180   int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
181                         const char * const * envp);
182
183
184   /// addGlobalMapping - Tell the execution engine that the specified global is
185   /// at the specified location.  This is used internally as functions are JIT'd
186   /// and as global variables are laid out in memory.  It can and should also be
187   /// used by clients of the EE that want to have an LLVM global overlay
188   /// existing data in memory.
189   void addGlobalMapping(const GlobalValue *GV, void *Addr);
190   
191   /// clearAllGlobalMappings - Clear all global mappings and start over again
192   /// use in dynamic compilation scenarios when you want to move globals
193   void clearAllGlobalMappings();
194   
195   /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
196   /// particular module, because it has been removed from the JIT.
197   void clearGlobalMappingsFromModule(Module *M);
198   
199   /// updateGlobalMapping - Replace an existing mapping for GV with a new
200   /// address.  This updates both maps as required.  If "Addr" is null, the
201   /// entry for the global is removed from the mappings.  This returns the old
202   /// value of the pointer, or null if it was not in the map.
203   void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
204   
205   /// getPointerToGlobalIfAvailable - This returns the address of the specified
206   /// global value if it is has already been codegen'd, otherwise it returns
207   /// null.
208   ///
209   void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
210
211   /// getPointerToGlobal - This returns the address of the specified global
212   /// value.  This may involve code generation if it's a function.
213   ///
214   void *getPointerToGlobal(const GlobalValue *GV);
215
216   /// getPointerToFunction - The different EE's represent function bodies in
217   /// different ways.  They should each implement this to say what a function
218   /// pointer should look like.
219   ///
220   virtual void *getPointerToFunction(Function *F) = 0;
221
222   /// getPointerToFunctionOrStub - If the specified function has been
223   /// code-gen'd, return a pointer to the function.  If not, compile it, or use
224   /// a stub to implement lazy compilation if available.
225   ///
226   virtual void *getPointerToFunctionOrStub(Function *F) {
227     // Default implementation, just codegen the function.
228     return getPointerToFunction(F);
229   }
230
231   /// getGlobalValueAtAddress - Return the LLVM global value object that starts
232   /// at the specified address.
233   ///
234   const GlobalValue *getGlobalValueAtAddress(void *Addr);
235
236
237   void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
238                           const Type *Ty);
239   void InitializeMemory(const Constant *Init, void *Addr);
240
241   /// recompileAndRelinkFunction - This method is used to force a function
242   /// which has already been compiled to be compiled again, possibly
243   /// after it has been modified. Then the entry to the old copy is overwritten
244   /// with a branch to the new copy. If there was no old copy, this acts
245   /// just like VM::getPointerToFunction().
246   ///
247   virtual void *recompileAndRelinkFunction(Function *F) = 0;
248
249   /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
250   /// corresponding to the machine code emitted to execute this function, useful
251   /// for garbage-collecting generated code.
252   ///
253   virtual void freeMachineCodeForFunction(Function *F) = 0;
254
255   /// getOrEmitGlobalVariable - Return the address of the specified global
256   /// variable, possibly emitting it to memory if needed.  This is used by the
257   /// Emitter.
258   virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
259     return getPointerToGlobal((GlobalValue*)GV);
260   }
261   
262   /// DisableLazyCompilation - If called, the JIT will abort if lazy compilation
263   /// is ever attempted.
264   void DisableLazyCompilation(bool Disabled = true) {
265     LazyCompilationDisabled = Disabled;
266   }
267   bool isLazyCompilationDisabled() const {
268     return LazyCompilationDisabled;
269   }
270
271   /// DisableGVCompilation - If called, the JIT will abort if it's asked to
272   /// allocate space and populate a GlobalVariable that is not internal to
273   /// the module.
274   void DisableGVCompilation(bool Disabled = true) {
275     GVCompilationDisabled = Disabled;
276   }
277   bool isGVCompilationDisabled() const {
278     return GVCompilationDisabled;
279   }
280
281   /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
282   /// symbols with dlsym.  A client can still use InstallLazyFunctionCreator to
283   /// resolve symbols in a custom way.
284   void DisableSymbolSearching(bool Disabled = true) {
285     SymbolSearchingDisabled = Disabled;
286   }
287   bool isSymbolSearchingDisabled() const {
288     return SymbolSearchingDisabled;
289   }
290   
291   
292   /// InstallLazyFunctionCreator - If an unknown function is needed, the
293   /// specified function pointer is invoked to create it.  If it returns null,
294   /// the JIT will abort.
295   void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
296     LazyFunctionCreator = P;
297   }
298   
299   /// InstallExceptionTableRegister - The JIT will use the given function
300   /// to register the exception tables it generates.
301   static void InstallExceptionTableRegister(void (*F)(void*)) {
302     ExceptionTableRegister = F;
303   }
304   
305   /// RegisterTable - Registers the given pointer as an exception table. It uses
306   /// the ExceptionTableRegister function.
307   static void RegisterTable(void* res) {
308     if (ExceptionTableRegister)
309       ExceptionTableRegister(res);
310   }
311
312 protected:
313   explicit ExecutionEngine(ModuleProvider *P);
314
315   void emitGlobals();
316
317   // EmitGlobalVariable - This method emits the specified global variable to the
318   // address specified in GlobalAddresses, or allocates new memory if it's not
319   // already in the map.
320   void EmitGlobalVariable(const GlobalVariable *GV);
321
322   GenericValue getConstantValue(const Constant *C);
323   void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr, 
324                            const Type *Ty);
325 };
326
327 } // End llvm namespace
328
329 #endif