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