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