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