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 "llvm-c/ExecutionEngine.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/ValueHandle.h"
23 #include "llvm/IR/ValueMap.h"
24 #include "llvm/MC/MCCodeGenInfo.h"
25 #include "llvm/Object/Binary.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/Mutex.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
39 class ExecutionEngine;
43 class JITEventListener;
44 class JITMemoryManager;
45 class MachineCodeInfo;
48 class RTDyldMemoryManager;
57 /// \brief Helper class for helping synchronize access to the global address map
58 /// table. Access to this class should be serialized under a mutex.
59 class ExecutionEngineState {
61 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
62 typedef ExecutionEngineState *ExtraData;
63 static sys::Mutex *getMutex(ExecutionEngineState *EES);
64 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
65 static void onRAUW(ExecutionEngineState *, const GlobalValue *,
69 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
75 /// GlobalAddressMap - A mapping between LLVM global values and their
76 /// actualized version...
77 GlobalAddressMapTy GlobalAddressMap;
79 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
80 /// used to convert raw addresses into the LLVM global value that is emitted
81 /// at the address. This map is not computed unless getGlobalValueAtAddress
82 /// is called at some point.
83 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
86 ExecutionEngineState(ExecutionEngine &EE);
88 GlobalAddressMapTy &getGlobalAddressMap() {
89 return GlobalAddressMap;
92 std::map<void*, AssertingVH<const GlobalValue> > &
93 getGlobalAddressReverseMap() {
94 return GlobalAddressReverseMap;
97 /// \brief Erase an entry from the mapping table.
99 /// \returns The address that \p ToUnmap was happed to.
100 void *RemoveMapping(const GlobalValue *ToUnmap);
103 /// \brief Abstract interface for implementation execution of LLVM modules,
104 /// designed to support both interpreter and just-in-time (JIT) compiler
106 class ExecutionEngine {
107 /// The state object holding the global address mapping, which must be
108 /// accessed synchronously.
110 // FIXME: There is no particular need the entire map needs to be
111 // synchronized. Wouldn't a reader-writer design be better here?
112 ExecutionEngineState EEState;
114 /// The target data for the platform for which execution is being performed.
115 const DataLayout *DL;
117 /// Whether lazy JIT compilation is enabled.
118 bool CompilingLazily;
120 /// Whether JIT compilation of external global variables is allowed.
121 bool GVCompilationDisabled;
123 /// Whether the JIT should perform lookups of external symbols (e.g.,
125 bool SymbolSearchingDisabled;
127 /// Whether the JIT should verify IR modules during compilation.
130 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
133 /// The list of Modules that we are JIT'ing from. We use a SmallVector to
134 /// optimize for the case where there is only one module.
135 SmallVector<std::unique_ptr<Module>, 1> Modules;
137 void setDataLayout(const DataLayout *Val) { DL = Val; }
139 /// getMemoryforGV - Allocate memory for a global variable.
140 virtual char *getMemoryForGV(const GlobalVariable *GV);
142 static ExecutionEngine *(*MCJITCtor)(
143 std::unique_ptr<Module> M,
144 std::string *ErrorStr,
145 RTDyldMemoryManager *MCJMM,
147 static ExecutionEngine *(*InterpCtor)(std::unique_ptr<Module> M,
148 std::string *ErrorStr);
150 /// LazyFunctionCreator - If an unknown function is needed, this function
151 /// pointer is invoked to create it. If this returns null, the JIT will
153 void *(*LazyFunctionCreator)(const std::string &);
156 /// lock - This lock protects the ExecutionEngine, MCJIT, JIT, JITResolver and
157 /// JITEmitter classes. It must be held while changing the internal state of
158 /// any of those classes.
161 //===--------------------------------------------------------------------===//
162 // ExecutionEngine Startup
163 //===--------------------------------------------------------------------===//
165 virtual ~ExecutionEngine();
167 /// Add a Module to the list of modules that we can JIT from.
168 virtual void addModule(std::unique_ptr<Module> M) {
169 Modules.push_back(std::move(M));
172 /// addObjectFile - Add an ObjectFile to the execution engine.
174 /// This method is only supported by MCJIT. MCJIT will immediately load the
175 /// object into memory and adds its symbols to the list used to resolve
176 /// external symbols while preparing other objects for execution.
178 /// Objects added using this function will not be made executable until
179 /// needed by another object.
181 /// MCJIT will take ownership of the ObjectFile.
182 virtual void addObjectFile(std::unique_ptr<object::ObjectFile> O);
183 virtual void addObjectFile(object::OwningBinary<object::ObjectFile> O);
185 /// addArchive - Add an Archive to the execution engine.
187 /// This method is only supported by MCJIT. MCJIT will use the archive to
188 /// resolve external symbols in objects it is loading. If a symbol is found
189 /// in the Archive the contained object file will be extracted (in memory)
190 /// and loaded for possible execution.
191 virtual void addArchive(object::OwningBinary<object::Archive> A);
193 //===--------------------------------------------------------------------===//
195 const DataLayout *getDataLayout() const { return DL; }
197 /// removeModule - Remove a Module from the list of modules. Returns true if
199 virtual bool removeModule(Module *M);
201 /// FindFunctionNamed - Search all of the active modules to find the one that
202 /// defines FnName. This is very slow operation and shouldn't be used for
204 virtual Function *FindFunctionNamed(const char *FnName);
206 /// runFunction - Execute the specified function with the specified arguments,
207 /// and return the result.
208 virtual GenericValue runFunction(Function *F,
209 const std::vector<GenericValue> &ArgValues) = 0;
211 /// getPointerToNamedFunction - This method returns the address of the
212 /// specified function by using the dlsym function call. As such it is only
213 /// useful for resolving library symbols, not code generated symbols.
215 /// If AbortOnFailure is false and no function with the given name is
216 /// found, this function silently returns a null pointer. Otherwise,
217 /// it prints a message to stderr and aborts.
219 /// This function is deprecated for the MCJIT execution engine.
221 /// FIXME: the JIT and MCJIT interfaces should be disentangled or united
222 /// again, if possible.
224 virtual void *getPointerToNamedFunction(const std::string &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, uint64_t TargetAddress) {
232 llvm_unreachable("Re-mapping of section addresses not supported with this "
236 /// generateCodeForModule - Run code generationen for the specified module and
237 /// load it into memory.
239 /// When this function has completed, all code and data for the specified
240 /// module, and any module on which this module depends, will be generated
241 /// and loaded into memory, but relocations will not yet have been applied
242 /// and all memory will be readable and writable but not executable.
244 /// This function is primarily useful when generating code for an external
245 /// target, allowing the client an opportunity to remap section addresses
246 /// before relocations are applied. Clients that intend to execute code
247 /// locally can use the getFunctionAddress call, which will generate code
248 /// and apply final preparations all in one step.
250 /// This method has no effect for the legacy JIT engine or the interpeter.
251 virtual void generateCodeForModule(Module *M) {}
253 /// finalizeObject - ensure the module is fully processed and is usable.
255 /// It is the user-level function for completing the process of making the
256 /// object usable for execution. It should be called after sections within an
257 /// object have been relocated using mapSectionAddress. When this method is
258 /// called the MCJIT execution engine will reapply relocations for a loaded
259 /// object. This method has no effect for the legacy JIT engine or the
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);
291 /// clearAllGlobalMappings - Clear all global mappings and start over again,
292 /// for use in dynamic compilation scenarios to move globals.
293 void clearAllGlobalMappings();
295 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
296 /// particular module, because it has been removed from the JIT.
297 void clearGlobalMappingsFromModule(Module *M);
299 /// updateGlobalMapping - Replace an existing mapping for GV with a new
300 /// address. This updates both maps as required. If "Addr" is null, the
301 /// entry for the global is removed from the mappings. This returns the old
302 /// value of the pointer, or null if it was not in the map.
303 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
305 /// getPointerToGlobalIfAvailable - This returns the address of the specified
306 /// global value if it is has already been codegen'd, otherwise it returns
309 /// This function is deprecated for the MCJIT execution engine. It doesn't
310 /// seem to be needed in that case, but an equivalent can be added if it is.
311 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
313 /// getPointerToGlobal - This returns the address of the specified global
314 /// value. This may involve code generation if it's a function.
316 /// This function is deprecated for the MCJIT execution engine. Use
317 /// getGlobalValueAddress instead.
318 void *getPointerToGlobal(const GlobalValue *GV);
320 /// getPointerToFunction - The different EE's represent function bodies in
321 /// different ways. They should each implement this to say what a function
322 /// pointer should look like. When F is destroyed, the ExecutionEngine will
323 /// remove its global mapping and free any machine code. Be sure no threads
324 /// are running inside F when that happens.
326 /// This function is deprecated for the MCJIT execution engine. Use
327 /// getFunctionAddress instead.
328 virtual void *getPointerToFunction(Function *F) = 0;
330 /// getPointerToFunctionOrStub - If the specified function has been
331 /// code-gen'd, return a pointer to the function. If not, compile it, or use
332 /// a stub to implement lazy compilation if available. See
333 /// getPointerToFunction for the requirements on destroying F.
335 /// This function is deprecated for the MCJIT execution engine. Use
336 /// getFunctionAddress instead.
337 virtual void *getPointerToFunctionOrStub(Function *F) {
338 // Default implementation, just codegen the function.
339 return getPointerToFunction(F);
342 /// getGlobalValueAddress - Return the address of the specified global
343 /// value. This may involve code generation.
345 /// This function should not be called with the JIT or interpreter engines.
346 virtual uint64_t getGlobalValueAddress(const std::string &Name) {
347 // Default implementation for JIT and interpreter. MCJIT will override this.
348 // JIT and interpreter clients should use getPointerToGlobal instead.
352 /// getFunctionAddress - Return the address of the specified function.
353 /// This may involve code generation.
354 virtual uint64_t getFunctionAddress(const std::string &Name) {
355 // Default implementation for JIT and interpreter. MCJIT will override this.
356 // JIT and interpreter clients should use getPointerToFunction instead.
360 // The JIT overrides a version that actually does this.
361 virtual void runJITOnFunction(Function *, MachineCodeInfo * = nullptr) { }
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 JIT.
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;
437 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
438 // Remove this in LLVM 2.8.
439 bool isLazyCompilationDisabled() const {
440 return !CompilingLazily;
443 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
444 /// allocate space and populate a GlobalVariable that is not internal to
446 void DisableGVCompilation(bool Disabled = true) {
447 GVCompilationDisabled = Disabled;
449 bool isGVCompilationDisabled() const {
450 return GVCompilationDisabled;
453 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
454 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
455 /// resolve symbols in a custom way.
456 void DisableSymbolSearching(bool Disabled = true) {
457 SymbolSearchingDisabled = Disabled;
459 bool isSymbolSearchingDisabled() const {
460 return SymbolSearchingDisabled;
463 /// Enable/Disable IR module verification.
465 /// Note: Module verification is enabled by default in Debug builds, and
466 /// disabled by default in Release. Use this method to override the default.
467 void setVerifyModules(bool Verify) {
468 VerifyModules = Verify;
470 bool getVerifyModules() const {
471 return VerifyModules;
474 /// InstallLazyFunctionCreator - If an unknown function is needed, the
475 /// specified function pointer is invoked to create it. If it returns null,
476 /// the JIT will abort.
477 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
478 LazyFunctionCreator = P;
482 explicit ExecutionEngine(std::unique_ptr<Module> M);
486 void EmitGlobalVariable(const GlobalVariable *GV);
488 GenericValue getConstantValue(const Constant *C);
489 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
493 namespace EngineKind {
494 // These are actually bitmasks that get or-ed together.
499 const static Kind Either = (Kind)(JIT | Interpreter);
502 /// Builder class for ExecutionEngines. Use this by stack-allocating a builder,
503 /// chaining the various set* methods, and terminating it with a .create()
505 class EngineBuilder {
507 std::unique_ptr<Module> M;
508 EngineKind::Kind WhichEngine;
509 std::string *ErrorStr;
510 CodeGenOpt::Level OptLevel;
511 RTDyldMemoryManager *MCJMM;
512 JITMemoryManager *JMM;
513 TargetOptions Options;
514 Reloc::Model RelocModel;
515 CodeModel::Model CMModel;
518 SmallVector<std::string, 4> MAttrs;
521 /// InitEngine - Does the common initialization of default options.
525 /// Constructor for EngineBuilder.
526 EngineBuilder(std::unique_ptr<Module> M) : M(std::move(M)) {
530 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
531 /// or whichever engine works. This option defaults to EngineKind::Either.
532 EngineBuilder &setEngineKind(EngineKind::Kind w) {
537 /// setMCJITMemoryManager - Sets the MCJIT memory manager to use. This allows
538 /// clients to customize their memory allocation policies for the MCJIT. This
539 /// is only appropriate for the MCJIT; setting this and configuring the builder
540 /// to create anything other than MCJIT will cause a runtime error. If create()
541 /// is called and is successful, the created engine takes ownership of the
542 /// memory manager. This option defaults to NULL. Using this option nullifies
543 /// the setJITMemoryManager() option.
544 EngineBuilder &setMCJITMemoryManager(RTDyldMemoryManager *mcjmm) {
550 /// setJITMemoryManager - Sets the JIT memory manager to use. This allows
551 /// clients to customize their memory allocation policies. This is only
552 /// appropriate for either JIT or MCJIT; setting this and configuring the
553 /// builder to create an interpreter will cause a runtime error. If create()
554 /// is called and is successful, the created engine takes ownership of the
555 /// memory manager. This option defaults to NULL. This option overrides
556 /// setMCJITMemoryManager() as well.
557 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
563 /// setErrorStr - Set the error string to write to on error. This option
564 /// defaults to NULL.
565 EngineBuilder &setErrorStr(std::string *e) {
570 /// setOptLevel - Set the optimization level for the JIT. This option
571 /// defaults to CodeGenOpt::Default.
572 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
577 /// setTargetOptions - Set the target options that the ExecutionEngine
578 /// target is using. Defaults to TargetOptions().
579 EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
584 /// setRelocationModel - Set the relocation model that the ExecutionEngine
585 /// target is using. Defaults to target specific default "Reloc::Default".
586 EngineBuilder &setRelocationModel(Reloc::Model RM) {
591 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
592 /// data is using. Defaults to target specific default
593 /// "CodeModel::JITDefault".
594 EngineBuilder &setCodeModel(CodeModel::Model M) {
599 /// setMArch - Override the architecture set by the Module's triple.
600 EngineBuilder &setMArch(StringRef march) {
601 MArch.assign(march.begin(), march.end());
605 /// setMCPU - Target a specific cpu type.
606 EngineBuilder &setMCPU(StringRef mcpu) {
607 MCPU.assign(mcpu.begin(), mcpu.end());
611 /// setVerifyModules - Set whether the JIT implementation should verify
612 /// IR modules during compilation.
613 EngineBuilder &setVerifyModules(bool Verify) {
614 VerifyModules = Verify;
618 /// setMAttrs - Set cpu-specific attributes.
619 template<typename StringSequence>
620 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
622 MAttrs.append(mattrs.begin(), mattrs.end());
626 TargetMachine *selectTarget();
628 /// selectTarget - Pick a target either via -march or by guessing the native
629 /// arch. Add any CPU features specified via -mcpu or -mattr.
630 TargetMachine *selectTarget(const Triple &TargetTriple,
633 const SmallVectorImpl<std::string>& MAttrs);
635 ExecutionEngine *create() {
636 return create(selectTarget());
639 ExecutionEngine *create(TargetMachine *TM);
642 // Create wrappers for C Binding types (see CBindingWrapping.h).
643 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ExecutionEngine, LLVMExecutionEngineRef)
645 } // End llvm namespace