Remove dlsym stubs, with Nate Begeman's permission.
[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/ADT/SmallVector.h"
22 #include "llvm/ADT/ValueMap.h"
23 #include "llvm/Support/ValueHandle.h"
24 #include "llvm/System/Mutex.h"
25 #include "llvm/Target/TargetMachine.h"
26
27 namespace llvm {
28
29 struct GenericValue;
30 class Constant;
31 class ExecutionEngine;
32 class Function;
33 class GlobalVariable;
34 class GlobalValue;
35 class JITEventListener;
36 class JITMemoryManager;
37 class MachineCodeInfo;
38 class Module;
39 class ModuleProvider;
40 class MutexGuard;
41 class TargetData;
42 class Type;
43
44 class ExecutionEngineState {
45 public:
46   struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
47     typedef ExecutionEngineState *ExtraData;
48     static sys::Mutex *getMutex(ExecutionEngineState *EES);
49     static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
50     static void onRAUW(ExecutionEngineState *, const GlobalValue *,
51                        const GlobalValue *);
52   };
53
54   typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
55       GlobalAddressMapTy;
56
57 private:
58   ExecutionEngine &EE;
59
60   /// GlobalAddressMap - A mapping between LLVM global values and their
61   /// actualized version...
62   GlobalAddressMapTy GlobalAddressMap;
63
64   /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
65   /// used to convert raw addresses into the LLVM global value that is emitted
66   /// at the address.  This map is not computed unless getGlobalValueAtAddress
67   /// is called at some point.
68   std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
69
70 public:
71   ExecutionEngineState(ExecutionEngine &EE);
72
73   GlobalAddressMapTy &
74   getGlobalAddressMap(const MutexGuard &) {
75     return GlobalAddressMap;
76   }
77
78   std::map<void*, AssertingVH<const GlobalValue> > &
79   getGlobalAddressReverseMap(const MutexGuard &) {
80     return GlobalAddressReverseMap;
81   }
82
83   // Returns the address ToUnmap was mapped to.
84   void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
85 };
86
87
88 class ExecutionEngine {
89   const TargetData *TD;
90   ExecutionEngineState EEState;
91   bool CompilingLazily;
92   bool GVCompilationDisabled;
93   bool SymbolSearchingDisabled;
94
95   friend class EngineBuilder;  // To allow access to JITCtor and InterpCtor.
96
97 protected:
98   /// Modules - This is a list of ModuleProvider's that we are JIT'ing from.  We
99   /// use a smallvector to optimize for the case where there is only one module.
100   SmallVector<ModuleProvider*, 1> Modules;
101   
102   void setTargetData(const TargetData *td) {
103     TD = td;
104   }
105   
106   /// getMemoryforGV - Allocate memory for a global variable.
107   virtual char* getMemoryForGV(const GlobalVariable* GV);
108
109   // To avoid having libexecutionengine depend on the JIT and interpreter
110   // libraries, the JIT and Interpreter set these functions to ctor pointers
111   // at startup time if they are linked in.
112   static ExecutionEngine *(*JITCtor)(ModuleProvider *MP,
113                                      std::string *ErrorStr,
114                                      JITMemoryManager *JMM,
115                                      CodeGenOpt::Level OptLevel,
116                                      bool GVsWithCode);
117   static ExecutionEngine *(*InterpCtor)(ModuleProvider *MP,
118                                         std::string *ErrorStr);
119
120   /// LazyFunctionCreator - If an unknown function is needed, this function
121   /// pointer is invoked to create it. If this returns null, the JIT will abort.
122   void* (*LazyFunctionCreator)(const std::string &);
123   
124   /// ExceptionTableRegister - If Exception Handling is set, the JIT will 
125   /// register dwarf tables with this function
126   typedef void (*EERegisterFn)(void*);
127   static EERegisterFn ExceptionTableRegister;
128
129 public:
130   /// lock - This lock is protects the ExecutionEngine, JIT, JITResolver and
131   /// JITEmitter classes.  It must be held while changing the internal state of
132   /// any of those classes.
133   sys::Mutex lock; // Used to make this class and subclasses thread-safe
134
135   //===--------------------------------------------------------------------===//
136   //  ExecutionEngine Startup
137   //===--------------------------------------------------------------------===//
138
139   virtual ~ExecutionEngine();
140
141   /// create - This is the factory method for creating an execution engine which
142   /// is appropriate for the current machine.  This takes ownership of the
143   /// module provider.
144   static ExecutionEngine *create(ModuleProvider *MP,
145                                  bool ForceInterpreter = false,
146                                  std::string *ErrorStr = 0,
147                                  CodeGenOpt::Level OptLevel =
148                                    CodeGenOpt::Default,
149                                  // Allocating globals with code breaks
150                                  // freeMachineCodeForFunction and is probably
151                                  // unsafe and bad for performance.  However,
152                                  // we have clients who depend on this
153                                  // behavior, so we must support it.
154                                  // Eventually, when we're willing to break
155                                  // some backwards compatability, this flag
156                                  // should be flipped to false, so that by
157                                  // default freeMachineCodeForFunction works.
158                                  bool GVsWithCode = true);
159
160   /// create - This is the factory method for creating an execution engine which
161   /// is appropriate for the current machine.  This takes ownership of the
162   /// module.
163   static ExecutionEngine *create(Module *M);
164
165   /// createJIT - This is the factory method for creating a JIT for the current
166   /// machine, it does not fall back to the interpreter.  This takes ownership
167   /// of the ModuleProvider and JITMemoryManager if successful.
168   ///
169   /// Clients should make sure to initialize targets prior to calling this
170   /// function.
171   static ExecutionEngine *createJIT(ModuleProvider *MP,
172                                     std::string *ErrorStr = 0,
173                                     JITMemoryManager *JMM = 0,
174                                     CodeGenOpt::Level OptLevel =
175                                       CodeGenOpt::Default,
176                                     bool GVsWithCode = true);
177
178   /// addModuleProvider - Add a ModuleProvider to the list of modules that we
179   /// can JIT from.  Note that this takes ownership of the ModuleProvider: when
180   /// the ExecutionEngine is destroyed, it destroys the MP as well.
181   virtual void addModuleProvider(ModuleProvider *P) {
182     Modules.push_back(P);
183   }
184   
185   //===----------------------------------------------------------------------===//
186
187   const TargetData *getTargetData() const { return TD; }
188
189
190   /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
191   /// Relases the Module from the ModuleProvider, materializing it in the
192   /// process, and returns the materialized Module.
193   virtual Module* removeModuleProvider(ModuleProvider *P,
194                                        std::string *ErrInfo = 0);
195
196   /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
197   /// and deletes the ModuleProvider and owned Module.  Avoids materializing 
198   /// the underlying module.
199   virtual void deleteModuleProvider(ModuleProvider *P,std::string *ErrInfo = 0);
200
201   /// FindFunctionNamed - Search all of the active modules to find the one that
202   /// defines FnName.  This is very slow operation and shouldn't be used for
203   /// general code.
204   Function *FindFunctionNamed(const char *FnName);
205   
206   /// runFunction - Execute the specified function with the specified arguments,
207   /// and return the result.
208   ///
209   virtual GenericValue runFunction(Function *F,
210                                 const std::vector<GenericValue> &ArgValues) = 0;
211
212   /// runStaticConstructorsDestructors - This method is used to execute all of
213   /// the static constructors or destructors for a program, depending on the
214   /// value of isDtors.
215   void runStaticConstructorsDestructors(bool isDtors);
216   /// runStaticConstructorsDestructors - This method is used to execute all of
217   /// the static constructors or destructors for a module, depending on the
218   /// value of isDtors.
219   void runStaticConstructorsDestructors(Module *module, bool isDtors);
220   
221   
222   /// runFunctionAsMain - This is a helper function which wraps runFunction to
223   /// handle the common task of starting up main with the specified argc, argv,
224   /// and envp parameters.
225   int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
226                         const char * const * envp);
227
228
229   /// addGlobalMapping - Tell the execution engine that the specified global is
230   /// at the specified location.  This is used internally as functions are JIT'd
231   /// and as global variables are laid out in memory.  It can and should also be
232   /// used by clients of the EE that want to have an LLVM global overlay
233   /// existing data in memory.  Mappings are automatically removed when their
234   /// GlobalValue is destroyed.
235   void addGlobalMapping(const GlobalValue *GV, void *Addr);
236   
237   /// clearAllGlobalMappings - Clear all global mappings and start over again
238   /// use in dynamic compilation scenarios when you want to move globals
239   void clearAllGlobalMappings();
240   
241   /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
242   /// particular module, because it has been removed from the JIT.
243   void clearGlobalMappingsFromModule(Module *M);
244   
245   /// updateGlobalMapping - Replace an existing mapping for GV with a new
246   /// address.  This updates both maps as required.  If "Addr" is null, the
247   /// entry for the global is removed from the mappings.  This returns the old
248   /// value of the pointer, or null if it was not in the map.
249   void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
250   
251   /// getPointerToGlobalIfAvailable - This returns the address of the specified
252   /// global value if it is has already been codegen'd, otherwise it returns
253   /// null.
254   ///
255   void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
256
257   /// getPointerToGlobal - This returns the address of the specified global
258   /// value.  This may involve code generation if it's a function.
259   ///
260   void *getPointerToGlobal(const GlobalValue *GV);
261
262   /// getPointerToFunction - The different EE's represent function bodies in
263   /// different ways.  They should each implement this to say what a function
264   /// pointer should look like.  When F is destroyed, the ExecutionEngine will
265   /// remove its global mapping and free any machine code.  Be sure no threads
266   /// are running inside F when that happens.
267   ///
268   virtual void *getPointerToFunction(Function *F) = 0;
269
270   /// getPointerToBasicBlock - The different EE's represent basic blocks in
271   /// different ways.  Return the representation for a blockaddress of the
272   /// specified block.
273   ///
274   virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
275   
276   /// getPointerToFunctionOrStub - If the specified function has been
277   /// code-gen'd, return a pointer to the function.  If not, compile it, or use
278   /// a stub to implement lazy compilation if available.  See
279   /// getPointerToFunction for the requirements on destroying F.
280   ///
281   virtual void *getPointerToFunctionOrStub(Function *F) {
282     // Default implementation, just codegen the function.
283     return getPointerToFunction(F);
284   }
285
286   // The JIT overrides a version that actually does this.
287   virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
288
289   /// getGlobalValueAtAddress - Return the LLVM global value object that starts
290   /// at the specified address.
291   ///
292   const GlobalValue *getGlobalValueAtAddress(void *Addr);
293
294
295   void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
296                           const Type *Ty);
297   void InitializeMemory(const Constant *Init, void *Addr);
298
299   /// recompileAndRelinkFunction - This method is used to force a function
300   /// which has already been compiled to be compiled again, possibly
301   /// after it has been modified. Then the entry to the old copy is overwritten
302   /// with a branch to the new copy. If there was no old copy, this acts
303   /// just like VM::getPointerToFunction().
304   ///
305   virtual void *recompileAndRelinkFunction(Function *F) = 0;
306
307   /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
308   /// corresponding to the machine code emitted to execute this function, useful
309   /// for garbage-collecting generated code.
310   ///
311   virtual void freeMachineCodeForFunction(Function *F) = 0;
312
313   /// getOrEmitGlobalVariable - Return the address of the specified global
314   /// variable, possibly emitting it to memory if needed.  This is used by the
315   /// Emitter.
316   virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
317     return getPointerToGlobal((GlobalValue*)GV);
318   }
319
320   /// Registers a listener to be called back on various events within
321   /// the JIT.  See JITEventListener.h for more details.  Does not
322   /// take ownership of the argument.  The argument may be NULL, in
323   /// which case these functions do nothing.
324   virtual void RegisterJITEventListener(JITEventListener *) {}
325   virtual void UnregisterJITEventListener(JITEventListener *) {}
326
327   /// DisableLazyCompilation - When lazy compilation is off (the default), the
328   /// JIT will eagerly compile every function reachable from the argument to
329   /// getPointerToFunction.  If lazy compilation is turned on, the JIT will only
330   /// compile the one function and emit stubs to compile the rest when they're
331   /// first called.  If lazy compilation is turned off again while some lazy
332   /// stubs are still around, and one of those stubs is called, the program will
333   /// abort.
334   ///
335   /// In order to safely compile lazily in a threaded program, the user must
336   /// ensure that 1) only one thread at a time can call any particular lazy
337   /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
338   /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
339   /// lazy stub.  See http://llvm.org/PR5184 for details.
340   void DisableLazyCompilation(bool Disabled = true) {
341     CompilingLazily = !Disabled;
342   }
343   bool isCompilingLazily() const {
344     return CompilingLazily;
345   }
346   // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
347   // Remove this in LLVM 2.8.
348   bool isLazyCompilationDisabled() const {
349     return !CompilingLazily;
350   }
351
352   /// DisableGVCompilation - If called, the JIT will abort if it's asked to
353   /// allocate space and populate a GlobalVariable that is not internal to
354   /// the module.
355   void DisableGVCompilation(bool Disabled = true) {
356     GVCompilationDisabled = Disabled;
357   }
358   bool isGVCompilationDisabled() const {
359     return GVCompilationDisabled;
360   }
361
362   /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
363   /// symbols with dlsym.  A client can still use InstallLazyFunctionCreator to
364   /// resolve symbols in a custom way.
365   void DisableSymbolSearching(bool Disabled = true) {
366     SymbolSearchingDisabled = Disabled;
367   }
368   bool isSymbolSearchingDisabled() const {
369     return SymbolSearchingDisabled;
370   }
371
372   /// InstallLazyFunctionCreator - If an unknown function is needed, the
373   /// specified function pointer is invoked to create it.  If it returns null,
374   /// the JIT will abort.
375   void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
376     LazyFunctionCreator = P;
377   }
378   
379   /// InstallExceptionTableRegister - The JIT will use the given function
380   /// to register the exception tables it generates.
381   static void InstallExceptionTableRegister(void (*F)(void*)) {
382     ExceptionTableRegister = F;
383   }
384   
385   /// RegisterTable - Registers the given pointer as an exception table. It uses
386   /// the ExceptionTableRegister function.
387   static void RegisterTable(void* res) {
388     if (ExceptionTableRegister)
389       ExceptionTableRegister(res);
390   }
391
392 protected:
393   explicit ExecutionEngine(ModuleProvider *P);
394
395   void emitGlobals();
396
397   // EmitGlobalVariable - This method emits the specified global variable to the
398   // address specified in GlobalAddresses, or allocates new memory if it's not
399   // already in the map.
400   void EmitGlobalVariable(const GlobalVariable *GV);
401
402   GenericValue getConstantValue(const Constant *C);
403   void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr, 
404                            const Type *Ty);
405 };
406
407 namespace EngineKind {
408   // These are actually bitmasks that get or-ed together.
409   enum Kind {
410     JIT         = 0x1,
411     Interpreter = 0x2
412   };
413   const static Kind Either = (Kind)(JIT | Interpreter);
414 }
415
416 /// EngineBuilder - Builder class for ExecutionEngines.  Use this by
417 /// stack-allocating a builder, chaining the various set* methods, and
418 /// terminating it with a .create() call.
419 class EngineBuilder {
420
421  private:
422   ModuleProvider *MP;
423   EngineKind::Kind WhichEngine;
424   std::string *ErrorStr;
425   CodeGenOpt::Level OptLevel;
426   JITMemoryManager *JMM;
427   bool AllocateGVsWithCode;
428
429   /// InitEngine - Does the common initialization of default options.
430   ///
431   void InitEngine() {
432     WhichEngine = EngineKind::Either;
433     ErrorStr = NULL;
434     OptLevel = CodeGenOpt::Default;
435     JMM = NULL;
436     AllocateGVsWithCode = false;
437   }
438
439  public:
440   /// EngineBuilder - Constructor for EngineBuilder.  If create() is called and
441   /// is successful, the created engine takes ownership of the module
442   /// provider.
443   EngineBuilder(ModuleProvider *mp) : MP(mp) {
444     InitEngine();
445   }
446
447   /// EngineBuilder - Overloaded constructor that automatically creates an
448   /// ExistingModuleProvider for an existing module.
449   EngineBuilder(Module *m);
450
451   /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
452   /// or whichever engine works.  This option defaults to EngineKind::Either.
453   EngineBuilder &setEngineKind(EngineKind::Kind w) {
454     WhichEngine = w;
455     return *this;
456   }
457
458   /// setJITMemoryManager - Sets the memory manager to use.  This allows
459   /// clients to customize their memory allocation policies.  If create() is
460   /// called and is successful, the created engine takes ownership of the
461   /// memory manager.  This option defaults to NULL.
462   EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
463     JMM = jmm;
464     return *this;
465   }
466
467   /// setErrorStr - Set the error string to write to on error.  This option
468   /// defaults to NULL.
469   EngineBuilder &setErrorStr(std::string *e) {
470     ErrorStr = e;
471     return *this;
472   }
473
474   /// setOptLevel - Set the optimization level for the JIT.  This option
475   /// defaults to CodeGenOpt::Default.
476   EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
477     OptLevel = l;
478     return *this;
479   }
480
481   /// setAllocateGVsWithCode - Sets whether global values should be allocated
482   /// into the same buffer as code.  For most applications this should be set
483   /// to false.  Allocating globals with code breaks freeMachineCodeForFunction
484   /// and is probably unsafe and bad for performance.  However, we have clients
485   /// who depend on this behavior, so we must support it.  This option defaults
486   /// to false so that users of the new API can safely use the new memory
487   /// manager and free machine code.
488   EngineBuilder &setAllocateGVsWithCode(bool a) {
489     AllocateGVsWithCode = a;
490     return *this;
491   }
492
493   ExecutionEngine *create();
494 };
495
496 } // End llvm namespace
497
498 #endif