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