xref: /freebsd/contrib/llvm-project/llvm/lib/ExecutionEngine/Orc/ObjectLinkingLayer.cpp (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
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/ExecutionEngine/JITLink/EHFrameSupport.h"
11fe6060f1SDimitry Andric #include "llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h"
12*bdd1243dSDimitry Andric #include "llvm/ExecutionEngine/Orc/ObjectFileInterface.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 
61*bdd1243dSDimitry Andric     if (hasInitializerSection(G))
62fe6060f1SDimitry Andric       LGI.InitSymbol = makeInitSymbol(ES, G);
63fe6060f1SDimitry Andric 
64fe6060f1SDimitry Andric     return LGI;
65fe6060f1SDimitry Andric   }
66fe6060f1SDimitry Andric 
67fe6060f1SDimitry Andric   static SymbolStringPtr makeInitSymbol(ExecutionSession &ES, LinkGraph &G) {
68fe6060f1SDimitry Andric     std::string InitSymString;
69fe6060f1SDimitry Andric     raw_string_ostream(InitSymString)
70fe6060f1SDimitry Andric         << "$." << G.getName() << ".__inits" << Counter++;
71fe6060f1SDimitry Andric     return ES.intern(InitSymString);
72fe6060f1SDimitry Andric   }
73fe6060f1SDimitry Andric 
74fe6060f1SDimitry Andric   LinkGraphMaterializationUnit(ObjectLinkingLayer &ObjLinkingLayer,
750eae32dcSDimitry Andric                                std::unique_ptr<LinkGraph> G, Interface LGI)
760eae32dcSDimitry Andric       : MaterializationUnit(std::move(LGI)), ObjLinkingLayer(ObjLinkingLayer),
770eae32dcSDimitry Andric         G(std::move(G)) {}
78fe6060f1SDimitry Andric 
79fe6060f1SDimitry Andric   void discard(const JITDylib &JD, const SymbolStringPtr &Name) override {
80fe6060f1SDimitry Andric     for (auto *Sym : G->defined_symbols())
81fe6060f1SDimitry Andric       if (Sym->getName() == *Name) {
82fe6060f1SDimitry Andric         assert(Sym->getLinkage() == Linkage::Weak &&
83fe6060f1SDimitry Andric                "Discarding non-weak definition");
84fe6060f1SDimitry Andric         G->makeExternal(*Sym);
85fe6060f1SDimitry Andric         break;
86fe6060f1SDimitry Andric       }
87fe6060f1SDimitry Andric   }
88fe6060f1SDimitry Andric 
89fe6060f1SDimitry Andric   ObjectLinkingLayer &ObjLinkingLayer;
90fe6060f1SDimitry Andric   std::unique_ptr<LinkGraph> G;
91fe6060f1SDimitry Andric   static std::atomic<uint64_t> Counter;
92fe6060f1SDimitry Andric };
93fe6060f1SDimitry Andric 
94fe6060f1SDimitry Andric std::atomic<uint64_t> LinkGraphMaterializationUnit::Counter{0};
95fe6060f1SDimitry Andric 
96fe6060f1SDimitry Andric } // end anonymous namespace
97fe6060f1SDimitry Andric 
980b57cec5SDimitry Andric namespace llvm {
990b57cec5SDimitry Andric namespace orc {
1000b57cec5SDimitry Andric 
1010b57cec5SDimitry Andric class ObjectLinkingLayerJITLinkContext final : public JITLinkContext {
1020b57cec5SDimitry Andric public:
103e8d8bef9SDimitry Andric   ObjectLinkingLayerJITLinkContext(
104e8d8bef9SDimitry Andric       ObjectLinkingLayer &Layer,
105e8d8bef9SDimitry Andric       std::unique_ptr<MaterializationResponsibility> MR,
1060b57cec5SDimitry Andric       std::unique_ptr<MemoryBuffer> ObjBuffer)
107e8d8bef9SDimitry Andric       : JITLinkContext(&MR->getTargetJITDylib()), Layer(Layer),
108e8d8bef9SDimitry Andric         MR(std::move(MR)), ObjBuffer(std::move(ObjBuffer)) {}
1090b57cec5SDimitry Andric 
1108bcb0991SDimitry Andric   ~ObjectLinkingLayerJITLinkContext() {
1118bcb0991SDimitry Andric     // If there is an object buffer return function then use it to
1128bcb0991SDimitry Andric     // return ownership of the buffer.
113e8d8bef9SDimitry Andric     if (Layer.ReturnObjectBuffer && ObjBuffer)
1148bcb0991SDimitry Andric       Layer.ReturnObjectBuffer(std::move(ObjBuffer));
1158bcb0991SDimitry Andric   }
1168bcb0991SDimitry Andric 
117e8d8bef9SDimitry Andric   JITLinkMemoryManager &getMemoryManager() override { return Layer.MemMgr; }
1180b57cec5SDimitry Andric 
119fe6060f1SDimitry Andric   void notifyMaterializing(LinkGraph &G) {
120fe6060f1SDimitry Andric     for (auto &P : Layer.Plugins)
121fe6060f1SDimitry Andric       P->notifyMaterializing(*MR, G, *this,
122fe6060f1SDimitry Andric                              ObjBuffer ? ObjBuffer->getMemBufferRef()
123fe6060f1SDimitry Andric                              : MemoryBufferRef());
124fe6060f1SDimitry Andric   }
125fe6060f1SDimitry Andric 
1260b57cec5SDimitry Andric   void notifyFailed(Error Err) override {
127e8d8bef9SDimitry Andric     for (auto &P : Layer.Plugins)
128e8d8bef9SDimitry Andric       Err = joinErrors(std::move(Err), P->notifyFailed(*MR));
1290b57cec5SDimitry Andric     Layer.getExecutionSession().reportError(std::move(Err));
130e8d8bef9SDimitry Andric     MR->failMaterialization();
1310b57cec5SDimitry Andric   }
1320b57cec5SDimitry Andric 
133480093f4SDimitry Andric   void lookup(const LookupMap &Symbols,
1348bcb0991SDimitry Andric               std::unique_ptr<JITLinkAsyncLookupContinuation> LC) override {
1350b57cec5SDimitry Andric 
1365ffd83dbSDimitry Andric     JITDylibSearchOrder LinkOrder;
137e8d8bef9SDimitry Andric     MR->getTargetJITDylib().withLinkOrderDo(
1385ffd83dbSDimitry Andric         [&](const JITDylibSearchOrder &LO) { LinkOrder = LO; });
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric     auto &ES = Layer.getExecutionSession();
1410b57cec5SDimitry Andric 
142480093f4SDimitry Andric     SymbolLookupSet LookupSet;
143480093f4SDimitry Andric     for (auto &KV : Symbols) {
144480093f4SDimitry Andric       orc::SymbolLookupFlags LookupFlags;
145480093f4SDimitry Andric       switch (KV.second) {
146480093f4SDimitry Andric       case jitlink::SymbolLookupFlags::RequiredSymbol:
147480093f4SDimitry Andric         LookupFlags = orc::SymbolLookupFlags::RequiredSymbol;
148480093f4SDimitry Andric         break;
149480093f4SDimitry Andric       case jitlink::SymbolLookupFlags::WeaklyReferencedSymbol:
150480093f4SDimitry Andric         LookupFlags = orc::SymbolLookupFlags::WeaklyReferencedSymbol;
151480093f4SDimitry Andric         break;
152480093f4SDimitry Andric       }
153480093f4SDimitry Andric       LookupSet.add(ES.intern(KV.first), LookupFlags);
154480093f4SDimitry Andric     }
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric     // OnResolve -- De-intern the symbols and pass the result to the linker.
157e8d8bef9SDimitry Andric     auto OnResolve = [LookupContinuation =
158e8d8bef9SDimitry Andric                           std::move(LC)](Expected<SymbolMap> Result) mutable {
1590b57cec5SDimitry Andric       if (!Result)
1608bcb0991SDimitry Andric         LookupContinuation->run(Result.takeError());
1610b57cec5SDimitry Andric       else {
1620b57cec5SDimitry Andric         AsyncLookupResult LR;
1630b57cec5SDimitry Andric         for (auto &KV : *Result)
1640b57cec5SDimitry Andric           LR[*KV.first] = KV.second;
1658bcb0991SDimitry Andric         LookupContinuation->run(std::move(LR));
1660b57cec5SDimitry Andric       }
1670b57cec5SDimitry Andric     };
1680b57cec5SDimitry Andric 
1695ffd83dbSDimitry Andric     for (auto &KV : InternalNamedSymbolDeps) {
1705ffd83dbSDimitry Andric       SymbolDependenceMap InternalDeps;
171e8d8bef9SDimitry Andric       InternalDeps[&MR->getTargetJITDylib()] = std::move(KV.second);
172e8d8bef9SDimitry Andric       MR->addDependencies(KV.first, InternalDeps);
1735ffd83dbSDimitry Andric     }
1745ffd83dbSDimitry Andric 
1755ffd83dbSDimitry Andric     ES.lookup(LookupKind::Static, LinkOrder, std::move(LookupSet),
176480093f4SDimitry Andric               SymbolState::Resolved, std::move(OnResolve),
177480093f4SDimitry Andric               [this](const SymbolDependenceMap &Deps) {
1780b57cec5SDimitry Andric                 registerDependencies(Deps);
1790b57cec5SDimitry Andric               });
1800b57cec5SDimitry Andric   }
1810b57cec5SDimitry Andric 
182e8d8bef9SDimitry Andric   Error notifyResolved(LinkGraph &G) override {
1830b57cec5SDimitry Andric     auto &ES = Layer.getExecutionSession();
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric     SymbolFlagsMap ExtraSymbolsToClaim;
1860b57cec5SDimitry Andric     bool AutoClaim = Layer.AutoClaimObjectSymbols;
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric     SymbolMap InternedResult;
1898bcb0991SDimitry Andric     for (auto *Sym : G.defined_symbols())
1908bcb0991SDimitry Andric       if (Sym->hasName() && Sym->getScope() != Scope::Local) {
1918bcb0991SDimitry Andric         auto InternedName = ES.intern(Sym->getName());
1920b57cec5SDimitry Andric         JITSymbolFlags Flags;
1930b57cec5SDimitry Andric 
1948bcb0991SDimitry Andric         if (Sym->isCallable())
1950b57cec5SDimitry Andric           Flags |= JITSymbolFlags::Callable;
1968bcb0991SDimitry Andric         if (Sym->getScope() == Scope::Default)
1978bcb0991SDimitry Andric           Flags |= JITSymbolFlags::Exported;
198*bdd1243dSDimitry Andric         if (Sym->getLinkage() == Linkage::Weak)
199*bdd1243dSDimitry Andric           Flags |= JITSymbolFlags::Weak;
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric         InternedResult[InternedName] =
20204eeddc0SDimitry Andric             JITEvaluatedSymbol(Sym->getAddress().getValue(), Flags);
203e8d8bef9SDimitry Andric         if (AutoClaim && !MR->getSymbols().count(InternedName)) {
2040b57cec5SDimitry Andric           assert(!ExtraSymbolsToClaim.count(InternedName) &&
2050b57cec5SDimitry Andric                  "Duplicate symbol to claim?");
2060b57cec5SDimitry Andric           ExtraSymbolsToClaim[InternedName] = Flags;
2070b57cec5SDimitry Andric         }
2080b57cec5SDimitry Andric       }
2090b57cec5SDimitry Andric 
2108bcb0991SDimitry Andric     for (auto *Sym : G.absolute_symbols())
21181ad6265SDimitry Andric       if (Sym->hasName() && Sym->getScope() != Scope::Local) {
2128bcb0991SDimitry Andric         auto InternedName = ES.intern(Sym->getName());
2130b57cec5SDimitry Andric         JITSymbolFlags Flags;
2148bcb0991SDimitry Andric         if (Sym->isCallable())
2150b57cec5SDimitry Andric           Flags |= JITSymbolFlags::Callable;
21681ad6265SDimitry Andric         if (Sym->getScope() == Scope::Default)
21781ad6265SDimitry Andric           Flags |= JITSymbolFlags::Exported;
2188bcb0991SDimitry Andric         if (Sym->getLinkage() == Linkage::Weak)
2198bcb0991SDimitry Andric           Flags |= JITSymbolFlags::Weak;
2200b57cec5SDimitry Andric         InternedResult[InternedName] =
22104eeddc0SDimitry Andric             JITEvaluatedSymbol(Sym->getAddress().getValue(), Flags);
222e8d8bef9SDimitry Andric         if (AutoClaim && !MR->getSymbols().count(InternedName)) {
2230b57cec5SDimitry Andric           assert(!ExtraSymbolsToClaim.count(InternedName) &&
2240b57cec5SDimitry Andric                  "Duplicate symbol to claim?");
2250b57cec5SDimitry Andric           ExtraSymbolsToClaim[InternedName] = Flags;
2260b57cec5SDimitry Andric         }
2270b57cec5SDimitry Andric       }
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric     if (!ExtraSymbolsToClaim.empty())
230e8d8bef9SDimitry Andric       if (auto Err = MR->defineMaterializing(ExtraSymbolsToClaim))
231e8d8bef9SDimitry Andric         return Err;
2325ffd83dbSDimitry Andric 
2335ffd83dbSDimitry Andric     {
2345ffd83dbSDimitry Andric 
2350eae32dcSDimitry Andric       // Check that InternedResult matches up with MR->getSymbols(), overriding
2360eae32dcSDimitry Andric       // flags if requested.
2375ffd83dbSDimitry Andric       // This guards against faulty transformations / compilers / object caches.
2385ffd83dbSDimitry Andric 
2395ffd83dbSDimitry Andric       // First check that there aren't any missing symbols.
2405ffd83dbSDimitry Andric       size_t NumMaterializationSideEffectsOnlySymbols = 0;
2415ffd83dbSDimitry Andric       SymbolNameVector ExtraSymbols;
2425ffd83dbSDimitry Andric       SymbolNameVector MissingSymbols;
243e8d8bef9SDimitry Andric       for (auto &KV : MR->getSymbols()) {
2445ffd83dbSDimitry Andric 
2450eae32dcSDimitry Andric         auto I = InternedResult.find(KV.first);
2460eae32dcSDimitry Andric 
2475ffd83dbSDimitry Andric         // If this is a materialization-side-effects only symbol then bump
2485ffd83dbSDimitry Andric         // the counter and make sure it's *not* defined, otherwise make
2495ffd83dbSDimitry Andric         // sure that it is defined.
2505ffd83dbSDimitry Andric         if (KV.second.hasMaterializationSideEffectsOnly()) {
2515ffd83dbSDimitry Andric           ++NumMaterializationSideEffectsOnlySymbols;
2520eae32dcSDimitry Andric           if (I != InternedResult.end())
2535ffd83dbSDimitry Andric             ExtraSymbols.push_back(KV.first);
2545ffd83dbSDimitry Andric           continue;
2550eae32dcSDimitry Andric         } else if (I == InternedResult.end())
2565ffd83dbSDimitry Andric           MissingSymbols.push_back(KV.first);
2570eae32dcSDimitry Andric         else if (Layer.OverrideObjectFlags)
2580eae32dcSDimitry Andric           I->second.setFlags(KV.second);
2595ffd83dbSDimitry Andric       }
2605ffd83dbSDimitry Andric 
2615ffd83dbSDimitry Andric       // If there were missing symbols then report the error.
262e8d8bef9SDimitry Andric       if (!MissingSymbols.empty())
263349cc55cSDimitry Andric         return make_error<MissingSymbolDefinitions>(
264349cc55cSDimitry Andric             Layer.getExecutionSession().getSymbolStringPool(), G.getName(),
265e8d8bef9SDimitry Andric             std::move(MissingSymbols));
2665ffd83dbSDimitry Andric 
2675ffd83dbSDimitry Andric       // If there are more definitions than expected, add them to the
2685ffd83dbSDimitry Andric       // ExtraSymbols vector.
2695ffd83dbSDimitry Andric       if (InternedResult.size() >
270e8d8bef9SDimitry Andric           MR->getSymbols().size() - NumMaterializationSideEffectsOnlySymbols) {
2715ffd83dbSDimitry Andric         for (auto &KV : InternedResult)
272e8d8bef9SDimitry Andric           if (!MR->getSymbols().count(KV.first))
2735ffd83dbSDimitry Andric             ExtraSymbols.push_back(KV.first);
2745ffd83dbSDimitry Andric       }
2755ffd83dbSDimitry Andric 
2765ffd83dbSDimitry Andric       // If there were extra definitions then report the error.
277e8d8bef9SDimitry Andric       if (!ExtraSymbols.empty())
278349cc55cSDimitry Andric         return make_error<UnexpectedSymbolDefinitions>(
279349cc55cSDimitry Andric             Layer.getExecutionSession().getSymbolStringPool(), G.getName(),
280e8d8bef9SDimitry Andric             std::move(ExtraSymbols));
2815ffd83dbSDimitry Andric     }
2825ffd83dbSDimitry Andric 
283e8d8bef9SDimitry Andric     if (auto Err = MR->notifyResolved(InternedResult))
284e8d8bef9SDimitry Andric       return Err;
285e8d8bef9SDimitry Andric 
286e8d8bef9SDimitry Andric     Layer.notifyLoaded(*MR);
287e8d8bef9SDimitry Andric     return Error::success();
2880b57cec5SDimitry Andric   }
2890b57cec5SDimitry Andric 
290349cc55cSDimitry Andric   void notifyFinalized(JITLinkMemoryManager::FinalizedAlloc A) override {
291e8d8bef9SDimitry Andric     if (auto Err = Layer.notifyEmitted(*MR, std::move(A))) {
2920b57cec5SDimitry Andric       Layer.getExecutionSession().reportError(std::move(Err));
293e8d8bef9SDimitry Andric       MR->failMaterialization();
2940b57cec5SDimitry Andric       return;
2950b57cec5SDimitry Andric     }
296e8d8bef9SDimitry Andric     if (auto Err = MR->notifyEmitted()) {
2978bcb0991SDimitry Andric       Layer.getExecutionSession().reportError(std::move(Err));
298e8d8bef9SDimitry Andric       MR->failMaterialization();
2998bcb0991SDimitry Andric     }
3000b57cec5SDimitry Andric   }
3010b57cec5SDimitry Andric 
3028bcb0991SDimitry Andric   LinkGraphPassFunction getMarkLivePass(const Triple &TT) const override {
3038bcb0991SDimitry Andric     return [this](LinkGraph &G) { return markResponsibilitySymbolsLive(G); };
3040b57cec5SDimitry Andric   }
3050b57cec5SDimitry Andric 
306fe6060f1SDimitry Andric   Error modifyPassConfig(LinkGraph &LG, PassConfiguration &Config) override {
3070b57cec5SDimitry Andric     // Add passes to mark duplicate defs as should-discard, and to walk the
3088bcb0991SDimitry Andric     // link graph to build the symbol dependence graph.
309e8d8bef9SDimitry Andric     Config.PrePrunePasses.push_back([this](LinkGraph &G) {
310e8d8bef9SDimitry Andric       return claimOrExternalizeWeakAndCommonSymbols(G);
311e8d8bef9SDimitry Andric     });
3120b57cec5SDimitry Andric 
313fe6060f1SDimitry Andric     Layer.modifyPassConfig(*MR, LG, Config);
3140b57cec5SDimitry Andric 
3155ffd83dbSDimitry Andric     Config.PostPrunePasses.push_back(
3165ffd83dbSDimitry Andric         [this](LinkGraph &G) { return computeNamedSymbolDependencies(G); });
3175ffd83dbSDimitry Andric 
3180b57cec5SDimitry Andric     return Error::success();
3190b57cec5SDimitry Andric   }
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric private:
322fe6060f1SDimitry Andric   // Symbol name dependencies:
323fe6060f1SDimitry Andric   // Internal: Defined in this graph.
324fe6060f1SDimitry Andric   // External: Defined externally.
325fe6060f1SDimitry Andric   struct BlockSymbolDependencies {
3265ffd83dbSDimitry Andric     SymbolNameSet Internal, External;
3275ffd83dbSDimitry Andric   };
3285ffd83dbSDimitry Andric 
329fe6060f1SDimitry Andric   // Lazily populated map of blocks to BlockSymbolDependencies values.
330fe6060f1SDimitry Andric   class BlockDependenciesMap {
331fe6060f1SDimitry Andric   public:
332fe6060f1SDimitry Andric     BlockDependenciesMap(ExecutionSession &ES,
333fe6060f1SDimitry Andric                          DenseMap<const Block *, DenseSet<Block *>> BlockDeps)
334fe6060f1SDimitry Andric         : ES(ES), BlockDeps(std::move(BlockDeps)) {}
335fe6060f1SDimitry Andric 
336fe6060f1SDimitry Andric     const BlockSymbolDependencies &operator[](const Block &B) {
337fe6060f1SDimitry Andric       // Check the cache first.
338fe6060f1SDimitry Andric       auto I = BlockTransitiveDepsCache.find(&B);
339fe6060f1SDimitry Andric       if (I != BlockTransitiveDepsCache.end())
340fe6060f1SDimitry Andric         return I->second;
341fe6060f1SDimitry Andric 
342fe6060f1SDimitry Andric       // No value. Populate the cache.
343fe6060f1SDimitry Andric       BlockSymbolDependencies BTDCacheVal;
344fe6060f1SDimitry Andric       auto BDI = BlockDeps.find(&B);
345fe6060f1SDimitry Andric       assert(BDI != BlockDeps.end() && "No block dependencies");
346fe6060f1SDimitry Andric 
347fe6060f1SDimitry Andric       for (auto *BDep : BDI->second) {
348fe6060f1SDimitry Andric         auto &BID = getBlockImmediateDeps(*BDep);
349fe6060f1SDimitry Andric         for (auto &ExternalDep : BID.External)
350fe6060f1SDimitry Andric           BTDCacheVal.External.insert(ExternalDep);
351fe6060f1SDimitry Andric         for (auto &InternalDep : BID.Internal)
352fe6060f1SDimitry Andric           BTDCacheVal.Internal.insert(InternalDep);
353fe6060f1SDimitry Andric       }
354fe6060f1SDimitry Andric 
355fe6060f1SDimitry Andric       return BlockTransitiveDepsCache
356fe6060f1SDimitry Andric           .insert(std::make_pair(&B, std::move(BTDCacheVal)))
357fe6060f1SDimitry Andric           .first->second;
358fe6060f1SDimitry Andric     }
359fe6060f1SDimitry Andric 
360fe6060f1SDimitry Andric     SymbolStringPtr &getInternedName(Symbol &Sym) {
361fe6060f1SDimitry Andric       auto I = NameCache.find(&Sym);
362fe6060f1SDimitry Andric       if (I != NameCache.end())
363fe6060f1SDimitry Andric         return I->second;
364fe6060f1SDimitry Andric 
365fe6060f1SDimitry Andric       return NameCache.insert(std::make_pair(&Sym, ES.intern(Sym.getName())))
366fe6060f1SDimitry Andric           .first->second;
367fe6060f1SDimitry Andric     }
368fe6060f1SDimitry Andric 
369fe6060f1SDimitry Andric   private:
370fe6060f1SDimitry Andric     BlockSymbolDependencies &getBlockImmediateDeps(Block &B) {
371fe6060f1SDimitry Andric       // Check the cache first.
372fe6060f1SDimitry Andric       auto I = BlockImmediateDepsCache.find(&B);
373fe6060f1SDimitry Andric       if (I != BlockImmediateDepsCache.end())
374fe6060f1SDimitry Andric         return I->second;
375fe6060f1SDimitry Andric 
376fe6060f1SDimitry Andric       BlockSymbolDependencies BIDCacheVal;
377fe6060f1SDimitry Andric       for (auto &E : B.edges()) {
378fe6060f1SDimitry Andric         auto &Tgt = E.getTarget();
379fe6060f1SDimitry Andric         if (Tgt.getScope() != Scope::Local) {
380fe6060f1SDimitry Andric           if (Tgt.isExternal())
381fe6060f1SDimitry Andric             BIDCacheVal.External.insert(getInternedName(Tgt));
382fe6060f1SDimitry Andric           else
383fe6060f1SDimitry Andric             BIDCacheVal.Internal.insert(getInternedName(Tgt));
384fe6060f1SDimitry Andric         }
385fe6060f1SDimitry Andric       }
386fe6060f1SDimitry Andric 
387fe6060f1SDimitry Andric       return BlockImmediateDepsCache
388fe6060f1SDimitry Andric           .insert(std::make_pair(&B, std::move(BIDCacheVal)))
389fe6060f1SDimitry Andric           .first->second;
390fe6060f1SDimitry Andric     }
391fe6060f1SDimitry Andric 
392fe6060f1SDimitry Andric     ExecutionSession &ES;
393fe6060f1SDimitry Andric     DenseMap<const Block *, DenseSet<Block *>> BlockDeps;
394fe6060f1SDimitry Andric     DenseMap<const Symbol *, SymbolStringPtr> NameCache;
395fe6060f1SDimitry Andric     DenseMap<const Block *, BlockSymbolDependencies> BlockImmediateDepsCache;
396fe6060f1SDimitry Andric     DenseMap<const Block *, BlockSymbolDependencies> BlockTransitiveDepsCache;
397fe6060f1SDimitry Andric   };
3980b57cec5SDimitry Andric 
399e8d8bef9SDimitry Andric   Error claimOrExternalizeWeakAndCommonSymbols(LinkGraph &G) {
4000b57cec5SDimitry Andric     auto &ES = Layer.getExecutionSession();
4010b57cec5SDimitry Andric 
402e8d8bef9SDimitry Andric     SymbolFlagsMap NewSymbolsToClaim;
403e8d8bef9SDimitry Andric     std::vector<std::pair<SymbolStringPtr, Symbol *>> NameToSym;
404e8d8bef9SDimitry Andric 
405e8d8bef9SDimitry Andric     auto ProcessSymbol = [&](Symbol *Sym) {
406349cc55cSDimitry Andric       if (Sym->hasName() && Sym->getLinkage() == Linkage::Weak &&
407349cc55cSDimitry Andric           Sym->getScope() != Scope::Local) {
408e8d8bef9SDimitry Andric         auto Name = ES.intern(Sym->getName());
409e8d8bef9SDimitry Andric         if (!MR->getSymbols().count(ES.intern(Sym->getName()))) {
410e8d8bef9SDimitry Andric           JITSymbolFlags SF = JITSymbolFlags::Weak;
411e8d8bef9SDimitry Andric           if (Sym->getScope() == Scope::Default)
412e8d8bef9SDimitry Andric             SF |= JITSymbolFlags::Exported;
413e8d8bef9SDimitry Andric           NewSymbolsToClaim[Name] = SF;
414e8d8bef9SDimitry Andric           NameToSym.push_back(std::make_pair(std::move(Name), Sym));
4150b57cec5SDimitry Andric         }
416e8d8bef9SDimitry Andric       }
417e8d8bef9SDimitry Andric     };
418e8d8bef9SDimitry Andric 
419e8d8bef9SDimitry Andric     for (auto *Sym : G.defined_symbols())
420e8d8bef9SDimitry Andric       ProcessSymbol(Sym);
421e8d8bef9SDimitry Andric     for (auto *Sym : G.absolute_symbols())
422e8d8bef9SDimitry Andric       ProcessSymbol(Sym);
423e8d8bef9SDimitry Andric 
424e8d8bef9SDimitry Andric     // Attempt to claim all weak defs that we're not already responsible for.
425e8d8bef9SDimitry Andric     // This cannot fail -- any clashes will just result in rejection of our
426e8d8bef9SDimitry Andric     // claim, at which point we'll externalize that symbol.
427e8d8bef9SDimitry Andric     cantFail(MR->defineMaterializing(std::move(NewSymbolsToClaim)));
428e8d8bef9SDimitry Andric 
429*bdd1243dSDimitry Andric     // Walk the list of symbols that we just tried to claim. Symbols that we're
430*bdd1243dSDimitry Andric     // responsible for are marked live. Symbols that we're not responsible for
431*bdd1243dSDimitry Andric     // are turned into external references.
432*bdd1243dSDimitry Andric     for (auto &KV : NameToSym) {
433*bdd1243dSDimitry Andric       if (MR->getSymbols().count(KV.first))
434*bdd1243dSDimitry Andric         KV.second->setLive(true);
435*bdd1243dSDimitry Andric       else
436e8d8bef9SDimitry Andric         G.makeExternal(*KV.second);
437*bdd1243dSDimitry Andric     }
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric     return Error::success();
4400b57cec5SDimitry Andric   }
4410b57cec5SDimitry Andric 
4428bcb0991SDimitry Andric   Error markResponsibilitySymbolsLive(LinkGraph &G) const {
4430b57cec5SDimitry Andric     auto &ES = Layer.getExecutionSession();
4448bcb0991SDimitry Andric     for (auto *Sym : G.defined_symbols())
445e8d8bef9SDimitry Andric       if (Sym->hasName() && MR->getSymbols().count(ES.intern(Sym->getName())))
4468bcb0991SDimitry Andric         Sym->setLive(true);
4470b57cec5SDimitry Andric     return Error::success();
4480b57cec5SDimitry Andric   }
4490b57cec5SDimitry Andric 
4508bcb0991SDimitry Andric   Error computeNamedSymbolDependencies(LinkGraph &G) {
451e8d8bef9SDimitry Andric     auto &ES = MR->getTargetJITDylib().getExecutionSession();
452fe6060f1SDimitry Andric     auto BlockDeps = computeBlockNonLocalDeps(G);
4530b57cec5SDimitry Andric 
4545ffd83dbSDimitry Andric     // Compute dependencies for symbols defined in the JITLink graph.
4558bcb0991SDimitry Andric     for (auto *Sym : G.defined_symbols()) {
4560b57cec5SDimitry Andric 
4575ffd83dbSDimitry Andric       // Skip local symbols: we do not track dependencies for these.
4588bcb0991SDimitry Andric       if (Sym->getScope() == Scope::Local)
4590b57cec5SDimitry Andric         continue;
4605ffd83dbSDimitry Andric       assert(Sym->hasName() &&
4615ffd83dbSDimitry Andric              "Defined non-local jitlink::Symbol should have a name");
4620b57cec5SDimitry Andric 
463fe6060f1SDimitry Andric       auto &SymDeps = BlockDeps[Sym->getBlock()];
464fe6060f1SDimitry Andric       if (SymDeps.External.empty() && SymDeps.Internal.empty())
4655ffd83dbSDimitry Andric         continue;
4665ffd83dbSDimitry Andric 
4675ffd83dbSDimitry Andric       auto SymName = ES.intern(Sym->getName());
468fe6060f1SDimitry Andric       if (!SymDeps.External.empty())
469fe6060f1SDimitry Andric         ExternalNamedSymbolDeps[SymName] = SymDeps.External;
470fe6060f1SDimitry Andric       if (!SymDeps.Internal.empty())
471fe6060f1SDimitry Andric         InternalNamedSymbolDeps[SymName] = SymDeps.Internal;
4725ffd83dbSDimitry Andric     }
4735ffd83dbSDimitry Andric 
4745ffd83dbSDimitry Andric     for (auto &P : Layer.Plugins) {
475fe6060f1SDimitry Andric       auto SynthDeps = P->getSyntheticSymbolDependencies(*MR);
476fe6060f1SDimitry Andric       if (SynthDeps.empty())
4775ffd83dbSDimitry Andric         continue;
4785ffd83dbSDimitry Andric 
479fe6060f1SDimitry Andric       DenseSet<Block *> BlockVisited;
480fe6060f1SDimitry Andric       for (auto &KV : SynthDeps) {
4815ffd83dbSDimitry Andric         auto &Name = KV.first;
482fe6060f1SDimitry Andric         auto &DepsForName = KV.second;
483fe6060f1SDimitry Andric         for (auto *Sym : DepsForName) {
484fe6060f1SDimitry Andric           if (Sym->getScope() == Scope::Local) {
485fe6060f1SDimitry Andric             auto &BDeps = BlockDeps[Sym->getBlock()];
486fe6060f1SDimitry Andric             for (auto &S : BDeps.Internal)
4875ffd83dbSDimitry Andric               InternalNamedSymbolDeps[Name].insert(S);
488fe6060f1SDimitry Andric             for (auto &S : BDeps.External)
4895ffd83dbSDimitry Andric               ExternalNamedSymbolDeps[Name].insert(S);
490fe6060f1SDimitry Andric           } else {
491fe6060f1SDimitry Andric             if (Sym->isExternal())
492fe6060f1SDimitry Andric               ExternalNamedSymbolDeps[Name].insert(
493fe6060f1SDimitry Andric                   BlockDeps.getInternedName(*Sym));
494fe6060f1SDimitry Andric             else
495fe6060f1SDimitry Andric               InternalNamedSymbolDeps[Name].insert(
496fe6060f1SDimitry Andric                   BlockDeps.getInternedName(*Sym));
497fe6060f1SDimitry Andric           }
4980b57cec5SDimitry Andric         }
4990b57cec5SDimitry Andric       }
5000b57cec5SDimitry Andric     }
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric     return Error::success();
5030b57cec5SDimitry Andric   }
5040b57cec5SDimitry Andric 
505fe6060f1SDimitry Andric   BlockDependenciesMap computeBlockNonLocalDeps(LinkGraph &G) {
506fe6060f1SDimitry Andric     // First calculate the reachable-via-non-local-symbol blocks for each block.
507fe6060f1SDimitry Andric     struct BlockInfo {
508fe6060f1SDimitry Andric       DenseSet<Block *> Dependencies;
509fe6060f1SDimitry Andric       DenseSet<Block *> Dependants;
510fe6060f1SDimitry Andric       bool DependenciesChanged = true;
5110b57cec5SDimitry Andric     };
512fe6060f1SDimitry Andric     DenseMap<Block *, BlockInfo> BlockInfos;
513fe6060f1SDimitry Andric     SmallVector<Block *> WorkList;
5140b57cec5SDimitry Andric 
515fe6060f1SDimitry Andric     // Pre-allocate map entries. This prevents any iterator/reference
516fe6060f1SDimitry Andric     // invalidation in the next loop.
517fe6060f1SDimitry Andric     for (auto *B : G.blocks())
518fe6060f1SDimitry Andric       (void)BlockInfos[B];
519fe6060f1SDimitry Andric 
520fe6060f1SDimitry Andric     // Build initial worklist, record block dependencies/dependants and
521fe6060f1SDimitry Andric     // non-local symbol dependencies.
522fe6060f1SDimitry Andric     for (auto *B : G.blocks()) {
523fe6060f1SDimitry Andric       auto &BI = BlockInfos[B];
524fe6060f1SDimitry Andric       for (auto &E : B->edges()) {
525*bdd1243dSDimitry Andric         if (E.getTarget().getScope() == Scope::Local &&
526*bdd1243dSDimitry Andric             !E.getTarget().isAbsolute()) {
527fe6060f1SDimitry Andric           auto &TgtB = E.getTarget().getBlock();
528fe6060f1SDimitry Andric           if (&TgtB != B) {
529fe6060f1SDimitry Andric             BI.Dependencies.insert(&TgtB);
530fe6060f1SDimitry Andric             BlockInfos[&TgtB].Dependants.insert(B);
531fe6060f1SDimitry Andric           }
5320b57cec5SDimitry Andric         }
5330b57cec5SDimitry Andric       }
5340b57cec5SDimitry Andric 
535fe6060f1SDimitry Andric       // If this node has both dependants and dependencies then add it to the
536fe6060f1SDimitry Andric       // worklist to propagate the dependencies to the dependants.
537fe6060f1SDimitry Andric       if (!BI.Dependants.empty() && !BI.Dependencies.empty())
538fe6060f1SDimitry Andric         WorkList.push_back(B);
5390b57cec5SDimitry Andric     }
5400b57cec5SDimitry Andric 
541fe6060f1SDimitry Andric     // Propagate block-level dependencies through the block-dependence graph.
542fe6060f1SDimitry Andric     while (!WorkList.empty()) {
543349cc55cSDimitry Andric       auto *B = WorkList.pop_back_val();
5440b57cec5SDimitry Andric 
545fe6060f1SDimitry Andric       auto &BI = BlockInfos[B];
546fe6060f1SDimitry Andric       assert(BI.DependenciesChanged &&
547fe6060f1SDimitry Andric              "Block in worklist has unchanged dependencies");
548fe6060f1SDimitry Andric       BI.DependenciesChanged = false;
549fe6060f1SDimitry Andric       for (auto *Dependant : BI.Dependants) {
550fe6060f1SDimitry Andric         auto &DependantBI = BlockInfos[Dependant];
551fe6060f1SDimitry Andric         for (auto *Dependency : BI.Dependencies) {
552fe6060f1SDimitry Andric           if (Dependant != Dependency &&
553fe6060f1SDimitry Andric               DependantBI.Dependencies.insert(Dependency).second)
554fe6060f1SDimitry Andric             if (!DependantBI.DependenciesChanged) {
555fe6060f1SDimitry Andric               DependantBI.DependenciesChanged = true;
556fe6060f1SDimitry Andric               WorkList.push_back(Dependant);
5570b57cec5SDimitry Andric             }
5580b57cec5SDimitry Andric         }
5595ffd83dbSDimitry Andric       }
5605ffd83dbSDimitry Andric     }
5615ffd83dbSDimitry Andric 
562fe6060f1SDimitry Andric     DenseMap<const Block *, DenseSet<Block *>> BlockDeps;
563fe6060f1SDimitry Andric     for (auto &KV : BlockInfos)
564fe6060f1SDimitry Andric       BlockDeps[KV.first] = std::move(KV.second.Dependencies);
565fe6060f1SDimitry Andric 
566fe6060f1SDimitry Andric     return BlockDependenciesMap(Layer.getExecutionSession(),
567fe6060f1SDimitry Andric                                 std::move(BlockDeps));
5680b57cec5SDimitry Andric   }
5690b57cec5SDimitry Andric 
5700b57cec5SDimitry Andric   void registerDependencies(const SymbolDependenceMap &QueryDeps) {
5715ffd83dbSDimitry Andric     for (auto &NamedDepsEntry : ExternalNamedSymbolDeps) {
5720b57cec5SDimitry Andric       auto &Name = NamedDepsEntry.first;
5730b57cec5SDimitry Andric       auto &NameDeps = NamedDepsEntry.second;
5740b57cec5SDimitry Andric       SymbolDependenceMap SymbolDeps;
5750b57cec5SDimitry Andric 
5760b57cec5SDimitry Andric       for (const auto &QueryDepsEntry : QueryDeps) {
5770b57cec5SDimitry Andric         JITDylib &SourceJD = *QueryDepsEntry.first;
5780b57cec5SDimitry Andric         const SymbolNameSet &Symbols = QueryDepsEntry.second;
5790b57cec5SDimitry Andric         auto &DepsForJD = SymbolDeps[&SourceJD];
5800b57cec5SDimitry Andric 
5810b57cec5SDimitry Andric         for (const auto &S : Symbols)
5820b57cec5SDimitry Andric           if (NameDeps.count(S))
5830b57cec5SDimitry Andric             DepsForJD.insert(S);
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric         if (DepsForJD.empty())
5860b57cec5SDimitry Andric           SymbolDeps.erase(&SourceJD);
5870b57cec5SDimitry Andric       }
5880b57cec5SDimitry Andric 
589e8d8bef9SDimitry Andric       MR->addDependencies(Name, SymbolDeps);
5900b57cec5SDimitry Andric     }
5910b57cec5SDimitry Andric   }
5920b57cec5SDimitry Andric 
5930b57cec5SDimitry Andric   ObjectLinkingLayer &Layer;
594e8d8bef9SDimitry Andric   std::unique_ptr<MaterializationResponsibility> MR;
5950b57cec5SDimitry Andric   std::unique_ptr<MemoryBuffer> ObjBuffer;
5965ffd83dbSDimitry Andric   DenseMap<SymbolStringPtr, SymbolNameSet> ExternalNamedSymbolDeps;
5975ffd83dbSDimitry Andric   DenseMap<SymbolStringPtr, SymbolNameSet> InternalNamedSymbolDeps;
5980b57cec5SDimitry Andric };
5990b57cec5SDimitry Andric 
60081ad6265SDimitry Andric ObjectLinkingLayer::Plugin::~Plugin() = default;
6010b57cec5SDimitry Andric 
602fe6060f1SDimitry Andric char ObjectLinkingLayer::ID;
603fe6060f1SDimitry Andric 
604fe6060f1SDimitry Andric using BaseT = RTTIExtends<ObjectLinkingLayer, ObjectLayer>;
605fe6060f1SDimitry Andric 
606fe6060f1SDimitry Andric ObjectLinkingLayer::ObjectLinkingLayer(ExecutionSession &ES)
607fe6060f1SDimitry Andric     : BaseT(ES), MemMgr(ES.getExecutorProcessControl().getMemMgr()) {
608fe6060f1SDimitry Andric   ES.registerResourceManager(*this);
609fe6060f1SDimitry Andric }
610fe6060f1SDimitry Andric 
611e8d8bef9SDimitry Andric ObjectLinkingLayer::ObjectLinkingLayer(ExecutionSession &ES,
612e8d8bef9SDimitry Andric                                        JITLinkMemoryManager &MemMgr)
613fe6060f1SDimitry Andric     : BaseT(ES), MemMgr(MemMgr) {
614e8d8bef9SDimitry Andric   ES.registerResourceManager(*this);
6150b57cec5SDimitry Andric }
6160b57cec5SDimitry Andric 
617e8d8bef9SDimitry Andric ObjectLinkingLayer::ObjectLinkingLayer(
618e8d8bef9SDimitry Andric     ExecutionSession &ES, std::unique_ptr<JITLinkMemoryManager> MemMgr)
619fe6060f1SDimitry Andric     : BaseT(ES), MemMgr(*MemMgr), MemMgrOwnership(std::move(MemMgr)) {
620e8d8bef9SDimitry Andric   ES.registerResourceManager(*this);
621e8d8bef9SDimitry Andric }
622e8d8bef9SDimitry Andric 
623e8d8bef9SDimitry Andric ObjectLinkingLayer::~ObjectLinkingLayer() {
624e8d8bef9SDimitry Andric   assert(Allocs.empty() && "Layer destroyed with resources still attached");
625e8d8bef9SDimitry Andric   getExecutionSession().deregisterResourceManager(*this);
626e8d8bef9SDimitry Andric }
627e8d8bef9SDimitry Andric 
628fe6060f1SDimitry Andric Error ObjectLinkingLayer::add(ResourceTrackerSP RT,
629fe6060f1SDimitry Andric                               std::unique_ptr<LinkGraph> G) {
630fe6060f1SDimitry Andric   auto &JD = RT->getJITDylib();
631fe6060f1SDimitry Andric   return JD.define(LinkGraphMaterializationUnit::Create(*this, std::move(G)),
632fe6060f1SDimitry Andric                    std::move(RT));
633fe6060f1SDimitry Andric }
634fe6060f1SDimitry Andric 
635e8d8bef9SDimitry Andric void ObjectLinkingLayer::emit(std::unique_ptr<MaterializationResponsibility> R,
6360b57cec5SDimitry Andric                               std::unique_ptr<MemoryBuffer> O) {
6370b57cec5SDimitry Andric   assert(O && "Object must not be null");
638fe6060f1SDimitry Andric   MemoryBufferRef ObjBuffer = O->getMemBufferRef();
639fe6060f1SDimitry Andric 
640e8d8bef9SDimitry Andric   auto Ctx = std::make_unique<ObjectLinkingLayerJITLinkContext>(
641e8d8bef9SDimitry Andric       *this, std::move(R), std::move(O));
642fe6060f1SDimitry Andric   if (auto G = createLinkGraphFromObject(ObjBuffer)) {
643fe6060f1SDimitry Andric     Ctx->notifyMaterializing(**G);
644e8d8bef9SDimitry Andric     link(std::move(*G), std::move(Ctx));
645fe6060f1SDimitry Andric   } else {
646e8d8bef9SDimitry Andric     Ctx->notifyFailed(G.takeError());
647e8d8bef9SDimitry Andric   }
648fe6060f1SDimitry Andric }
649e8d8bef9SDimitry Andric 
650e8d8bef9SDimitry Andric void ObjectLinkingLayer::emit(std::unique_ptr<MaterializationResponsibility> R,
651e8d8bef9SDimitry Andric                               std::unique_ptr<LinkGraph> G) {
652fe6060f1SDimitry Andric   auto Ctx = std::make_unique<ObjectLinkingLayerJITLinkContext>(
653fe6060f1SDimitry Andric       *this, std::move(R), nullptr);
654fe6060f1SDimitry Andric   Ctx->notifyMaterializing(*G);
655fe6060f1SDimitry Andric   link(std::move(G), std::move(Ctx));
6560b57cec5SDimitry Andric }
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric void ObjectLinkingLayer::modifyPassConfig(MaterializationResponsibility &MR,
659fe6060f1SDimitry Andric                                           LinkGraph &G,
6600b57cec5SDimitry Andric                                           PassConfiguration &PassConfig) {
6610b57cec5SDimitry Andric   for (auto &P : Plugins)
662fe6060f1SDimitry Andric     P->modifyPassConfig(MR, G, PassConfig);
6630b57cec5SDimitry Andric }
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric void ObjectLinkingLayer::notifyLoaded(MaterializationResponsibility &MR) {
6660b57cec5SDimitry Andric   for (auto &P : Plugins)
6670b57cec5SDimitry Andric     P->notifyLoaded(MR);
6680b57cec5SDimitry Andric }
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric Error ObjectLinkingLayer::notifyEmitted(MaterializationResponsibility &MR,
671349cc55cSDimitry Andric                                         FinalizedAlloc FA) {
6720b57cec5SDimitry Andric   Error Err = Error::success();
6730b57cec5SDimitry Andric   for (auto &P : Plugins)
6740b57cec5SDimitry Andric     Err = joinErrors(std::move(Err), P->notifyEmitted(MR));
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric   if (Err)
6770b57cec5SDimitry Andric     return Err;
6780b57cec5SDimitry Andric 
679e8d8bef9SDimitry Andric   return MR.withResourceKeyDo(
680349cc55cSDimitry Andric       [&](ResourceKey K) { Allocs[K].push_back(std::move(FA)); });
6810b57cec5SDimitry Andric }
6820b57cec5SDimitry Andric 
683*bdd1243dSDimitry Andric Error ObjectLinkingLayer::handleRemoveResources(JITDylib &JD, ResourceKey K) {
6840b57cec5SDimitry Andric 
685349cc55cSDimitry Andric   {
6860b57cec5SDimitry Andric     Error Err = Error::success();
6870b57cec5SDimitry Andric     for (auto &P : Plugins)
688*bdd1243dSDimitry Andric       Err = joinErrors(std::move(Err), P->notifyRemovingResources(JD, K));
689349cc55cSDimitry Andric     if (Err)
690349cc55cSDimitry Andric       return Err;
691349cc55cSDimitry Andric   }
6920b57cec5SDimitry Andric 
693349cc55cSDimitry Andric   std::vector<FinalizedAlloc> AllocsToRemove;
694e8d8bef9SDimitry Andric   getExecutionSession().runSessionLocked([&] {
695e8d8bef9SDimitry Andric     auto I = Allocs.find(K);
696e8d8bef9SDimitry Andric     if (I != Allocs.end()) {
697e8d8bef9SDimitry Andric       std::swap(AllocsToRemove, I->second);
698e8d8bef9SDimitry Andric       Allocs.erase(I);
6990b57cec5SDimitry Andric     }
700e8d8bef9SDimitry Andric   });
7010b57cec5SDimitry Andric 
702349cc55cSDimitry Andric   if (AllocsToRemove.empty())
703349cc55cSDimitry Andric     return Error::success();
7040b57cec5SDimitry Andric 
705349cc55cSDimitry Andric   return MemMgr.deallocate(std::move(AllocsToRemove));
7060b57cec5SDimitry Andric }
7070b57cec5SDimitry Andric 
708*bdd1243dSDimitry Andric void ObjectLinkingLayer::handleTransferResources(JITDylib &JD,
709*bdd1243dSDimitry Andric                                                  ResourceKey DstKey,
710e8d8bef9SDimitry Andric                                                  ResourceKey SrcKey) {
711e8d8bef9SDimitry Andric   auto I = Allocs.find(SrcKey);
712e8d8bef9SDimitry Andric   if (I != Allocs.end()) {
713e8d8bef9SDimitry Andric     auto &SrcAllocs = I->second;
714e8d8bef9SDimitry Andric     auto &DstAllocs = Allocs[DstKey];
715e8d8bef9SDimitry Andric     DstAllocs.reserve(DstAllocs.size() + SrcAllocs.size());
716e8d8bef9SDimitry Andric     for (auto &Alloc : SrcAllocs)
717e8d8bef9SDimitry Andric       DstAllocs.push_back(std::move(Alloc));
718e8d8bef9SDimitry Andric 
719e8d8bef9SDimitry Andric     // Erase SrcKey entry using value rather than iterator I: I may have been
720e8d8bef9SDimitry Andric     // invalidated when we looked up DstKey.
721e8d8bef9SDimitry Andric     Allocs.erase(SrcKey);
722e8d8bef9SDimitry Andric   }
723e8d8bef9SDimitry Andric 
724e8d8bef9SDimitry Andric   for (auto &P : Plugins)
725*bdd1243dSDimitry Andric     P->notifyTransferringResources(JD, DstKey, SrcKey);
726e8d8bef9SDimitry Andric }
727e8d8bef9SDimitry Andric 
7280b57cec5SDimitry Andric EHFrameRegistrationPlugin::EHFrameRegistrationPlugin(
729e8d8bef9SDimitry Andric     ExecutionSession &ES, std::unique_ptr<EHFrameRegistrar> Registrar)
730e8d8bef9SDimitry Andric     : ES(ES), Registrar(std::move(Registrar)) {}
7310b57cec5SDimitry Andric 
7320b57cec5SDimitry Andric void EHFrameRegistrationPlugin::modifyPassConfig(
733fe6060f1SDimitry Andric     MaterializationResponsibility &MR, LinkGraph &G,
7340b57cec5SDimitry Andric     PassConfiguration &PassConfig) {
7350b57cec5SDimitry Andric 
7365ffd83dbSDimitry Andric   PassConfig.PostFixupPasses.push_back(createEHFrameRecorderPass(
73704eeddc0SDimitry Andric       G.getTargetTriple(), [this, &MR](ExecutorAddr Addr, size_t Size) {
7385ffd83dbSDimitry Andric         if (Addr) {
7395ffd83dbSDimitry Andric           std::lock_guard<std::mutex> Lock(EHFramePluginMutex);
7405ffd83dbSDimitry Andric           assert(!InProcessLinks.count(&MR) &&
7415ffd83dbSDimitry Andric                  "Link for MR already being tracked?");
7428bcb0991SDimitry Andric           InProcessLinks[&MR] = {Addr, Size};
7435ffd83dbSDimitry Andric         }
7440b57cec5SDimitry Andric       }));
7450b57cec5SDimitry Andric }
7460b57cec5SDimitry Andric 
7470b57cec5SDimitry Andric Error EHFrameRegistrationPlugin::notifyEmitted(
7480b57cec5SDimitry Andric     MaterializationResponsibility &MR) {
749e8d8bef9SDimitry Andric 
75004eeddc0SDimitry Andric   ExecutorAddrRange EmittedRange;
751e8d8bef9SDimitry Andric   {
7525ffd83dbSDimitry Andric     std::lock_guard<std::mutex> Lock(EHFramePluginMutex);
7530b57cec5SDimitry Andric 
7548bcb0991SDimitry Andric     auto EHFrameRangeItr = InProcessLinks.find(&MR);
7558bcb0991SDimitry Andric     if (EHFrameRangeItr == InProcessLinks.end())
7560b57cec5SDimitry Andric       return Error::success();
7570b57cec5SDimitry Andric 
758e8d8bef9SDimitry Andric     EmittedRange = EHFrameRangeItr->second;
75904eeddc0SDimitry Andric     assert(EmittedRange.Start && "eh-frame addr to register can not be null");
7608bcb0991SDimitry Andric     InProcessLinks.erase(EHFrameRangeItr);
7610b57cec5SDimitry Andric   }
7620b57cec5SDimitry Andric 
763e8d8bef9SDimitry Andric   if (auto Err = MR.withResourceKeyDo(
764e8d8bef9SDimitry Andric           [&](ResourceKey K) { EHFrameRanges[K].push_back(EmittedRange); }))
765e8d8bef9SDimitry Andric     return Err;
7665ffd83dbSDimitry Andric 
76704eeddc0SDimitry Andric   return Registrar->registerEHFrames(EmittedRange);
768e8d8bef9SDimitry Andric }
769e8d8bef9SDimitry Andric 
770e8d8bef9SDimitry Andric Error EHFrameRegistrationPlugin::notifyFailed(
771e8d8bef9SDimitry Andric     MaterializationResponsibility &MR) {
772e8d8bef9SDimitry Andric   std::lock_guard<std::mutex> Lock(EHFramePluginMutex);
773e8d8bef9SDimitry Andric   InProcessLinks.erase(&MR);
7740b57cec5SDimitry Andric   return Error::success();
7750b57cec5SDimitry Andric }
7760b57cec5SDimitry Andric 
777*bdd1243dSDimitry Andric Error EHFrameRegistrationPlugin::notifyRemovingResources(JITDylib &JD,
778*bdd1243dSDimitry Andric                                                          ResourceKey K) {
77904eeddc0SDimitry Andric   std::vector<ExecutorAddrRange> RangesToRemove;
7800b57cec5SDimitry Andric 
781e8d8bef9SDimitry Andric   ES.runSessionLocked([&] {
782e8d8bef9SDimitry Andric     auto I = EHFrameRanges.find(K);
783e8d8bef9SDimitry Andric     if (I != EHFrameRanges.end()) {
784e8d8bef9SDimitry Andric       RangesToRemove = std::move(I->second);
785e8d8bef9SDimitry Andric       EHFrameRanges.erase(I);
786e8d8bef9SDimitry Andric     }
787e8d8bef9SDimitry Andric   });
7880b57cec5SDimitry Andric 
7890b57cec5SDimitry Andric   Error Err = Error::success();
790e8d8bef9SDimitry Andric   while (!RangesToRemove.empty()) {
791e8d8bef9SDimitry Andric     auto RangeToRemove = RangesToRemove.back();
792e8d8bef9SDimitry Andric     RangesToRemove.pop_back();
79304eeddc0SDimitry Andric     assert(RangeToRemove.Start && "Untracked eh-frame range must not be null");
79404eeddc0SDimitry Andric     Err = joinErrors(std::move(Err),
79504eeddc0SDimitry Andric                      Registrar->deregisterEHFrames(RangeToRemove));
7960b57cec5SDimitry Andric   }
7970b57cec5SDimitry Andric 
7980b57cec5SDimitry Andric   return Err;
7990b57cec5SDimitry Andric }
8000b57cec5SDimitry Andric 
801e8d8bef9SDimitry Andric void EHFrameRegistrationPlugin::notifyTransferringResources(
802*bdd1243dSDimitry Andric     JITDylib &JD, ResourceKey DstKey, ResourceKey SrcKey) {
803e8d8bef9SDimitry Andric   auto SI = EHFrameRanges.find(SrcKey);
804fe6060f1SDimitry Andric   if (SI == EHFrameRanges.end())
805fe6060f1SDimitry Andric     return;
806fe6060f1SDimitry Andric 
807fe6060f1SDimitry Andric   auto DI = EHFrameRanges.find(DstKey);
808fe6060f1SDimitry Andric   if (DI != EHFrameRanges.end()) {
809e8d8bef9SDimitry Andric     auto &SrcRanges = SI->second;
810fe6060f1SDimitry Andric     auto &DstRanges = DI->second;
811e8d8bef9SDimitry Andric     DstRanges.reserve(DstRanges.size() + SrcRanges.size());
812e8d8bef9SDimitry Andric     for (auto &SrcRange : SrcRanges)
813e8d8bef9SDimitry Andric       DstRanges.push_back(std::move(SrcRange));
814e8d8bef9SDimitry Andric     EHFrameRanges.erase(SI);
815fe6060f1SDimitry Andric   } else {
816fe6060f1SDimitry Andric     // We need to move SrcKey's ranges over without invalidating the SI
817fe6060f1SDimitry Andric     // iterator.
818fe6060f1SDimitry Andric     auto Tmp = std::move(SI->second);
819fe6060f1SDimitry Andric     EHFrameRanges.erase(SI);
820fe6060f1SDimitry Andric     EHFrameRanges[DstKey] = std::move(Tmp);
821e8d8bef9SDimitry Andric   }
822e8d8bef9SDimitry Andric }
823e8d8bef9SDimitry Andric 
8240b57cec5SDimitry Andric } // End namespace orc.
8250b57cec5SDimitry Andric } // End namespace llvm.
826