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