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