PR19553: Memory leak in RuntimeDyldELF::createObjectImageFromFile
[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_EXECUTIONENGINE_EXECUTIONENGINE_H
16 #define LLVM_EXECUTIONENGINE_EXECUTIONENGINE_H
17
18 #include "llvm-c/ExecutionEngine.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/IR/ValueHandle.h"
22 #include "llvm/IR/ValueMap.h"
23 #include "llvm/MC/MCCodeGenInfo.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/Mutex.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetOptions.h"
28 #include <map>
29 #include <string>
30 #include <vector>
31
32 namespace llvm {
33
34 struct GenericValue;
35 class Constant;
36 class DataLayout;
37 class ExecutionEngine;
38 class Function;
39 class GlobalVariable;
40 class GlobalValue;
41 class JITEventListener;
42 class JITMemoryManager;
43 class MachineCodeInfo;
44 class Module;
45 class MutexGuard;
46 class ObjectCache;
47 class RTDyldMemoryManager;
48 class Triple;
49 class Type;
50
51 namespace object {
52   class Archive;
53   class ObjectFile;
54 }
55
56 /// \brief Helper class for helping synchronize access to the global address map
57 /// table.
58 class ExecutionEngineState {
59 public:
60   struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
61     typedef ExecutionEngineState *ExtraData;
62     static sys::Mutex *getMutex(ExecutionEngineState *EES);
63     static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
64     static void onRAUW(ExecutionEngineState *, const GlobalValue *,
65                        const GlobalValue *);
66   };
67
68   typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
69       GlobalAddressMapTy;
70
71 private:
72   ExecutionEngine &EE;
73
74   /// GlobalAddressMap - A mapping between LLVM global values and their
75   /// actualized version...
76   GlobalAddressMapTy GlobalAddressMap;
77
78   /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
79   /// used to convert raw addresses into the LLVM global value that is emitted
80   /// at the address.  This map is not computed unless getGlobalValueAtAddress
81   /// is called at some point.
82   std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
83
84 public:
85   ExecutionEngineState(ExecutionEngine &EE);
86
87   GlobalAddressMapTy &getGlobalAddressMap(const MutexGuard &) {
88     return GlobalAddressMap;
89   }
90
91   std::map<void*, AssertingVH<const GlobalValue> > &
92   getGlobalAddressReverseMap(const MutexGuard &) {
93     return GlobalAddressReverseMap;
94   }
95
96   /// \brief Erase an entry from the mapping table.
97   ///
98   /// \returns The address that \p ToUnmap was happed to.
99   void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
100 };
101
102 /// \brief Abstract interface for implementation execution of LLVM modules,
103 /// designed to support both interpreter and just-in-time (JIT) compiler
104 /// implementations.
105 class ExecutionEngine {
106   /// The state object holding the global address mapping, which must be
107   /// accessed synchronously.
108   //
109   // FIXME: There is no particular need the entire map needs to be
110   // synchronized.  Wouldn't a reader-writer design be better here?
111   ExecutionEngineState EEState;
112
113   /// The target data for the platform for which execution is being performed.
114   const DataLayout *DL;
115
116   /// Whether lazy JIT compilation is enabled.
117   bool CompilingLazily;
118
119   /// Whether JIT compilation of external global variables is allowed.
120   bool GVCompilationDisabled;
121
122   /// Whether the JIT should perform lookups of external symbols (e.g.,
123   /// using dlsym).
124   bool SymbolSearchingDisabled;
125
126   /// Whether the JIT should verify IR modules during compilation.
127   bool VerifyModules;
128
129   friend class EngineBuilder;  // To allow access to JITCtor and InterpCtor.
130
131 protected:
132   /// The list of Modules that we are JIT'ing from.  We use a SmallVector to
133   /// optimize for the case where there is only one module.
134   SmallVector<Module*, 1> Modules;
135
136   void setDataLayout(const DataLayout *Val) { DL = Val; }
137
138   /// getMemoryforGV - Allocate memory for a global variable.
139   virtual char *getMemoryForGV(const GlobalVariable *GV);
140
141   // To avoid having libexecutionengine depend on the JIT and interpreter
142   // libraries, the execution engine implementations set these functions to ctor
143   // pointers at startup time if they are linked in.
144   static ExecutionEngine *(*JITCtor)(
145     Module *M,
146     std::string *ErrorStr,
147     JITMemoryManager *JMM,
148     bool GVsWithCode,
149     TargetMachine *TM);
150   static ExecutionEngine *(*MCJITCtor)(
151     Module *M,
152     std::string *ErrorStr,
153     RTDyldMemoryManager *MCJMM,
154     bool GVsWithCode,
155     TargetMachine *TM);
156   static ExecutionEngine *(*InterpCtor)(Module *M, std::string *ErrorStr);
157
158   /// LazyFunctionCreator - If an unknown function is needed, this function
159   /// pointer is invoked to create it.  If this returns null, the JIT will
160   /// abort.
161   void *(*LazyFunctionCreator)(const std::string &);
162
163 public:
164   /// lock - This lock protects the ExecutionEngine, MCJIT, JIT, JITResolver and
165   /// JITEmitter classes.  It must be held while changing the internal state of
166   /// any of those classes.
167   sys::Mutex lock;
168
169   //===--------------------------------------------------------------------===//
170   //  ExecutionEngine Startup
171   //===--------------------------------------------------------------------===//
172
173   virtual ~ExecutionEngine();
174
175   /// create - This is the factory method for creating an execution engine which
176   /// is appropriate for the current machine.  This takes ownership of the
177   /// module.
178   ///
179   /// \param GVsWithCode - Allocating globals with code breaks
180   /// freeMachineCodeForFunction and is probably unsafe and bad for performance.
181   /// However, we have clients who depend on this behavior, so we must support
182   /// it.  Eventually, when we're willing to break some backwards compatibility,
183   /// this flag should be flipped to false, so that by default
184   /// freeMachineCodeForFunction works.
185   static ExecutionEngine *create(Module *M,
186                                  bool ForceInterpreter = false,
187                                  std::string *ErrorStr = nullptr,
188                                  CodeGenOpt::Level OptLevel =
189                                  CodeGenOpt::Default,
190                                  bool GVsWithCode = true);
191
192   /// createJIT - This is the factory method for creating a JIT for the current
193   /// machine, it does not fall back to the interpreter.  This takes ownership
194   /// of the Module and JITMemoryManager if successful.
195   ///
196   /// Clients should make sure to initialize targets prior to calling this
197   /// function.
198   static ExecutionEngine *createJIT(Module *M,
199                                     std::string *ErrorStr = nullptr,
200                                     JITMemoryManager *JMM = nullptr,
201                                     CodeGenOpt::Level OptLevel =
202                                     CodeGenOpt::Default,
203                                     bool GVsWithCode = true,
204                                     Reloc::Model RM = Reloc::Default,
205                                     CodeModel::Model CMM =
206                                     CodeModel::JITDefault);
207
208   /// addModule - Add a Module to the list of modules that we can JIT from.
209   /// Note that this takes ownership of the Module: when the ExecutionEngine is
210   /// destroyed, it destroys the Module as well.
211   virtual void addModule(Module *M) {
212     Modules.push_back(M);
213   }
214
215   /// addObjectFile - Add an ObjectFile to the execution engine.
216   ///
217   /// This method is only supported by MCJIT.  MCJIT will immediately load the
218   /// object into memory and adds its symbols to the list used to resolve
219   /// external symbols while preparing other objects for execution.
220   ///
221   /// Objects added using this function will not be made executable until
222   /// needed by another object.
223   ///
224   /// MCJIT will take ownership of the ObjectFile.
225   virtual void addObjectFile(std::unique_ptr<object::ObjectFile> O) {
226     llvm_unreachable(
227       "ExecutionEngine subclass doesn't implement addObjectFile.");
228   }
229
230   /// addArchive - Add an Archive to the execution engine.
231   ///
232   /// This method is only supported by MCJIT.  MCJIT will use the archive to
233   /// resolve external symbols in objects it is loading.  If a symbol is found
234   /// in the Archive the contained object file will be extracted (in memory)
235   /// and loaded for possible execution.
236   ///
237   /// MCJIT will take ownership of the Archive.
238   virtual void addArchive(object::Archive *A) {
239     llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
240   }
241
242   //===--------------------------------------------------------------------===//
243
244   const DataLayout *getDataLayout() const { return DL; }
245
246   /// removeModule - Remove a Module from the list of modules.  Returns true if
247   /// M is found.
248   virtual bool removeModule(Module *M);
249
250   /// FindFunctionNamed - Search all of the active modules to find the one that
251   /// defines FnName.  This is very slow operation and shouldn't be used for
252   /// general code.
253   virtual Function *FindFunctionNamed(const char *FnName);
254
255   /// runFunction - Execute the specified function with the specified arguments,
256   /// and return the result.
257   virtual GenericValue runFunction(Function *F,
258                                 const std::vector<GenericValue> &ArgValues) = 0;
259
260   /// getPointerToNamedFunction - This method returns the address of the
261   /// specified function by using the dlsym function call.  As such it is only
262   /// useful for resolving library symbols, not code generated symbols.
263   ///
264   /// If AbortOnFailure is false and no function with the given name is
265   /// found, this function silently returns a null pointer. Otherwise,
266   /// it prints a message to stderr and aborts.
267   ///
268   /// This function is deprecated for the MCJIT execution engine.
269   ///
270   /// FIXME: the JIT and MCJIT interfaces should be disentangled or united
271   /// again, if possible.
272   ///
273   virtual void *getPointerToNamedFunction(const std::string &Name,
274                                           bool AbortOnFailure = true) = 0;
275
276   /// mapSectionAddress - map a section to its target address space value.
277   /// Map the address of a JIT section as returned from the memory manager
278   /// to the address in the target process as the running code will see it.
279   /// This is the address which will be used for relocation resolution.
280   virtual void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress) {
281     llvm_unreachable("Re-mapping of section addresses not supported with this "
282                      "EE!");
283   }
284
285   /// generateCodeForModule - Run code generationen for the specified module and
286   /// load it into memory.
287   ///
288   /// When this function has completed, all code and data for the specified
289   /// module, and any module on which this module depends, will be generated
290   /// and loaded into memory, but relocations will not yet have been applied
291   /// and all memory will be readable and writable but not executable.
292   ///
293   /// This function is primarily useful when generating code for an external
294   /// target, allowing the client an opportunity to remap section addresses
295   /// before relocations are applied.  Clients that intend to execute code
296   /// locally can use the getFunctionAddress call, which will generate code
297   /// and apply final preparations all in one step.
298   ///
299   /// This method has no effect for the legacy JIT engine or the interpeter.
300   virtual void generateCodeForModule(Module *M) {}
301
302   /// finalizeObject - ensure the module is fully processed and is usable.
303   ///
304   /// It is the user-level function for completing the process of making the
305   /// object usable for execution.  It should be called after sections within an
306   /// object have been relocated using mapSectionAddress.  When this method is
307   /// called the MCJIT execution engine will reapply relocations for a loaded
308   /// object.  This method has no effect for the legacy JIT engine or the
309   /// interpeter.
310   virtual void finalizeObject() {}
311
312   /// runStaticConstructorsDestructors - This method is used to execute all of
313   /// the static constructors or destructors for a program.
314   ///
315   /// \param isDtors - Run the destructors instead of constructors.
316   virtual void runStaticConstructorsDestructors(bool isDtors);
317
318   /// runStaticConstructorsDestructors - This method is used to execute all of
319   /// the static constructors or destructors for a particular module.
320   ///
321   /// \param isDtors - Run the destructors instead of constructors.
322   void runStaticConstructorsDestructors(Module *module, bool isDtors);
323
324
325   /// runFunctionAsMain - This is a helper function which wraps runFunction to
326   /// handle the common task of starting up main with the specified argc, argv,
327   /// and envp parameters.
328   int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
329                         const char * const * envp);
330
331
332   /// addGlobalMapping - Tell the execution engine that the specified global is
333   /// at the specified location.  This is used internally as functions are JIT'd
334   /// and as global variables are laid out in memory.  It can and should also be
335   /// used by clients of the EE that want to have an LLVM global overlay
336   /// existing data in memory.  Mappings are automatically removed when their
337   /// GlobalValue is destroyed.
338   void addGlobalMapping(const GlobalValue *GV, void *Addr);
339
340   /// clearAllGlobalMappings - Clear all global mappings and start over again,
341   /// for use in dynamic compilation scenarios to move globals.
342   void clearAllGlobalMappings();
343
344   /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
345   /// particular module, because it has been removed from the JIT.
346   void clearGlobalMappingsFromModule(Module *M);
347
348   /// updateGlobalMapping - Replace an existing mapping for GV with a new
349   /// address.  This updates both maps as required.  If "Addr" is null, the
350   /// entry for the global is removed from the mappings.  This returns the old
351   /// value of the pointer, or null if it was not in the map.
352   void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
353
354   /// getPointerToGlobalIfAvailable - This returns the address of the specified
355   /// global value if it is has already been codegen'd, otherwise it returns
356   /// null.
357   ///
358   /// This function is deprecated for the MCJIT execution engine.  It doesn't
359   /// seem to be needed in that case, but an equivalent can be added if it is.
360   void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
361
362   /// getPointerToGlobal - This returns the address of the specified global
363   /// value. This may involve code generation if it's a function.
364   ///
365   /// This function is deprecated for the MCJIT execution engine.  Use
366   /// getGlobalValueAddress instead.
367   void *getPointerToGlobal(const GlobalValue *GV);
368
369   /// getPointerToFunction - The different EE's represent function bodies in
370   /// different ways.  They should each implement this to say what a function
371   /// pointer should look like.  When F is destroyed, the ExecutionEngine will
372   /// remove its global mapping and free any machine code.  Be sure no threads
373   /// are running inside F when that happens.
374   ///
375   /// This function is deprecated for the MCJIT execution engine.  Use
376   /// getFunctionAddress instead.
377   virtual void *getPointerToFunction(Function *F) = 0;
378
379   /// getPointerToBasicBlock - The different EE's represent basic blocks in
380   /// different ways.  Return the representation for a blockaddress of the
381   /// specified block.
382   ///
383   /// This function will not be implemented for the MCJIT execution engine.
384   virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
385
386   /// getPointerToFunctionOrStub - If the specified function has been
387   /// code-gen'd, return a pointer to the function.  If not, compile it, or use
388   /// a stub to implement lazy compilation if available.  See
389   /// getPointerToFunction for the requirements on destroying F.
390   ///
391   /// This function is deprecated for the MCJIT execution engine.  Use
392   /// getFunctionAddress instead.
393   virtual void *getPointerToFunctionOrStub(Function *F) {
394     // Default implementation, just codegen the function.
395     return getPointerToFunction(F);
396   }
397
398   /// getGlobalValueAddress - Return the address of the specified global
399   /// value. This may involve code generation.
400   ///
401   /// This function should not be called with the JIT or interpreter engines.
402   virtual uint64_t getGlobalValueAddress(const std::string &Name) {
403     // Default implementation for JIT and interpreter.  MCJIT will override this.
404     // JIT and interpreter clients should use getPointerToGlobal instead.
405     return 0;
406   }
407
408   /// getFunctionAddress - Return the address of the specified function.
409   /// This may involve code generation.
410   virtual uint64_t getFunctionAddress(const std::string &Name) {
411     // Default implementation for JIT and interpreter.  MCJIT will override this.
412     // JIT and interpreter clients should use getPointerToFunction instead.
413     return 0;
414   }
415
416   // The JIT overrides a version that actually does this.
417   virtual void runJITOnFunction(Function *, MachineCodeInfo * = nullptr) { }
418
419   /// getGlobalValueAtAddress - Return the LLVM global value object that starts
420   /// at the specified address.
421   ///
422   const GlobalValue *getGlobalValueAtAddress(void *Addr);
423
424   /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
425   /// Ptr is the address of the memory at which to store Val, cast to
426   /// GenericValue *.  It is not a pointer to a GenericValue containing the
427   /// address at which to store Val.
428   void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
429                           Type *Ty);
430
431   void InitializeMemory(const Constant *Init, void *Addr);
432
433   /// recompileAndRelinkFunction - This method is used to force a function which
434   /// has already been compiled to be compiled again, possibly after it has been
435   /// modified.  Then the entry to the old copy is overwritten with a branch to
436   /// the new copy.  If there was no old copy, this acts just like
437   /// VM::getPointerToFunction().
438   virtual void *recompileAndRelinkFunction(Function *F) = 0;
439
440   /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
441   /// corresponding to the machine code emitted to execute this function, useful
442   /// for garbage-collecting generated code.
443   virtual void freeMachineCodeForFunction(Function *F) = 0;
444
445   /// getOrEmitGlobalVariable - Return the address of the specified global
446   /// variable, possibly emitting it to memory if needed.  This is used by the
447   /// Emitter.
448   ///
449   /// This function is deprecated for the MCJIT execution engine.  Use
450   /// getGlobalValueAddress instead.
451   virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
452     return getPointerToGlobal((const GlobalValue *)GV);
453   }
454
455   /// Registers a listener to be called back on various events within
456   /// the JIT.  See JITEventListener.h for more details.  Does not
457   /// take ownership of the argument.  The argument may be NULL, in
458   /// which case these functions do nothing.
459   virtual void RegisterJITEventListener(JITEventListener *) {}
460   virtual void UnregisterJITEventListener(JITEventListener *) {}
461
462   /// Sets the pre-compiled object cache.  The ownership of the ObjectCache is
463   /// not changed.  Supported by MCJIT but not JIT.
464   virtual void setObjectCache(ObjectCache *) {
465     llvm_unreachable("No support for an object cache");
466   }
467
468   /// setProcessAllSections (MCJIT Only): By default, only sections that are
469   /// "required for execution" are passed to the RTDyldMemoryManager, and other
470   /// sections are discarded. Passing 'true' to this method will cause
471   /// RuntimeDyld to pass all sections to its RTDyldMemoryManager regardless
472   /// of whether they are "required to execute" in the usual sense.
473   ///
474   /// Rationale: Some MCJIT clients want to be able to inspect metadata
475   /// sections (e.g. Dwarf, Stack-maps) to enable functionality or analyze
476   /// performance. Passing these sections to the memory manager allows the
477   /// client to make policy about the relevant sections, rather than having
478   /// MCJIT do it.
479   virtual void setProcessAllSections(bool ProcessAllSections) {
480     llvm_unreachable("No support for ProcessAllSections option");
481   }
482
483   /// Return the target machine (if available).
484   virtual TargetMachine *getTargetMachine() { return nullptr; }
485
486   /// DisableLazyCompilation - When lazy compilation is off (the default), the
487   /// JIT will eagerly compile every function reachable from the argument to
488   /// getPointerToFunction.  If lazy compilation is turned on, the JIT will only
489   /// compile the one function and emit stubs to compile the rest when they're
490   /// first called.  If lazy compilation is turned off again while some lazy
491   /// stubs are still around, and one of those stubs is called, the program will
492   /// abort.
493   ///
494   /// In order to safely compile lazily in a threaded program, the user must
495   /// ensure that 1) only one thread at a time can call any particular lazy
496   /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
497   /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
498   /// lazy stub.  See http://llvm.org/PR5184 for details.
499   void DisableLazyCompilation(bool Disabled = true) {
500     CompilingLazily = !Disabled;
501   }
502   bool isCompilingLazily() const {
503     return CompilingLazily;
504   }
505   // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
506   // Remove this in LLVM 2.8.
507   bool isLazyCompilationDisabled() const {
508     return !CompilingLazily;
509   }
510
511   /// DisableGVCompilation - If called, the JIT will abort if it's asked to
512   /// allocate space and populate a GlobalVariable that is not internal to
513   /// the module.
514   void DisableGVCompilation(bool Disabled = true) {
515     GVCompilationDisabled = Disabled;
516   }
517   bool isGVCompilationDisabled() const {
518     return GVCompilationDisabled;
519   }
520
521   /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
522   /// symbols with dlsym.  A client can still use InstallLazyFunctionCreator to
523   /// resolve symbols in a custom way.
524   void DisableSymbolSearching(bool Disabled = true) {
525     SymbolSearchingDisabled = Disabled;
526   }
527   bool isSymbolSearchingDisabled() const {
528     return SymbolSearchingDisabled;
529   }
530
531   /// Enable/Disable IR module verification.
532   ///
533   /// Note: Module verification is enabled by default in Debug builds, and
534   /// disabled by default in Release. Use this method to override the default.
535   void setVerifyModules(bool Verify) {
536     VerifyModules = Verify;
537   }
538   bool getVerifyModules() const {
539     return VerifyModules;
540   }
541
542   /// InstallLazyFunctionCreator - If an unknown function is needed, the
543   /// specified function pointer is invoked to create it.  If it returns null,
544   /// the JIT will abort.
545   void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
546     LazyFunctionCreator = P;
547   }
548
549 protected:
550   explicit ExecutionEngine(Module *M);
551
552   void emitGlobals();
553
554   void EmitGlobalVariable(const GlobalVariable *GV);
555
556   GenericValue getConstantValue(const Constant *C);
557   void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
558                            Type *Ty);
559 };
560
561 namespace EngineKind {
562   // These are actually bitmasks that get or-ed together.
563   enum Kind {
564     JIT         = 0x1,
565     Interpreter = 0x2
566   };
567   const static Kind Either = (Kind)(JIT | Interpreter);
568 }
569
570 /// EngineBuilder - Builder class for ExecutionEngines.  Use this by
571 /// stack-allocating a builder, chaining the various set* methods, and
572 /// terminating it with a .create() call.
573 class EngineBuilder {
574 private:
575   Module *M;
576   EngineKind::Kind WhichEngine;
577   std::string *ErrorStr;
578   CodeGenOpt::Level OptLevel;
579   RTDyldMemoryManager *MCJMM;
580   JITMemoryManager *JMM;
581   bool AllocateGVsWithCode;
582   TargetOptions Options;
583   Reloc::Model RelocModel;
584   CodeModel::Model CMModel;
585   std::string MArch;
586   std::string MCPU;
587   SmallVector<std::string, 4> MAttrs;
588   bool UseMCJIT;
589   bool VerifyModules;
590
591   /// InitEngine - Does the common initialization of default options.
592   void InitEngine() {
593     WhichEngine = EngineKind::Either;
594     ErrorStr = nullptr;
595     OptLevel = CodeGenOpt::Default;
596     MCJMM = nullptr;
597     JMM = nullptr;
598     Options = TargetOptions();
599     AllocateGVsWithCode = false;
600     RelocModel = Reloc::Default;
601     CMModel = CodeModel::JITDefault;
602     UseMCJIT = false;
603
604   // IR module verification is enabled by default in debug builds, and disabled
605   // by default in release builds.
606 #ifndef NDEBUG
607   VerifyModules = true;
608 #else
609   VerifyModules = false;
610 #endif
611   }
612
613 public:
614   /// EngineBuilder - Constructor for EngineBuilder.  If create() is called and
615   /// is successful, the created engine takes ownership of the module.
616   EngineBuilder(Module *m) : M(m) {
617     InitEngine();
618   }
619
620   /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
621   /// or whichever engine works.  This option defaults to EngineKind::Either.
622   EngineBuilder &setEngineKind(EngineKind::Kind w) {
623     WhichEngine = w;
624     return *this;
625   }
626
627   /// setMCJITMemoryManager - Sets the MCJIT memory manager to use. This allows
628   /// clients to customize their memory allocation policies for the MCJIT. This
629   /// is only appropriate for the MCJIT; setting this and configuring the builder
630   /// to create anything other than MCJIT will cause a runtime error. If create()
631   /// is called and is successful, the created engine takes ownership of the
632   /// memory manager. This option defaults to NULL. Using this option nullifies
633   /// the setJITMemoryManager() option.
634   EngineBuilder &setMCJITMemoryManager(RTDyldMemoryManager *mcjmm) {
635     MCJMM = mcjmm;
636     JMM = nullptr;
637     return *this;
638   }
639
640   /// setJITMemoryManager - Sets the JIT memory manager to use.  This allows
641   /// clients to customize their memory allocation policies.  This is only
642   /// appropriate for either JIT or MCJIT; setting this and configuring the
643   /// builder to create an interpreter will cause a runtime error. If create()
644   /// is called and is successful, the created engine takes ownership of the
645   /// memory manager.  This option defaults to NULL. This option overrides
646   /// setMCJITMemoryManager() as well.
647   EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
648     MCJMM = nullptr;
649     JMM = jmm;
650     return *this;
651   }
652
653   /// setErrorStr - Set the error string to write to on error.  This option
654   /// defaults to NULL.
655   EngineBuilder &setErrorStr(std::string *e) {
656     ErrorStr = e;
657     return *this;
658   }
659
660   /// setOptLevel - Set the optimization level for the JIT.  This option
661   /// defaults to CodeGenOpt::Default.
662   EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
663     OptLevel = l;
664     return *this;
665   }
666
667   /// setTargetOptions - Set the target options that the ExecutionEngine
668   /// target is using. Defaults to TargetOptions().
669   EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
670     Options = Opts;
671     return *this;
672   }
673
674   /// setRelocationModel - Set the relocation model that the ExecutionEngine
675   /// target is using. Defaults to target specific default "Reloc::Default".
676   EngineBuilder &setRelocationModel(Reloc::Model RM) {
677     RelocModel = RM;
678     return *this;
679   }
680
681   /// setCodeModel - Set the CodeModel that the ExecutionEngine target
682   /// data is using. Defaults to target specific default
683   /// "CodeModel::JITDefault".
684   EngineBuilder &setCodeModel(CodeModel::Model M) {
685     CMModel = M;
686     return *this;
687   }
688
689   /// setAllocateGVsWithCode - Sets whether global values should be allocated
690   /// into the same buffer as code.  For most applications this should be set
691   /// to false.  Allocating globals with code breaks freeMachineCodeForFunction
692   /// and is probably unsafe and bad for performance.  However, we have clients
693   /// who depend on this behavior, so we must support it.  This option defaults
694   /// to false so that users of the new API can safely use the new memory
695   /// manager and free machine code.
696   EngineBuilder &setAllocateGVsWithCode(bool a) {
697     AllocateGVsWithCode = a;
698     return *this;
699   }
700
701   /// setMArch - Override the architecture set by the Module's triple.
702   EngineBuilder &setMArch(StringRef march) {
703     MArch.assign(march.begin(), march.end());
704     return *this;
705   }
706
707   /// setMCPU - Target a specific cpu type.
708   EngineBuilder &setMCPU(StringRef mcpu) {
709     MCPU.assign(mcpu.begin(), mcpu.end());
710     return *this;
711   }
712
713   /// setUseMCJIT - Set whether the MC-JIT implementation should be used
714   /// (experimental).
715   EngineBuilder &setUseMCJIT(bool Value) {
716     UseMCJIT = Value;
717     return *this;
718   }
719
720   /// setVerifyModules - Set whether the JIT implementation should verify
721   /// IR modules during compilation.
722   EngineBuilder &setVerifyModules(bool Verify) {
723     VerifyModules = Verify;
724     return *this;
725   }
726
727   /// setMAttrs - Set cpu-specific attributes.
728   template<typename StringSequence>
729   EngineBuilder &setMAttrs(const StringSequence &mattrs) {
730     MAttrs.clear();
731     MAttrs.append(mattrs.begin(), mattrs.end());
732     return *this;
733   }
734
735   TargetMachine *selectTarget();
736
737   /// selectTarget - Pick a target either via -march or by guessing the native
738   /// arch.  Add any CPU features specified via -mcpu or -mattr.
739   TargetMachine *selectTarget(const Triple &TargetTriple,
740                               StringRef MArch,
741                               StringRef MCPU,
742                               const SmallVectorImpl<std::string>& MAttrs);
743
744   ExecutionEngine *create() {
745     return create(selectTarget());
746   }
747
748   ExecutionEngine *create(TargetMachine *TM);
749 };
750
751 // Create wrappers for C Binding types (see CBindingWrapping.h).
752 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ExecutionEngine, LLVMExecutionEngineRef)
753
754 } // End llvm namespace
755
756 #endif