18 #define DEBUG_TYPE "jitlink" 28 if (
auto GraphOrErr =
buildGraph(Ctx->getObjectBuffer()))
29 G = std::move(*GraphOrErr);
31 return Ctx->notifyFailed(GraphOrErr.takeError());
32 assert(G &&
"Graph should have been created by buildGraph above");
36 return Ctx->notifyFailed(std::move(Err));
39 dbgs() <<
"Link graph \"" << G->getName() <<
"\" pre-pruning:\n";
46 dbgs() <<
"Link graph \"" << G->getName() <<
"\" post-pruning:\n";
52 return Ctx->notifyFailed(std::move(Err));
55 auto Layout = layOutBlocks();
58 if (
auto Err = allocateSegments(Layout))
59 return Ctx->notifyFailed(std::move(Err));
62 Ctx->notifyResolved(*G);
64 auto ExternalSymbols = getExternalSymbolNames();
76 auto *TmpCtx = Ctx.get();
77 TmpCtx->lookup(std::move(ExternalSymbols),
79 [S = std::move(Self), L = std::move(Layout)](
82 TmpSelf.linkPhase2(std::move(S), std::move(LookupResult),
92 return deallocateAndBailOut(LR.
takeError());
95 applyLookupResult(*LR);
98 dbgs() <<
"Link graph \"" << G->getName() <<
"\" before copy-and-fixup:\n";
103 if (
auto Err = copyAndFixUpBlocks(Layout, *Alloc))
104 return deallocateAndBailOut(std::move(Err));
107 dbgs() <<
"Link graph \"" << G->getName() <<
"\" after copy-and-fixup:\n";
112 return deallocateAndBailOut(std::move(Err));
115 auto *UnownedSelf = Self.release();
116 auto Phase3Continuation = [UnownedSelf](
Error Err) {
117 std::unique_ptr<JITLinkerBase> Self(UnownedSelf);
118 UnownedSelf->linkPhase3(std::move(Self), std::move(Err));
121 Alloc->finalizeAsync(std::move(Phase3Continuation));
126 return deallocateAndBailOut(std::move(Err));
127 Ctx->notifyFinalized(std::move(Alloc));
131 for (
auto &
P : Passes)
132 if (
auto Err =
P(*G))
142 for (
auto *
B : G->blocks()) {
143 auto &SegLists = Layout[
B->getSection().getProtectionFlags()];
144 if (!
B->isZeroFill())
145 SegLists.ContentBlocks.push_back(
B);
147 SegLists.ZeroFillBlocks.push_back(
B);
151 for (
auto &KV : Layout) {
153 auto CompareBlocks = [](
const Block *LHS,
const Block *RHS) {
159 return LHS->
getSize() < RHS->getSize();
162 auto &SegLists = KV.second;
163 llvm::sort(SegLists.ContentBlocks, CompareBlocks);
164 llvm::sort(SegLists.ZeroFillBlocks, CompareBlocks);
168 dbgs() <<
"Segment ordering:\n";
169 for (
auto &KV : Layout) {
170 dbgs() <<
" Segment " 172 auto &SL = KV.second;
174 {std::make_pair(&SL.ContentBlocks,
"content block"),
175 std::make_pair(&SL.ZeroFillBlocks,
"zero-fill block")}) {
176 dbgs() <<
" " << SIEntry.second <<
":\n";
177 for (
auto *
B : *SIEntry.first)
178 dbgs() <<
" " << *
B <<
"\n";
191 for (
auto &KV : Layout) {
192 auto &Prot = KV.first;
193 auto &SegLists = KV.second;
195 uint64_t SegAlign = 1;
198 size_t SegContentSize = 0;
199 for (
auto *
B : SegLists.ContentBlocks) {
200 SegAlign =
std::max(SegAlign,
B->getAlignment());
202 SegContentSize +=
B->getSize();
205 uint64_t SegZeroFillStart = SegContentSize;
206 uint64_t SegZeroFillEnd = SegZeroFillStart;
208 for (
auto *
B : SegLists.ZeroFillBlocks) {
209 SegAlign =
std::max(SegAlign,
B->getAlignment());
211 SegZeroFillEnd +=
B->getSize();
214 Segments[Prot] = {SegAlign, SegContentSize,
215 SegZeroFillEnd - SegZeroFillStart};
218 dbgs() << (&KV == &*Layout.begin() ?
"" :
"; ")
219 << static_cast<sys::Memory::ProtectionFlags>(Prot)
220 <<
": alignment = " << SegAlign
221 <<
", content size = " << SegContentSize
222 <<
", zero-fill size = " << (SegZeroFillEnd - SegZeroFillStart);
227 if (
auto AllocOrErr = Ctx->getMemoryManager().allocate(Segments))
228 Alloc = std::move(*AllocOrErr);
230 return AllocOrErr.takeError();
233 dbgs() <<
"JIT linker got working memory:\n";
234 for (
auto &KV : Layout) {
236 dbgs() <<
" " << Prot <<
": " 237 << (
const void *)Alloc->getWorkingMemory(Prot).data() <<
"\n";
242 for (
auto &KV : Layout) {
243 auto &Prot = KV.first;
244 auto &SL = KV.second;
247 Alloc->getTargetMemory(static_cast<sys::Memory::ProtectionFlags>(Prot));
249 for (
auto *SIList : {&SL.ContentBlocks, &SL.ZeroFillBlocks})
250 for (
auto *
B : *SIList) {
252 B->setAddress(NextBlockAddr);
253 NextBlockAddr +=
B->getSize();
263 for (
auto *Sym : G->external_symbols()) {
264 assert(Sym->getAddress() == 0 &&
265 "External has already been assigned an address");
267 "Externals must be named");
272 UnresolvedExternals[Sym->getName()] = LookupFlags;
274 return UnresolvedExternals;
278 for (
auto *Sym : G->external_symbols()) {
279 assert(Sym->getOffset() == 0 &&
280 "External symbol is not at the start of its addressable block");
281 assert(Sym->getAddress() == 0 &&
"Symbol already resolved");
282 assert(!Sym->isDefined() &&
"Symbol being resolved is already defined");
283 auto ResultI = Result.
find(Sym->getName());
284 if (ResultI != Result.
end())
285 Sym->getAddressable().setAddress(ResultI->second.getAddress());
288 "Failed to resolve non-weak reference");
292 dbgs() <<
"Externals after applying lookup result:\n";
293 for (
auto *Sym : G->external_symbols())
294 dbgs() <<
" " << Sym->getName() <<
": " 295 <<
formatv(
"{0:x16}", Sym->getAddress()) <<
"\n";
299 return Sym->getAddress() != 0 ||
302 "All strong external symbols should have been resolved by now");
305 void JITLinkerBase::deallocateAndBailOut(
Error Err) {
306 assert(Err &&
"Should not be bailing out on success value");
307 assert(Alloc &&
"can not call deallocateAndBailOut before allocation");
308 Ctx->notifyFailed(
joinErrors(std::move(Err), Alloc->deallocate()));
312 assert(G &&
"Graph is not set yet");
317 std::vector<Symbol *> Worklist;
323 Worklist.push_back(Sym);
326 while (!Worklist.empty()) {
327 auto *Sym = Worklist.back();
330 auto &
B = Sym->getBlock();
333 if (VisitedBlocks.
count(&
B))
338 for (
auto &
E : Sym->getBlock().edges()) {
339 if (
E.getTarget().isDefined() && !
E.getTarget().isLive()) {
340 E.getTarget().setLive(
true);
341 Worklist.push_back(&
E.getTarget());
349 std::vector<Symbol *> SymbolsToRemove;
352 SymbolsToRemove.push_back(Sym);
353 for (
auto *Sym : SymbolsToRemove) {
362 std::vector<Block *> BlocksToRemove;
364 if (!VisitedBlocks.
count(
B))
365 BlocksToRemove.push_back(
B);
366 for (
auto *
B : BlocksToRemove) {
static JITTargetAddress alignToBlock(JITTargetAddress Addr, Block &B)
This class represents lattice values for constants.
SymbolLookupFlags
Flags for symbol lookup.
std::unique_ptr< JITLinkAsyncLookupContinuation > createLookupContinuation(Continuation Cont)
Create a lookup continuation from a function object.
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Error takeError()
Take ownership of the stored error.
An Addressable with content and edges.
JITTargetAddress getAddress() const
void linkPhase3(std::unique_ptr< JITLinkerBase > Self, Error Err)
Tagged union holding either a T or a Error.
uint64_t JITTargetAddress
Represents an address in the target process's address space.
SectionOrdinal getOrdinal() const
Returns the ordinal for this section.
void prune(LinkGraph &G)
Removes dead symbols/blocks/addressables.
iterator find(const_arg_type_t< KeyT > Val)
iterator_range< block_iterator > blocks()
LinkGraphPassList PostFixupPasses
Post-fixup passes.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::pair< iterator, bool > insert(const ValueT &V)
Section & getSection() const
Return the parent section for this block.
LinkGraphPassList PostPrunePasses
Post-prune passes.
virtual Expected< std::unique_ptr< LinkGraph > > buildGraph(MemoryBufferRef ObjBuffer)=0
void removeBlock(Block &B)
Remove a block.
LinkGraphPassList PrePrunePasses
Pre-prune passes.
void sort(IteratorTy Start, IteratorTy End)
static ErrorSuccess success()
Create a success value.
Align max(MaybeAlign Lhs, Align Rhs)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void removeDefinedSymbol(Symbol &Sym)
Removes defined symbols. Does not remove the underlying block.
Error joinErrors(Error E1, Error E2)
Concatenate errors.
std::vector< LinkGraphPassFunction > LinkGraphPassList
A list of LinkGraph passes.
void linkPhase1(std::unique_ptr< JITLinkerBase > Self)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
virtual StringRef getEdgeKindName(Edge::Kind K) const =0
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Lightweight error class with error context and mandatory checking.
This class implements an extremely fast bulk output stream that can only output to a stream...
size_t getSize() const
Returns the size of this defined addressable.
StringRef - Represent a constant reference to a string, i.e.
iterator_range< defined_symbol_iterator > defined_symbols()
void linkPhase2(std::unique_ptr< JITLinkerBase > Self, Expected< AsyncLookupResult > LookupResult, SegmentLayoutMap Layout)