LLVM 24.0.0git
ExecutionUtils.cpp
Go to the documentation of this file.
1//===---- ExecutionUtils.cpp - Utilities for executing functions in Orc ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
16#include "llvm/IR/Constants.h"
17#include "llvm/IR/Function.h"
19#include "llvm/IR/Module.h"
22#include <string>
23
24namespace llvm {
25namespace orc {
26
28 : InitList(
29 GV ? dyn_cast_or_null<ConstantArray>(GV->getInitializer()) : nullptr),
30 I((InitList && End) ? InitList->getNumOperands() : 0) {
31}
32
34 assert(InitList == Other.InitList && "Incomparable iterators.");
35 return I == Other.I;
36}
37
39 return !(*this == Other);
40}
41
43 ++I;
44 return *this;
45}
46
48 CtorDtorIterator Temp = *this;
49 ++I;
50 return Temp;
51}
52
54 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(I));
55 assert(CS && "Unrecognized type in llvm.global_ctors/llvm.global_dtors");
56
57 Constant *FuncC = CS->getOperand(1);
58 Function *Func = nullptr;
59
60 // Extract function pointer, pulling off any casts.
61 while (FuncC) {
63 Func = F;
64 break;
65 } else if (ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(FuncC)) {
66 if (CE->isCast())
67 FuncC = CE->getOperand(0);
68 else
69 break;
70 } else {
71 // This isn't anything we recognize. Bail out with Func left set to null.
72 break;
73 }
74 }
75
76 auto *Priority = cast<ConstantInt>(CS->getOperand(0));
77 Value *Data = CS->getNumOperands() == 3 ? CS->getOperand(2) : nullptr;
78 if (Data && !isa<GlobalValue>(Data))
79 Data = nullptr;
80 return Element(Priority->getZExtValue(), Func, Data);
81}
82
84 const GlobalVariable *CtorsList = M.getNamedGlobal("llvm.global_ctors");
85 return make_range(CtorDtorIterator(CtorsList, false),
86 CtorDtorIterator(CtorsList, true));
87}
88
90 const GlobalVariable *DtorsList = M.getNamedGlobal("llvm.global_dtors");
91 return make_range(CtorDtorIterator(DtorsList, false),
92 CtorDtorIterator(DtorsList, true));
93}
94
95bool StaticInitGVIterator::isStaticInitGlobal(GlobalValue &GV) {
96 if (GV.isDeclaration())
97 return false;
98
99 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
100 GV.getName() == "llvm.global_dtors"))
101 return true;
102
103 if (ObjFmt == Triple::MachO) {
104 // FIXME: These section checks are too strict: We should match first and
105 // second word split by comma.
106 if (GV.hasSection() &&
107 (GV.getSection().starts_with("__DATA,__objc_classlist") ||
108 GV.getSection().starts_with("__DATA,__objc_selrefs")))
109 return true;
110 }
111
112 return false;
113}
114
116 if (CtorDtors.empty())
117 return;
118
119 MangleAndInterner Mangle(
120 JD.getExecutionSession(),
121 (*CtorDtors.begin()).Func->getDataLayout());
122
123 for (auto CtorDtor : CtorDtors) {
124 assert(CtorDtor.Func && CtorDtor.Func->hasName() &&
125 "Ctor/Dtor function must be named to be runnable under the JIT");
126
127 // FIXME: Maybe use a symbol promoter here instead.
128 if (CtorDtor.Func->hasLocalLinkage()) {
129 CtorDtor.Func->setLinkage(GlobalValue::ExternalLinkage);
130 CtorDtor.Func->setVisibility(GlobalValue::HiddenVisibility);
131 }
132
133 if (CtorDtor.Data && cast<GlobalValue>(CtorDtor.Data)->isDeclaration())
134 continue;
135
136 CtorDtorsByPriority[CtorDtor.Priority].push_back(
137 Mangle(CtorDtor.Func->getName()));
138 }
139}
140
142 using CtorDtorTy = void (*)();
143
144 SymbolLookupSet LookupSet;
145 for (auto &KV : CtorDtorsByPriority)
146 for (auto &Name : KV.second)
147 LookupSet.add(Name);
148 assert(!LookupSet.containsDuplicates() &&
149 "Ctor/Dtor list contains duplicates");
150
151 auto &ES = JD.getExecutionSession();
152 if (auto CtorDtorMap = ES.lookup(
154 std::move(LookupSet))) {
155 for (auto &KV : CtorDtorsByPriority) {
156 for (auto &Name : KV.second) {
157 assert(CtorDtorMap->count(Name) && "No entry for Name");
158 auto CtorDtor = (*CtorDtorMap)[Name].getAddress().toPtr<CtorDtorTy>();
159 CtorDtor();
160 }
161 }
162 CtorDtorsByPriority.clear();
163 return Error::success();
164 } else
165 return CtorDtorMap.takeError();
166}
167
169 auto& CXXDestructorDataPairs = DSOHandleOverride;
170 for (auto &P : CXXDestructorDataPairs)
171 P.first(P.second);
172 CXXDestructorDataPairs.clear();
173}
174
176 void *Arg,
177 void *DSOHandle) {
178 auto& CXXDestructorDataPairs =
179 *reinterpret_cast<CXXDestructorDataPairList*>(DSOHandle);
180 CXXDestructorDataPairs.push_back(std::make_pair(Destructor, Arg));
181 return 0;
182}
183
185 MangleAndInterner &Mangle) {
186 SymbolMap RuntimeInterposes;
187 RuntimeInterposes[Mangle("__dso_handle")] = {
189 RuntimeInterposes[Mangle("__cxa_atexit")] = {
191
192 return JD.define(absoluteSymbols(std::move(RuntimeInterposes)));
193}
194
195void ItaniumCXAAtExitSupport::registerAtExit(void (*F)(void *), void *Ctx,
196 void *DSOHandle) {
197 std::lock_guard<std::mutex> Lock(AtExitsMutex);
198 AtExitRecords[DSOHandle].push_back({F, Ctx});
199}
200
202 std::vector<AtExitRecord> AtExitsToRun;
203
204 {
205 std::lock_guard<std::mutex> Lock(AtExitsMutex);
206 auto I = AtExitRecords.find(DSOHandle);
207 if (I != AtExitRecords.end()) {
208 AtExitsToRun = std::move(I->second);
209 AtExitRecords.erase(I);
210 }
211 }
212
213 while (!AtExitsToRun.empty()) {
214 AtExitsToRun.back().F(AtExitsToRun.back().Ctx);
215 AtExitsToRun.pop_back();
216 }
217}
218
220 sys::DynamicLibrary Dylib, char GlobalPrefix, SymbolPredicate Allow,
221 AddAbsoluteSymbolsFn AddAbsoluteSymbols)
222 : Dylib(std::move(Dylib)), Allow(std::move(Allow)),
223 AddAbsoluteSymbols(std::move(AddAbsoluteSymbols)),
224 GlobalPrefix(GlobalPrefix) {}
225
227DynamicLibrarySearchGenerator::Load(const char *FileName, char GlobalPrefix,
228 SymbolPredicate Allow,
229 AddAbsoluteSymbolsFn AddAbsoluteSymbols) {
230 std::string ErrMsg;
231 auto Lib = sys::DynamicLibrary::getPermanentLibrary(FileName, &ErrMsg);
232 if (!Lib.isValid())
233 return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
234 return std::make_unique<DynamicLibrarySearchGenerator>(
235 std::move(Lib), GlobalPrefix, std::move(Allow),
236 std::move(AddAbsoluteSymbols));
237}
238
240 LookupState &LS, LookupKind K, JITDylib &JD,
241 JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
242 orc::SymbolMap NewSymbols;
243
244 bool HasGlobalPrefix = (GlobalPrefix != '\0');
245
246 for (auto &KV : Symbols) {
247 auto &Name = KV.first;
248
249 if ((*Name).empty())
250 continue;
251
252 if (Allow && !Allow(Name))
253 continue;
254
255 if (HasGlobalPrefix && (*Name).front() != GlobalPrefix)
256 continue;
257
258 std::string Tmp((*Name).data() + HasGlobalPrefix,
259 (*Name).size() - HasGlobalPrefix);
260 if (void *P = Dylib.getAddressOfSymbol(Tmp.c_str()))
261 NewSymbols[Name] = {ExecutorAddr::fromPtr(P), JITSymbolFlags::Exported};
262 }
263
264 if (NewSymbols.empty())
265 return Error::success();
266
267 if (AddAbsoluteSymbols)
268 return AddAbsoluteSymbols(JD, std::move(NewSymbols));
269 return JD.define(absoluteSymbols(std::move(NewSymbols)));
270}
271
274 JITDylib &JD) {
275 return [&](object::Archive &A, MemoryBufferRef Buf,
276 size_t Index) -> Expected<bool> {
277 switch (identify_magic(Buf.getBuffer())) {
281 if (auto Err = L.add(JD, createMemberBuffer(A, Buf, Index)))
282 return std::move(Err);
283 // Since we've loaded it already, mark this as not loadable.
284 return false;
285 default:
286 // Non-object-file members are not loadable.
287 return false;
288 }
289 };
290}
291
294 ObjectLayer &L, const char *FileName, VisitMembersFunction VisitMembers,
295 GetObjectFileInterface GetObjFileInterface) {
296
297 const auto &TT = L.getExecutionSession().getTargetTriple();
298 auto Linkable = loadLinkableFile(FileName, TT, LoadArchives::Required);
299 if (!Linkable)
300 return Linkable.takeError();
301
302 return Create(L, std::move(Linkable->first), std::move(VisitMembers),
303 std::move(GetObjFileInterface));
304}
305
308 ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
309 std::unique_ptr<object::Archive> Archive, VisitMembersFunction VisitMembers,
310 GetObjectFileInterface GetObjFileInterface) {
311
312 DenseSet<uint64_t> Excluded;
313
314 if (VisitMembers) {
315 size_t Index = 0;
316 Error Err = Error::success();
317 for (auto Child : Archive->children(Err)) {
318 if (auto ChildBuf = Child.getMemoryBufferRef()) {
319 if (auto Loadable = VisitMembers(*Archive, *ChildBuf, Index++)) {
320 if (!*Loadable)
321 Excluded.insert(Child.getDataOffset());
322 } else
323 return Loadable.takeError();
324 } else {
325 // We silently allow non-object archive members. This matches the
326 // behavior of ld.
327 consumeError(ChildBuf.takeError());
328 }
329 }
330 if (Err)
331 return std::move(Err);
332 }
333
334 DenseMap<SymbolStringPtr, size_t> SymbolToMemberIndexMap;
335 {
336 DenseMap<uint64_t, size_t> OffsetToIndex;
337 size_t Index = 0;
338 Error Err = Error::success();
339 for (auto &Child : Archive->children(Err)) {
340 // For all members not excluded above, add them to the OffsetToIndex map.
341 if (!Excluded.count(Child.getDataOffset()))
342 OffsetToIndex[Child.getDataOffset()] = Index;
343 ++Index;
344 }
345 if (Err)
346 return Err;
347
348 auto &ES = L.getExecutionSession();
349 for (auto &Sym : Archive->symbols()) {
350 auto Member = Sym.getMember();
351 if (!Member)
352 return Member.takeError();
353 auto EntryItr = OffsetToIndex.find(Member->getDataOffset());
354
355 // Missing entry means this member should be ignored.
356 if (EntryItr == OffsetToIndex.end())
357 continue;
358
359 SymbolToMemberIndexMap[ES.intern(Sym.getName())] = EntryItr->second;
360 }
361 }
362
363 return std::unique_ptr<StaticLibraryDefinitionGenerator>(
364 new StaticLibraryDefinitionGenerator(
365 L, std::move(ArchiveBuffer), std::move(Archive),
366 std::move(GetObjFileInterface), std::move(SymbolToMemberIndexMap)));
367}
368
371 ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
372 VisitMembersFunction VisitMembers,
373 GetObjectFileInterface GetObjFileInterface) {
374
375 auto B = object::createBinary(ArchiveBuffer->getMemBufferRef());
376 if (!B)
377 return B.takeError();
378
379 // If this is a regular archive then create an instance from it.
381 return Create(L, std::move(ArchiveBuffer),
382 std::unique_ptr<object::Archive>(
383 static_cast<object::Archive *>(B->release())),
384 std::move(VisitMembers), std::move(GetObjFileInterface));
385
386 // If this is a universal binary then search for a slice matching the given
387 // Triple.
388 if (auto *UB = dyn_cast<object::MachOUniversalBinary>(B->get())) {
389
390 const auto &TT = L.getExecutionSession().getTargetTriple();
391
392 auto SliceRange = getMachOSliceRangeForTriple(*UB, TT);
393 if (!SliceRange)
394 return SliceRange.takeError();
395
396 MemoryBufferRef SliceRef(
397 StringRef(ArchiveBuffer->getBufferStart() + SliceRange->first,
398 SliceRange->second),
399 ArchiveBuffer->getBufferIdentifier());
400
401 auto Archive = object::Archive::create(SliceRef);
402 if (!Archive)
403 return Archive.takeError();
404
405 return Create(L, std::move(ArchiveBuffer), std::move(*Archive),
406 std::move(VisitMembers), std::move(GetObjFileInterface));
407 }
408
409 return make_error<StringError>(Twine("Unrecognized file type for ") +
410 ArchiveBuffer->getBufferIdentifier(),
412}
413
415 LookupState &LS, LookupKind K, JITDylib &JD,
416 JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
417 // Don't materialize symbols from static archives unless this is a static
418 // lookup.
419 if (K != LookupKind::Static)
420 return Error::success();
421
422 // Bail out early if we've already freed the archive.
423 if (!Archive)
424 return Error::success();
425
427
428 for (const auto &[Name, _] : Symbols) {
429 // Check whehter the archive contains this symbol.
430 auto It = SymbolToMemberIndexMap.find(Name);
431 if (It == SymbolToMemberIndexMap.end())
432 continue;
433 size_t Index = It->second;
434
435 // If we're already loading the member containing this symbol then we're
436 // done.
437 if (ToLoad.count(Index))
438 continue;
439
440 auto Member = Archive->findSym(*Name);
441 if (!Member)
442 return Member.takeError();
443 if (!*Member) // Skip "none" children.
444 continue;
445
446 auto MemberBuf = (*Member)->getMemoryBufferRef();
447 if (!MemberBuf)
448 return MemberBuf.takeError();
449
450 ToLoad[Index] = *MemberBuf;
451 }
452
453 // Remove symbols to be loaded.
454 {
455 // FIXME: Enable DenseMap removal using NonOwningSymbolStringPtr?
456 std::vector<SymbolStringPtr> ToRemove;
457 for (auto &[Name, Index] : SymbolToMemberIndexMap)
458 if (ToLoad.count(Index))
459 ToRemove.push_back(Name);
460 for (auto &Name : ToRemove)
461 SymbolToMemberIndexMap.erase(Name);
462 }
463
464 // Add loaded files to JITDylib.
465 for (auto &[Index, Buf] : ToLoad) {
466 auto MemberBuf = createMemberBuffer(*Archive, Buf, Index);
467
468 auto Interface = GetObjFileInterface(L.getExecutionSession(),
469 MemberBuf->getMemBufferRef());
470 if (!Interface)
471 return Interface.takeError();
472
473 if (auto Err = L.add(JD, std::move(MemberBuf), std::move(*Interface)))
474 return Err;
475 }
476
477 return Error::success();
478}
479
480std::unique_ptr<MemoryBuffer>
482 MemoryBufferRef BufRef,
483 size_t Index) {
485 (A.getFileName() + "[" + Twine(Index) +
486 "](" + BufRef.getBufferIdentifier() + ")")
487 .str(),
488 false);
489}
490
491StaticLibraryDefinitionGenerator::StaticLibraryDefinitionGenerator(
492 ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
493 std::unique_ptr<object::Archive> Archive,
494 GetObjectFileInterface GetObjFileInterface,
495 DenseMap<SymbolStringPtr, size_t> SymbolToMemberIndexMap)
496 : L(L), GetObjFileInterface(std::move(GetObjFileInterface)),
497 ArchiveBuffer(std::move(ArchiveBuffer)), Archive(std::move(Archive)),
498 SymbolToMemberIndexMap(std::move(SymbolToMemberIndexMap)) {
499 if (!this->GetObjFileInterface)
500 this->GetObjFileInterface = getObjectFileInterface;
501}
502
503std::unique_ptr<DLLImportDefinitionGenerator>
506 return std::unique_ptr<DLLImportDefinitionGenerator>(
507 new DLLImportDefinitionGenerator(ES, L));
508}
509
511 LookupState &LS, LookupKind K, JITDylib &JD,
512 JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
513 JITDylibSearchOrder LinkOrder;
514 JD.withLinkOrderDo([&](const JITDylibSearchOrder &LO) {
515 LinkOrder.reserve(LO.size());
516 for (auto &KV : LO) {
517 if (KV.first == &JD)
518 continue;
519 LinkOrder.push_back(KV);
520 }
521 });
522
523 // FIXME: if regular symbol name start with __imp_ we have to issue lookup of
524 // both __imp_ and stripped name and use the lookup information to resolve the
525 // real symbol name.
526 SymbolLookupSet LookupSet;
528 for (auto &KV : Symbols) {
529 StringRef Deinterned = *KV.first;
530 if (Deinterned.starts_with(getImpPrefix()))
531 Deinterned = Deinterned.drop_front(StringRef(getImpPrefix()).size());
532 // Don't degrade the required state
533 auto [It, Inserted] = ToLookUpSymbols.try_emplace(Deinterned);
534 if (Inserted || It->second != SymbolLookupFlags::RequiredSymbol)
535 It->second = KV.second;
536 }
537
538 for (auto &KV : ToLookUpSymbols)
539 LookupSet.add(ES.intern(KV.first), KV.second);
540
541 auto Resolved = ES.lookup(LinkOrder, LookupSet, LookupKind::Static,
543 if (!Resolved)
544 return Resolved.takeError();
545
546 auto G = createStubsGraph(*Resolved);
547 if (!G)
548 return G.takeError();
549 return L.add(JD, std::move(*G));
550}
551
553DLLImportDefinitionGenerator::createStubsGraph(const SymbolMap &Resolved) {
554 Triple TT = ES.getTargetTriple();
555
556 auto CreatePointer = jitlink::getAnonymousPointerCreator(TT);
557 if (!CreatePointer)
559 "DLLImportDefinitionGenerator: no pointer creator for " + TT.str(),
561
562 auto CreateStub = jitlink::getPointerJumpStubCreator(TT);
563 if (!CreateStub)
565 "DLLImportDefinitionGenerator: no stub creator for " + TT.str(),
567
568 auto G = std::make_unique<jitlink::LinkGraph>(
569 "<DLLIMPORT_STUBS>", ES.getSymbolStringPool(), TT, SubtargetFeatures(),
571 jitlink::Section &Sec =
572 G->createSection(getSectionName(), MemProt::Read | MemProt::Exec);
573
574 for (auto &KV : Resolved) {
575 jitlink::Symbol &Target = G->addAbsoluteSymbol(
576 *KV.first, KV.second.getAddress(), G->getPointerSize(),
578
579 // Create __imp_ symbol
580 jitlink::Symbol &Ptr = CreatePointer(*G, Sec, &Target, 0);
581 Ptr.setName(G->intern((Twine(getImpPrefix()) + *KV.first).str()));
584
585 // Create PLT stub
586 // FIXME: check PLT stub of data symbol is not accessed
587 jitlink::Symbol &Stub = CreateStub(*G, Sec, Ptr);
588 Stub.setName(G->intern(*KV.first));
591 }
592
593 return std::move(G);
594}
595
596} // End namespace orc.
597} // End namespace llvm.
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
ReachingDefInfo InstSet & ToRemove
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define _
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define P(N)
ConstantArray - Constant Array Declarations.
Definition Constants.h:590
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1316
This is an important base class in LLVM.
Definition Constant.h:43
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
bool empty() const
Definition DenseMap.h:171
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:219
iterator end()
Definition DenseMap.h:141
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
LLVM_ABI StringRef getSection() const
Definition Globals.cpp:264
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
bool hasSection() const
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
StringRef getBufferIdentifier() const
StringRef getBuffer() const
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:635
Manages the enabling and disabling of subtarget specific features.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
bool hasName() const
Definition Value.h:261
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
A range adaptor for a pair of iterators.
IteratorT begin() const
static Expected< std::unique_ptr< Archive > > create(MemoryBufferRef Source)
Definition Archive.cpp:785
This iterator provides a convenient way to iterate over the elements of an llvm.global_ctors/llvm....
LLVM_ABI bool operator!=(const CtorDtorIterator &Other) const
Test iterators for inequality.
LLVM_ABI Element operator*() const
Dereference iterator.
LLVM_ABI CtorDtorIterator(const GlobalVariable *GV, bool End)
Construct an iterator instance.
LLVM_ABI CtorDtorIterator & operator++()
Pre-increment iterator.
LLVM_ABI bool operator==(const CtorDtorIterator &Other) const
Test iterators for equality.
LLVM_ABI void add(iterator_range< CtorDtorIterator > CtorDtors)
static std::unique_ptr< DLLImportDefinitionGenerator > Create(ExecutionSession &ES, ObjectLinkingLayer &L)
Creates a DLLImportDefinitionGenerator instance.
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
friend class ExecutionSession
Definition Core.h:633
std::function< bool(const SymbolStringPtr &)> SymbolPredicate
unique_function< Error(JITDylib &, SymbolMap)> AddAbsoluteSymbolsFn
DynamicLibrarySearchGenerator(sys::DynamicLibrary Dylib, char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate(), AddAbsoluteSymbolsFn AddAbsoluteSymbols=nullptr)
Create a DynamicLibrarySearchGenerator that searches for symbols in the given sys::DynamicLibrary.
static Expected< std::unique_ptr< DynamicLibrarySearchGenerator > > Load(const char *FileName, char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate(), AddAbsoluteSymbolsFn AddAbsoluteSymbols=nullptr)
Permanently loads the library at the given path and, on success, returns a DynamicLibrarySearchGenera...
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
const Triple & getTargetTriple() const
Return the triple for the executor.
Definition Core.h:1159
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
Definition Core.h:1165
static ExecutorAddr fromPtr(T *Ptr, UnwrapFn &&Unwrap=UnwrapFn())
Create an ExecutorAddr from the given pointer.
LLVM_ABI void runAtExits(void *DSOHandle)
LLVM_ABI void registerAtExit(void(*F)(void *), void *Ctx, void *DSOHandle)
Represents a JIT'd dynamic library.
Definition Core.h:675
Error define(std::unique_ptr< MaterializationUnitType > &&MU, ResourceTrackerSP RT=nullptr)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Definition Core.h:1654
auto withLinkOrderDo(Func &&F) -> decltype(F(std::declval< const JITDylibSearchOrder & >()))
Do something with the link order (run under the session lock).
Definition Core.h:1647
static LLVM_ABI int CXAAtExitOverride(DestructorPtr Destructor, void *Arg, void *DSOHandle)
std::vector< CXXDestructorDataPair > CXXDestructorDataPairList
CXXDestructorDataPairList DSOHandleOverride
LLVM_ABI void runDestructors()
Run any destructors recorded by the overriden __cxa_atexit function (CXAAtExitOverride).
LLVM_ABI Error enable(JITDylib &JD, MangleAndInterner &Mangler)
Wraps state for a lookup-in-progress.
Definition Core.h:607
Mangles symbol names then uniques them in the context of an ExecutionSession.
Definition Mangling.h:27
Interface for Layers that accept object files.
Definition Layer.h:134
An ObjectLayer implementation built on JITLink.
static VisitMembersFunction loadAllObjectFileMembers(ObjectLayer &L, JITDylib &JD)
A VisitMembersFunction that unconditionally loads all object files from the archive.
unique_function< Expected< MaterializationUnit::Interface >( ExecutionSession &ES, MemoryBufferRef ObjBuffer)> GetObjectFileInterface
Interface builder function for objects loaded from this archive.
unique_function< Expected< bool >( object::Archive &, MemoryBufferRef, size_t)> VisitMembersFunction
Callback for visiting archive members at construction time.
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Create(ObjectLayer &L, std::unique_ptr< MemoryBuffer > ArchiveBuffer, std::unique_ptr< object::Archive > Archive, VisitMembersFunction VisitMembers=VisitMembersFunction(), GetObjectFileInterface GetObjFileInterface=GetObjectFileInterface())
Try to create a StaticLibrarySearchGenerator from the given memory buffer and Archive object.
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Load(ObjectLayer &L, const char *FileName, VisitMembersFunction VisitMembers=VisitMembersFunction(), GetObjectFileInterface GetObjFileInterface=GetObjectFileInterface())
Try to create a StaticLibraryDefinitionGenerator from the given path.
static std::unique_ptr< MemoryBuffer > createMemberBuffer(object::Archive &A, MemoryBufferRef BufRef, size_t Index)
A set of symbols to look up, each associated with a SymbolLookupFlags value.
SymbolLookupSet & add(SymbolStringPtr Name, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Add an element to the set.
bool containsDuplicates()
Returns true if this set contains any duplicates.
This class provides a portable interface to dynamic libraries which also might be known as shared lib...
static LLVM_ABI DynamicLibrary getPermanentLibrary(const char *filename, std::string *errMsg=nullptr)
This function permanently loads the dynamic library at the given path using the library load operatio...
static constexpr const StringLiteral & getSectionName(DebugSectionKind SectionKind)
Return the name of the section.
LLVM_ABI Expected< std::unique_ptr< Binary > > createBinary(MemoryBufferRef Source, LLVMContext *Context=nullptr, bool InitContent=true)
Create a Binary from Source, autodetecting the file type.
Definition Binary.cpp:45
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...
Definition Core.h:153
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
Definition Core.h:148
LLVM_ABI Expected< std::pair< std::unique_ptr< MemoryBuffer >, LinkableFileKind > > loadLinkableFile(StringRef Path, const Triple &TT, LoadArchives LA, std::optional< StringRef > IdentifierOverride=std::nullopt)
Create a MemoryBuffer covering the "linkable" part of the given path.
LLVM_ABI iterator_range< CtorDtorIterator > getDestructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
std::unique_ptr< AbsoluteSymbolsMaterializationUnit > absoluteSymbols(SymbolMap Symbols)
Create an AbsoluteSymbolsMaterializationUnit with the given symbols.
LLVM_ABI iterator_range< CtorDtorIterator > getConstructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
Definition Core.h:132
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
LLVM_ABI Expected< MaterializationUnit::Interface > getObjectFileInterface(ExecutionSession &ES, MemoryBufferRef ObjBuffer)
Returns a MaterializationUnit::Interface for the object file contained in the given buffer,...
LLVM_ABI Expected< std::pair< size_t, size_t > > getMachOSliceRangeForTriple(object::MachOUniversalBinary &UB, const Triple &TT)
Utility for identifying the file-slice compatible with TT in a universal binary.
Definition MachO.cpp:206
LookupKind
Describes the kind of lookup being performed.
Definition Core.h:144
@ Resolved
Queried, materialization begun.
Definition Core.h:549
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI file_magic identify_magic(StringRef magic)
Identify the type of a binary file based on how magical it is.
Definition Magic.cpp:33
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
@ Other
Any other memory.
Definition ModRef.h:68
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
@ elf_relocatable
ELF Relocatable object file.
Definition Magic.h:28
@ macho_object
Mach-O Object file.
Definition Magic.h:33
@ coff_object
COFF object file.
Definition Magic.h:48
Accessor for an element of the global_ctors/global_dtors array.