1 //===- ExecutionEngine.h - Abstract Execution Engine Interface --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the abstract interface that implements execution support
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_EXECUTIONENGINE_EXECUTIONENGINE_H
16 #define LLVM_EXECUTIONENGINE_EXECUTIONENGINE_H
18 #include "RuntimeDyld.h"
19 #include "llvm-c/ExecutionEngine.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/ValueHandle.h"
24 #include "llvm/IR/ValueMap.h"
25 #include "llvm/MC/MCCodeGenInfo.h"
26 #include "llvm/Object/Binary.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/Mutex.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
40 class ExecutionEngine;
44 class JITEventListener;
45 class MachineCodeInfo;
46 class MCJITMemoryManager;
49 class RTDyldMemoryManager;
58 /// \brief Helper class for helping synchronize access to the global address map
59 /// table. Access to this class should be serialized under a mutex.
60 class ExecutionEngineState {
62 typedef StringMap<uint64_t> GlobalAddressMapTy;
66 /// GlobalAddressMap - A mapping between LLVM global symbol names values and
67 /// their actualized version...
68 GlobalAddressMapTy GlobalAddressMap;
70 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
71 /// used to convert raw addresses into the LLVM global value that is emitted
72 /// at the address. This map is not computed unless getGlobalValueAtAddress
73 /// is called at some point.
74 std::map<uint64_t, std::string> GlobalAddressReverseMap;
78 GlobalAddressMapTy &getGlobalAddressMap() {
79 return GlobalAddressMap;
82 std::map<uint64_t, std::string> &getGlobalAddressReverseMap() {
83 return GlobalAddressReverseMap;
86 /// \brief Erase an entry from the mapping table.
88 /// \returns The address that \p ToUnmap was happed to.
89 uint64_t RemoveMapping(StringRef Name);
92 /// \brief Abstract interface for implementation execution of LLVM modules,
93 /// designed to support both interpreter and just-in-time (JIT) compiler
95 class ExecutionEngine {
96 /// The state object holding the global address mapping, which must be
97 /// accessed synchronously.
99 // FIXME: There is no particular need the entire map needs to be
100 // synchronized. Wouldn't a reader-writer design be better here?
101 ExecutionEngineState EEState;
103 /// The target data for the platform for which execution is being performed.
104 const DataLayout *DL;
106 /// Whether lazy JIT compilation is enabled.
107 bool CompilingLazily;
109 /// Whether JIT compilation of external global variables is allowed.
110 bool GVCompilationDisabled;
112 /// Whether the JIT should perform lookups of external symbols (e.g.,
114 bool SymbolSearchingDisabled;
116 /// Whether the JIT should verify IR modules during compilation.
119 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
122 /// The list of Modules that we are JIT'ing from. We use a SmallVector to
123 /// optimize for the case where there is only one module.
124 SmallVector<std::unique_ptr<Module>, 1> Modules;
126 void setDataLayout(const DataLayout *Val) { DL = Val; }
128 /// getMemoryforGV - Allocate memory for a global variable.
129 virtual char *getMemoryForGV(const GlobalVariable *GV);
131 static ExecutionEngine *(*MCJITCtor)(
132 std::unique_ptr<Module> M,
133 std::string *ErrorStr,
134 std::shared_ptr<MCJITMemoryManager> MM,
135 std::shared_ptr<RuntimeDyld::SymbolResolver> SR,
136 std::unique_ptr<TargetMachine> TM);
138 static ExecutionEngine *(*OrcMCJITReplacementCtor)(
139 std::string *ErrorStr,
140 std::shared_ptr<MCJITMemoryManager> MM,
141 std::shared_ptr<RuntimeDyld::SymbolResolver> SR,
142 std::unique_ptr<TargetMachine> TM);
144 static ExecutionEngine *(*InterpCtor)(std::unique_ptr<Module> M,
145 std::string *ErrorStr);
147 /// LazyFunctionCreator - If an unknown function is needed, this function
148 /// pointer is invoked to create it. If this returns null, the JIT will
150 void *(*LazyFunctionCreator)(const std::string &);
152 /// getMangledName - Get mangled name.
153 std::string getMangledName(const GlobalValue *GV);
156 /// lock - This lock protects the ExecutionEngine and MCJIT classes. It must
157 /// be held while changing the internal state of any of those classes.
160 //===--------------------------------------------------------------------===//
161 // ExecutionEngine Startup
162 //===--------------------------------------------------------------------===//
164 virtual ~ExecutionEngine();
166 /// Add a Module to the list of modules that we can JIT from.
167 virtual void addModule(std::unique_ptr<Module> M) {
168 Modules.push_back(std::move(M));
171 /// addObjectFile - Add an ObjectFile to the execution engine.
173 /// This method is only supported by MCJIT. MCJIT will immediately load the
174 /// object into memory and adds its symbols to the list used to resolve
175 /// external symbols while preparing other objects for execution.
177 /// Objects added using this function will not be made executable until
178 /// needed by another object.
180 /// MCJIT will take ownership of the ObjectFile.
181 virtual void addObjectFile(std::unique_ptr<object::ObjectFile> O);
182 virtual void addObjectFile(object::OwningBinary<object::ObjectFile> O);
184 /// addArchive - Add an Archive to the execution engine.
186 /// This method is only supported by MCJIT. MCJIT will use the archive to
187 /// resolve external symbols in objects it is loading. If a symbol is found
188 /// in the Archive the contained object file will be extracted (in memory)
189 /// and loaded for possible execution.
190 virtual void addArchive(object::OwningBinary<object::Archive> A);
192 //===--------------------------------------------------------------------===//
194 const DataLayout *getDataLayout() const { return DL; }
196 /// removeModule - Remove a Module from the list of modules. Returns true if
198 virtual bool removeModule(Module *M);
200 /// FindFunctionNamed - Search all of the active modules to find the function that
201 /// defines FnName. This is very slow operation and shouldn't be used for
203 virtual Function *FindFunctionNamed(const char *FnName);
205 /// FindGlobalVariableNamed - Search all of the active modules to find the global variable
206 /// that defines Name. This is very slow operation and shouldn't be used for
208 virtual GlobalVariable *FindGlobalVariableNamed(const char *Name, bool AllowInternal = false);
210 /// runFunction - Execute the specified function with the specified arguments,
211 /// and return the result.
212 virtual GenericValue runFunction(Function *F,
213 ArrayRef<GenericValue> ArgValues) = 0;
215 /// getPointerToNamedFunction - This method returns the address of the
216 /// specified function by using the dlsym function call. As such it is only
217 /// useful for resolving library symbols, not code generated symbols.
219 /// If AbortOnFailure is false and no function with the given name is
220 /// found, this function silently returns a null pointer. Otherwise,
221 /// it prints a message to stderr and aborts.
223 /// This function is deprecated for the MCJIT execution engine.
224 virtual void *getPointerToNamedFunction(StringRef Name,
225 bool AbortOnFailure = true) = 0;
227 /// mapSectionAddress - map a section to its target address space value.
228 /// Map the address of a JIT section as returned from the memory manager
229 /// to the address in the target process as the running code will see it.
230 /// This is the address which will be used for relocation resolution.
231 virtual void mapSectionAddress(const void *LocalAddress,
232 uint64_t TargetAddress) {
233 llvm_unreachable("Re-mapping of section addresses not supported with this "
237 /// generateCodeForModule - Run code generation for the specified module and
238 /// load it into memory.
240 /// When this function has completed, all code and data for the specified
241 /// module, and any module on which this module depends, will be generated
242 /// and loaded into memory, but relocations will not yet have been applied
243 /// and all memory will be readable and writable but not executable.
245 /// This function is primarily useful when generating code for an external
246 /// target, allowing the client an opportunity to remap section addresses
247 /// before relocations are applied. Clients that intend to execute code
248 /// locally can use the getFunctionAddress call, which will generate code
249 /// and apply final preparations all in one step.
251 /// This method has no effect for the interpeter.
252 virtual void generateCodeForModule(Module *M) {}
254 /// finalizeObject - ensure the module is fully processed and is usable.
256 /// It is the user-level function for completing the process of making the
257 /// object usable for execution. It should be called after sections within an
258 /// object have been relocated using mapSectionAddress. When this method is
259 /// called the MCJIT execution engine will reapply relocations for a loaded
260 /// object. This method has no effect for the interpeter.
261 virtual void finalizeObject() {}
263 /// runStaticConstructorsDestructors - This method is used to execute all of
264 /// the static constructors or destructors for a program.
266 /// \param isDtors - Run the destructors instead of constructors.
267 virtual void runStaticConstructorsDestructors(bool isDtors);
269 /// This method is used to execute all of the static constructors or
270 /// destructors for a particular module.
272 /// \param isDtors - Run the destructors instead of constructors.
273 void runStaticConstructorsDestructors(Module &module, bool isDtors);
276 /// runFunctionAsMain - This is a helper function which wraps runFunction to
277 /// handle the common task of starting up main with the specified argc, argv,
278 /// and envp parameters.
279 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
280 const char * const * envp);
283 /// addGlobalMapping - Tell the execution engine that the specified global is
284 /// at the specified location. This is used internally as functions are JIT'd
285 /// and as global variables are laid out in memory. It can and should also be
286 /// used by clients of the EE that want to have an LLVM global overlay
287 /// existing data in memory. Mappings are automatically removed when their
288 /// GlobalValue is destroyed.
289 void addGlobalMapping(const GlobalValue *GV, void *Addr);
290 void addGlobalMapping(StringRef Name, uint64_t Addr);
292 /// clearAllGlobalMappings - Clear all global mappings and start over again,
293 /// for use in dynamic compilation scenarios to move globals.
294 void clearAllGlobalMappings();
296 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
297 /// particular module, because it has been removed from the JIT.
298 void clearGlobalMappingsFromModule(Module *M);
300 /// updateGlobalMapping - Replace an existing mapping for GV with a new
301 /// address. This updates both maps as required. If "Addr" is null, the
302 /// entry for the global is removed from the mappings. This returns the old
303 /// value of the pointer, or null if it was not in the map.
304 uint64_t updateGlobalMapping(const GlobalValue *GV, void *Addr);
305 uint64_t updateGlobalMapping(StringRef Name, uint64_t Addr);
307 /// getAddressToGlobalIfAvailable - This returns the address of the specified
309 uint64_t getAddressToGlobalIfAvailable(StringRef S);
311 /// getPointerToGlobalIfAvailable - This returns the address of the specified
312 /// global value if it is has already been codegen'd, otherwise it returns
314 void *getPointerToGlobalIfAvailable(StringRef S);
315 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
317 /// getPointerToGlobal - This returns the address of the specified global
318 /// value. This may involve code generation if it's a function.
320 /// This function is deprecated for the MCJIT execution engine. Use
321 /// getGlobalValueAddress instead.
322 void *getPointerToGlobal(const GlobalValue *GV);
324 /// getPointerToFunction - The different EE's represent function bodies in
325 /// different ways. They should each implement this to say what a function
326 /// pointer should look like. When F is destroyed, the ExecutionEngine will
327 /// remove its global mapping and free any machine code. Be sure no threads
328 /// are running inside F when that happens.
330 /// This function is deprecated for the MCJIT execution engine. Use
331 /// getFunctionAddress instead.
332 virtual void *getPointerToFunction(Function *F) = 0;
334 /// getPointerToFunctionOrStub - If the specified function has been
335 /// code-gen'd, return a pointer to the function. If not, compile it, or use
336 /// a stub to implement lazy compilation if available. See
337 /// getPointerToFunction for the requirements on destroying F.
339 /// This function is deprecated for the MCJIT execution engine. Use
340 /// getFunctionAddress instead.
341 virtual void *getPointerToFunctionOrStub(Function *F) {
342 // Default implementation, just codegen the function.
343 return getPointerToFunction(F);
346 /// getGlobalValueAddress - Return the address of the specified global
347 /// value. This may involve code generation.
349 /// This function should not be called with the interpreter engine.
350 virtual uint64_t getGlobalValueAddress(const std::string &Name) {
351 // Default implementation for the interpreter. MCJIT will override this.
352 // JIT and interpreter clients should use getPointerToGlobal instead.
356 /// getFunctionAddress - Return the address of the specified function.
357 /// This may involve code generation.
358 virtual uint64_t getFunctionAddress(const std::string &Name) {
359 // Default implementation for the interpreter. MCJIT will override this.
360 // Interpreter clients should use getPointerToFunction instead.
364 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
365 /// at the specified address.
367 const GlobalValue *getGlobalValueAtAddress(void *Addr);
369 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
370 /// Ptr is the address of the memory at which to store Val, cast to
371 /// GenericValue *. It is not a pointer to a GenericValue containing the
372 /// address at which to store Val.
373 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
376 void InitializeMemory(const Constant *Init, void *Addr);
378 /// getOrEmitGlobalVariable - Return the address of the specified global
379 /// variable, possibly emitting it to memory if needed. This is used by the
382 /// This function is deprecated for the MCJIT execution engine. Use
383 /// getGlobalValueAddress instead.
384 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
385 return getPointerToGlobal((const GlobalValue *)GV);
388 /// Registers a listener to be called back on various events within
389 /// the JIT. See JITEventListener.h for more details. Does not
390 /// take ownership of the argument. The argument may be NULL, in
391 /// which case these functions do nothing.
392 virtual void RegisterJITEventListener(JITEventListener *) {}
393 virtual void UnregisterJITEventListener(JITEventListener *) {}
395 /// Sets the pre-compiled object cache. The ownership of the ObjectCache is
396 /// not changed. Supported by MCJIT but not the interpreter.
397 virtual void setObjectCache(ObjectCache *) {
398 llvm_unreachable("No support for an object cache");
401 /// setProcessAllSections (MCJIT Only): By default, only sections that are
402 /// "required for execution" are passed to the RTDyldMemoryManager, and other
403 /// sections are discarded. Passing 'true' to this method will cause
404 /// RuntimeDyld to pass all sections to its RTDyldMemoryManager regardless
405 /// of whether they are "required to execute" in the usual sense.
407 /// Rationale: Some MCJIT clients want to be able to inspect metadata
408 /// sections (e.g. Dwarf, Stack-maps) to enable functionality or analyze
409 /// performance. Passing these sections to the memory manager allows the
410 /// client to make policy about the relevant sections, rather than having
412 virtual void setProcessAllSections(bool ProcessAllSections) {
413 llvm_unreachable("No support for ProcessAllSections option");
416 /// Return the target machine (if available).
417 virtual TargetMachine *getTargetMachine() { return nullptr; }
419 /// DisableLazyCompilation - When lazy compilation is off (the default), the
420 /// JIT will eagerly compile every function reachable from the argument to
421 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
422 /// compile the one function and emit stubs to compile the rest when they're
423 /// first called. If lazy compilation is turned off again while some lazy
424 /// stubs are still around, and one of those stubs is called, the program will
427 /// In order to safely compile lazily in a threaded program, the user must
428 /// ensure that 1) only one thread at a time can call any particular lazy
429 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
430 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
431 /// lazy stub. See http://llvm.org/PR5184 for details.
432 void DisableLazyCompilation(bool Disabled = true) {
433 CompilingLazily = !Disabled;
435 bool isCompilingLazily() const {
436 return CompilingLazily;
439 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
440 /// allocate space and populate a GlobalVariable that is not internal to
442 void DisableGVCompilation(bool Disabled = true) {
443 GVCompilationDisabled = Disabled;
445 bool isGVCompilationDisabled() const {
446 return GVCompilationDisabled;
449 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
450 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
451 /// resolve symbols in a custom way.
452 void DisableSymbolSearching(bool Disabled = true) {
453 SymbolSearchingDisabled = Disabled;
455 bool isSymbolSearchingDisabled() const {
456 return SymbolSearchingDisabled;
459 /// Enable/Disable IR module verification.
461 /// Note: Module verification is enabled by default in Debug builds, and
462 /// disabled by default in Release. Use this method to override the default.
463 void setVerifyModules(bool Verify) {
464 VerifyModules = Verify;
466 bool getVerifyModules() const {
467 return VerifyModules;
470 /// InstallLazyFunctionCreator - If an unknown function is needed, the
471 /// specified function pointer is invoked to create it. If it returns null,
472 /// the JIT will abort.
473 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
474 LazyFunctionCreator = P;
479 explicit ExecutionEngine(std::unique_ptr<Module> M);
483 void EmitGlobalVariable(const GlobalVariable *GV);
485 GenericValue getConstantValue(const Constant *C);
486 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
490 namespace EngineKind {
491 // These are actually bitmasks that get or-ed together.
496 const static Kind Either = (Kind)(JIT | Interpreter);
499 /// Builder class for ExecutionEngines. Use this by stack-allocating a builder,
500 /// chaining the various set* methods, and terminating it with a .create()
502 class EngineBuilder {
504 std::unique_ptr<Module> M;
505 EngineKind::Kind WhichEngine;
506 std::string *ErrorStr;
507 CodeGenOpt::Level OptLevel;
508 std::shared_ptr<MCJITMemoryManager> MemMgr;
509 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver;
510 TargetOptions Options;
511 Reloc::Model RelocModel;
512 CodeModel::Model CMModel;
515 SmallVector<std::string, 4> MAttrs;
517 bool UseOrcMCJITReplacement;
520 /// Default constructor for EngineBuilder.
523 /// Constructor for EngineBuilder.
524 EngineBuilder(std::unique_ptr<Module> M);
526 // Out-of-line since we don't have the def'n of RTDyldMemoryManager here.
529 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
530 /// or whichever engine works. This option defaults to EngineKind::Either.
531 EngineBuilder &setEngineKind(EngineKind::Kind w) {
536 /// setMCJITMemoryManager - Sets the MCJIT memory manager to use. This allows
537 /// clients to customize their memory allocation policies for the MCJIT. This
538 /// is only appropriate for the MCJIT; setting this and configuring the builder
539 /// to create anything other than MCJIT will cause a runtime error. If create()
540 /// is called and is successful, the created engine takes ownership of the
541 /// memory manager. This option defaults to NULL.
542 EngineBuilder &setMCJITMemoryManager(std::unique_ptr<RTDyldMemoryManager> mcjmm);
545 setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM);
548 setSymbolResolver(std::unique_ptr<RuntimeDyld::SymbolResolver> SR);
550 /// setErrorStr - Set the error string to write to on error. This option
551 /// defaults to NULL.
552 EngineBuilder &setErrorStr(std::string *e) {
557 /// setOptLevel - Set the optimization level for the JIT. This option
558 /// defaults to CodeGenOpt::Default.
559 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
564 /// setTargetOptions - Set the target options that the ExecutionEngine
565 /// target is using. Defaults to TargetOptions().
566 EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
571 /// setRelocationModel - Set the relocation model that the ExecutionEngine
572 /// target is using. Defaults to target specific default "Reloc::Default".
573 EngineBuilder &setRelocationModel(Reloc::Model RM) {
578 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
579 /// data is using. Defaults to target specific default
580 /// "CodeModel::JITDefault".
581 EngineBuilder &setCodeModel(CodeModel::Model M) {
586 /// setMArch - Override the architecture set by the Module's triple.
587 EngineBuilder &setMArch(StringRef march) {
588 MArch.assign(march.begin(), march.end());
592 /// setMCPU - Target a specific cpu type.
593 EngineBuilder &setMCPU(StringRef mcpu) {
594 MCPU.assign(mcpu.begin(), mcpu.end());
598 /// setVerifyModules - Set whether the JIT implementation should verify
599 /// IR modules during compilation.
600 EngineBuilder &setVerifyModules(bool Verify) {
601 VerifyModules = Verify;
605 /// setMAttrs - Set cpu-specific attributes.
606 template<typename StringSequence>
607 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
609 MAttrs.append(mattrs.begin(), mattrs.end());
613 // \brief Use OrcMCJITReplacement instead of MCJIT. Off by default.
614 void setUseOrcMCJITReplacement(bool UseOrcMCJITReplacement) {
615 this->UseOrcMCJITReplacement = UseOrcMCJITReplacement;
618 TargetMachine *selectTarget();
620 /// selectTarget - Pick a target either via -march or by guessing the native
621 /// arch. Add any CPU features specified via -mcpu or -mattr.
622 TargetMachine *selectTarget(const Triple &TargetTriple,
625 const SmallVectorImpl<std::string>& MAttrs);
627 ExecutionEngine *create() {
628 return create(selectTarget());
631 ExecutionEngine *create(TargetMachine *TM);
634 // Create wrappers for C Binding types (see CBindingWrapping.h).
635 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ExecutionEngine, LLVMExecutionEngineRef)
637 } // End llvm namespace