32 static struct RegisterJIT {
43 std::shared_ptr<MCJITMemoryManager> MemMgr,
44 std::shared_ptr<LegacyJITSymbolResolver>
Resolver,
45 std::unique_ptr<TargetMachine>
TM) {
51 if (!MemMgr || !Resolver) {
52 auto RTDyldMM = std::make_shared<SectionMemoryManager>();
59 return new MCJIT(std::move(M), std::move(TM), std::move(MemMgr),
63 MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine>
TM,
64 std::shared_ptr<MCJITMemoryManager> MemMgr,
65 std::shared_ptr<LegacyJITSymbolResolver>
Resolver)
67 Ctx(
nullptr), MemMgr(std::move(MemMgr)),
80 std::unique_ptr<Module> First = std::move(Modules[0]);
83 if (First->getDataLayout().isDefault())
84 First->setDataLayout(getDataLayout());
86 OwnedModules.addModule(std::move(First));
91 std::lock_guard<sys::Mutex> locked(lock);
93 Dyld.deregisterEHFrames();
95 for (
auto &Obj : LoadedObjects)
97 notifyFreeingObject(*Obj);
103 std::lock_guard<sys::Mutex> locked(lock);
105 if (M->getDataLayout().isDefault())
106 M->setDataLayout(getDataLayout());
108 OwnedModules.addModule(std::move(M));
112 std::lock_guard<sys::Mutex> locked(lock);
113 return OwnedModules.removeModule(M);
117 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L = Dyld.loadObject(*Obj);
121 notifyObjectLoaded(*Obj, *L);
123 LoadedObjects.push_back(std::move(Obj));
127 std::unique_ptr<object::ObjectFile> ObjFile;
128 std::unique_ptr<MemoryBuffer> MemBuf;
130 addObjectFile(std::move(ObjFile));
131 Buffers.push_back(std::move(MemBuf));
135 Archives.push_back(std::move(A));
139 std::lock_guard<sys::Mutex> locked(lock);
144 assert(M &&
"Can not emit a null module");
146 std::lock_guard<sys::Mutex> locked(lock);
164 if (
TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
171 std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
180 ObjCache->notifyObjectCompiled(M, MB);
183 return CompiledObjBuffer;
188 std::lock_guard<sys::Mutex> locked(lock);
191 assert(OwnedModules.ownsModule(M) &&
192 "MCJIT::generateCodeForModule: Unknown module.");
195 if (OwnedModules.hasModuleBeenLoaded(M))
198 std::unique_ptr<MemoryBuffer> ObjectToLoad;
201 ObjectToLoad = ObjCache->getObject(M);
207 ObjectToLoad = emitObject(M);
208 assert(ObjectToLoad &&
"Compilation did not produce an object.");
222 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
223 Dyld.loadObject(*LoadedObject.
get());
228 notifyObjectLoaded(*LoadedObject.
get(), *L);
230 Buffers.push_back(std::move(ObjectToLoad));
231 LoadedObjects.push_back(std::move(*LoadedObject));
233 OwnedModules.markModuleAsLoaded(M);
237 std::lock_guard<sys::Mutex> locked(lock);
240 Dyld.resolveRelocations();
242 OwnedModules.markAllLoadedModulesAsFinalized();
245 Dyld.registerEHFrames();
248 MemMgr->finalizeMemory();
253 std::lock_guard<sys::Mutex> locked(lock);
258 for (
auto M : OwnedModules.added())
261 for (
auto M : ModsToAdd)
262 generateCodeForModule(M);
264 finalizeLoadedModules();
268 std::lock_guard<sys::Mutex> locked(lock);
271 assert(OwnedModules.ownsModule(M) &&
"MCJIT::finalizeModule: Unknown module.");
274 if (!OwnedModules.hasModuleBeenLoaded(M))
275 generateCodeForModule(M);
277 finalizeLoadedModules();
281 if (
void *Addr = getPointerToGlobalIfAvailable(Name))
283 reinterpret_cast<uintptr_t>(Addr)),
286 return Dyld.getSymbol(Name);
290 bool CheckFunctionsOnly) {
292 if (DemangledName[0] == getDataLayout().getGlobalPrefix())
293 DemangledName = DemangledName.
substr(1);
295 std::lock_guard<sys::Mutex> locked(lock);
298 for (ModulePtrSet::iterator
I = OwnedModules.begin_added(),
299 E = OwnedModules.end_added();
305 if (!CheckFunctionsOnly) {
317 bool CheckFunctionsOnly) {
318 std::string MangledName;
323 if (
auto Sym = findSymbol(MangledName, CheckFunctionsOnly)) {
324 if (
auto AddrOrErr = Sym.getAddress())
328 }
else if (
auto Err = Sym.takeError())
334 bool CheckFunctionsOnly) {
335 std::lock_guard<sys::Mutex> locked(lock);
338 if (
auto Sym = findExistingSymbol(Name))
344 auto OptionalChildOrErr = A->
findSym(Name);
345 if (!OptionalChildOrErr)
347 auto &OptionalChild = *OptionalChildOrErr;
351 OptionalChild->getAsBinary();
352 if (!ChildBinOrErr) {
357 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.
get();
358 if (ChildBin->isObject()) {
359 std::unique_ptr<object::ObjectFile> OF(
360 static_cast<object::ObjectFile *>(ChildBin.release()));
362 addObjectFile(std::move(OF));
364 if (
auto Sym = findExistingSymbol(Name))
371 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
373 generateCodeForModule(M);
376 return findExistingSymbol(Name);
381 if (LazyFunctionCreator) {
382 auto Addr =
static_cast<uint64_t
>(
383 reinterpret_cast<uintptr_t
>(LazyFunctionCreator(Name)));
391 std::lock_guard<sys::Mutex> locked(lock);
392 uint64_t Result = getSymbolAddress(Name,
false);
394 finalizeLoadedModules();
399 std::lock_guard<sys::Mutex> locked(lock);
400 uint64_t Result = getSymbolAddress(Name,
true);
402 finalizeLoadedModules();
408 std::lock_guard<sys::Mutex> locked(lock);
412 TM->getNameWithPrefix(Name, F, Mang);
416 void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
417 updateGlobalMapping(F, Addr);
422 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
425 if (HasBeenAddedButNotLoaded)
426 generateCodeForModule(M);
427 else if (!OwnedModules.hasModuleBeenLoaded(M)) {
439 return (
void*)Dyld.getSymbol(Name).getAddress();
442 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
443 bool isDtors, ModulePtrSet::iterator
I, ModulePtrSet::iterator
E) {
444 for (;
I !=
E; ++
I) {
451 runStaticConstructorsDestructorsInModulePtrSet(
452 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
453 runStaticConstructorsDestructorsInModulePtrSet(
454 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
455 runStaticConstructorsDestructorsInModulePtrSet(
456 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
460 ModulePtrSet::iterator
I,
461 ModulePtrSet::iterator
E) {
462 for (;
I !=
E; ++
I) {
472 ModulePtrSet::iterator
I,
473 ModulePtrSet::iterator
E) {
474 for (;
I !=
E; ++
I) {
475 GlobalVariable *GV = (*I)->getGlobalVariable(Name, AllowInternal);
484 Function *
F = FindFunctionNamedInModulePtrSet(
485 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
487 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
488 OwnedModules.end_loaded());
490 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
491 OwnedModules.end_finalized());
497 Name, AllowInternal, OwnedModules.begin_added(), OwnedModules.end_added());
499 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_loaded(),
500 OwnedModules.end_loaded());
502 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_finalized(),
503 OwnedModules.end_finalized());
508 assert(F &&
"Function *F was null at entry to run()");
510 void *FPtr = getPointerToFunction(F);
512 assert(FPtr &&
"Pointer to fn's code was null after getPointerToFunction");
518 "Wrong number of arguments passed into function!");
520 "This doesn't support passing arguments through varargs (yet)!");
525 switch (ArgValues.
size()) {
530 int (*PF)(int,
char **,
const char **) =
531 (
int(*)(int,
char **,
const char **))(
intptr_t)FPtr;
536 (
char **)
GVTOP(ArgValues[1]),
537 (
const char **)
GVTOP(ArgValues[2])));
544 int (*PF)(int,
char **) = (
int(*)(int,
char **))(
intptr_t)FPtr;
549 (
char **)
GVTOP(ArgValues[1])));
557 int (*PF)(int) = (
int(*)(int))(
intptr_t)FPtr;
566 if (ArgValues.
empty()) {
571 unsigned BitWidth = cast<IntegerType>(RetTy)->
getBitWidth();
574 else if (BitWidth <= 8)
576 else if (BitWidth <= 16)
578 else if (BitWidth <= 32)
580 else if (BitWidth <= 64)
605 "argument passing. Please use " 606 "ExecutionEngine::getFunctionAddress and cast the result " 607 "to the desired function pointer type.");
611 if (!isSymbolSearchingDisabled()) {
612 if (
auto Sym =
Resolver.findSymbol(Name)) {
613 if (
auto AddrOrErr = Sym.getAddress())
614 return reinterpret_cast<void*>(
615 static_cast<uintptr_t>(*AddrOrErr));
616 }
else if (
auto Err = Sym.takeError())
621 if (LazyFunctionCreator)
622 if (
void *
RP = LazyFunctionCreator(Name))
625 if (AbortOnFailure) {
627 "' which could not be resolved!");
635 std::lock_guard<sys::Mutex> locked(lock);
636 EventListeners.push_back(L);
642 std::lock_guard<sys::Mutex> locked(lock);
644 if (
I != EventListeners.rend()) {
646 EventListeners.pop_back();
653 static_cast<uint64_t
>(
reinterpret_cast<uintptr_t
>(Obj.
getData().
data()));
654 std::lock_guard<sys::Mutex> locked(lock);
655 MemMgr->notifyObjectLoaded(
this, Obj);
656 for (
unsigned I = 0, S = EventListeners.size();
I < S; ++
I) {
657 EventListeners[
I]->notifyObjectLoaded(Key, Obj, L);
663 static_cast<uint64_t
>(
reinterpret_cast<uintptr_t
>(Obj.
getData().
data()));
664 std::lock_guard<sys::Mutex> locked(lock);
666 L->notifyFreeingObject(Key);
671 auto Result = ParentEngine.findSymbol(Name,
false);
674 if (ParentEngine.isSymbolSearchingDisabled())
676 return ClientResolver->findSymbol(Name);
679 void LinkingSymbolResolver::anchor() {}
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Function * FindFunctionNamed(StringRef FnName) override
FindFunctionNamed - Search all of the active modules to find the function that defines FnName...
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
static Expected< OwningBinary< ObjectFile > > createObjectFile(StringRef ObjectPath)
Information about the loaded object.
void setObjectCache(ObjectCache *manager) override
Sets the object manager that MCJIT should use to avoid compilation.
llvm::Error materializeAll()
Make sure all GlobalValues in this Module are fully read and clear the Materializer.
Represents a symbol in the JIT.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
Type * getParamType(unsigned i) const
Parameter type accessors.
A Module instance is used to store all the information related to an LLVM module. ...
2: 32-bit floating point type
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
void push_back(const T &Elt)
JITEventListener - Abstract interface for use by the JIT to notify clients about significant events d...
Expected< Optional< Child > > findSym(StringRef name) const
bool hasAvailableExternallyLinkage() const
static JITEventListener * createGDBRegistrationListener()
This class is the base class for all object file types.
A raw_ostream that writes to an SmallVector or SmallString.
void generateCodeForModule(Module *M) override
generateCodeForModule - Run code generation for the specified module and load it into memory...
GlobalVariable * getGlobalVariable(StringRef Name) const
Look up the specified global variable in the module symbol table.
4: 80-bit floating point type (X87)
bool hasExternalWeakLinkage() const
Error takeError()
Take ownership of the stored error.
void UnregisterJITEventListener(JITEventListener *L) override
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
virtual void runStaticConstructorsDestructors(bool isDtors)
runStaticConstructorsDestructors - This method is used to execute all of the static constructors or d...
TypeID getTypeID() const
Return the type id for the type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
static bool LoadLibraryPermanently(const char *Filename, std::string *ErrMsg=nullptr)
This function permanently loads the dynamic library at the given path.
Tagged union holding either a T or a Error.
void runStaticConstructorsDestructors(bool isDtors) override
runStaticConstructorsDestructors - This method is used to execute all of the static constructors or d...
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
uint64_t getGlobalValueAddress(const std::string &Name) override
getGlobalValueAddress - Return the address of the specified global value.
Class to represent function types.
virtual void finalizeModule(Module *)
void notifyObjectLoaded(const object::ObjectFile &Obj, const RuntimeDyld::LoadedObjectInfo &L)
GlobalVariable * FindGlobalVariableNamed(StringRef Name, bool AllowInternal=false) override
FindGlobalVariableNamed - Search all of the active modules to find the global variable that defines N...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
void * getPointerToFunction(Function *F) override
getPointerToFunction - The different EE's represent function bodies in different ways.
JITSymbol findSymbol(const std::string &Name) override
This method returns the address of the specified function or variable.
JITSymbol findExistingSymbol(const std::string &Name)
void finalizeObject() override
finalizeObject - ensure the module is fully processed and is usable.
11: Arbitrary bit width integers
PassManager manages ModulePassManagers.
bool isVoidTy() const
Return true if this is 'void'.
void addModule(std::unique_ptr< Module > M) override
Add a Module to the list of modules that we can JIT from.
The instances of the Type class are immutable: once they are created, they are never changed...
static ExecutionEngine * createJIT(std::unique_ptr< Module > M, std::string *ErrorStr, std::shared_ptr< MCJITMemoryManager > MemMgr, std::shared_ptr< LegacyJITSymbolResolver > Resolver, std::unique_ptr< TargetMachine > TM)
bool removeModule(Module *M) override
removeModule - Removes a Module from the list of modules, but does not free the module's memory...
size_t size() const
size - Get the array size.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
void * getPointerToNamedFunction(StringRef Name, bool AbortOnFailure=true) override
getPointerToNamedFunction - This method returns the address of the specified function by using the dl...
bool isPointerTy() const
True if this is an instance of PointerType.
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
uint64_t getFunctionAddress(const std::string &Name) override
getFunctionAddress - Return the address of the specified function.
6: 128-bit floating point type (two 64-bits, PowerPC)
JITSymbol findSymbol(const std::string &Name, bool CheckFunctionsOnly)
void consumeError(Error Err)
Consume a Error without doing anything.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract interface for implementation execution of LLVM modules, designed to support both interpreter...
void * GVTOP(const GenericValue &GV)
std::pair< std::unique_ptr< T >, std::unique_ptr< MemoryBuffer > > takeBinary()
void addArchive(object::OwningBinary< object::Archive > O) override
addArchive - Add an Archive to the execution engine.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Type * getReturnType() const
reference get()
Returns a reference to the stored T value.
uint64_t getSymbolAddress(const std::string &Name, bool CheckFunctionsOnly)
void RegisterJITEventListener(JITEventListener *L) override
Registers a listener to be called back on various events within the JIT.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
GenericValue PTOGV(void *P)
Class for arbitrary precision integers.
Module * findModuleForSymbol(const std::string &Name, bool CheckFunctionsOnly)
GenericValue runFunction(Function *F, ArrayRef< GenericValue > ArgValues) override
runFunction - Execute the specified function with the specified arguments, and return the result...
void notifyFreeingObject(const object::ObjectFile &Obj)
std::unique_ptr< MemoryBuffer > emitObject(Module *M)
emitObject – Generate a JITed object in memory from the specified module Currently, MCJIT only supports a single module and the module passed to this function call is expected to be the contained module.
SmallVector-backed MemoryBuffer instance.
This is the base ObjectCache type which can be provided to an ExecutionEngine for the purpose of avoi...
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
3: 64-bit floating point type
LLVM_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Module * getParent()
Get the module that this global value is contained inside of...
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
StringRef - Represent a constant reference to a string, i.e.
StringRef getData() const
void finalizeLoadedModules()
bool empty() const
empty - Check if the array is empty.
5: 128-bit floating point type (112-bit mantissa)
void addObjectFile(std::unique_ptr< object::ObjectFile > O) override
addObjectFile - Add an ObjectFile to the execution engine.