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 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
63 typedef ExecutionEngineState *ExtraData;
64 static sys::Mutex *getMutex(ExecutionEngineState *EES);
65 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
66 static void onRAUW(ExecutionEngineState *, const GlobalValue *,
70 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
76 /// GlobalAddressMap - A mapping between LLVM global values and their
77 /// actualized version...
78 GlobalAddressMapTy GlobalAddressMap;
80 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
81 /// used to convert raw addresses into the LLVM global value that is emitted
82 /// at the address. This map is not computed unless getGlobalValueAtAddress
83 /// is called at some point.
84 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
87 ExecutionEngineState(ExecutionEngine &EE);
89 GlobalAddressMapTy &getGlobalAddressMap() {
90 return GlobalAddressMap;
93 std::map<void*, AssertingVH<const GlobalValue> > &
94 getGlobalAddressReverseMap() {
95 return GlobalAddressReverseMap;
98 /// \brief Erase an entry from the mapping table.
100 /// \returns The address that \p ToUnmap was happed to.
101 void *RemoveMapping(const GlobalValue *ToUnmap);
104 /// \brief Abstract interface for implementation execution of LLVM modules,
105 /// designed to support both interpreter and just-in-time (JIT) compiler
107 class ExecutionEngine {
108 /// The state object holding the global address mapping, which must be
109 /// accessed synchronously.
111 // FIXME: There is no particular need the entire map needs to be
112 // synchronized. Wouldn't a reader-writer design be better here?
113 ExecutionEngineState EEState;
115 /// The target data for the platform for which execution is being performed.
116 const DataLayout *DL;
118 /// Whether lazy JIT compilation is enabled.
119 bool CompilingLazily;
121 /// Whether JIT compilation of external global variables is allowed.
122 bool GVCompilationDisabled;
124 /// Whether the JIT should perform lookups of external symbols (e.g.,
126 bool SymbolSearchingDisabled;
128 /// Whether the JIT should verify IR modules during compilation.
131 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
134 /// The list of Modules that we are JIT'ing from. We use a SmallVector to
135 /// optimize for the case where there is only one module.
136 SmallVector<std::unique_ptr<Module>, 1> Modules;
138 void setDataLayout(const DataLayout *Val) { DL = Val; }
140 /// getMemoryforGV - Allocate memory for a global variable.
141 virtual char *getMemoryForGV(const GlobalVariable *GV);
143 static ExecutionEngine *(*MCJITCtor)(
144 std::unique_ptr<Module> M,
145 std::string *ErrorStr,
146 std::shared_ptr<MCJITMemoryManager> MM,
147 std::shared_ptr<RuntimeDyld::SymbolResolver> SR,
148 std::unique_ptr<TargetMachine> TM);
150 static ExecutionEngine *(*OrcMCJITReplacementCtor)(
151 std::string *ErrorStr,
152 std::shared_ptr<MCJITMemoryManager> MM,
153 std::shared_ptr<RuntimeDyld::SymbolResolver> SR,
154 std::unique_ptr<TargetMachine> TM);
156 static ExecutionEngine *(*InterpCtor)(std::unique_ptr<Module> M,
157 std::string *ErrorStr);
159 /// LazyFunctionCreator - If an unknown function is needed, this function
160 /// pointer is invoked to create it. If this returns null, the JIT will
162 void *(*LazyFunctionCreator)(const std::string &);
165 /// lock - This lock protects the ExecutionEngine and MCJIT classes. It must
166 /// be held while changing the internal state of any of those classes.
169 //===--------------------------------------------------------------------===//
170 // ExecutionEngine Startup
171 //===--------------------------------------------------------------------===//
173 virtual ~ExecutionEngine();
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));
180 /// addObjectFile - Add an ObjectFile to the execution engine.
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.
186 /// Objects added using this function will not be made executable until
187 /// needed by another object.
189 /// MCJIT will take ownership of the ObjectFile.
190 virtual void addObjectFile(std::unique_ptr<object::ObjectFile> O);
191 virtual void addObjectFile(object::OwningBinary<object::ObjectFile> O);
193 /// addArchive - Add an Archive to the execution engine.
195 /// This method is only supported by MCJIT. MCJIT will use the archive to
196 /// resolve external symbols in objects it is loading. If a symbol is found
197 /// in the Archive the contained object file will be extracted (in memory)
198 /// and loaded for possible execution.
199 virtual void addArchive(object::OwningBinary<object::Archive> A);
201 //===--------------------------------------------------------------------===//
203 const DataLayout *getDataLayout() const { return DL; }
205 /// removeModule - Remove a Module from the list of modules. Returns true if
207 virtual bool removeModule(Module *M);
209 /// FindFunctionNamed - Search all of the active modules to find the one that
210 /// defines FnName. This is very slow operation and shouldn't be used for
212 virtual Function *FindFunctionNamed(const char *FnName);
214 /// runFunction - Execute the specified function with the specified arguments,
215 /// and return the result.
216 virtual GenericValue runFunction(Function *F,
217 const std::vector<GenericValue> &ArgValues) = 0;
219 /// getPointerToNamedFunction - This method returns the address of the
220 /// specified function by using the dlsym function call. As such it is only
221 /// useful for resolving library symbols, not code generated symbols.
223 /// If AbortOnFailure is false and no function with the given name is
224 /// found, this function silently returns a null pointer. Otherwise,
225 /// it prints a message to stderr and aborts.
227 /// This function is deprecated for the MCJIT execution engine.
228 virtual void *getPointerToNamedFunction(StringRef Name,
229 bool AbortOnFailure = true) = 0;
231 /// mapSectionAddress - map a section to its target address space value.
232 /// Map the address of a JIT section as returned from the memory manager
233 /// to the address in the target process as the running code will see it.
234 /// This is the address which will be used for relocation resolution.
235 virtual void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress) {
236 llvm_unreachable("Re-mapping of section addresses not supported with this "
240 /// generateCodeForModule - Run code generation for the specified module and
241 /// load it into memory.
243 /// When this function has completed, all code and data for the specified
244 /// module, and any module on which this module depends, will be generated
245 /// and loaded into memory, but relocations will not yet have been applied
246 /// and all memory will be readable and writable but not executable.
248 /// This function is primarily useful when generating code for an external
249 /// target, allowing the client an opportunity to remap section addresses
250 /// before relocations are applied. Clients that intend to execute code
251 /// locally can use the getFunctionAddress call, which will generate code
252 /// and apply final preparations all in one step.
254 /// This method has no effect for the interpeter.
255 virtual void generateCodeForModule(Module *M) {}
257 /// finalizeObject - ensure the module is fully processed and is usable.
259 /// It is the user-level function for completing the process of making the
260 /// object usable for execution. It should be called after sections within an
261 /// object have been relocated using mapSectionAddress. When this method is
262 /// called the MCJIT execution engine will reapply relocations for a loaded
263 /// object. This method has no effect for the interpeter.
264 virtual void finalizeObject() {}
266 /// runStaticConstructorsDestructors - This method is used to execute all of
267 /// the static constructors or destructors for a program.
269 /// \param isDtors - Run the destructors instead of constructors.
270 virtual void runStaticConstructorsDestructors(bool isDtors);
272 /// This method is used to execute all of the static constructors or
273 /// destructors for a particular module.
275 /// \param isDtors - Run the destructors instead of constructors.
276 void runStaticConstructorsDestructors(Module &module, bool isDtors);
279 /// runFunctionAsMain - This is a helper function which wraps runFunction to
280 /// handle the common task of starting up main with the specified argc, argv,
281 /// and envp parameters.
282 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
283 const char * const * envp);
286 /// addGlobalMapping - Tell the execution engine that the specified global is
287 /// at the specified location. This is used internally as functions are JIT'd
288 /// and as global variables are laid out in memory. It can and should also be
289 /// used by clients of the EE that want to have an LLVM global overlay
290 /// existing data in memory. Mappings are automatically removed when their
291 /// GlobalValue is destroyed.
292 void addGlobalMapping(const GlobalValue *GV, void *Addr);
294 /// clearAllGlobalMappings - Clear all global mappings and start over again,
295 /// for use in dynamic compilation scenarios to move globals.
296 void clearAllGlobalMappings();
298 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
299 /// particular module, because it has been removed from the JIT.
300 void clearGlobalMappingsFromModule(Module *M);
302 /// updateGlobalMapping - Replace an existing mapping for GV with a new
303 /// address. This updates both maps as required. If "Addr" is null, the
304 /// entry for the global is removed from the mappings. This returns the old
305 /// value of the pointer, or null if it was not in the map.
306 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
308 /// getPointerToGlobalIfAvailable - This returns the address of the specified
309 /// global value if it is has already been codegen'd, otherwise it returns
312 /// This function is deprecated for the MCJIT execution engine. It doesn't
313 /// seem to be needed in that case, but an equivalent can be added if it is.
314 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
316 /// getPointerToGlobal - This returns the address of the specified global
317 /// value. This may involve code generation if it's a function.
319 /// This function is deprecated for the MCJIT execution engine. Use
320 /// getGlobalValueAddress instead.
321 void *getPointerToGlobal(const GlobalValue *GV);
323 /// getPointerToFunction - The different EE's represent function bodies in
324 /// different ways. They should each implement this to say what a function
325 /// pointer should look like. When F is destroyed, the ExecutionEngine will
326 /// remove its global mapping and free any machine code. Be sure no threads
327 /// are running inside F when that happens.
329 /// This function is deprecated for the MCJIT execution engine. Use
330 /// getFunctionAddress instead.
331 virtual void *getPointerToFunction(Function *F) = 0;
333 /// getPointerToFunctionOrStub - If the specified function has been
334 /// code-gen'd, return a pointer to the function. If not, compile it, or use
335 /// a stub to implement lazy compilation if available. See
336 /// getPointerToFunction for the requirements on destroying F.
338 /// This function is deprecated for the MCJIT execution engine. Use
339 /// getFunctionAddress instead.
340 virtual void *getPointerToFunctionOrStub(Function *F) {
341 // Default implementation, just codegen the function.
342 return getPointerToFunction(F);
345 /// getGlobalValueAddress - Return the address of the specified global
346 /// value. This may involve code generation.
348 /// This function should not be called with the interpreter engine.
349 virtual uint64_t getGlobalValueAddress(const std::string &Name) {
350 // Default implementation for the interpreter. MCJIT will override this.
351 // JIT and interpreter clients should use getPointerToGlobal instead.
355 /// getFunctionAddress - Return the address of the specified function.
356 /// This may involve code generation.
357 virtual uint64_t getFunctionAddress(const std::string &Name) {
358 // Default implementation for the interpreter. MCJIT will override this.
359 // Interpreter clients should use getPointerToFunction instead.
363 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
364 /// at the specified address.
366 const GlobalValue *getGlobalValueAtAddress(void *Addr);
368 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
369 /// Ptr is the address of the memory at which to store Val, cast to
370 /// GenericValue *. It is not a pointer to a GenericValue containing the
371 /// address at which to store Val.
372 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
375 void InitializeMemory(const Constant *Init, void *Addr);
377 /// getOrEmitGlobalVariable - Return the address of the specified global
378 /// variable, possibly emitting it to memory if needed. This is used by the
381 /// This function is deprecated for the MCJIT execution engine. Use
382 /// getGlobalValueAddress instead.
383 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
384 return getPointerToGlobal((const GlobalValue *)GV);
387 /// Registers a listener to be called back on various events within
388 /// the JIT. See JITEventListener.h for more details. Does not
389 /// take ownership of the argument. The argument may be NULL, in
390 /// which case these functions do nothing.
391 virtual void RegisterJITEventListener(JITEventListener *) {}
392 virtual void UnregisterJITEventListener(JITEventListener *) {}
394 /// Sets the pre-compiled object cache. The ownership of the ObjectCache is
395 /// not changed. Supported by MCJIT but not the interpreter.
396 virtual void setObjectCache(ObjectCache *) {
397 llvm_unreachable("No support for an object cache");
400 /// setProcessAllSections (MCJIT Only): By default, only sections that are
401 /// "required for execution" are passed to the RTDyldMemoryManager, and other
402 /// sections are discarded. Passing 'true' to this method will cause
403 /// RuntimeDyld to pass all sections to its RTDyldMemoryManager regardless
404 /// of whether they are "required to execute" in the usual sense.
406 /// Rationale: Some MCJIT clients want to be able to inspect metadata
407 /// sections (e.g. Dwarf, Stack-maps) to enable functionality or analyze
408 /// performance. Passing these sections to the memory manager allows the
409 /// client to make policy about the relevant sections, rather than having
411 virtual void setProcessAllSections(bool ProcessAllSections) {
412 llvm_unreachable("No support for ProcessAllSections option");
415 /// Return the target machine (if available).
416 virtual TargetMachine *getTargetMachine() { return nullptr; }
418 /// DisableLazyCompilation - When lazy compilation is off (the default), the
419 /// JIT will eagerly compile every function reachable from the argument to
420 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
421 /// compile the one function and emit stubs to compile the rest when they're
422 /// first called. If lazy compilation is turned off again while some lazy
423 /// stubs are still around, and one of those stubs is called, the program will
426 /// In order to safely compile lazily in a threaded program, the user must
427 /// ensure that 1) only one thread at a time can call any particular lazy
428 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
429 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
430 /// lazy stub. See http://llvm.org/PR5184 for details.
431 void DisableLazyCompilation(bool Disabled = true) {
432 CompilingLazily = !Disabled;
434 bool isCompilingLazily() const {
435 return CompilingLazily;
438 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
439 /// allocate space and populate a GlobalVariable that is not internal to
441 void DisableGVCompilation(bool Disabled = true) {
442 GVCompilationDisabled = Disabled;
444 bool isGVCompilationDisabled() const {
445 return GVCompilationDisabled;
448 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
449 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
450 /// resolve symbols in a custom way.
451 void DisableSymbolSearching(bool Disabled = true) {
452 SymbolSearchingDisabled = Disabled;
454 bool isSymbolSearchingDisabled() const {
455 return SymbolSearchingDisabled;
458 /// Enable/Disable IR module verification.
460 /// Note: Module verification is enabled by default in Debug builds, and
461 /// disabled by default in Release. Use this method to override the default.
462 void setVerifyModules(bool Verify) {
463 VerifyModules = Verify;
465 bool getVerifyModules() const {
466 return VerifyModules;
469 /// InstallLazyFunctionCreator - If an unknown function is needed, the
470 /// specified function pointer is invoked to create it. If it returns null,
471 /// the JIT will abort.
472 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
473 LazyFunctionCreator = P;
477 ExecutionEngine() : EEState(*this) {}
478 explicit ExecutionEngine(std::unique_ptr<Module> M);
482 void EmitGlobalVariable(const GlobalVariable *GV);
484 GenericValue getConstantValue(const Constant *C);
485 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
489 namespace EngineKind {
490 // These are actually bitmasks that get or-ed together.
495 const static Kind Either = (Kind)(JIT | Interpreter);
498 /// Builder class for ExecutionEngines. Use this by stack-allocating a builder,
499 /// chaining the various set* methods, and terminating it with a .create()
501 class EngineBuilder {
503 std::unique_ptr<Module> M;
504 EngineKind::Kind WhichEngine;
505 std::string *ErrorStr;
506 CodeGenOpt::Level OptLevel;
507 std::shared_ptr<MCJITMemoryManager> MemMgr;
508 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver;
509 TargetOptions Options;
510 Reloc::Model RelocModel;
511 CodeModel::Model CMModel;
514 SmallVector<std::string, 4> MAttrs;
516 bool UseOrcMCJITReplacement;
519 /// Default constructor for EngineBuilder.
522 /// Constructor for EngineBuilder.
523 EngineBuilder(std::unique_ptr<Module> M);
525 // Out-of-line since we don't have the def'n of RTDyldMemoryManager here.
528 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
529 /// or whichever engine works. This option defaults to EngineKind::Either.
530 EngineBuilder &setEngineKind(EngineKind::Kind w) {
535 /// setMCJITMemoryManager - Sets the MCJIT memory manager to use. This allows
536 /// clients to customize their memory allocation policies for the MCJIT. This
537 /// is only appropriate for the MCJIT; setting this and configuring the builder
538 /// to create anything other than MCJIT will cause a runtime error. If create()
539 /// is called and is successful, the created engine takes ownership of the
540 /// memory manager. This option defaults to NULL.
541 EngineBuilder &setMCJITMemoryManager(std::unique_ptr<RTDyldMemoryManager> mcjmm);
544 setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM);
547 setSymbolResolver(std::unique_ptr<RuntimeDyld::SymbolResolver> SR);
549 /// setErrorStr - Set the error string to write to on error. This option
550 /// defaults to NULL.
551 EngineBuilder &setErrorStr(std::string *e) {
556 /// setOptLevel - Set the optimization level for the JIT. This option
557 /// defaults to CodeGenOpt::Default.
558 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
563 /// setTargetOptions - Set the target options that the ExecutionEngine
564 /// target is using. Defaults to TargetOptions().
565 EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
570 /// setRelocationModel - Set the relocation model that the ExecutionEngine
571 /// target is using. Defaults to target specific default "Reloc::Default".
572 EngineBuilder &setRelocationModel(Reloc::Model RM) {
577 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
578 /// data is using. Defaults to target specific default
579 /// "CodeModel::JITDefault".
580 EngineBuilder &setCodeModel(CodeModel::Model M) {
585 /// setMArch - Override the architecture set by the Module's triple.
586 EngineBuilder &setMArch(StringRef march) {
587 MArch.assign(march.begin(), march.end());
591 /// setMCPU - Target a specific cpu type.
592 EngineBuilder &setMCPU(StringRef mcpu) {
593 MCPU.assign(mcpu.begin(), mcpu.end());
597 /// setVerifyModules - Set whether the JIT implementation should verify
598 /// IR modules during compilation.
599 EngineBuilder &setVerifyModules(bool Verify) {
600 VerifyModules = Verify;
604 /// setMAttrs - Set cpu-specific attributes.
605 template<typename StringSequence>
606 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
608 MAttrs.append(mattrs.begin(), mattrs.end());
612 // \brief Use OrcMCJITReplacement instead of MCJIT. Off by default.
613 void setUseOrcMCJITReplacement(bool UseOrcMCJITReplacement) {
614 this->UseOrcMCJITReplacement = UseOrcMCJITReplacement;
617 TargetMachine *selectTarget();
619 /// selectTarget - Pick a target either via -march or by guessing the native
620 /// arch. Add any CPU features specified via -mcpu or -mattr.
621 TargetMachine *selectTarget(const Triple &TargetTriple,
624 const SmallVectorImpl<std::string>& MAttrs);
626 ExecutionEngine *create() {
627 return create(selectTarget());
630 ExecutionEngine *create(TargetMachine *TM);
633 // Create wrappers for C Binding types (see CBindingWrapping.h).
634 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ExecutionEngine, LLVMExecutionEngineRef)
636 } // End llvm namespace