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