1//===- ExecutionEngine.h - Abstract Execution Engine Interface --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the abstract interface that implements execution support
10// for LLVM.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_EXECUTIONENGINE_EXECUTIONENGINE_H
15#define LLVM_EXECUTIONENGINE_EXECUTIONENGINE_H
16
17#include "llvm-c/ExecutionEngine.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/Optional.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/StringMap.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/ExecutionEngine/JITSymbol.h"
24#include "llvm/ExecutionEngine/OrcV1Deprecation.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Module.h"
27#include "llvm/Object/Binary.h"
28#include "llvm/Support/CBindingWrapping.h"
29#include "llvm/Support/CodeGen.h"
30#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/Mutex.h"
32#include "llvm/Target/TargetMachine.h"
33#include "llvm/Target/TargetOptions.h"
34#include <algorithm>
35#include <cstdint>
36#include <functional>
37#include <map>
38#include <memory>
39#include <string>
40#include <vector>
41
42namespace llvm {
43
44class Constant;
45class Function;
46struct GenericValue;
47class GlobalValue;
48class GlobalVariable;
49class JITEventListener;
50class MCJITMemoryManager;
51class ObjectCache;
52class RTDyldMemoryManager;
53class Triple;
54class Type;
55
56namespace object {
57
58class Archive;
59class ObjectFile;
60
61} // end namespace object
62
63/// Helper class for helping synchronize access to the global address map
64/// table.  Access to this class should be serialized under a mutex.
65class ExecutionEngineState {
66public:
67  using GlobalAddressMapTy = StringMap<uint64_t>;
68
69private:
70  /// GlobalAddressMap - A mapping between LLVM global symbol names values and
71  /// their actualized version...
72  GlobalAddressMapTy GlobalAddressMap;
73
74  /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
75  /// used to convert raw addresses into the LLVM global value that is emitted
76  /// at the address.  This map is not computed unless getGlobalValueAtAddress
77  /// is called at some point.
78  std::map<uint64_t, std::string> GlobalAddressReverseMap;
79
80public:
81  GlobalAddressMapTy &getGlobalAddressMap() {
82    return GlobalAddressMap;
83  }
84
85  std::map<uint64_t, std::string> &getGlobalAddressReverseMap() {
86    return GlobalAddressReverseMap;
87  }
88
89  /// Erase an entry from the mapping table.
90  ///
91  /// \returns The address that \p ToUnmap was happed to.
92  uint64_t RemoveMapping(StringRef Name);
93};
94
95using FunctionCreator = std::function<void *(const std::string &)>;
96
97/// Abstract interface for implementation execution of LLVM modules,
98/// designed to support both interpreter and just-in-time (JIT) compiler
99/// implementations.
100class ExecutionEngine {
101  /// The state object holding the global address mapping, which must be
102  /// accessed synchronously.
103  //
104  // FIXME: There is no particular need the entire map needs to be
105  // synchronized.  Wouldn't a reader-writer design be better here?
106  ExecutionEngineState EEState;
107
108  /// The target data for the platform for which execution is being performed.
109  ///
110  /// Note: the DataLayout is LLVMContext specific because it has an
111  /// internal cache based on type pointers. It makes unsafe to reuse the
112  /// ExecutionEngine across context, we don't enforce this rule but undefined
113  /// behavior can occurs if the user tries to do it.
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
131protected:
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  /// getMemoryforGV - Allocate memory for a global variable.
137  virtual char *getMemoryForGV(const GlobalVariable *GV);
138
139  static ExecutionEngine *(*MCJITCtor)(
140      std::unique_ptr<Module> M, std::string *ErrorStr,
141      std::shared_ptr<MCJITMemoryManager> MM,
142      std::shared_ptr<LegacyJITSymbolResolver> SR,
143      std::unique_ptr<TargetMachine> TM);
144
145  static ExecutionEngine *(*OrcMCJITReplacementCtor)(
146      std::string *ErrorStr, std::shared_ptr<MCJITMemoryManager> MM,
147      std::shared_ptr<LegacyJITSymbolResolver> SR,
148      std::unique_ptr<TargetMachine> TM);
149
150  static ExecutionEngine *(*InterpCtor)(std::unique_ptr<Module> M,
151                                        std::string *ErrorStr);
152
153  /// LazyFunctionCreator - If an unknown function is needed, this function
154  /// pointer is invoked to create it.  If this returns null, the JIT will
155  /// abort.
156  FunctionCreator LazyFunctionCreator;
157
158  /// getMangledName - Get mangled name.
159  std::string getMangledName(const GlobalValue *GV);
160
161public:
162  /// lock - This lock protects the ExecutionEngine and MCJIT classes. It must
163  /// be held while changing the internal state of any of those classes.
164  sys::Mutex lock;
165
166  //===--------------------------------------------------------------------===//
167  //  ExecutionEngine Startup
168  //===--------------------------------------------------------------------===//
169
170  virtual ~ExecutionEngine();
171
172  /// Add a Module to the list of modules that we can JIT from.
173  virtual void addModule(std::unique_ptr<Module> M) {
174    Modules.push_back(std::move(M));
175  }
176
177  /// addObjectFile - Add an ObjectFile to the execution engine.
178  ///
179  /// This method is only supported by MCJIT.  MCJIT will immediately load the
180  /// object into memory and adds its symbols to the list used to resolve
181  /// external symbols while preparing other objects for execution.
182  ///
183  /// Objects added using this function will not be made executable until
184  /// needed by another object.
185  ///
186  /// MCJIT will take ownership of the ObjectFile.
187  virtual void addObjectFile(std::unique_ptr<object::ObjectFile> O);
188  virtual void addObjectFile(object::OwningBinary<object::ObjectFile> O);
189
190  /// addArchive - Add an Archive to the execution engine.
191  ///
192  /// This method is only supported by MCJIT.  MCJIT will use the archive to
193  /// resolve external symbols in objects it is loading.  If a symbol is found
194  /// in the Archive the contained object file will be extracted (in memory)
195  /// and loaded for possible execution.
196  virtual void addArchive(object::OwningBinary<object::Archive> A);
197
198  //===--------------------------------------------------------------------===//
199
200  const DataLayout &getDataLayout() const { return DL; }
201
202  /// removeModule - Removes a Module from the list of modules, but does not
203  /// free the module's memory. Returns true if M is found, in which case the
204  /// caller assumes responsibility for deleting the module.
205  //
206  // FIXME: This stealth ownership transfer is horrible. This will probably be
207  //        fixed by deleting ExecutionEngine.
208  virtual bool removeModule(Module *M);
209
210  /// FindFunctionNamed - Search all of the active modules to find the function that
211  /// defines FnName.  This is very slow operation and shouldn't be used for
212  /// general code.
213  virtual Function *FindFunctionNamed(StringRef FnName);
214
215  /// FindGlobalVariableNamed - Search all of the active modules to find the global variable
216  /// that defines Name.  This is very slow operation and shouldn't be used for
217  /// general code.
218  virtual GlobalVariable *FindGlobalVariableNamed(StringRef Name, bool AllowInternal = false);
219
220  /// runFunction - Execute the specified function with the specified arguments,
221  /// and return the result.
222  ///
223  /// For MCJIT execution engines, clients are encouraged to use the
224  /// "GetFunctionAddress" method (rather than runFunction) and cast the
225  /// returned uint64_t to the desired function pointer type. However, for
226  /// backwards compatibility MCJIT's implementation can execute 'main-like'
227  /// function (i.e. those returning void or int, and taking either no
228  /// arguments or (int, char*[])).
229  virtual GenericValue runFunction(Function *F,
230                                   ArrayRef<GenericValue> ArgValues) = 0;
231
232  /// getPointerToNamedFunction - This method returns the address of the
233  /// specified function by using the dlsym function call.  As such it is only
234  /// useful for resolving library symbols, not code generated symbols.
235  ///
236  /// If AbortOnFailure is false and no function with the given name is
237  /// found, this function silently returns a null pointer. Otherwise,
238  /// it prints a message to stderr and aborts.
239  ///
240  /// This function is deprecated for the MCJIT execution engine.
241  virtual void *getPointerToNamedFunction(StringRef Name,
242                                          bool AbortOnFailure = true) = 0;
243
244  /// mapSectionAddress - map a section to its target address space value.
245  /// Map the address of a JIT section as returned from the memory manager
246  /// to the address in the target process as the running code will see it.
247  /// This is the address which will be used for relocation resolution.
248  virtual void mapSectionAddress(const void *LocalAddress,
249                                 uint64_t TargetAddress) {
250    llvm_unreachable("Re-mapping of section addresses not supported with this "
251                     "EE!");
252  }
253
254  /// generateCodeForModule - Run code generation for the specified module and
255  /// load it into memory.
256  ///
257  /// When this function has completed, all code and data for the specified
258  /// module, and any module on which this module depends, will be generated
259  /// and loaded into memory, but relocations will not yet have been applied
260  /// and all memory will be readable and writable but not executable.
261  ///
262  /// This function is primarily useful when generating code for an external
263  /// target, allowing the client an opportunity to remap section addresses
264  /// before relocations are applied.  Clients that intend to execute code
265  /// locally can use the getFunctionAddress call, which will generate code
266  /// and apply final preparations all in one step.
267  ///
268  /// This method has no effect for the interpeter.
269  virtual void generateCodeForModule(Module *M) {}
270
271  /// finalizeObject - ensure the module is fully processed and is usable.
272  ///
273  /// It is the user-level function for completing the process of making the
274  /// object usable for execution.  It should be called after sections within an
275  /// object have been relocated using mapSectionAddress.  When this method is
276  /// called the MCJIT execution engine will reapply relocations for a loaded
277  /// object.  This method has no effect for the interpeter.
278  virtual void finalizeObject() {}
279
280  /// runStaticConstructorsDestructors - This method is used to execute all of
281  /// the static constructors or destructors for a program.
282  ///
283  /// \param isDtors - Run the destructors instead of constructors.
284  virtual void runStaticConstructorsDestructors(bool isDtors);
285
286  /// This method is used to execute all of the static constructors or
287  /// destructors for a particular module.
288  ///
289  /// \param isDtors - Run the destructors instead of constructors.
290  void runStaticConstructorsDestructors(Module &module, bool isDtors);
291
292
293  /// runFunctionAsMain - This is a helper function which wraps runFunction to
294  /// handle the common task of starting up main with the specified argc, argv,
295  /// and envp parameters.
296  int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
297                        const char * const * envp);
298
299
300  /// addGlobalMapping - Tell the execution engine that the specified global is
301  /// at the specified location.  This is used internally as functions are JIT'd
302  /// and as global variables are laid out in memory.  It can and should also be
303  /// used by clients of the EE that want to have an LLVM global overlay
304  /// existing data in memory. Values to be mapped should be named, and have
305  /// external or weak linkage. Mappings are automatically removed when their
306  /// GlobalValue is destroyed.
307  void addGlobalMapping(const GlobalValue *GV, void *Addr);
308  void addGlobalMapping(StringRef Name, uint64_t Addr);
309
310  /// clearAllGlobalMappings - Clear all global mappings and start over again,
311  /// for use in dynamic compilation scenarios to move globals.
312  void clearAllGlobalMappings();
313
314  /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
315  /// particular module, because it has been removed from the JIT.
316  void clearGlobalMappingsFromModule(Module *M);
317
318  /// updateGlobalMapping - Replace an existing mapping for GV with a new
319  /// address.  This updates both maps as required.  If "Addr" is null, the
320  /// entry for the global is removed from the mappings.  This returns the old
321  /// value of the pointer, or null if it was not in the map.
322  uint64_t updateGlobalMapping(const GlobalValue *GV, void *Addr);
323  uint64_t updateGlobalMapping(StringRef Name, uint64_t Addr);
324
325  /// getAddressToGlobalIfAvailable - This returns the address of the specified
326  /// global symbol.
327  uint64_t getAddressToGlobalIfAvailable(StringRef S);
328
329  /// getPointerToGlobalIfAvailable - This returns the address of the specified
330  /// global value if it is has already been codegen'd, otherwise it returns
331  /// null.
332  void *getPointerToGlobalIfAvailable(StringRef S);
333  void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
334
335  /// getPointerToGlobal - This returns the address of the specified global
336  /// value. This may involve code generation if it's a function.
337  ///
338  /// This function is deprecated for the MCJIT execution engine.  Use
339  /// getGlobalValueAddress instead.
340  void *getPointerToGlobal(const GlobalValue *GV);
341
342  /// getPointerToFunction - The different EE's represent function bodies in
343  /// different ways.  They should each implement this to say what a function
344  /// pointer should look like.  When F is destroyed, the ExecutionEngine will
345  /// remove its global mapping and free any machine code.  Be sure no threads
346  /// are running inside F when that happens.
347  ///
348  /// This function is deprecated for the MCJIT execution engine.  Use
349  /// getFunctionAddress instead.
350  virtual void *getPointerToFunction(Function *F) = 0;
351
352  /// getPointerToFunctionOrStub - If the specified function has been
353  /// code-gen'd, return a pointer to the function.  If not, compile it, or use
354  /// a stub to implement lazy compilation if available.  See
355  /// getPointerToFunction for the requirements on destroying F.
356  ///
357  /// This function is deprecated for the MCJIT execution engine.  Use
358  /// getFunctionAddress instead.
359  virtual void *getPointerToFunctionOrStub(Function *F) {
360    // Default implementation, just codegen the function.
361    return getPointerToFunction(F);
362  }
363
364  /// getGlobalValueAddress - Return the address of the specified global
365  /// value. This may involve code generation.
366  ///
367  /// This function should not be called with the interpreter engine.
368  virtual uint64_t getGlobalValueAddress(const std::string &Name) {
369    // Default implementation for the interpreter.  MCJIT will override this.
370    // JIT and interpreter clients should use getPointerToGlobal instead.
371    return 0;
372  }
373
374  /// getFunctionAddress - Return the address of the specified function.
375  /// This may involve code generation.
376  virtual uint64_t getFunctionAddress(const std::string &Name) {
377    // Default implementation for the interpreter.  MCJIT will override this.
378    // Interpreter clients should use getPointerToFunction instead.
379    return 0;
380  }
381
382  /// getGlobalValueAtAddress - Return the LLVM global value object that starts
383  /// at the specified address.
384  ///
385  const GlobalValue *getGlobalValueAtAddress(void *Addr);
386
387  /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
388  /// Ptr is the address of the memory at which to store Val, cast to
389  /// GenericValue *.  It is not a pointer to a GenericValue containing the
390  /// address at which to store Val.
391  void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
392                          Type *Ty);
393
394  void InitializeMemory(const Constant *Init, void *Addr);
395
396  /// getOrEmitGlobalVariable - Return the address of the specified global
397  /// variable, possibly emitting it to memory if needed.  This is used by the
398  /// Emitter.
399  ///
400  /// This function is deprecated for the MCJIT execution engine.  Use
401  /// getGlobalValueAddress instead.
402  virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
403    return getPointerToGlobal((const GlobalValue *)GV);
404  }
405
406  /// Registers a listener to be called back on various events within
407  /// the JIT.  See JITEventListener.h for more details.  Does not
408  /// take ownership of the argument.  The argument may be NULL, in
409  /// which case these functions do nothing.
410  virtual void RegisterJITEventListener(JITEventListener *) {}
411  virtual void UnregisterJITEventListener(JITEventListener *) {}
412
413  /// Sets the pre-compiled object cache.  The ownership of the ObjectCache is
414  /// not changed.  Supported by MCJIT but not the interpreter.
415  virtual void setObjectCache(ObjectCache *) {
416    llvm_unreachable("No support for an object cache");
417  }
418
419  /// setProcessAllSections (MCJIT Only): By default, only sections that are
420  /// "required for execution" are passed to the RTDyldMemoryManager, and other
421  /// sections are discarded. Passing 'true' to this method will cause
422  /// RuntimeDyld to pass all sections to its RTDyldMemoryManager regardless
423  /// of whether they are "required to execute" in the usual sense.
424  ///
425  /// Rationale: Some MCJIT clients want to be able to inspect metadata
426  /// sections (e.g. Dwarf, Stack-maps) to enable functionality or analyze
427  /// performance. Passing these sections to the memory manager allows the
428  /// client to make policy about the relevant sections, rather than having
429  /// MCJIT do it.
430  virtual void setProcessAllSections(bool ProcessAllSections) {
431    llvm_unreachable("No support for ProcessAllSections option");
432  }
433
434  /// Return the target machine (if available).
435  virtual TargetMachine *getTargetMachine() { return nullptr; }
436
437  /// DisableLazyCompilation - When lazy compilation is off (the default), the
438  /// JIT will eagerly compile every function reachable from the argument to
439  /// getPointerToFunction.  If lazy compilation is turned on, the JIT will only
440  /// compile the one function and emit stubs to compile the rest when they're
441  /// first called.  If lazy compilation is turned off again while some lazy
442  /// stubs are still around, and one of those stubs is called, the program will
443  /// abort.
444  ///
445  /// In order to safely compile lazily in a threaded program, the user must
446  /// ensure that 1) only one thread at a time can call any particular lazy
447  /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
448  /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
449  /// lazy stub.  See http://llvm.org/PR5184 for details.
450  void DisableLazyCompilation(bool Disabled = true) {
451    CompilingLazily = !Disabled;
452  }
453  bool isCompilingLazily() const {
454    return CompilingLazily;
455  }
456
457  /// DisableGVCompilation - If called, the JIT will abort if it's asked to
458  /// allocate space and populate a GlobalVariable that is not internal to
459  /// the module.
460  void DisableGVCompilation(bool Disabled = true) {
461    GVCompilationDisabled = Disabled;
462  }
463  bool isGVCompilationDisabled() const {
464    return GVCompilationDisabled;
465  }
466
467  /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
468  /// symbols with dlsym.  A client can still use InstallLazyFunctionCreator to
469  /// resolve symbols in a custom way.
470  void DisableSymbolSearching(bool Disabled = true) {
471    SymbolSearchingDisabled = Disabled;
472  }
473  bool isSymbolSearchingDisabled() const {
474    return SymbolSearchingDisabled;
475  }
476
477  /// Enable/Disable IR module verification.
478  ///
479  /// Note: Module verification is enabled by default in Debug builds, and
480  /// disabled by default in Release. Use this method to override the default.
481  void setVerifyModules(bool Verify) {
482    VerifyModules = Verify;
483  }
484  bool getVerifyModules() const {
485    return VerifyModules;
486  }
487
488  /// InstallLazyFunctionCreator - If an unknown function is needed, the
489  /// specified function pointer is invoked to create it.  If it returns null,
490  /// the JIT will abort.
491  void InstallLazyFunctionCreator(FunctionCreator C) {
492    LazyFunctionCreator = std::move(C);
493  }
494
495protected:
496  ExecutionEngine(DataLayout DL) : DL(std::move(DL)) {}
497  explicit ExecutionEngine(DataLayout DL, std::unique_ptr<Module> M);
498  explicit ExecutionEngine(std::unique_ptr<Module> M);
499
500  void emitGlobals();
501
502  void EmitGlobalVariable(const GlobalVariable *GV);
503
504  GenericValue getConstantValue(const Constant *C);
505  void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
506                           Type *Ty);
507
508private:
509  void Init(std::unique_ptr<Module> M);
510};
511
512namespace EngineKind {
513
514  // These are actually bitmasks that get or-ed together.
515  enum Kind {
516    JIT         = 0x1,
517    Interpreter = 0x2
518  };
519  const static Kind Either = (Kind)(JIT | Interpreter);
520
521} // end namespace EngineKind
522
523/// Builder class for ExecutionEngines. Use this by stack-allocating a builder,
524/// chaining the various set* methods, and terminating it with a .create()
525/// call.
526class EngineBuilder {
527private:
528  std::unique_ptr<Module> M;
529  EngineKind::Kind WhichEngine;
530  std::string *ErrorStr;
531  CodeGenOpt::Level OptLevel;
532  std::shared_ptr<MCJITMemoryManager> MemMgr;
533  std::shared_ptr<LegacyJITSymbolResolver> Resolver;
534  TargetOptions Options;
535  Optional<Reloc::Model> RelocModel;
536  Optional<CodeModel::Model> CMModel;
537  std::string MArch;
538  std::string MCPU;
539  SmallVector<std::string, 4> MAttrs;
540  bool VerifyModules;
541  bool UseOrcMCJITReplacement;
542  bool EmulatedTLS = true;
543
544public:
545  /// Default constructor for EngineBuilder.
546  EngineBuilder();
547
548  /// Constructor for EngineBuilder.
549  EngineBuilder(std::unique_ptr<Module> M);
550
551  // Out-of-line since we don't have the def'n of RTDyldMemoryManager here.
552  ~EngineBuilder();
553
554  /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
555  /// or whichever engine works.  This option defaults to EngineKind::Either.
556  EngineBuilder &setEngineKind(EngineKind::Kind w) {
557    WhichEngine = w;
558    return *this;
559  }
560
561  /// setMCJITMemoryManager - Sets the MCJIT memory manager to use. This allows
562  /// clients to customize their memory allocation policies for the MCJIT. This
563  /// is only appropriate for the MCJIT; setting this and configuring the builder
564  /// to create anything other than MCJIT will cause a runtime error. If create()
565  /// is called and is successful, the created engine takes ownership of the
566  /// memory manager. This option defaults to NULL.
567  EngineBuilder &setMCJITMemoryManager(std::unique_ptr<RTDyldMemoryManager> mcjmm);
568
569  EngineBuilder&
570  setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM);
571
572  EngineBuilder &setSymbolResolver(std::unique_ptr<LegacyJITSymbolResolver> SR);
573
574  /// setErrorStr - Set the error string to write to on error.  This option
575  /// defaults to NULL.
576  EngineBuilder &setErrorStr(std::string *e) {
577    ErrorStr = e;
578    return *this;
579  }
580
581  /// setOptLevel - Set the optimization level for the JIT.  This option
582  /// defaults to CodeGenOpt::Default.
583  EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
584    OptLevel = l;
585    return *this;
586  }
587
588  /// setTargetOptions - Set the target options that the ExecutionEngine
589  /// target is using. Defaults to TargetOptions().
590  EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
591    Options = Opts;
592    return *this;
593  }
594
595  /// setRelocationModel - Set the relocation model that the ExecutionEngine
596  /// target is using. Defaults to target specific default "Reloc::Default".
597  EngineBuilder &setRelocationModel(Reloc::Model RM) {
598    RelocModel = RM;
599    return *this;
600  }
601
602  /// setCodeModel - Set the CodeModel that the ExecutionEngine target
603  /// data is using. Defaults to target specific default
604  /// "CodeModel::JITDefault".
605  EngineBuilder &setCodeModel(CodeModel::Model M) {
606    CMModel = M;
607    return *this;
608  }
609
610  /// setMArch - Override the architecture set by the Module's triple.
611  EngineBuilder &setMArch(StringRef march) {
612    MArch.assign(march.begin(), march.end());
613    return *this;
614  }
615
616  /// setMCPU - Target a specific cpu type.
617  EngineBuilder &setMCPU(StringRef mcpu) {
618    MCPU.assign(mcpu.begin(), mcpu.end());
619    return *this;
620  }
621
622  /// setVerifyModules - Set whether the JIT implementation should verify
623  /// IR modules during compilation.
624  EngineBuilder &setVerifyModules(bool Verify) {
625    VerifyModules = Verify;
626    return *this;
627  }
628
629  /// setMAttrs - Set cpu-specific attributes.
630  template<typename StringSequence>
631  EngineBuilder &setMAttrs(const StringSequence &mattrs) {
632    MAttrs.clear();
633    MAttrs.append(mattrs.begin(), mattrs.end());
634    return *this;
635  }
636
637  // Use OrcMCJITReplacement instead of MCJIT. Off by default.
638  LLVM_ATTRIBUTE_DEPRECATED(
639      inline void setUseOrcMCJITReplacement(bool UseOrcMCJITReplacement),
640      "ORCv1 utilities (including OrcMCJITReplacement) are deprecated. Please "
641      "use ORCv2/LLJIT instead (see docs/ORCv2.rst)");
642
643  void setUseOrcMCJITReplacement(ORCv1DeprecationAcknowledgement,
644                                 bool UseOrcMCJITReplacement) {
645    this->UseOrcMCJITReplacement = UseOrcMCJITReplacement;
646  }
647
648  void setEmulatedTLS(bool EmulatedTLS) {
649    this->EmulatedTLS = EmulatedTLS;
650  }
651
652  TargetMachine *selectTarget();
653
654  /// selectTarget - Pick a target either via -march or by guessing the native
655  /// arch.  Add any CPU features specified via -mcpu or -mattr.
656  TargetMachine *selectTarget(const Triple &TargetTriple,
657                              StringRef MArch,
658                              StringRef MCPU,
659                              const SmallVectorImpl<std::string>& MAttrs);
660
661  ExecutionEngine *create() {
662    return create(selectTarget());
663  }
664
665  ExecutionEngine *create(TargetMachine *TM);
666};
667
668void EngineBuilder::setUseOrcMCJITReplacement(bool UseOrcMCJITReplacement) {
669  this->UseOrcMCJITReplacement = UseOrcMCJITReplacement;
670}
671
672// Create wrappers for C Binding types (see CBindingWrapping.h).
673DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ExecutionEngine, LLVMExecutionEngineRef)
674
675} // end namespace llvm
676
677#endif // LLVM_EXECUTIONENGINE_EXECUTIONENGINE_H
678