xref: /freebsd/contrib/llvm-project/llvm/lib/ExecutionEngine/Orc/ObjectLinkingLayer.cpp (revision 04eeddc0aa8e0a417a16eaf9d7d095207f4a8623)
10b57cec5SDimitry Andric //===------- ObjectLinkingLayer.cpp - JITLink backed ORC ObjectLayer ------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
100b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
110b57cec5SDimitry Andric #include "llvm/ExecutionEngine/JITLink/EHFrameSupport.h"
12fe6060f1SDimitry Andric #include "llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h"
13fe6060f1SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
14fe6060f1SDimitry Andric #include <string>
150b57cec5SDimitry Andric #include <vector>
160b57cec5SDimitry Andric 
170b57cec5SDimitry Andric #define DEBUG_TYPE "orc"
180b57cec5SDimitry Andric 
190b57cec5SDimitry Andric using namespace llvm;
200b57cec5SDimitry Andric using namespace llvm::jitlink;
210b57cec5SDimitry Andric using namespace llvm::orc;
220b57cec5SDimitry Andric 
23fe6060f1SDimitry Andric namespace {
24fe6060f1SDimitry Andric 
25fe6060f1SDimitry Andric class LinkGraphMaterializationUnit : public MaterializationUnit {
26fe6060f1SDimitry Andric public:
27fe6060f1SDimitry Andric   static std::unique_ptr<LinkGraphMaterializationUnit>
28fe6060f1SDimitry Andric   Create(ObjectLinkingLayer &ObjLinkingLayer, std::unique_ptr<LinkGraph> G) {
29fe6060f1SDimitry Andric     auto LGI = scanLinkGraph(ObjLinkingLayer.getExecutionSession(), *G);
30fe6060f1SDimitry Andric     return std::unique_ptr<LinkGraphMaterializationUnit>(
31fe6060f1SDimitry Andric         new LinkGraphMaterializationUnit(ObjLinkingLayer, std::move(G),
32fe6060f1SDimitry Andric                                          std::move(LGI)));
33fe6060f1SDimitry Andric   }
34fe6060f1SDimitry Andric 
35fe6060f1SDimitry Andric   StringRef getName() const override { return G->getName(); }
36fe6060f1SDimitry Andric   void materialize(std::unique_ptr<MaterializationResponsibility> MR) override {
37fe6060f1SDimitry Andric     ObjLinkingLayer.emit(std::move(MR), std::move(G));
38fe6060f1SDimitry Andric   }
39fe6060f1SDimitry Andric 
40fe6060f1SDimitry Andric private:
410eae32dcSDimitry Andric   static Interface scanLinkGraph(ExecutionSession &ES, LinkGraph &G) {
42fe6060f1SDimitry Andric 
430eae32dcSDimitry Andric     Interface LGI;
44fe6060f1SDimitry Andric 
45fe6060f1SDimitry Andric     for (auto *Sym : G.defined_symbols()) {
46fe6060f1SDimitry Andric       // Skip local symbols.
47fe6060f1SDimitry Andric       if (Sym->getScope() == Scope::Local)
48fe6060f1SDimitry Andric         continue;
49fe6060f1SDimitry Andric       assert(Sym->hasName() && "Anonymous non-local symbol?");
50fe6060f1SDimitry Andric 
51fe6060f1SDimitry Andric       JITSymbolFlags Flags;
52fe6060f1SDimitry Andric       if (Sym->getScope() == Scope::Default)
53fe6060f1SDimitry Andric         Flags |= JITSymbolFlags::Exported;
54fe6060f1SDimitry Andric 
55fe6060f1SDimitry Andric       if (Sym->isCallable())
56fe6060f1SDimitry Andric         Flags |= JITSymbolFlags::Callable;
57fe6060f1SDimitry Andric 
58fe6060f1SDimitry Andric       LGI.SymbolFlags[ES.intern(Sym->getName())] = Flags;
59fe6060f1SDimitry Andric     }
60fe6060f1SDimitry Andric 
61349cc55cSDimitry Andric     if ((G.getTargetTriple().isOSBinFormatMachO() && hasMachOInitSection(G)) ||
62349cc55cSDimitry Andric         (G.getTargetTriple().isOSBinFormatELF() && hasELFInitSection(G)))
63fe6060f1SDimitry Andric       LGI.InitSymbol = makeInitSymbol(ES, G);
64fe6060f1SDimitry Andric 
65fe6060f1SDimitry Andric     return LGI;
66fe6060f1SDimitry Andric   }
67fe6060f1SDimitry Andric 
68fe6060f1SDimitry Andric   static bool hasMachOInitSection(LinkGraph &G) {
69fe6060f1SDimitry Andric     for (auto &Sec : G.sections())
70fe6060f1SDimitry Andric       if (Sec.getName() == "__DATA,__obj_selrefs" ||
71fe6060f1SDimitry Andric           Sec.getName() == "__DATA,__objc_classlist" ||
72fe6060f1SDimitry Andric           Sec.getName() == "__TEXT,__swift5_protos" ||
73fe6060f1SDimitry Andric           Sec.getName() == "__TEXT,__swift5_proto" ||
74349cc55cSDimitry Andric           Sec.getName() == "__TEXT,__swift5_types" ||
75fe6060f1SDimitry Andric           Sec.getName() == "__DATA,__mod_init_func")
76fe6060f1SDimitry Andric         return true;
77fe6060f1SDimitry Andric     return false;
78fe6060f1SDimitry Andric   }
79fe6060f1SDimitry Andric 
80349cc55cSDimitry Andric   static bool hasELFInitSection(LinkGraph &G) {
81349cc55cSDimitry Andric     for (auto &Sec : G.sections())
82349cc55cSDimitry Andric       if (Sec.getName() == ".init_array")
83349cc55cSDimitry Andric         return true;
84349cc55cSDimitry Andric     return false;
85349cc55cSDimitry Andric   }
86349cc55cSDimitry Andric 
87fe6060f1SDimitry Andric   static SymbolStringPtr makeInitSymbol(ExecutionSession &ES, LinkGraph &G) {
88fe6060f1SDimitry Andric     std::string InitSymString;
89fe6060f1SDimitry Andric     raw_string_ostream(InitSymString)
90fe6060f1SDimitry Andric         << "$." << G.getName() << ".__inits" << Counter++;
91fe6060f1SDimitry Andric     return ES.intern(InitSymString);
92fe6060f1SDimitry Andric   }
93fe6060f1SDimitry Andric 
94fe6060f1SDimitry Andric   LinkGraphMaterializationUnit(ObjectLinkingLayer &ObjLinkingLayer,
950eae32dcSDimitry Andric                                std::unique_ptr<LinkGraph> G, Interface LGI)
960eae32dcSDimitry Andric       : MaterializationUnit(std::move(LGI)), ObjLinkingLayer(ObjLinkingLayer),
970eae32dcSDimitry Andric         G(std::move(G)) {}
98fe6060f1SDimitry Andric 
99fe6060f1SDimitry Andric   void discard(const JITDylib &JD, const SymbolStringPtr &Name) override {
100fe6060f1SDimitry Andric     for (auto *Sym : G->defined_symbols())
101fe6060f1SDimitry Andric       if (Sym->getName() == *Name) {
102fe6060f1SDimitry Andric         assert(Sym->getLinkage() == Linkage::Weak &&
103fe6060f1SDimitry Andric                "Discarding non-weak definition");
104fe6060f1SDimitry Andric         G->makeExternal(*Sym);
105fe6060f1SDimitry Andric         break;
106fe6060f1SDimitry Andric       }
107fe6060f1SDimitry Andric   }
108fe6060f1SDimitry Andric 
109fe6060f1SDimitry Andric   ObjectLinkingLayer &ObjLinkingLayer;
110fe6060f1SDimitry Andric   std::unique_ptr<LinkGraph> G;
111fe6060f1SDimitry Andric   static std::atomic<uint64_t> Counter;
112fe6060f1SDimitry Andric };
113fe6060f1SDimitry Andric 
114fe6060f1SDimitry Andric std::atomic<uint64_t> LinkGraphMaterializationUnit::Counter{0};
115fe6060f1SDimitry Andric 
116fe6060f1SDimitry Andric } // end anonymous namespace
117fe6060f1SDimitry Andric 
1180b57cec5SDimitry Andric namespace llvm {
1190b57cec5SDimitry Andric namespace orc {
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric class ObjectLinkingLayerJITLinkContext final : public JITLinkContext {
1220b57cec5SDimitry Andric public:
123e8d8bef9SDimitry Andric   ObjectLinkingLayerJITLinkContext(
124e8d8bef9SDimitry Andric       ObjectLinkingLayer &Layer,
125e8d8bef9SDimitry Andric       std::unique_ptr<MaterializationResponsibility> MR,
1260b57cec5SDimitry Andric       std::unique_ptr<MemoryBuffer> ObjBuffer)
127e8d8bef9SDimitry Andric       : JITLinkContext(&MR->getTargetJITDylib()), Layer(Layer),
128e8d8bef9SDimitry Andric         MR(std::move(MR)), ObjBuffer(std::move(ObjBuffer)) {}
1290b57cec5SDimitry Andric 
1308bcb0991SDimitry Andric   ~ObjectLinkingLayerJITLinkContext() {
1318bcb0991SDimitry Andric     // If there is an object buffer return function then use it to
1328bcb0991SDimitry Andric     // return ownership of the buffer.
133e8d8bef9SDimitry Andric     if (Layer.ReturnObjectBuffer && ObjBuffer)
1348bcb0991SDimitry Andric       Layer.ReturnObjectBuffer(std::move(ObjBuffer));
1358bcb0991SDimitry Andric   }
1368bcb0991SDimitry Andric 
137e8d8bef9SDimitry Andric   JITLinkMemoryManager &getMemoryManager() override { return Layer.MemMgr; }
1380b57cec5SDimitry Andric 
139fe6060f1SDimitry Andric   void notifyMaterializing(LinkGraph &G) {
140fe6060f1SDimitry Andric     for (auto &P : Layer.Plugins)
141fe6060f1SDimitry Andric       P->notifyMaterializing(*MR, G, *this,
142fe6060f1SDimitry Andric                              ObjBuffer ? ObjBuffer->getMemBufferRef()
143fe6060f1SDimitry Andric                              : MemoryBufferRef());
144fe6060f1SDimitry Andric   }
145fe6060f1SDimitry Andric 
1460b57cec5SDimitry Andric   void notifyFailed(Error Err) override {
147e8d8bef9SDimitry Andric     for (auto &P : Layer.Plugins)
148e8d8bef9SDimitry Andric       Err = joinErrors(std::move(Err), P->notifyFailed(*MR));
1490b57cec5SDimitry Andric     Layer.getExecutionSession().reportError(std::move(Err));
150e8d8bef9SDimitry Andric     MR->failMaterialization();
1510b57cec5SDimitry Andric   }
1520b57cec5SDimitry Andric 
153480093f4SDimitry Andric   void lookup(const LookupMap &Symbols,
1548bcb0991SDimitry Andric               std::unique_ptr<JITLinkAsyncLookupContinuation> LC) override {
1550b57cec5SDimitry Andric 
1565ffd83dbSDimitry Andric     JITDylibSearchOrder LinkOrder;
157e8d8bef9SDimitry Andric     MR->getTargetJITDylib().withLinkOrderDo(
1585ffd83dbSDimitry Andric         [&](const JITDylibSearchOrder &LO) { LinkOrder = LO; });
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric     auto &ES = Layer.getExecutionSession();
1610b57cec5SDimitry Andric 
162480093f4SDimitry Andric     SymbolLookupSet LookupSet;
163480093f4SDimitry Andric     for (auto &KV : Symbols) {
164480093f4SDimitry Andric       orc::SymbolLookupFlags LookupFlags;
165480093f4SDimitry Andric       switch (KV.second) {
166480093f4SDimitry Andric       case jitlink::SymbolLookupFlags::RequiredSymbol:
167480093f4SDimitry Andric         LookupFlags = orc::SymbolLookupFlags::RequiredSymbol;
168480093f4SDimitry Andric         break;
169480093f4SDimitry Andric       case jitlink::SymbolLookupFlags::WeaklyReferencedSymbol:
170480093f4SDimitry Andric         LookupFlags = orc::SymbolLookupFlags::WeaklyReferencedSymbol;
171480093f4SDimitry Andric         break;
172480093f4SDimitry Andric       }
173480093f4SDimitry Andric       LookupSet.add(ES.intern(KV.first), LookupFlags);
174480093f4SDimitry Andric     }
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric     // OnResolve -- De-intern the symbols and pass the result to the linker.
177e8d8bef9SDimitry Andric     auto OnResolve = [LookupContinuation =
178e8d8bef9SDimitry Andric                           std::move(LC)](Expected<SymbolMap> Result) mutable {
1790b57cec5SDimitry Andric       if (!Result)
1808bcb0991SDimitry Andric         LookupContinuation->run(Result.takeError());
1810b57cec5SDimitry Andric       else {
1820b57cec5SDimitry Andric         AsyncLookupResult LR;
1830b57cec5SDimitry Andric         for (auto &KV : *Result)
1840b57cec5SDimitry Andric           LR[*KV.first] = KV.second;
1858bcb0991SDimitry Andric         LookupContinuation->run(std::move(LR));
1860b57cec5SDimitry Andric       }
1870b57cec5SDimitry Andric     };
1880b57cec5SDimitry Andric 
1895ffd83dbSDimitry Andric     for (auto &KV : InternalNamedSymbolDeps) {
1905ffd83dbSDimitry Andric       SymbolDependenceMap InternalDeps;
191e8d8bef9SDimitry Andric       InternalDeps[&MR->getTargetJITDylib()] = std::move(KV.second);
192e8d8bef9SDimitry Andric       MR->addDependencies(KV.first, InternalDeps);
1935ffd83dbSDimitry Andric     }
1945ffd83dbSDimitry Andric 
1955ffd83dbSDimitry Andric     ES.lookup(LookupKind::Static, LinkOrder, std::move(LookupSet),
196480093f4SDimitry Andric               SymbolState::Resolved, std::move(OnResolve),
197480093f4SDimitry Andric               [this](const SymbolDependenceMap &Deps) {
1980b57cec5SDimitry Andric                 registerDependencies(Deps);
1990b57cec5SDimitry Andric               });
2000b57cec5SDimitry Andric   }
2010b57cec5SDimitry Andric 
202e8d8bef9SDimitry Andric   Error notifyResolved(LinkGraph &G) override {
2030b57cec5SDimitry Andric     auto &ES = Layer.getExecutionSession();
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric     SymbolFlagsMap ExtraSymbolsToClaim;
2060b57cec5SDimitry Andric     bool AutoClaim = Layer.AutoClaimObjectSymbols;
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric     SymbolMap InternedResult;
2098bcb0991SDimitry Andric     for (auto *Sym : G.defined_symbols())
2108bcb0991SDimitry Andric       if (Sym->hasName() && Sym->getScope() != Scope::Local) {
2118bcb0991SDimitry Andric         auto InternedName = ES.intern(Sym->getName());
2120b57cec5SDimitry Andric         JITSymbolFlags Flags;
2130b57cec5SDimitry Andric 
2148bcb0991SDimitry Andric         if (Sym->isCallable())
2150b57cec5SDimitry Andric           Flags |= JITSymbolFlags::Callable;
2168bcb0991SDimitry Andric         if (Sym->getScope() == Scope::Default)
2178bcb0991SDimitry Andric           Flags |= JITSymbolFlags::Exported;
2180b57cec5SDimitry Andric 
2190b57cec5SDimitry Andric         InternedResult[InternedName] =
220*04eeddc0SDimitry Andric             JITEvaluatedSymbol(Sym->getAddress().getValue(), Flags);
221e8d8bef9SDimitry Andric         if (AutoClaim && !MR->getSymbols().count(InternedName)) {
2220b57cec5SDimitry Andric           assert(!ExtraSymbolsToClaim.count(InternedName) &&
2230b57cec5SDimitry Andric                  "Duplicate symbol to claim?");
2240b57cec5SDimitry Andric           ExtraSymbolsToClaim[InternedName] = Flags;
2250b57cec5SDimitry Andric         }
2260b57cec5SDimitry Andric       }
2270b57cec5SDimitry Andric 
2288bcb0991SDimitry Andric     for (auto *Sym : G.absolute_symbols())
2298bcb0991SDimitry Andric       if (Sym->hasName()) {
2308bcb0991SDimitry Andric         auto InternedName = ES.intern(Sym->getName());
2310b57cec5SDimitry Andric         JITSymbolFlags Flags;
2320b57cec5SDimitry Andric         Flags |= JITSymbolFlags::Absolute;
2338bcb0991SDimitry Andric         if (Sym->isCallable())
2340b57cec5SDimitry Andric           Flags |= JITSymbolFlags::Callable;
2358bcb0991SDimitry Andric         if (Sym->getLinkage() == Linkage::Weak)
2368bcb0991SDimitry Andric           Flags |= JITSymbolFlags::Weak;
2370b57cec5SDimitry Andric         InternedResult[InternedName] =
238*04eeddc0SDimitry Andric             JITEvaluatedSymbol(Sym->getAddress().getValue(), Flags);
239e8d8bef9SDimitry Andric         if (AutoClaim && !MR->getSymbols().count(InternedName)) {
2400b57cec5SDimitry Andric           assert(!ExtraSymbolsToClaim.count(InternedName) &&
2410b57cec5SDimitry Andric                  "Duplicate symbol to claim?");
2420b57cec5SDimitry Andric           ExtraSymbolsToClaim[InternedName] = Flags;
2430b57cec5SDimitry Andric         }
2440b57cec5SDimitry Andric       }
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric     if (!ExtraSymbolsToClaim.empty())
247e8d8bef9SDimitry Andric       if (auto Err = MR->defineMaterializing(ExtraSymbolsToClaim))
248e8d8bef9SDimitry Andric         return Err;
2495ffd83dbSDimitry Andric 
2505ffd83dbSDimitry Andric     {
2515ffd83dbSDimitry Andric 
2520eae32dcSDimitry Andric       // Check that InternedResult matches up with MR->getSymbols(), overriding
2530eae32dcSDimitry Andric       // flags if requested.
2545ffd83dbSDimitry Andric       // This guards against faulty transformations / compilers / object caches.
2555ffd83dbSDimitry Andric 
2565ffd83dbSDimitry Andric       // First check that there aren't any missing symbols.
2575ffd83dbSDimitry Andric       size_t NumMaterializationSideEffectsOnlySymbols = 0;
2585ffd83dbSDimitry Andric       SymbolNameVector ExtraSymbols;
2595ffd83dbSDimitry Andric       SymbolNameVector MissingSymbols;
260e8d8bef9SDimitry Andric       for (auto &KV : MR->getSymbols()) {
2615ffd83dbSDimitry Andric 
2620eae32dcSDimitry Andric         auto I = InternedResult.find(KV.first);
2630eae32dcSDimitry Andric 
2645ffd83dbSDimitry Andric         // If this is a materialization-side-effects only symbol then bump
2655ffd83dbSDimitry Andric         // the counter and make sure it's *not* defined, otherwise make
2665ffd83dbSDimitry Andric         // sure that it is defined.
2675ffd83dbSDimitry Andric         if (KV.second.hasMaterializationSideEffectsOnly()) {
2685ffd83dbSDimitry Andric           ++NumMaterializationSideEffectsOnlySymbols;
2690eae32dcSDimitry Andric           if (I != InternedResult.end())
2705ffd83dbSDimitry Andric             ExtraSymbols.push_back(KV.first);
2715ffd83dbSDimitry Andric           continue;
2720eae32dcSDimitry Andric         } else if (I == InternedResult.end())
2735ffd83dbSDimitry Andric           MissingSymbols.push_back(KV.first);
2740eae32dcSDimitry Andric         else if (Layer.OverrideObjectFlags)
2750eae32dcSDimitry Andric           I->second.setFlags(KV.second);
2765ffd83dbSDimitry Andric       }
2775ffd83dbSDimitry Andric 
2785ffd83dbSDimitry Andric       // If there were missing symbols then report the error.
279e8d8bef9SDimitry Andric       if (!MissingSymbols.empty())
280349cc55cSDimitry Andric         return make_error<MissingSymbolDefinitions>(
281349cc55cSDimitry Andric             Layer.getExecutionSession().getSymbolStringPool(), G.getName(),
282e8d8bef9SDimitry Andric             std::move(MissingSymbols));
2835ffd83dbSDimitry Andric 
2845ffd83dbSDimitry Andric       // If there are more definitions than expected, add them to the
2855ffd83dbSDimitry Andric       // ExtraSymbols vector.
2865ffd83dbSDimitry Andric       if (InternedResult.size() >
287e8d8bef9SDimitry Andric           MR->getSymbols().size() - NumMaterializationSideEffectsOnlySymbols) {
2885ffd83dbSDimitry Andric         for (auto &KV : InternedResult)
289e8d8bef9SDimitry Andric           if (!MR->getSymbols().count(KV.first))
2905ffd83dbSDimitry Andric             ExtraSymbols.push_back(KV.first);
2915ffd83dbSDimitry Andric       }
2925ffd83dbSDimitry Andric 
2935ffd83dbSDimitry Andric       // If there were extra definitions then report the error.
294e8d8bef9SDimitry Andric       if (!ExtraSymbols.empty())
295349cc55cSDimitry Andric         return make_error<UnexpectedSymbolDefinitions>(
296349cc55cSDimitry Andric             Layer.getExecutionSession().getSymbolStringPool(), G.getName(),
297e8d8bef9SDimitry Andric             std::move(ExtraSymbols));
2985ffd83dbSDimitry Andric     }
2995ffd83dbSDimitry Andric 
300e8d8bef9SDimitry Andric     if (auto Err = MR->notifyResolved(InternedResult))
301e8d8bef9SDimitry Andric       return Err;
302e8d8bef9SDimitry Andric 
303e8d8bef9SDimitry Andric     Layer.notifyLoaded(*MR);
304e8d8bef9SDimitry Andric     return Error::success();
3050b57cec5SDimitry Andric   }
3060b57cec5SDimitry Andric 
307349cc55cSDimitry Andric   void notifyFinalized(JITLinkMemoryManager::FinalizedAlloc A) override {
308e8d8bef9SDimitry Andric     if (auto Err = Layer.notifyEmitted(*MR, std::move(A))) {
3090b57cec5SDimitry Andric       Layer.getExecutionSession().reportError(std::move(Err));
310e8d8bef9SDimitry Andric       MR->failMaterialization();
3110b57cec5SDimitry Andric       return;
3120b57cec5SDimitry Andric     }
313e8d8bef9SDimitry Andric     if (auto Err = MR->notifyEmitted()) {
3148bcb0991SDimitry Andric       Layer.getExecutionSession().reportError(std::move(Err));
315e8d8bef9SDimitry Andric       MR->failMaterialization();
3168bcb0991SDimitry Andric     }
3170b57cec5SDimitry Andric   }
3180b57cec5SDimitry Andric 
3198bcb0991SDimitry Andric   LinkGraphPassFunction getMarkLivePass(const Triple &TT) const override {
3208bcb0991SDimitry Andric     return [this](LinkGraph &G) { return markResponsibilitySymbolsLive(G); };
3210b57cec5SDimitry Andric   }
3220b57cec5SDimitry Andric 
323fe6060f1SDimitry Andric   Error modifyPassConfig(LinkGraph &LG, PassConfiguration &Config) override {
3240b57cec5SDimitry Andric     // Add passes to mark duplicate defs as should-discard, and to walk the
3258bcb0991SDimitry Andric     // link graph to build the symbol dependence graph.
326e8d8bef9SDimitry Andric     Config.PrePrunePasses.push_back([this](LinkGraph &G) {
327e8d8bef9SDimitry Andric       return claimOrExternalizeWeakAndCommonSymbols(G);
328e8d8bef9SDimitry Andric     });
3290b57cec5SDimitry Andric 
330fe6060f1SDimitry Andric     Layer.modifyPassConfig(*MR, LG, Config);
3310b57cec5SDimitry Andric 
3325ffd83dbSDimitry Andric     Config.PostPrunePasses.push_back(
3335ffd83dbSDimitry Andric         [this](LinkGraph &G) { return computeNamedSymbolDependencies(G); });
3345ffd83dbSDimitry Andric 
3350b57cec5SDimitry Andric     return Error::success();
3360b57cec5SDimitry Andric   }
3370b57cec5SDimitry Andric 
3380b57cec5SDimitry Andric private:
339fe6060f1SDimitry Andric   // Symbol name dependencies:
340fe6060f1SDimitry Andric   // Internal: Defined in this graph.
341fe6060f1SDimitry Andric   // External: Defined externally.
342fe6060f1SDimitry Andric   struct BlockSymbolDependencies {
3435ffd83dbSDimitry Andric     SymbolNameSet Internal, External;
3445ffd83dbSDimitry Andric   };
3455ffd83dbSDimitry Andric 
346fe6060f1SDimitry Andric   // Lazily populated map of blocks to BlockSymbolDependencies values.
347fe6060f1SDimitry Andric   class BlockDependenciesMap {
348fe6060f1SDimitry Andric   public:
349fe6060f1SDimitry Andric     BlockDependenciesMap(ExecutionSession &ES,
350fe6060f1SDimitry Andric                          DenseMap<const Block *, DenseSet<Block *>> BlockDeps)
351fe6060f1SDimitry Andric         : ES(ES), BlockDeps(std::move(BlockDeps)) {}
352fe6060f1SDimitry Andric 
353fe6060f1SDimitry Andric     const BlockSymbolDependencies &operator[](const Block &B) {
354fe6060f1SDimitry Andric       // Check the cache first.
355fe6060f1SDimitry Andric       auto I = BlockTransitiveDepsCache.find(&B);
356fe6060f1SDimitry Andric       if (I != BlockTransitiveDepsCache.end())
357fe6060f1SDimitry Andric         return I->second;
358fe6060f1SDimitry Andric 
359fe6060f1SDimitry Andric       // No value. Populate the cache.
360fe6060f1SDimitry Andric       BlockSymbolDependencies BTDCacheVal;
361fe6060f1SDimitry Andric       auto BDI = BlockDeps.find(&B);
362fe6060f1SDimitry Andric       assert(BDI != BlockDeps.end() && "No block dependencies");
363fe6060f1SDimitry Andric 
364fe6060f1SDimitry Andric       for (auto *BDep : BDI->second) {
365fe6060f1SDimitry Andric         auto &BID = getBlockImmediateDeps(*BDep);
366fe6060f1SDimitry Andric         for (auto &ExternalDep : BID.External)
367fe6060f1SDimitry Andric           BTDCacheVal.External.insert(ExternalDep);
368fe6060f1SDimitry Andric         for (auto &InternalDep : BID.Internal)
369fe6060f1SDimitry Andric           BTDCacheVal.Internal.insert(InternalDep);
370fe6060f1SDimitry Andric       }
371fe6060f1SDimitry Andric 
372fe6060f1SDimitry Andric       return BlockTransitiveDepsCache
373fe6060f1SDimitry Andric           .insert(std::make_pair(&B, std::move(BTDCacheVal)))
374fe6060f1SDimitry Andric           .first->second;
375fe6060f1SDimitry Andric     }
376fe6060f1SDimitry Andric 
377fe6060f1SDimitry Andric     SymbolStringPtr &getInternedName(Symbol &Sym) {
378fe6060f1SDimitry Andric       auto I = NameCache.find(&Sym);
379fe6060f1SDimitry Andric       if (I != NameCache.end())
380fe6060f1SDimitry Andric         return I->second;
381fe6060f1SDimitry Andric 
382fe6060f1SDimitry Andric       return NameCache.insert(std::make_pair(&Sym, ES.intern(Sym.getName())))
383fe6060f1SDimitry Andric           .first->second;
384fe6060f1SDimitry Andric     }
385fe6060f1SDimitry Andric 
386fe6060f1SDimitry Andric   private:
387fe6060f1SDimitry Andric     BlockSymbolDependencies &getBlockImmediateDeps(Block &B) {
388fe6060f1SDimitry Andric       // Check the cache first.
389fe6060f1SDimitry Andric       auto I = BlockImmediateDepsCache.find(&B);
390fe6060f1SDimitry Andric       if (I != BlockImmediateDepsCache.end())
391fe6060f1SDimitry Andric         return I->second;
392fe6060f1SDimitry Andric 
393fe6060f1SDimitry Andric       BlockSymbolDependencies BIDCacheVal;
394fe6060f1SDimitry Andric       for (auto &E : B.edges()) {
395fe6060f1SDimitry Andric         auto &Tgt = E.getTarget();
396fe6060f1SDimitry Andric         if (Tgt.getScope() != Scope::Local) {
397fe6060f1SDimitry Andric           if (Tgt.isExternal())
398fe6060f1SDimitry Andric             BIDCacheVal.External.insert(getInternedName(Tgt));
399fe6060f1SDimitry Andric           else
400fe6060f1SDimitry Andric             BIDCacheVal.Internal.insert(getInternedName(Tgt));
401fe6060f1SDimitry Andric         }
402fe6060f1SDimitry Andric       }
403fe6060f1SDimitry Andric 
404fe6060f1SDimitry Andric       return BlockImmediateDepsCache
405fe6060f1SDimitry Andric           .insert(std::make_pair(&B, std::move(BIDCacheVal)))
406fe6060f1SDimitry Andric           .first->second;
407fe6060f1SDimitry Andric     }
408fe6060f1SDimitry Andric 
409fe6060f1SDimitry Andric     ExecutionSession &ES;
410fe6060f1SDimitry Andric     DenseMap<const Block *, DenseSet<Block *>> BlockDeps;
411fe6060f1SDimitry Andric     DenseMap<const Symbol *, SymbolStringPtr> NameCache;
412fe6060f1SDimitry Andric     DenseMap<const Block *, BlockSymbolDependencies> BlockImmediateDepsCache;
413fe6060f1SDimitry Andric     DenseMap<const Block *, BlockSymbolDependencies> BlockTransitiveDepsCache;
414fe6060f1SDimitry Andric   };
4150b57cec5SDimitry Andric 
416e8d8bef9SDimitry Andric   Error claimOrExternalizeWeakAndCommonSymbols(LinkGraph &G) {
4170b57cec5SDimitry Andric     auto &ES = Layer.getExecutionSession();
4180b57cec5SDimitry Andric 
419e8d8bef9SDimitry Andric     SymbolFlagsMap NewSymbolsToClaim;
420e8d8bef9SDimitry Andric     std::vector<std::pair<SymbolStringPtr, Symbol *>> NameToSym;
421e8d8bef9SDimitry Andric 
422e8d8bef9SDimitry Andric     auto ProcessSymbol = [&](Symbol *Sym) {
423349cc55cSDimitry Andric       if (Sym->hasName() && Sym->getLinkage() == Linkage::Weak &&
424349cc55cSDimitry Andric           Sym->getScope() != Scope::Local) {
425e8d8bef9SDimitry Andric         auto Name = ES.intern(Sym->getName());
426e8d8bef9SDimitry Andric         if (!MR->getSymbols().count(ES.intern(Sym->getName()))) {
427e8d8bef9SDimitry Andric           JITSymbolFlags SF = JITSymbolFlags::Weak;
428e8d8bef9SDimitry Andric           if (Sym->getScope() == Scope::Default)
429e8d8bef9SDimitry Andric             SF |= JITSymbolFlags::Exported;
430e8d8bef9SDimitry Andric           NewSymbolsToClaim[Name] = SF;
431e8d8bef9SDimitry Andric           NameToSym.push_back(std::make_pair(std::move(Name), Sym));
4320b57cec5SDimitry Andric         }
433e8d8bef9SDimitry Andric       }
434e8d8bef9SDimitry Andric     };
435e8d8bef9SDimitry Andric 
436e8d8bef9SDimitry Andric     for (auto *Sym : G.defined_symbols())
437e8d8bef9SDimitry Andric       ProcessSymbol(Sym);
438e8d8bef9SDimitry Andric     for (auto *Sym : G.absolute_symbols())
439e8d8bef9SDimitry Andric       ProcessSymbol(Sym);
440e8d8bef9SDimitry Andric 
441e8d8bef9SDimitry Andric     // Attempt to claim all weak defs that we're not already responsible for.
442e8d8bef9SDimitry Andric     // This cannot fail -- any clashes will just result in rejection of our
443e8d8bef9SDimitry Andric     // claim, at which point we'll externalize that symbol.
444e8d8bef9SDimitry Andric     cantFail(MR->defineMaterializing(std::move(NewSymbolsToClaim)));
445e8d8bef9SDimitry Andric 
446e8d8bef9SDimitry Andric     for (auto &KV : NameToSym)
447e8d8bef9SDimitry Andric       if (!MR->getSymbols().count(KV.first))
448e8d8bef9SDimitry Andric         G.makeExternal(*KV.second);
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric     return Error::success();
4510b57cec5SDimitry Andric   }
4520b57cec5SDimitry Andric 
4538bcb0991SDimitry Andric   Error markResponsibilitySymbolsLive(LinkGraph &G) const {
4540b57cec5SDimitry Andric     auto &ES = Layer.getExecutionSession();
4558bcb0991SDimitry Andric     for (auto *Sym : G.defined_symbols())
456e8d8bef9SDimitry Andric       if (Sym->hasName() && MR->getSymbols().count(ES.intern(Sym->getName())))
4578bcb0991SDimitry Andric         Sym->setLive(true);
4580b57cec5SDimitry Andric     return Error::success();
4590b57cec5SDimitry Andric   }
4600b57cec5SDimitry Andric 
4618bcb0991SDimitry Andric   Error computeNamedSymbolDependencies(LinkGraph &G) {
462e8d8bef9SDimitry Andric     auto &ES = MR->getTargetJITDylib().getExecutionSession();
463fe6060f1SDimitry Andric     auto BlockDeps = computeBlockNonLocalDeps(G);
4640b57cec5SDimitry Andric 
4655ffd83dbSDimitry Andric     // Compute dependencies for symbols defined in the JITLink graph.
4668bcb0991SDimitry Andric     for (auto *Sym : G.defined_symbols()) {
4670b57cec5SDimitry Andric 
4685ffd83dbSDimitry Andric       // Skip local symbols: we do not track dependencies for these.
4698bcb0991SDimitry Andric       if (Sym->getScope() == Scope::Local)
4700b57cec5SDimitry Andric         continue;
4715ffd83dbSDimitry Andric       assert(Sym->hasName() &&
4725ffd83dbSDimitry Andric              "Defined non-local jitlink::Symbol should have a name");
4730b57cec5SDimitry Andric 
474fe6060f1SDimitry Andric       auto &SymDeps = BlockDeps[Sym->getBlock()];
475fe6060f1SDimitry Andric       if (SymDeps.External.empty() && SymDeps.Internal.empty())
4765ffd83dbSDimitry Andric         continue;
4775ffd83dbSDimitry Andric 
4785ffd83dbSDimitry Andric       auto SymName = ES.intern(Sym->getName());
479fe6060f1SDimitry Andric       if (!SymDeps.External.empty())
480fe6060f1SDimitry Andric         ExternalNamedSymbolDeps[SymName] = SymDeps.External;
481fe6060f1SDimitry Andric       if (!SymDeps.Internal.empty())
482fe6060f1SDimitry Andric         InternalNamedSymbolDeps[SymName] = SymDeps.Internal;
4835ffd83dbSDimitry Andric     }
4845ffd83dbSDimitry Andric 
4855ffd83dbSDimitry Andric     for (auto &P : Layer.Plugins) {
486fe6060f1SDimitry Andric       auto SynthDeps = P->getSyntheticSymbolDependencies(*MR);
487fe6060f1SDimitry Andric       if (SynthDeps.empty())
4885ffd83dbSDimitry Andric         continue;
4895ffd83dbSDimitry Andric 
490fe6060f1SDimitry Andric       DenseSet<Block *> BlockVisited;
491fe6060f1SDimitry Andric       for (auto &KV : SynthDeps) {
4925ffd83dbSDimitry Andric         auto &Name = KV.first;
493fe6060f1SDimitry Andric         auto &DepsForName = KV.second;
494fe6060f1SDimitry Andric         for (auto *Sym : DepsForName) {
495fe6060f1SDimitry Andric           if (Sym->getScope() == Scope::Local) {
496fe6060f1SDimitry Andric             auto &BDeps = BlockDeps[Sym->getBlock()];
497fe6060f1SDimitry Andric             for (auto &S : BDeps.Internal)
4985ffd83dbSDimitry Andric               InternalNamedSymbolDeps[Name].insert(S);
499fe6060f1SDimitry Andric             for (auto &S : BDeps.External)
5005ffd83dbSDimitry Andric               ExternalNamedSymbolDeps[Name].insert(S);
501fe6060f1SDimitry Andric           } else {
502fe6060f1SDimitry Andric             if (Sym->isExternal())
503fe6060f1SDimitry Andric               ExternalNamedSymbolDeps[Name].insert(
504fe6060f1SDimitry Andric                   BlockDeps.getInternedName(*Sym));
505fe6060f1SDimitry Andric             else
506fe6060f1SDimitry Andric               InternalNamedSymbolDeps[Name].insert(
507fe6060f1SDimitry Andric                   BlockDeps.getInternedName(*Sym));
508fe6060f1SDimitry Andric           }
5090b57cec5SDimitry Andric         }
5100b57cec5SDimitry Andric       }
5110b57cec5SDimitry Andric     }
5120b57cec5SDimitry Andric 
5130b57cec5SDimitry Andric     return Error::success();
5140b57cec5SDimitry Andric   }
5150b57cec5SDimitry Andric 
516fe6060f1SDimitry Andric   BlockDependenciesMap computeBlockNonLocalDeps(LinkGraph &G) {
517fe6060f1SDimitry Andric     // First calculate the reachable-via-non-local-symbol blocks for each block.
518fe6060f1SDimitry Andric     struct BlockInfo {
519fe6060f1SDimitry Andric       DenseSet<Block *> Dependencies;
520fe6060f1SDimitry Andric       DenseSet<Block *> Dependants;
521fe6060f1SDimitry Andric       bool DependenciesChanged = true;
5220b57cec5SDimitry Andric     };
523fe6060f1SDimitry Andric     DenseMap<Block *, BlockInfo> BlockInfos;
524fe6060f1SDimitry Andric     SmallVector<Block *> WorkList;
5250b57cec5SDimitry Andric 
526fe6060f1SDimitry Andric     // Pre-allocate map entries. This prevents any iterator/reference
527fe6060f1SDimitry Andric     // invalidation in the next loop.
528fe6060f1SDimitry Andric     for (auto *B : G.blocks())
529fe6060f1SDimitry Andric       (void)BlockInfos[B];
530fe6060f1SDimitry Andric 
531fe6060f1SDimitry Andric     // Build initial worklist, record block dependencies/dependants and
532fe6060f1SDimitry Andric     // non-local symbol dependencies.
533fe6060f1SDimitry Andric     for (auto *B : G.blocks()) {
534fe6060f1SDimitry Andric       auto &BI = BlockInfos[B];
535fe6060f1SDimitry Andric       for (auto &E : B->edges()) {
536fe6060f1SDimitry Andric         if (E.getTarget().getScope() == Scope::Local) {
537fe6060f1SDimitry Andric           auto &TgtB = E.getTarget().getBlock();
538fe6060f1SDimitry Andric           if (&TgtB != B) {
539fe6060f1SDimitry Andric             BI.Dependencies.insert(&TgtB);
540fe6060f1SDimitry Andric             BlockInfos[&TgtB].Dependants.insert(B);
541fe6060f1SDimitry Andric           }
5420b57cec5SDimitry Andric         }
5430b57cec5SDimitry Andric       }
5440b57cec5SDimitry Andric 
545fe6060f1SDimitry Andric       // If this node has both dependants and dependencies then add it to the
546fe6060f1SDimitry Andric       // worklist to propagate the dependencies to the dependants.
547fe6060f1SDimitry Andric       if (!BI.Dependants.empty() && !BI.Dependencies.empty())
548fe6060f1SDimitry Andric         WorkList.push_back(B);
5490b57cec5SDimitry Andric     }
5500b57cec5SDimitry Andric 
551fe6060f1SDimitry Andric     // Propagate block-level dependencies through the block-dependence graph.
552fe6060f1SDimitry Andric     while (!WorkList.empty()) {
553349cc55cSDimitry Andric       auto *B = WorkList.pop_back_val();
5540b57cec5SDimitry Andric 
555fe6060f1SDimitry Andric       auto &BI = BlockInfos[B];
556fe6060f1SDimitry Andric       assert(BI.DependenciesChanged &&
557fe6060f1SDimitry Andric              "Block in worklist has unchanged dependencies");
558fe6060f1SDimitry Andric       BI.DependenciesChanged = false;
559fe6060f1SDimitry Andric       for (auto *Dependant : BI.Dependants) {
560fe6060f1SDimitry Andric         auto &DependantBI = BlockInfos[Dependant];
561fe6060f1SDimitry Andric         for (auto *Dependency : BI.Dependencies) {
562fe6060f1SDimitry Andric           if (Dependant != Dependency &&
563fe6060f1SDimitry Andric               DependantBI.Dependencies.insert(Dependency).second)
564fe6060f1SDimitry Andric             if (!DependantBI.DependenciesChanged) {
565fe6060f1SDimitry Andric               DependantBI.DependenciesChanged = true;
566fe6060f1SDimitry Andric               WorkList.push_back(Dependant);
5670b57cec5SDimitry Andric             }
5680b57cec5SDimitry Andric         }
5695ffd83dbSDimitry Andric       }
5705ffd83dbSDimitry Andric     }
5715ffd83dbSDimitry Andric 
572fe6060f1SDimitry Andric     DenseMap<const Block *, DenseSet<Block *>> BlockDeps;
573fe6060f1SDimitry Andric     for (auto &KV : BlockInfos)
574fe6060f1SDimitry Andric       BlockDeps[KV.first] = std::move(KV.second.Dependencies);
575fe6060f1SDimitry Andric 
576fe6060f1SDimitry Andric     return BlockDependenciesMap(Layer.getExecutionSession(),
577fe6060f1SDimitry Andric                                 std::move(BlockDeps));
5780b57cec5SDimitry Andric   }
5790b57cec5SDimitry Andric 
5800b57cec5SDimitry Andric   void registerDependencies(const SymbolDependenceMap &QueryDeps) {
5815ffd83dbSDimitry Andric     for (auto &NamedDepsEntry : ExternalNamedSymbolDeps) {
5820b57cec5SDimitry Andric       auto &Name = NamedDepsEntry.first;
5830b57cec5SDimitry Andric       auto &NameDeps = NamedDepsEntry.second;
5840b57cec5SDimitry Andric       SymbolDependenceMap SymbolDeps;
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric       for (const auto &QueryDepsEntry : QueryDeps) {
5870b57cec5SDimitry Andric         JITDylib &SourceJD = *QueryDepsEntry.first;
5880b57cec5SDimitry Andric         const SymbolNameSet &Symbols = QueryDepsEntry.second;
5890b57cec5SDimitry Andric         auto &DepsForJD = SymbolDeps[&SourceJD];
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric         for (const auto &S : Symbols)
5920b57cec5SDimitry Andric           if (NameDeps.count(S))
5930b57cec5SDimitry Andric             DepsForJD.insert(S);
5940b57cec5SDimitry Andric 
5950b57cec5SDimitry Andric         if (DepsForJD.empty())
5960b57cec5SDimitry Andric           SymbolDeps.erase(&SourceJD);
5970b57cec5SDimitry Andric       }
5980b57cec5SDimitry Andric 
599e8d8bef9SDimitry Andric       MR->addDependencies(Name, SymbolDeps);
6000b57cec5SDimitry Andric     }
6010b57cec5SDimitry Andric   }
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric   ObjectLinkingLayer &Layer;
604e8d8bef9SDimitry Andric   std::unique_ptr<MaterializationResponsibility> MR;
6050b57cec5SDimitry Andric   std::unique_ptr<MemoryBuffer> ObjBuffer;
6065ffd83dbSDimitry Andric   DenseMap<SymbolStringPtr, SymbolNameSet> ExternalNamedSymbolDeps;
6075ffd83dbSDimitry Andric   DenseMap<SymbolStringPtr, SymbolNameSet> InternalNamedSymbolDeps;
6080b57cec5SDimitry Andric };
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric ObjectLinkingLayer::Plugin::~Plugin() {}
6110b57cec5SDimitry Andric 
612fe6060f1SDimitry Andric char ObjectLinkingLayer::ID;
613fe6060f1SDimitry Andric 
614fe6060f1SDimitry Andric using BaseT = RTTIExtends<ObjectLinkingLayer, ObjectLayer>;
615fe6060f1SDimitry Andric 
616fe6060f1SDimitry Andric ObjectLinkingLayer::ObjectLinkingLayer(ExecutionSession &ES)
617fe6060f1SDimitry Andric     : BaseT(ES), MemMgr(ES.getExecutorProcessControl().getMemMgr()) {
618fe6060f1SDimitry Andric   ES.registerResourceManager(*this);
619fe6060f1SDimitry Andric }
620fe6060f1SDimitry Andric 
621e8d8bef9SDimitry Andric ObjectLinkingLayer::ObjectLinkingLayer(ExecutionSession &ES,
622e8d8bef9SDimitry Andric                                        JITLinkMemoryManager &MemMgr)
623fe6060f1SDimitry Andric     : BaseT(ES), MemMgr(MemMgr) {
624e8d8bef9SDimitry Andric   ES.registerResourceManager(*this);
6250b57cec5SDimitry Andric }
6260b57cec5SDimitry Andric 
627e8d8bef9SDimitry Andric ObjectLinkingLayer::ObjectLinkingLayer(
628e8d8bef9SDimitry Andric     ExecutionSession &ES, std::unique_ptr<JITLinkMemoryManager> MemMgr)
629fe6060f1SDimitry Andric     : BaseT(ES), MemMgr(*MemMgr), MemMgrOwnership(std::move(MemMgr)) {
630e8d8bef9SDimitry Andric   ES.registerResourceManager(*this);
631e8d8bef9SDimitry Andric }
632e8d8bef9SDimitry Andric 
633e8d8bef9SDimitry Andric ObjectLinkingLayer::~ObjectLinkingLayer() {
634e8d8bef9SDimitry Andric   assert(Allocs.empty() && "Layer destroyed with resources still attached");
635e8d8bef9SDimitry Andric   getExecutionSession().deregisterResourceManager(*this);
636e8d8bef9SDimitry Andric }
637e8d8bef9SDimitry Andric 
638fe6060f1SDimitry Andric Error ObjectLinkingLayer::add(ResourceTrackerSP RT,
639fe6060f1SDimitry Andric                               std::unique_ptr<LinkGraph> G) {
640fe6060f1SDimitry Andric   auto &JD = RT->getJITDylib();
641fe6060f1SDimitry Andric   return JD.define(LinkGraphMaterializationUnit::Create(*this, std::move(G)),
642fe6060f1SDimitry Andric                    std::move(RT));
643fe6060f1SDimitry Andric }
644fe6060f1SDimitry Andric 
645e8d8bef9SDimitry Andric void ObjectLinkingLayer::emit(std::unique_ptr<MaterializationResponsibility> R,
6460b57cec5SDimitry Andric                               std::unique_ptr<MemoryBuffer> O) {
6470b57cec5SDimitry Andric   assert(O && "Object must not be null");
648fe6060f1SDimitry Andric   MemoryBufferRef ObjBuffer = O->getMemBufferRef();
649fe6060f1SDimitry Andric 
650e8d8bef9SDimitry Andric   auto Ctx = std::make_unique<ObjectLinkingLayerJITLinkContext>(
651e8d8bef9SDimitry Andric       *this, std::move(R), std::move(O));
652fe6060f1SDimitry Andric   if (auto G = createLinkGraphFromObject(ObjBuffer)) {
653fe6060f1SDimitry Andric     Ctx->notifyMaterializing(**G);
654e8d8bef9SDimitry Andric     link(std::move(*G), std::move(Ctx));
655fe6060f1SDimitry Andric   } else {
656e8d8bef9SDimitry Andric     Ctx->notifyFailed(G.takeError());
657e8d8bef9SDimitry Andric   }
658fe6060f1SDimitry Andric }
659e8d8bef9SDimitry Andric 
660e8d8bef9SDimitry Andric void ObjectLinkingLayer::emit(std::unique_ptr<MaterializationResponsibility> R,
661e8d8bef9SDimitry Andric                               std::unique_ptr<LinkGraph> G) {
662fe6060f1SDimitry Andric   auto Ctx = std::make_unique<ObjectLinkingLayerJITLinkContext>(
663fe6060f1SDimitry Andric       *this, std::move(R), nullptr);
664fe6060f1SDimitry Andric   Ctx->notifyMaterializing(*G);
665fe6060f1SDimitry Andric   link(std::move(G), std::move(Ctx));
6660b57cec5SDimitry Andric }
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric void ObjectLinkingLayer::modifyPassConfig(MaterializationResponsibility &MR,
669fe6060f1SDimitry Andric                                           LinkGraph &G,
6700b57cec5SDimitry Andric                                           PassConfiguration &PassConfig) {
6710b57cec5SDimitry Andric   for (auto &P : Plugins)
672fe6060f1SDimitry Andric     P->modifyPassConfig(MR, G, PassConfig);
6730b57cec5SDimitry Andric }
6740b57cec5SDimitry Andric 
6750b57cec5SDimitry Andric void ObjectLinkingLayer::notifyLoaded(MaterializationResponsibility &MR) {
6760b57cec5SDimitry Andric   for (auto &P : Plugins)
6770b57cec5SDimitry Andric     P->notifyLoaded(MR);
6780b57cec5SDimitry Andric }
6790b57cec5SDimitry Andric 
6800b57cec5SDimitry Andric Error ObjectLinkingLayer::notifyEmitted(MaterializationResponsibility &MR,
681349cc55cSDimitry Andric                                         FinalizedAlloc FA) {
6820b57cec5SDimitry Andric   Error Err = Error::success();
6830b57cec5SDimitry Andric   for (auto &P : Plugins)
6840b57cec5SDimitry Andric     Err = joinErrors(std::move(Err), P->notifyEmitted(MR));
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric   if (Err)
6870b57cec5SDimitry Andric     return Err;
6880b57cec5SDimitry Andric 
689e8d8bef9SDimitry Andric   return MR.withResourceKeyDo(
690349cc55cSDimitry Andric       [&](ResourceKey K) { Allocs[K].push_back(std::move(FA)); });
6910b57cec5SDimitry Andric }
6920b57cec5SDimitry Andric 
693e8d8bef9SDimitry Andric Error ObjectLinkingLayer::handleRemoveResources(ResourceKey K) {
6940b57cec5SDimitry Andric 
695349cc55cSDimitry Andric   {
6960b57cec5SDimitry Andric     Error Err = Error::success();
6970b57cec5SDimitry Andric     for (auto &P : Plugins)
698e8d8bef9SDimitry Andric       Err = joinErrors(std::move(Err), P->notifyRemovingResources(K));
699349cc55cSDimitry Andric     if (Err)
700349cc55cSDimitry Andric       return Err;
701349cc55cSDimitry Andric   }
7020b57cec5SDimitry Andric 
703349cc55cSDimitry Andric   std::vector<FinalizedAlloc> AllocsToRemove;
704e8d8bef9SDimitry Andric   getExecutionSession().runSessionLocked([&] {
705e8d8bef9SDimitry Andric     auto I = Allocs.find(K);
706e8d8bef9SDimitry Andric     if (I != Allocs.end()) {
707e8d8bef9SDimitry Andric       std::swap(AllocsToRemove, I->second);
708e8d8bef9SDimitry Andric       Allocs.erase(I);
7090b57cec5SDimitry Andric     }
710e8d8bef9SDimitry Andric   });
7110b57cec5SDimitry Andric 
712349cc55cSDimitry Andric   if (AllocsToRemove.empty())
713349cc55cSDimitry Andric     return Error::success();
7140b57cec5SDimitry Andric 
715349cc55cSDimitry Andric   return MemMgr.deallocate(std::move(AllocsToRemove));
7160b57cec5SDimitry Andric }
7170b57cec5SDimitry Andric 
718e8d8bef9SDimitry Andric void ObjectLinkingLayer::handleTransferResources(ResourceKey DstKey,
719e8d8bef9SDimitry Andric                                                  ResourceKey SrcKey) {
720e8d8bef9SDimitry Andric   auto I = Allocs.find(SrcKey);
721e8d8bef9SDimitry Andric   if (I != Allocs.end()) {
722e8d8bef9SDimitry Andric     auto &SrcAllocs = I->second;
723e8d8bef9SDimitry Andric     auto &DstAllocs = Allocs[DstKey];
724e8d8bef9SDimitry Andric     DstAllocs.reserve(DstAllocs.size() + SrcAllocs.size());
725e8d8bef9SDimitry Andric     for (auto &Alloc : SrcAllocs)
726e8d8bef9SDimitry Andric       DstAllocs.push_back(std::move(Alloc));
727e8d8bef9SDimitry Andric 
728e8d8bef9SDimitry Andric     // Erase SrcKey entry using value rather than iterator I: I may have been
729e8d8bef9SDimitry Andric     // invalidated when we looked up DstKey.
730e8d8bef9SDimitry Andric     Allocs.erase(SrcKey);
731e8d8bef9SDimitry Andric   }
732e8d8bef9SDimitry Andric 
733e8d8bef9SDimitry Andric   for (auto &P : Plugins)
734e8d8bef9SDimitry Andric     P->notifyTransferringResources(DstKey, SrcKey);
735e8d8bef9SDimitry Andric }
736e8d8bef9SDimitry Andric 
7370b57cec5SDimitry Andric EHFrameRegistrationPlugin::EHFrameRegistrationPlugin(
738e8d8bef9SDimitry Andric     ExecutionSession &ES, std::unique_ptr<EHFrameRegistrar> Registrar)
739e8d8bef9SDimitry Andric     : ES(ES), Registrar(std::move(Registrar)) {}
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric void EHFrameRegistrationPlugin::modifyPassConfig(
742fe6060f1SDimitry Andric     MaterializationResponsibility &MR, LinkGraph &G,
7430b57cec5SDimitry Andric     PassConfiguration &PassConfig) {
7440b57cec5SDimitry Andric 
7455ffd83dbSDimitry Andric   PassConfig.PostFixupPasses.push_back(createEHFrameRecorderPass(
746*04eeddc0SDimitry Andric       G.getTargetTriple(), [this, &MR](ExecutorAddr Addr, size_t Size) {
7475ffd83dbSDimitry Andric         if (Addr) {
7485ffd83dbSDimitry Andric           std::lock_guard<std::mutex> Lock(EHFramePluginMutex);
7495ffd83dbSDimitry Andric           assert(!InProcessLinks.count(&MR) &&
7505ffd83dbSDimitry Andric                  "Link for MR already being tracked?");
7518bcb0991SDimitry Andric           InProcessLinks[&MR] = {Addr, Size};
7525ffd83dbSDimitry Andric         }
7530b57cec5SDimitry Andric       }));
7540b57cec5SDimitry Andric }
7550b57cec5SDimitry Andric 
7560b57cec5SDimitry Andric Error EHFrameRegistrationPlugin::notifyEmitted(
7570b57cec5SDimitry Andric     MaterializationResponsibility &MR) {
758e8d8bef9SDimitry Andric 
759*04eeddc0SDimitry Andric   ExecutorAddrRange EmittedRange;
760e8d8bef9SDimitry Andric   {
7615ffd83dbSDimitry Andric     std::lock_guard<std::mutex> Lock(EHFramePluginMutex);
7620b57cec5SDimitry Andric 
7638bcb0991SDimitry Andric     auto EHFrameRangeItr = InProcessLinks.find(&MR);
7648bcb0991SDimitry Andric     if (EHFrameRangeItr == InProcessLinks.end())
7650b57cec5SDimitry Andric       return Error::success();
7660b57cec5SDimitry Andric 
767e8d8bef9SDimitry Andric     EmittedRange = EHFrameRangeItr->second;
768*04eeddc0SDimitry Andric     assert(EmittedRange.Start && "eh-frame addr to register can not be null");
7698bcb0991SDimitry Andric     InProcessLinks.erase(EHFrameRangeItr);
7700b57cec5SDimitry Andric   }
7710b57cec5SDimitry Andric 
772e8d8bef9SDimitry Andric   if (auto Err = MR.withResourceKeyDo(
773e8d8bef9SDimitry Andric           [&](ResourceKey K) { EHFrameRanges[K].push_back(EmittedRange); }))
774e8d8bef9SDimitry Andric     return Err;
7755ffd83dbSDimitry Andric 
776*04eeddc0SDimitry Andric   return Registrar->registerEHFrames(EmittedRange);
777e8d8bef9SDimitry Andric }
778e8d8bef9SDimitry Andric 
779e8d8bef9SDimitry Andric Error EHFrameRegistrationPlugin::notifyFailed(
780e8d8bef9SDimitry Andric     MaterializationResponsibility &MR) {
781e8d8bef9SDimitry Andric   std::lock_guard<std::mutex> Lock(EHFramePluginMutex);
782e8d8bef9SDimitry Andric   InProcessLinks.erase(&MR);
7830b57cec5SDimitry Andric   return Error::success();
7840b57cec5SDimitry Andric }
7850b57cec5SDimitry Andric 
786e8d8bef9SDimitry Andric Error EHFrameRegistrationPlugin::notifyRemovingResources(ResourceKey K) {
787*04eeddc0SDimitry Andric   std::vector<ExecutorAddrRange> RangesToRemove;
7880b57cec5SDimitry Andric 
789e8d8bef9SDimitry Andric   ES.runSessionLocked([&] {
790e8d8bef9SDimitry Andric     auto I = EHFrameRanges.find(K);
791e8d8bef9SDimitry Andric     if (I != EHFrameRanges.end()) {
792e8d8bef9SDimitry Andric       RangesToRemove = std::move(I->second);
793e8d8bef9SDimitry Andric       EHFrameRanges.erase(I);
794e8d8bef9SDimitry Andric     }
795e8d8bef9SDimitry Andric   });
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric   Error Err = Error::success();
798e8d8bef9SDimitry Andric   while (!RangesToRemove.empty()) {
799e8d8bef9SDimitry Andric     auto RangeToRemove = RangesToRemove.back();
800e8d8bef9SDimitry Andric     RangesToRemove.pop_back();
801*04eeddc0SDimitry Andric     assert(RangeToRemove.Start && "Untracked eh-frame range must not be null");
802*04eeddc0SDimitry Andric     Err = joinErrors(std::move(Err),
803*04eeddc0SDimitry Andric                      Registrar->deregisterEHFrames(RangeToRemove));
8040b57cec5SDimitry Andric   }
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric   return Err;
8070b57cec5SDimitry Andric }
8080b57cec5SDimitry Andric 
809e8d8bef9SDimitry Andric void EHFrameRegistrationPlugin::notifyTransferringResources(
810e8d8bef9SDimitry Andric     ResourceKey DstKey, ResourceKey SrcKey) {
811e8d8bef9SDimitry Andric   auto SI = EHFrameRanges.find(SrcKey);
812fe6060f1SDimitry Andric   if (SI == EHFrameRanges.end())
813fe6060f1SDimitry Andric     return;
814fe6060f1SDimitry Andric 
815fe6060f1SDimitry Andric   auto DI = EHFrameRanges.find(DstKey);
816fe6060f1SDimitry Andric   if (DI != EHFrameRanges.end()) {
817e8d8bef9SDimitry Andric     auto &SrcRanges = SI->second;
818fe6060f1SDimitry Andric     auto &DstRanges = DI->second;
819e8d8bef9SDimitry Andric     DstRanges.reserve(DstRanges.size() + SrcRanges.size());
820e8d8bef9SDimitry Andric     for (auto &SrcRange : SrcRanges)
821e8d8bef9SDimitry Andric       DstRanges.push_back(std::move(SrcRange));
822e8d8bef9SDimitry Andric     EHFrameRanges.erase(SI);
823fe6060f1SDimitry Andric   } else {
824fe6060f1SDimitry Andric     // We need to move SrcKey's ranges over without invalidating the SI
825fe6060f1SDimitry Andric     // iterator.
826fe6060f1SDimitry Andric     auto Tmp = std::move(SI->second);
827fe6060f1SDimitry Andric     EHFrameRanges.erase(SI);
828fe6060f1SDimitry Andric     EHFrameRanges[DstKey] = std::move(Tmp);
829e8d8bef9SDimitry Andric   }
830e8d8bef9SDimitry Andric }
831e8d8bef9SDimitry Andric 
8320b57cec5SDimitry Andric } // End namespace orc.
8330b57cec5SDimitry Andric } // End namespace llvm.
834