24 std::vector<std::unique_ptr<char[]>> ArgVStorage;
25 std::vector<char *> ArgV;
27 ArgVStorage.reserve(Args.
size() + (ProgramName ? 1 : 0));
28 ArgV.reserve(Args.
size() + 1 + (ProgramName ? 1 : 0));
31 ArgVStorage.push_back(std::make_unique<
char[]>(ProgramName->size() + 1));
32 llvm::copy(*ProgramName, &ArgVStorage.back()[0]);
33 ArgVStorage.back()[ProgramName->size()] =
'\0';
34 ArgV.push_back(ArgVStorage.back().get());
37 for (
auto &
Arg : Args) {
38 ArgVStorage.push_back(std::make_unique<
char[]>(
Arg.size() + 1));
40 ArgVStorage.back()[
Arg.size()] =
'\0';
41 ArgV.push_back(ArgVStorage.back().get());
43 ArgV.push_back(
nullptr);
45 return Main(Args.size() + !!ProgramName, ArgV.data());
51 I((InitList && End) ? InitList->getNumOperands() : 0) {
55 assert(InitList == Other.InitList &&
"Incomparable iterators.");
60 return !(*
this == Other);
76 assert(CS &&
"Unrecognized type in llvm.global_ctors/llvm.global_dtors");
83 if (
Function *
F = dyn_cast_or_null<Function>(FuncC)) {
86 }
else if (
ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(FuncC)) {
88 FuncC = dyn_cast_or_null<ConstantExpr>(CE->getOperand(0));
97 auto *Priority = cast<ConstantInt>(CS->
getOperand(0));
99 if (Data && !isa<GlobalValue>(Data))
101 return Element(Priority->getZExtValue(), Func, Data);
117 if (CtorDtors.
empty())
121 JD.getExecutionSession(),
122 (*CtorDtors.
begin()).Func->getParent()->getDataLayout());
124 for (
auto CtorDtor : CtorDtors) {
125 assert(CtorDtor.Func && CtorDtor.Func->hasName() &&
126 "Ctor/Dtor function must be named to be runnable under the JIT");
129 if (CtorDtor.Func->hasLocalLinkage()) {
134 if (CtorDtor.Data && cast<GlobalValue>(CtorDtor.Data)->isDeclaration()) {
135 dbgs() <<
" Skipping because why now?\n";
139 CtorDtorsByPriority[CtorDtor.Priority].push_back(
140 Mangle(CtorDtor.Func->getName()));
145 using CtorDtorTy = void (*)();
148 for (
auto &KV : CtorDtorsByPriority)
149 for (
auto &
Name : KV.second)
152 "Ctor/Dtor list contains duplicates");
154 auto &ES = JD.getExecutionSession();
155 if (
auto CtorDtorMap = ES.lookup(
157 std::move(LookupSet))) {
158 for (
auto &KV : CtorDtorsByPriority) {
159 for (
auto &
Name : KV.second) {
160 assert(CtorDtorMap->count(
Name) &&
"No entry for Name");
161 auto CtorDtor =
reinterpret_cast<CtorDtorTy
>(
162 static_cast<uintptr_t
>((*CtorDtorMap)[
Name].getAddress()));
166 CtorDtorsByPriority.clear();
169 return CtorDtorMap.takeError();
173 auto& CXXDestructorDataPairs = DSOHandleOverride;
174 for (
auto &
P : CXXDestructorDataPairs)
176 CXXDestructorDataPairs.clear();
182 auto& CXXDestructorDataPairs =
184 CXXDestructorDataPairs.push_back(std::make_pair(Destructor, Arg));
191 RuntimeInterposes[Mangle(
"__dso_handle")] =
194 RuntimeInterposes[Mangle(
"__cxa_atexit")] =
203 : Dylib(
std::move(Dylib)), Allow(
std::move(Allow)),
204 GlobalPrefix(GlobalPrefix) {}
213 return std::make_unique<DynamicLibrarySearchGenerator>(
214 std::move(Lib), GlobalPrefix, std::move(Allow));
222 bool HasGlobalPrefix = (GlobalPrefix !=
'\0');
224 for (
auto &KV : Symbols) {
225 auto &
Name = KV.first;
230 if (Allow && !Allow(
Name))
233 if (HasGlobalPrefix && (*Name).front() != GlobalPrefix)
236 std::string Tmp((*Name).data() + HasGlobalPrefix,
237 (*Name).size() - HasGlobalPrefix);
240 static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(Addr)),
245 if (NewSymbols.
empty())
256 return ArchiveBuffer.takeError();
258 return Create(L, std::move(*ArchiveBuffer));
263 ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer) {
266 std::unique_ptr<StaticLibraryDefinitionGenerator> ADG(
270 return std::move(Err);
272 return std::move(ADG);
290 for (
const auto &KV : Symbols) {
291 const auto &
Name = KV.first;
292 auto Child = Archive->findSym(*
Name);
294 return Child.takeError();
297 auto ChildBuffer = (*Child)->getMemoryBufferRef();
299 return ChildBuffer.takeError();
301 {ChildBuffer->getBuffer(), ChildBuffer->getBufferIdentifier()});
304 for (
auto ChildBufferInfo : ChildBufferInfos) {
306 ChildBufferInfo.second);
316 StaticLibraryDefinitionGenerator::StaticLibraryDefinitionGenerator(
318 : L(L), ArchiveBuffer(std::move(ArchiveBuffer)),
319 Archive(std::make_unique<object::Archive>(*this->ArchiveBuffer, Err)) {}
static Expected< std::unique_ptr< DynamicLibrarySearchGenerator > > Load(const char *FileName, char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate())
Permanently loads the library at the given path and, on success, returns a DynamicLibrarySearchGenera...
Accessor for an element of the global_ctors/global_dtors array.
LookupKind
Describes the kind of lookup being performed.
This class represents lattice values for constants.
bool operator==(const CtorDtorIterator &Other) const
Test iterators for equality.
A Module instance is used to store all the information related to an LLVM module. ...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
std::function< bool(const SymbolStringPtr &)> SymbolPredicate
Implements a dense probed hash-table based set.
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
const GlobalVariable * getNamedGlobal(StringRef Name) const
Return the global variable in the module with the specified name, of arbitrary type.
Externally visible function.
std::vector< CXXDestructorDataPair > CXXDestructorDataPairList
Error enable(JITDylib &JD, MangleAndInterner &Mangler)
void(*)(void *) DestructorPtr
CtorDtorIterator & operator++()
Pre-increment iterator.
std::unique_ptr< AbsoluteSymbolsMaterializationUnit > absoluteSymbols(SymbolMap Symbols, VModuleKey K=VModuleKey())
Create an AbsoluteSymbolsMaterializationUnit with the given symbols.
A utility class to expose symbols from a static library.
Error define(std::unique_ptr< MaterializationUnitType > &&MU)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Mangles symbol names then uniques them in the context of an ExecutionSession.
void * getAddressOfSymbol(const char *symbolName)
Searches through the library for the symbol symbolName.
Tagged union holding either a T or a Error.
void add(iterator_range< CtorDtorIterator > CtorDtors)
This class provides a portable interface to dynamic libraries which also might be known as shared lib...
A constant value that is initialized with an expression using other constant values.
iterator_range< CtorDtorIterator > getDestructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
CtorDtorIterator(const GlobalVariable *GV, bool End)
Construct an iterator instance.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
DynamicLibrarySearchGenerator(sys::DynamicLibrary Dylib, char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate())
Create a DynamicLibrarySearchGenerator that searches for symbols in the given sys::DynamicLibrary.
Value * getOperand(unsigned i) const
bool containsDuplicates()
Returns true if this set contains any duplicates.
size_t size() const
size - Get the array size.
This is an important base class in LLVM.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(const ValueT &V)
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
void add(SymbolStringPtr Name, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Add an element to the set.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
JITDylibSearchOrder makeJITDylibSearchOrder(ArrayRef< JITDylib *> JDs, JITDylibLookupFlags Flags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Convenience function for creating a search order from an ArrayRef of JITDylib*, all with the same fla...
Error tryToGenerate(LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib...
static DynamicLibrary getPermanentLibrary(const char *filename, std::string *errMsg=nullptr)
This function permanently loads the dynamic library at the given path.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast_or_null(const Y &Val)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Error tryToGenerate(LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib...
static ErrorSuccess success()
Create a success value.
unsigned getNumOperands() const
static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg, void *DSOHandle)
This iterator provides a convenient way to iterate over the elements of an llvm.global_ctors/llvm.global_dtors instance.
Module.h This file contains the declarations for the Module class.
A set of symbols to look up, each associated with a SymbolLookupFlags value.
static Constant * getInitializer(Constant *C)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
A range adaptor for a pair of iterators.
ConstantArray - Constant Array Declarations.
Represents a symbol that has been evaluated to an address already.
void runDestructors()
Run any destructors recorded by the overriden __cxa_atexit function (CXAAtExitOverride).
uint8_t uint64_t VModuleKey
VModuleKey provides a unique identifier (allocated and managed by ExecutionSessions) for a module add...
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Load(ObjectLayer &L, const char *FileName)
Try to create a StaticLibraryDefinitionGenerator from the given path.
iterator_range< CtorDtorIterator > getConstructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
LLVM_NODISCARD bool empty() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
int runAsMain(int(*Main)(int, char *[]), ArrayRef< std::string > Args, Optional< StringRef > ProgramName=None)
Run a main function, returning the result.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Element operator*() const
Dereference iterator.
Lightweight error class with error context and mandatory checking.
Interface for Layers that accept object files.
bool operator!=(const CtorDtorIterator &Other) const
Test iterators for inequality.
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
OutputIt copy(R &&Range, OutputIt Out)
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Create(ObjectLayer &L, std::unique_ptr< MemoryBuffer > ArchiveBuffer)
Try to create a StaticLibrarySearchGenerator from the given memory buffer.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
A symbol table that supports asynchoronous symbol queries.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...