xref: /freebsd/contrib/llvm-project/llvm/lib/ExecutionEngine/Orc/ObjectLinkingLayer.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
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"
11*06c3fb27SDimitry Andric #include "llvm/ExecutionEngine/JITLink/aarch32.h"
12fe6060f1SDimitry Andric #include "llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h"
13bdd1243dSDimitry Andric #include "llvm/ExecutionEngine/Orc/ObjectFileInterface.h"
14*06c3fb27SDimitry Andric #include "llvm/ExecutionEngine/Orc/Shared/ObjectFormats.h"
15fe6060f1SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
16fe6060f1SDimitry Andric #include <string>
170b57cec5SDimitry Andric #include <vector>
180b57cec5SDimitry Andric 
190b57cec5SDimitry Andric #define DEBUG_TYPE "orc"
200b57cec5SDimitry Andric 
210b57cec5SDimitry Andric using namespace llvm;
220b57cec5SDimitry Andric using namespace llvm::jitlink;
230b57cec5SDimitry Andric using namespace llvm::orc;
240b57cec5SDimitry Andric 
25fe6060f1SDimitry Andric namespace {
26fe6060f1SDimitry Andric 
27*06c3fb27SDimitry Andric bool hasInitializerSection(jitlink::LinkGraph &G) {
28*06c3fb27SDimitry Andric   bool IsMachO = G.getTargetTriple().isOSBinFormatMachO();
29*06c3fb27SDimitry Andric   bool IsElf = G.getTargetTriple().isOSBinFormatELF();
30*06c3fb27SDimitry Andric   if (!IsMachO && !IsElf)
31*06c3fb27SDimitry Andric     return false;
32*06c3fb27SDimitry Andric 
33*06c3fb27SDimitry Andric   for (auto &Sec : G.sections()) {
34*06c3fb27SDimitry Andric     if (IsMachO && isMachOInitializerSection(Sec.getName()))
35*06c3fb27SDimitry Andric       return true;
36*06c3fb27SDimitry Andric     if (IsElf && isELFInitializerSection(Sec.getName()))
37*06c3fb27SDimitry Andric       return true;
38*06c3fb27SDimitry Andric   }
39*06c3fb27SDimitry Andric 
40*06c3fb27SDimitry Andric   return false;
41*06c3fb27SDimitry Andric }
42*06c3fb27SDimitry Andric 
43*06c3fb27SDimitry Andric ExecutorAddr getJITSymbolPtrForSymbol(Symbol &Sym, const Triple &TT) {
44*06c3fb27SDimitry Andric   switch (TT.getArch()) {
45*06c3fb27SDimitry Andric   case Triple::arm:
46*06c3fb27SDimitry Andric   case Triple::armeb:
47*06c3fb27SDimitry Andric   case Triple::thumb:
48*06c3fb27SDimitry Andric   case Triple::thumbeb:
49*06c3fb27SDimitry Andric     if (Sym.hasTargetFlags(aarch32::ThumbSymbol)) {
50*06c3fb27SDimitry Andric       // Set LSB to indicate thumb target
51*06c3fb27SDimitry Andric       assert(Sym.isCallable() && "Only callable symbols can have thumb flag");
52*06c3fb27SDimitry Andric       assert((Sym.getAddress().getValue() & 0x01) == 0 && "LSB is clear");
53*06c3fb27SDimitry Andric       return Sym.getAddress() + 0x01;
54*06c3fb27SDimitry Andric     }
55*06c3fb27SDimitry Andric     return Sym.getAddress();
56*06c3fb27SDimitry Andric   default:
57*06c3fb27SDimitry Andric     return Sym.getAddress();
58*06c3fb27SDimitry Andric   }
59*06c3fb27SDimitry Andric }
60*06c3fb27SDimitry Andric 
61*06c3fb27SDimitry Andric JITSymbolFlags getJITSymbolFlagsForSymbol(Symbol &Sym) {
62*06c3fb27SDimitry Andric   JITSymbolFlags Flags;
63*06c3fb27SDimitry Andric 
64*06c3fb27SDimitry Andric   if (Sym.getLinkage() == Linkage::Weak)
65*06c3fb27SDimitry Andric     Flags |= JITSymbolFlags::Weak;
66*06c3fb27SDimitry Andric 
67*06c3fb27SDimitry Andric   if (Sym.getScope() == Scope::Default)
68*06c3fb27SDimitry Andric     Flags |= JITSymbolFlags::Exported;
69*06c3fb27SDimitry Andric 
70*06c3fb27SDimitry Andric   if (Sym.isCallable())
71*06c3fb27SDimitry Andric     Flags |= JITSymbolFlags::Callable;
72*06c3fb27SDimitry Andric 
73*06c3fb27SDimitry Andric   return Flags;
74*06c3fb27SDimitry Andric }
75*06c3fb27SDimitry Andric 
76fe6060f1SDimitry Andric class LinkGraphMaterializationUnit : public MaterializationUnit {
77fe6060f1SDimitry Andric public:
78fe6060f1SDimitry Andric   static std::unique_ptr<LinkGraphMaterializationUnit>
79fe6060f1SDimitry Andric   Create(ObjectLinkingLayer &ObjLinkingLayer, std::unique_ptr<LinkGraph> G) {
80fe6060f1SDimitry Andric     auto LGI = scanLinkGraph(ObjLinkingLayer.getExecutionSession(), *G);
81fe6060f1SDimitry Andric     return std::unique_ptr<LinkGraphMaterializationUnit>(
82fe6060f1SDimitry Andric         new LinkGraphMaterializationUnit(ObjLinkingLayer, std::move(G),
83fe6060f1SDimitry Andric                                          std::move(LGI)));
84fe6060f1SDimitry Andric   }
85fe6060f1SDimitry Andric 
86fe6060f1SDimitry Andric   StringRef getName() const override { return G->getName(); }
87fe6060f1SDimitry Andric   void materialize(std::unique_ptr<MaterializationResponsibility> MR) override {
88fe6060f1SDimitry Andric     ObjLinkingLayer.emit(std::move(MR), std::move(G));
89fe6060f1SDimitry Andric   }
90fe6060f1SDimitry Andric 
91fe6060f1SDimitry Andric private:
920eae32dcSDimitry Andric   static Interface scanLinkGraph(ExecutionSession &ES, LinkGraph &G) {
93fe6060f1SDimitry Andric 
940eae32dcSDimitry Andric     Interface LGI;
95fe6060f1SDimitry Andric 
96fe6060f1SDimitry Andric     for (auto *Sym : G.defined_symbols()) {
97fe6060f1SDimitry Andric       // Skip local symbols.
98fe6060f1SDimitry Andric       if (Sym->getScope() == Scope::Local)
99fe6060f1SDimitry Andric         continue;
100fe6060f1SDimitry Andric       assert(Sym->hasName() && "Anonymous non-local symbol?");
101fe6060f1SDimitry Andric 
102*06c3fb27SDimitry Andric       LGI.SymbolFlags[ES.intern(Sym->getName())] =
103*06c3fb27SDimitry Andric           getJITSymbolFlagsForSymbol(*Sym);
104fe6060f1SDimitry Andric     }
105fe6060f1SDimitry Andric 
106bdd1243dSDimitry Andric     if (hasInitializerSection(G))
107fe6060f1SDimitry Andric       LGI.InitSymbol = makeInitSymbol(ES, G);
108fe6060f1SDimitry Andric 
109fe6060f1SDimitry Andric     return LGI;
110fe6060f1SDimitry Andric   }
111fe6060f1SDimitry Andric 
112fe6060f1SDimitry Andric   static SymbolStringPtr makeInitSymbol(ExecutionSession &ES, LinkGraph &G) {
113fe6060f1SDimitry Andric     std::string InitSymString;
114fe6060f1SDimitry Andric     raw_string_ostream(InitSymString)
115fe6060f1SDimitry Andric         << "$." << G.getName() << ".__inits" << Counter++;
116fe6060f1SDimitry Andric     return ES.intern(InitSymString);
117fe6060f1SDimitry Andric   }
118fe6060f1SDimitry Andric 
119fe6060f1SDimitry Andric   LinkGraphMaterializationUnit(ObjectLinkingLayer &ObjLinkingLayer,
1200eae32dcSDimitry Andric                                std::unique_ptr<LinkGraph> G, Interface LGI)
1210eae32dcSDimitry Andric       : MaterializationUnit(std::move(LGI)), ObjLinkingLayer(ObjLinkingLayer),
1220eae32dcSDimitry Andric         G(std::move(G)) {}
123fe6060f1SDimitry Andric 
124fe6060f1SDimitry Andric   void discard(const JITDylib &JD, const SymbolStringPtr &Name) override {
125fe6060f1SDimitry Andric     for (auto *Sym : G->defined_symbols())
126fe6060f1SDimitry Andric       if (Sym->getName() == *Name) {
127fe6060f1SDimitry Andric         assert(Sym->getLinkage() == Linkage::Weak &&
128fe6060f1SDimitry Andric                "Discarding non-weak definition");
129fe6060f1SDimitry Andric         G->makeExternal(*Sym);
130fe6060f1SDimitry Andric         break;
131fe6060f1SDimitry Andric       }
132fe6060f1SDimitry Andric   }
133fe6060f1SDimitry Andric 
134fe6060f1SDimitry Andric   ObjectLinkingLayer &ObjLinkingLayer;
135fe6060f1SDimitry Andric   std::unique_ptr<LinkGraph> G;
136fe6060f1SDimitry Andric   static std::atomic<uint64_t> Counter;
137fe6060f1SDimitry Andric };
138fe6060f1SDimitry Andric 
139fe6060f1SDimitry Andric std::atomic<uint64_t> LinkGraphMaterializationUnit::Counter{0};
140fe6060f1SDimitry Andric 
141fe6060f1SDimitry Andric } // end anonymous namespace
142fe6060f1SDimitry Andric 
1430b57cec5SDimitry Andric namespace llvm {
1440b57cec5SDimitry Andric namespace orc {
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric class ObjectLinkingLayerJITLinkContext final : public JITLinkContext {
1470b57cec5SDimitry Andric public:
148e8d8bef9SDimitry Andric   ObjectLinkingLayerJITLinkContext(
149e8d8bef9SDimitry Andric       ObjectLinkingLayer &Layer,
150e8d8bef9SDimitry Andric       std::unique_ptr<MaterializationResponsibility> MR,
1510b57cec5SDimitry Andric       std::unique_ptr<MemoryBuffer> ObjBuffer)
152e8d8bef9SDimitry Andric       : JITLinkContext(&MR->getTargetJITDylib()), Layer(Layer),
153e8d8bef9SDimitry Andric         MR(std::move(MR)), ObjBuffer(std::move(ObjBuffer)) {}
1540b57cec5SDimitry Andric 
1558bcb0991SDimitry Andric   ~ObjectLinkingLayerJITLinkContext() {
1568bcb0991SDimitry Andric     // If there is an object buffer return function then use it to
1578bcb0991SDimitry Andric     // return ownership of the buffer.
158e8d8bef9SDimitry Andric     if (Layer.ReturnObjectBuffer && ObjBuffer)
1598bcb0991SDimitry Andric       Layer.ReturnObjectBuffer(std::move(ObjBuffer));
1608bcb0991SDimitry Andric   }
1618bcb0991SDimitry Andric 
162e8d8bef9SDimitry Andric   JITLinkMemoryManager &getMemoryManager() override { return Layer.MemMgr; }
1630b57cec5SDimitry Andric 
164fe6060f1SDimitry Andric   void notifyMaterializing(LinkGraph &G) {
165fe6060f1SDimitry Andric     for (auto &P : Layer.Plugins)
166fe6060f1SDimitry Andric       P->notifyMaterializing(*MR, G, *this,
167fe6060f1SDimitry Andric                              ObjBuffer ? ObjBuffer->getMemBufferRef()
168fe6060f1SDimitry Andric                              : MemoryBufferRef());
169fe6060f1SDimitry Andric   }
170fe6060f1SDimitry Andric 
1710b57cec5SDimitry Andric   void notifyFailed(Error Err) override {
172e8d8bef9SDimitry Andric     for (auto &P : Layer.Plugins)
173e8d8bef9SDimitry Andric       Err = joinErrors(std::move(Err), P->notifyFailed(*MR));
1740b57cec5SDimitry Andric     Layer.getExecutionSession().reportError(std::move(Err));
175e8d8bef9SDimitry Andric     MR->failMaterialization();
1760b57cec5SDimitry Andric   }
1770b57cec5SDimitry Andric 
178480093f4SDimitry Andric   void lookup(const LookupMap &Symbols,
1798bcb0991SDimitry Andric               std::unique_ptr<JITLinkAsyncLookupContinuation> LC) override {
1800b57cec5SDimitry Andric 
1815ffd83dbSDimitry Andric     JITDylibSearchOrder LinkOrder;
182e8d8bef9SDimitry Andric     MR->getTargetJITDylib().withLinkOrderDo(
1835ffd83dbSDimitry Andric         [&](const JITDylibSearchOrder &LO) { LinkOrder = LO; });
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric     auto &ES = Layer.getExecutionSession();
1860b57cec5SDimitry Andric 
187480093f4SDimitry Andric     SymbolLookupSet LookupSet;
188480093f4SDimitry Andric     for (auto &KV : Symbols) {
189480093f4SDimitry Andric       orc::SymbolLookupFlags LookupFlags;
190480093f4SDimitry Andric       switch (KV.second) {
191480093f4SDimitry Andric       case jitlink::SymbolLookupFlags::RequiredSymbol:
192480093f4SDimitry Andric         LookupFlags = orc::SymbolLookupFlags::RequiredSymbol;
193480093f4SDimitry Andric         break;
194480093f4SDimitry Andric       case jitlink::SymbolLookupFlags::WeaklyReferencedSymbol:
195480093f4SDimitry Andric         LookupFlags = orc::SymbolLookupFlags::WeaklyReferencedSymbol;
196480093f4SDimitry Andric         break;
197480093f4SDimitry Andric       }
198480093f4SDimitry Andric       LookupSet.add(ES.intern(KV.first), LookupFlags);
199480093f4SDimitry Andric     }
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric     // OnResolve -- De-intern the symbols and pass the result to the linker.
202e8d8bef9SDimitry Andric     auto OnResolve = [LookupContinuation =
203e8d8bef9SDimitry Andric                           std::move(LC)](Expected<SymbolMap> Result) mutable {
2040b57cec5SDimitry Andric       if (!Result)
2058bcb0991SDimitry Andric         LookupContinuation->run(Result.takeError());
2060b57cec5SDimitry Andric       else {
2070b57cec5SDimitry Andric         AsyncLookupResult LR;
2080b57cec5SDimitry Andric         for (auto &KV : *Result)
2090b57cec5SDimitry Andric           LR[*KV.first] = KV.second;
2108bcb0991SDimitry Andric         LookupContinuation->run(std::move(LR));
2110b57cec5SDimitry Andric       }
2120b57cec5SDimitry Andric     };
2130b57cec5SDimitry Andric 
2145ffd83dbSDimitry Andric     for (auto &KV : InternalNamedSymbolDeps) {
2155ffd83dbSDimitry Andric       SymbolDependenceMap InternalDeps;
216e8d8bef9SDimitry Andric       InternalDeps[&MR->getTargetJITDylib()] = std::move(KV.second);
217e8d8bef9SDimitry Andric       MR->addDependencies(KV.first, InternalDeps);
2185ffd83dbSDimitry Andric     }
2195ffd83dbSDimitry Andric 
2205ffd83dbSDimitry Andric     ES.lookup(LookupKind::Static, LinkOrder, std::move(LookupSet),
221480093f4SDimitry Andric               SymbolState::Resolved, std::move(OnResolve),
222480093f4SDimitry Andric               [this](const SymbolDependenceMap &Deps) {
2230b57cec5SDimitry Andric                 registerDependencies(Deps);
2240b57cec5SDimitry Andric               });
2250b57cec5SDimitry Andric   }
2260b57cec5SDimitry Andric 
227e8d8bef9SDimitry Andric   Error notifyResolved(LinkGraph &G) override {
2280b57cec5SDimitry Andric     auto &ES = Layer.getExecutionSession();
2290b57cec5SDimitry Andric 
2300b57cec5SDimitry Andric     SymbolFlagsMap ExtraSymbolsToClaim;
2310b57cec5SDimitry Andric     bool AutoClaim = Layer.AutoClaimObjectSymbols;
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric     SymbolMap InternedResult;
2348bcb0991SDimitry Andric     for (auto *Sym : G.defined_symbols())
2358bcb0991SDimitry Andric       if (Sym->hasName() && Sym->getScope() != Scope::Local) {
2368bcb0991SDimitry Andric         auto InternedName = ES.intern(Sym->getName());
237*06c3fb27SDimitry Andric         auto Ptr = getJITSymbolPtrForSymbol(*Sym, G.getTargetTriple());
238*06c3fb27SDimitry Andric         auto Flags = getJITSymbolFlagsForSymbol(*Sym);
239*06c3fb27SDimitry Andric         InternedResult[InternedName] = {Ptr, Flags};
240e8d8bef9SDimitry Andric         if (AutoClaim && !MR->getSymbols().count(InternedName)) {
2410b57cec5SDimitry Andric           assert(!ExtraSymbolsToClaim.count(InternedName) &&
2420b57cec5SDimitry Andric                  "Duplicate symbol to claim?");
2430b57cec5SDimitry Andric           ExtraSymbolsToClaim[InternedName] = Flags;
2440b57cec5SDimitry Andric         }
2450b57cec5SDimitry Andric       }
2460b57cec5SDimitry Andric 
2478bcb0991SDimitry Andric     for (auto *Sym : G.absolute_symbols())
24881ad6265SDimitry Andric       if (Sym->hasName() && Sym->getScope() != Scope::Local) {
2498bcb0991SDimitry Andric         auto InternedName = ES.intern(Sym->getName());
250*06c3fb27SDimitry Andric         auto Ptr = getJITSymbolPtrForSymbol(*Sym, G.getTargetTriple());
251*06c3fb27SDimitry Andric         auto Flags = getJITSymbolFlagsForSymbol(*Sym);
252*06c3fb27SDimitry Andric         InternedResult[InternedName] = {Ptr, Flags};
253e8d8bef9SDimitry Andric         if (AutoClaim && !MR->getSymbols().count(InternedName)) {
2540b57cec5SDimitry Andric           assert(!ExtraSymbolsToClaim.count(InternedName) &&
2550b57cec5SDimitry Andric                  "Duplicate symbol to claim?");
2560b57cec5SDimitry Andric           ExtraSymbolsToClaim[InternedName] = Flags;
2570b57cec5SDimitry Andric         }
2580b57cec5SDimitry Andric       }
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric     if (!ExtraSymbolsToClaim.empty())
261e8d8bef9SDimitry Andric       if (auto Err = MR->defineMaterializing(ExtraSymbolsToClaim))
262e8d8bef9SDimitry Andric         return Err;
2635ffd83dbSDimitry Andric 
2645ffd83dbSDimitry Andric     {
2655ffd83dbSDimitry Andric 
2660eae32dcSDimitry Andric       // Check that InternedResult matches up with MR->getSymbols(), overriding
2670eae32dcSDimitry Andric       // flags if requested.
2685ffd83dbSDimitry Andric       // This guards against faulty transformations / compilers / object caches.
2695ffd83dbSDimitry Andric 
2705ffd83dbSDimitry Andric       // First check that there aren't any missing symbols.
2715ffd83dbSDimitry Andric       size_t NumMaterializationSideEffectsOnlySymbols = 0;
2725ffd83dbSDimitry Andric       SymbolNameVector ExtraSymbols;
2735ffd83dbSDimitry Andric       SymbolNameVector MissingSymbols;
274e8d8bef9SDimitry Andric       for (auto &KV : MR->getSymbols()) {
2755ffd83dbSDimitry Andric 
2760eae32dcSDimitry Andric         auto I = InternedResult.find(KV.first);
2770eae32dcSDimitry Andric 
2785ffd83dbSDimitry Andric         // If this is a materialization-side-effects only symbol then bump
2795ffd83dbSDimitry Andric         // the counter and make sure it's *not* defined, otherwise make
2805ffd83dbSDimitry Andric         // sure that it is defined.
2815ffd83dbSDimitry Andric         if (KV.second.hasMaterializationSideEffectsOnly()) {
2825ffd83dbSDimitry Andric           ++NumMaterializationSideEffectsOnlySymbols;
2830eae32dcSDimitry Andric           if (I != InternedResult.end())
2845ffd83dbSDimitry Andric             ExtraSymbols.push_back(KV.first);
2855ffd83dbSDimitry Andric           continue;
2860eae32dcSDimitry Andric         } else if (I == InternedResult.end())
2875ffd83dbSDimitry Andric           MissingSymbols.push_back(KV.first);
2880eae32dcSDimitry Andric         else if (Layer.OverrideObjectFlags)
2890eae32dcSDimitry Andric           I->second.setFlags(KV.second);
2905ffd83dbSDimitry Andric       }
2915ffd83dbSDimitry Andric 
2925ffd83dbSDimitry Andric       // If there were missing symbols then report the error.
293e8d8bef9SDimitry Andric       if (!MissingSymbols.empty())
294349cc55cSDimitry Andric         return make_error<MissingSymbolDefinitions>(
295349cc55cSDimitry Andric             Layer.getExecutionSession().getSymbolStringPool(), G.getName(),
296e8d8bef9SDimitry Andric             std::move(MissingSymbols));
2975ffd83dbSDimitry Andric 
2985ffd83dbSDimitry Andric       // If there are more definitions than expected, add them to the
2995ffd83dbSDimitry Andric       // ExtraSymbols vector.
3005ffd83dbSDimitry Andric       if (InternedResult.size() >
301e8d8bef9SDimitry Andric           MR->getSymbols().size() - NumMaterializationSideEffectsOnlySymbols) {
3025ffd83dbSDimitry Andric         for (auto &KV : InternedResult)
303e8d8bef9SDimitry Andric           if (!MR->getSymbols().count(KV.first))
3045ffd83dbSDimitry Andric             ExtraSymbols.push_back(KV.first);
3055ffd83dbSDimitry Andric       }
3065ffd83dbSDimitry Andric 
3075ffd83dbSDimitry Andric       // If there were extra definitions then report the error.
308e8d8bef9SDimitry Andric       if (!ExtraSymbols.empty())
309349cc55cSDimitry Andric         return make_error<UnexpectedSymbolDefinitions>(
310349cc55cSDimitry Andric             Layer.getExecutionSession().getSymbolStringPool(), G.getName(),
311e8d8bef9SDimitry Andric             std::move(ExtraSymbols));
3125ffd83dbSDimitry Andric     }
3135ffd83dbSDimitry Andric 
314e8d8bef9SDimitry Andric     if (auto Err = MR->notifyResolved(InternedResult))
315e8d8bef9SDimitry Andric       return Err;
316e8d8bef9SDimitry Andric 
317e8d8bef9SDimitry Andric     Layer.notifyLoaded(*MR);
318e8d8bef9SDimitry Andric     return Error::success();
3190b57cec5SDimitry Andric   }
3200b57cec5SDimitry Andric 
321349cc55cSDimitry Andric   void notifyFinalized(JITLinkMemoryManager::FinalizedAlloc A) override {
322e8d8bef9SDimitry Andric     if (auto Err = Layer.notifyEmitted(*MR, std::move(A))) {
3230b57cec5SDimitry Andric       Layer.getExecutionSession().reportError(std::move(Err));
324e8d8bef9SDimitry Andric       MR->failMaterialization();
3250b57cec5SDimitry Andric       return;
3260b57cec5SDimitry Andric     }
327e8d8bef9SDimitry Andric     if (auto Err = MR->notifyEmitted()) {
3288bcb0991SDimitry Andric       Layer.getExecutionSession().reportError(std::move(Err));
329e8d8bef9SDimitry Andric       MR->failMaterialization();
3308bcb0991SDimitry Andric     }
3310b57cec5SDimitry Andric   }
3320b57cec5SDimitry Andric 
3338bcb0991SDimitry Andric   LinkGraphPassFunction getMarkLivePass(const Triple &TT) const override {
3348bcb0991SDimitry Andric     return [this](LinkGraph &G) { return markResponsibilitySymbolsLive(G); };
3350b57cec5SDimitry Andric   }
3360b57cec5SDimitry Andric 
337fe6060f1SDimitry Andric   Error modifyPassConfig(LinkGraph &LG, PassConfiguration &Config) override {
3380b57cec5SDimitry Andric     // Add passes to mark duplicate defs as should-discard, and to walk the
3398bcb0991SDimitry Andric     // link graph to build the symbol dependence graph.
340e8d8bef9SDimitry Andric     Config.PrePrunePasses.push_back([this](LinkGraph &G) {
341e8d8bef9SDimitry Andric       return claimOrExternalizeWeakAndCommonSymbols(G);
342e8d8bef9SDimitry Andric     });
3430b57cec5SDimitry Andric 
344fe6060f1SDimitry Andric     Layer.modifyPassConfig(*MR, LG, Config);
3450b57cec5SDimitry Andric 
3465ffd83dbSDimitry Andric     Config.PostPrunePasses.push_back(
3475ffd83dbSDimitry Andric         [this](LinkGraph &G) { return computeNamedSymbolDependencies(G); });
3485ffd83dbSDimitry Andric 
3490b57cec5SDimitry Andric     return Error::success();
3500b57cec5SDimitry Andric   }
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric private:
353fe6060f1SDimitry Andric   // Symbol name dependencies:
354fe6060f1SDimitry Andric   // Internal: Defined in this graph.
355fe6060f1SDimitry Andric   // External: Defined externally.
356fe6060f1SDimitry Andric   struct BlockSymbolDependencies {
3575ffd83dbSDimitry Andric     SymbolNameSet Internal, External;
3585ffd83dbSDimitry Andric   };
3595ffd83dbSDimitry Andric 
360fe6060f1SDimitry Andric   // Lazily populated map of blocks to BlockSymbolDependencies values.
361fe6060f1SDimitry Andric   class BlockDependenciesMap {
362fe6060f1SDimitry Andric   public:
363fe6060f1SDimitry Andric     BlockDependenciesMap(ExecutionSession &ES,
364fe6060f1SDimitry Andric                          DenseMap<const Block *, DenseSet<Block *>> BlockDeps)
365fe6060f1SDimitry Andric         : ES(ES), BlockDeps(std::move(BlockDeps)) {}
366fe6060f1SDimitry Andric 
367fe6060f1SDimitry Andric     const BlockSymbolDependencies &operator[](const Block &B) {
368fe6060f1SDimitry Andric       // Check the cache first.
369fe6060f1SDimitry Andric       auto I = BlockTransitiveDepsCache.find(&B);
370fe6060f1SDimitry Andric       if (I != BlockTransitiveDepsCache.end())
371fe6060f1SDimitry Andric         return I->second;
372fe6060f1SDimitry Andric 
373fe6060f1SDimitry Andric       // No value. Populate the cache.
374fe6060f1SDimitry Andric       BlockSymbolDependencies BTDCacheVal;
375fe6060f1SDimitry Andric       auto BDI = BlockDeps.find(&B);
376fe6060f1SDimitry Andric       assert(BDI != BlockDeps.end() && "No block dependencies");
377fe6060f1SDimitry Andric 
378fe6060f1SDimitry Andric       for (auto *BDep : BDI->second) {
379fe6060f1SDimitry Andric         auto &BID = getBlockImmediateDeps(*BDep);
380fe6060f1SDimitry Andric         for (auto &ExternalDep : BID.External)
381fe6060f1SDimitry Andric           BTDCacheVal.External.insert(ExternalDep);
382fe6060f1SDimitry Andric         for (auto &InternalDep : BID.Internal)
383fe6060f1SDimitry Andric           BTDCacheVal.Internal.insert(InternalDep);
384fe6060f1SDimitry Andric       }
385fe6060f1SDimitry Andric 
386fe6060f1SDimitry Andric       return BlockTransitiveDepsCache
387fe6060f1SDimitry Andric           .insert(std::make_pair(&B, std::move(BTDCacheVal)))
388fe6060f1SDimitry Andric           .first->second;
389fe6060f1SDimitry Andric     }
390fe6060f1SDimitry Andric 
391fe6060f1SDimitry Andric     SymbolStringPtr &getInternedName(Symbol &Sym) {
392fe6060f1SDimitry Andric       auto I = NameCache.find(&Sym);
393fe6060f1SDimitry Andric       if (I != NameCache.end())
394fe6060f1SDimitry Andric         return I->second;
395fe6060f1SDimitry Andric 
396fe6060f1SDimitry Andric       return NameCache.insert(std::make_pair(&Sym, ES.intern(Sym.getName())))
397fe6060f1SDimitry Andric           .first->second;
398fe6060f1SDimitry Andric     }
399fe6060f1SDimitry Andric 
400fe6060f1SDimitry Andric   private:
401fe6060f1SDimitry Andric     BlockSymbolDependencies &getBlockImmediateDeps(Block &B) {
402fe6060f1SDimitry Andric       // Check the cache first.
403fe6060f1SDimitry Andric       auto I = BlockImmediateDepsCache.find(&B);
404fe6060f1SDimitry Andric       if (I != BlockImmediateDepsCache.end())
405fe6060f1SDimitry Andric         return I->second;
406fe6060f1SDimitry Andric 
407fe6060f1SDimitry Andric       BlockSymbolDependencies BIDCacheVal;
408fe6060f1SDimitry Andric       for (auto &E : B.edges()) {
409fe6060f1SDimitry Andric         auto &Tgt = E.getTarget();
410fe6060f1SDimitry Andric         if (Tgt.getScope() != Scope::Local) {
411fe6060f1SDimitry Andric           if (Tgt.isExternal())
412fe6060f1SDimitry Andric             BIDCacheVal.External.insert(getInternedName(Tgt));
413fe6060f1SDimitry Andric           else
414fe6060f1SDimitry Andric             BIDCacheVal.Internal.insert(getInternedName(Tgt));
415fe6060f1SDimitry Andric         }
416fe6060f1SDimitry Andric       }
417fe6060f1SDimitry Andric 
418fe6060f1SDimitry Andric       return BlockImmediateDepsCache
419fe6060f1SDimitry Andric           .insert(std::make_pair(&B, std::move(BIDCacheVal)))
420fe6060f1SDimitry Andric           .first->second;
421fe6060f1SDimitry Andric     }
422fe6060f1SDimitry Andric 
423fe6060f1SDimitry Andric     ExecutionSession &ES;
424fe6060f1SDimitry Andric     DenseMap<const Block *, DenseSet<Block *>> BlockDeps;
425fe6060f1SDimitry Andric     DenseMap<const Symbol *, SymbolStringPtr> NameCache;
426fe6060f1SDimitry Andric     DenseMap<const Block *, BlockSymbolDependencies> BlockImmediateDepsCache;
427fe6060f1SDimitry Andric     DenseMap<const Block *, BlockSymbolDependencies> BlockTransitiveDepsCache;
428fe6060f1SDimitry Andric   };
4290b57cec5SDimitry Andric 
430e8d8bef9SDimitry Andric   Error claimOrExternalizeWeakAndCommonSymbols(LinkGraph &G) {
4310b57cec5SDimitry Andric     auto &ES = Layer.getExecutionSession();
4320b57cec5SDimitry Andric 
433e8d8bef9SDimitry Andric     SymbolFlagsMap NewSymbolsToClaim;
434e8d8bef9SDimitry Andric     std::vector<std::pair<SymbolStringPtr, Symbol *>> NameToSym;
435e8d8bef9SDimitry Andric 
436e8d8bef9SDimitry Andric     auto ProcessSymbol = [&](Symbol *Sym) {
437349cc55cSDimitry Andric       if (Sym->hasName() && Sym->getLinkage() == Linkage::Weak &&
438349cc55cSDimitry Andric           Sym->getScope() != Scope::Local) {
439e8d8bef9SDimitry Andric         auto Name = ES.intern(Sym->getName());
440e8d8bef9SDimitry Andric         if (!MR->getSymbols().count(ES.intern(Sym->getName()))) {
441*06c3fb27SDimitry Andric           NewSymbolsToClaim[Name] =
442*06c3fb27SDimitry Andric               getJITSymbolFlagsForSymbol(*Sym) | JITSymbolFlags::Weak;
443e8d8bef9SDimitry Andric           NameToSym.push_back(std::make_pair(std::move(Name), Sym));
4440b57cec5SDimitry Andric         }
445e8d8bef9SDimitry Andric       }
446e8d8bef9SDimitry Andric     };
447e8d8bef9SDimitry Andric 
448e8d8bef9SDimitry Andric     for (auto *Sym : G.defined_symbols())
449e8d8bef9SDimitry Andric       ProcessSymbol(Sym);
450e8d8bef9SDimitry Andric     for (auto *Sym : G.absolute_symbols())
451e8d8bef9SDimitry Andric       ProcessSymbol(Sym);
452e8d8bef9SDimitry Andric 
453e8d8bef9SDimitry Andric     // Attempt to claim all weak defs that we're not already responsible for.
454e8d8bef9SDimitry Andric     // This cannot fail -- any clashes will just result in rejection of our
455e8d8bef9SDimitry Andric     // claim, at which point we'll externalize that symbol.
456e8d8bef9SDimitry Andric     cantFail(MR->defineMaterializing(std::move(NewSymbolsToClaim)));
457e8d8bef9SDimitry Andric 
458bdd1243dSDimitry Andric     // Walk the list of symbols that we just tried to claim. Symbols that we're
459bdd1243dSDimitry Andric     // responsible for are marked live. Symbols that we're not responsible for
460bdd1243dSDimitry Andric     // are turned into external references.
461bdd1243dSDimitry Andric     for (auto &KV : NameToSym) {
462bdd1243dSDimitry Andric       if (MR->getSymbols().count(KV.first))
463bdd1243dSDimitry Andric         KV.second->setLive(true);
464bdd1243dSDimitry Andric       else
465e8d8bef9SDimitry Andric         G.makeExternal(*KV.second);
466bdd1243dSDimitry Andric     }
4670b57cec5SDimitry Andric 
4680b57cec5SDimitry Andric     return Error::success();
4690b57cec5SDimitry Andric   }
4700b57cec5SDimitry Andric 
4718bcb0991SDimitry Andric   Error markResponsibilitySymbolsLive(LinkGraph &G) const {
4720b57cec5SDimitry Andric     auto &ES = Layer.getExecutionSession();
4738bcb0991SDimitry Andric     for (auto *Sym : G.defined_symbols())
474e8d8bef9SDimitry Andric       if (Sym->hasName() && MR->getSymbols().count(ES.intern(Sym->getName())))
4758bcb0991SDimitry Andric         Sym->setLive(true);
4760b57cec5SDimitry Andric     return Error::success();
4770b57cec5SDimitry Andric   }
4780b57cec5SDimitry Andric 
4798bcb0991SDimitry Andric   Error computeNamedSymbolDependencies(LinkGraph &G) {
480e8d8bef9SDimitry Andric     auto &ES = MR->getTargetJITDylib().getExecutionSession();
481fe6060f1SDimitry Andric     auto BlockDeps = computeBlockNonLocalDeps(G);
4820b57cec5SDimitry Andric 
4835ffd83dbSDimitry Andric     // Compute dependencies for symbols defined in the JITLink graph.
4848bcb0991SDimitry Andric     for (auto *Sym : G.defined_symbols()) {
4850b57cec5SDimitry Andric 
4865ffd83dbSDimitry Andric       // Skip local symbols: we do not track dependencies for these.
4878bcb0991SDimitry Andric       if (Sym->getScope() == Scope::Local)
4880b57cec5SDimitry Andric         continue;
4895ffd83dbSDimitry Andric       assert(Sym->hasName() &&
4905ffd83dbSDimitry Andric              "Defined non-local jitlink::Symbol should have a name");
4910b57cec5SDimitry Andric 
492fe6060f1SDimitry Andric       auto &SymDeps = BlockDeps[Sym->getBlock()];
493fe6060f1SDimitry Andric       if (SymDeps.External.empty() && SymDeps.Internal.empty())
4945ffd83dbSDimitry Andric         continue;
4955ffd83dbSDimitry Andric 
4965ffd83dbSDimitry Andric       auto SymName = ES.intern(Sym->getName());
497fe6060f1SDimitry Andric       if (!SymDeps.External.empty())
498fe6060f1SDimitry Andric         ExternalNamedSymbolDeps[SymName] = SymDeps.External;
499fe6060f1SDimitry Andric       if (!SymDeps.Internal.empty())
500fe6060f1SDimitry Andric         InternalNamedSymbolDeps[SymName] = SymDeps.Internal;
5015ffd83dbSDimitry Andric     }
5025ffd83dbSDimitry Andric 
5035ffd83dbSDimitry Andric     for (auto &P : Layer.Plugins) {
504fe6060f1SDimitry Andric       auto SynthDeps = P->getSyntheticSymbolDependencies(*MR);
505fe6060f1SDimitry Andric       if (SynthDeps.empty())
5065ffd83dbSDimitry Andric         continue;
5075ffd83dbSDimitry Andric 
508fe6060f1SDimitry Andric       DenseSet<Block *> BlockVisited;
509fe6060f1SDimitry Andric       for (auto &KV : SynthDeps) {
5105ffd83dbSDimitry Andric         auto &Name = KV.first;
511fe6060f1SDimitry Andric         auto &DepsForName = KV.second;
512fe6060f1SDimitry Andric         for (auto *Sym : DepsForName) {
513fe6060f1SDimitry Andric           if (Sym->getScope() == Scope::Local) {
514fe6060f1SDimitry Andric             auto &BDeps = BlockDeps[Sym->getBlock()];
515fe6060f1SDimitry Andric             for (auto &S : BDeps.Internal)
5165ffd83dbSDimitry Andric               InternalNamedSymbolDeps[Name].insert(S);
517fe6060f1SDimitry Andric             for (auto &S : BDeps.External)
5185ffd83dbSDimitry Andric               ExternalNamedSymbolDeps[Name].insert(S);
519fe6060f1SDimitry Andric           } else {
520fe6060f1SDimitry Andric             if (Sym->isExternal())
521fe6060f1SDimitry Andric               ExternalNamedSymbolDeps[Name].insert(
522fe6060f1SDimitry Andric                   BlockDeps.getInternedName(*Sym));
523fe6060f1SDimitry Andric             else
524fe6060f1SDimitry Andric               InternalNamedSymbolDeps[Name].insert(
525fe6060f1SDimitry Andric                   BlockDeps.getInternedName(*Sym));
526fe6060f1SDimitry Andric           }
5270b57cec5SDimitry Andric         }
5280b57cec5SDimitry Andric       }
5290b57cec5SDimitry Andric     }
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric     return Error::success();
5320b57cec5SDimitry Andric   }
5330b57cec5SDimitry Andric 
534fe6060f1SDimitry Andric   BlockDependenciesMap computeBlockNonLocalDeps(LinkGraph &G) {
535fe6060f1SDimitry Andric     // First calculate the reachable-via-non-local-symbol blocks for each block.
536fe6060f1SDimitry Andric     struct BlockInfo {
537fe6060f1SDimitry Andric       DenseSet<Block *> Dependencies;
538fe6060f1SDimitry Andric       DenseSet<Block *> Dependants;
539fe6060f1SDimitry Andric       bool DependenciesChanged = true;
5400b57cec5SDimitry Andric     };
541fe6060f1SDimitry Andric     DenseMap<Block *, BlockInfo> BlockInfos;
542fe6060f1SDimitry Andric     SmallVector<Block *> WorkList;
5430b57cec5SDimitry Andric 
544fe6060f1SDimitry Andric     // Pre-allocate map entries. This prevents any iterator/reference
545fe6060f1SDimitry Andric     // invalidation in the next loop.
546fe6060f1SDimitry Andric     for (auto *B : G.blocks())
547fe6060f1SDimitry Andric       (void)BlockInfos[B];
548fe6060f1SDimitry Andric 
549fe6060f1SDimitry Andric     // Build initial worklist, record block dependencies/dependants and
550fe6060f1SDimitry Andric     // non-local symbol dependencies.
551fe6060f1SDimitry Andric     for (auto *B : G.blocks()) {
552fe6060f1SDimitry Andric       auto &BI = BlockInfos[B];
553fe6060f1SDimitry Andric       for (auto &E : B->edges()) {
554bdd1243dSDimitry Andric         if (E.getTarget().getScope() == Scope::Local &&
555bdd1243dSDimitry Andric             !E.getTarget().isAbsolute()) {
556fe6060f1SDimitry Andric           auto &TgtB = E.getTarget().getBlock();
557fe6060f1SDimitry Andric           if (&TgtB != B) {
558fe6060f1SDimitry Andric             BI.Dependencies.insert(&TgtB);
559fe6060f1SDimitry Andric             BlockInfos[&TgtB].Dependants.insert(B);
560fe6060f1SDimitry Andric           }
5610b57cec5SDimitry Andric         }
5620b57cec5SDimitry Andric       }
5630b57cec5SDimitry Andric 
564fe6060f1SDimitry Andric       // If this node has both dependants and dependencies then add it to the
565fe6060f1SDimitry Andric       // worklist to propagate the dependencies to the dependants.
566fe6060f1SDimitry Andric       if (!BI.Dependants.empty() && !BI.Dependencies.empty())
567fe6060f1SDimitry Andric         WorkList.push_back(B);
5680b57cec5SDimitry Andric     }
5690b57cec5SDimitry Andric 
570fe6060f1SDimitry Andric     // Propagate block-level dependencies through the block-dependence graph.
571fe6060f1SDimitry Andric     while (!WorkList.empty()) {
572349cc55cSDimitry Andric       auto *B = WorkList.pop_back_val();
5730b57cec5SDimitry Andric 
574fe6060f1SDimitry Andric       auto &BI = BlockInfos[B];
575fe6060f1SDimitry Andric       assert(BI.DependenciesChanged &&
576fe6060f1SDimitry Andric              "Block in worklist has unchanged dependencies");
577fe6060f1SDimitry Andric       BI.DependenciesChanged = false;
578fe6060f1SDimitry Andric       for (auto *Dependant : BI.Dependants) {
579fe6060f1SDimitry Andric         auto &DependantBI = BlockInfos[Dependant];
580fe6060f1SDimitry Andric         for (auto *Dependency : BI.Dependencies) {
581fe6060f1SDimitry Andric           if (Dependant != Dependency &&
582fe6060f1SDimitry Andric               DependantBI.Dependencies.insert(Dependency).second)
583fe6060f1SDimitry Andric             if (!DependantBI.DependenciesChanged) {
584fe6060f1SDimitry Andric               DependantBI.DependenciesChanged = true;
585fe6060f1SDimitry Andric               WorkList.push_back(Dependant);
5860b57cec5SDimitry Andric             }
5870b57cec5SDimitry Andric         }
5885ffd83dbSDimitry Andric       }
5895ffd83dbSDimitry Andric     }
5905ffd83dbSDimitry Andric 
591fe6060f1SDimitry Andric     DenseMap<const Block *, DenseSet<Block *>> BlockDeps;
592fe6060f1SDimitry Andric     for (auto &KV : BlockInfos)
593fe6060f1SDimitry Andric       BlockDeps[KV.first] = std::move(KV.second.Dependencies);
594fe6060f1SDimitry Andric 
595fe6060f1SDimitry Andric     return BlockDependenciesMap(Layer.getExecutionSession(),
596fe6060f1SDimitry Andric                                 std::move(BlockDeps));
5970b57cec5SDimitry Andric   }
5980b57cec5SDimitry Andric 
5990b57cec5SDimitry Andric   void registerDependencies(const SymbolDependenceMap &QueryDeps) {
6005ffd83dbSDimitry Andric     for (auto &NamedDepsEntry : ExternalNamedSymbolDeps) {
6010b57cec5SDimitry Andric       auto &Name = NamedDepsEntry.first;
6020b57cec5SDimitry Andric       auto &NameDeps = NamedDepsEntry.second;
6030b57cec5SDimitry Andric       SymbolDependenceMap SymbolDeps;
6040b57cec5SDimitry Andric 
6050b57cec5SDimitry Andric       for (const auto &QueryDepsEntry : QueryDeps) {
6060b57cec5SDimitry Andric         JITDylib &SourceJD = *QueryDepsEntry.first;
6070b57cec5SDimitry Andric         const SymbolNameSet &Symbols = QueryDepsEntry.second;
6080b57cec5SDimitry Andric         auto &DepsForJD = SymbolDeps[&SourceJD];
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric         for (const auto &S : Symbols)
6110b57cec5SDimitry Andric           if (NameDeps.count(S))
6120b57cec5SDimitry Andric             DepsForJD.insert(S);
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric         if (DepsForJD.empty())
6150b57cec5SDimitry Andric           SymbolDeps.erase(&SourceJD);
6160b57cec5SDimitry Andric       }
6170b57cec5SDimitry Andric 
618e8d8bef9SDimitry Andric       MR->addDependencies(Name, SymbolDeps);
6190b57cec5SDimitry Andric     }
6200b57cec5SDimitry Andric   }
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric   ObjectLinkingLayer &Layer;
623e8d8bef9SDimitry Andric   std::unique_ptr<MaterializationResponsibility> MR;
6240b57cec5SDimitry Andric   std::unique_ptr<MemoryBuffer> ObjBuffer;
6255ffd83dbSDimitry Andric   DenseMap<SymbolStringPtr, SymbolNameSet> ExternalNamedSymbolDeps;
6265ffd83dbSDimitry Andric   DenseMap<SymbolStringPtr, SymbolNameSet> InternalNamedSymbolDeps;
6270b57cec5SDimitry Andric };
6280b57cec5SDimitry Andric 
62981ad6265SDimitry Andric ObjectLinkingLayer::Plugin::~Plugin() = default;
6300b57cec5SDimitry Andric 
631fe6060f1SDimitry Andric char ObjectLinkingLayer::ID;
632fe6060f1SDimitry Andric 
633fe6060f1SDimitry Andric using BaseT = RTTIExtends<ObjectLinkingLayer, ObjectLayer>;
634fe6060f1SDimitry Andric 
635fe6060f1SDimitry Andric ObjectLinkingLayer::ObjectLinkingLayer(ExecutionSession &ES)
636fe6060f1SDimitry Andric     : BaseT(ES), MemMgr(ES.getExecutorProcessControl().getMemMgr()) {
637fe6060f1SDimitry Andric   ES.registerResourceManager(*this);
638fe6060f1SDimitry Andric }
639fe6060f1SDimitry Andric 
640e8d8bef9SDimitry Andric ObjectLinkingLayer::ObjectLinkingLayer(ExecutionSession &ES,
641e8d8bef9SDimitry Andric                                        JITLinkMemoryManager &MemMgr)
642fe6060f1SDimitry Andric     : BaseT(ES), MemMgr(MemMgr) {
643e8d8bef9SDimitry Andric   ES.registerResourceManager(*this);
6440b57cec5SDimitry Andric }
6450b57cec5SDimitry Andric 
646e8d8bef9SDimitry Andric ObjectLinkingLayer::ObjectLinkingLayer(
647e8d8bef9SDimitry Andric     ExecutionSession &ES, std::unique_ptr<JITLinkMemoryManager> MemMgr)
648fe6060f1SDimitry Andric     : BaseT(ES), MemMgr(*MemMgr), MemMgrOwnership(std::move(MemMgr)) {
649e8d8bef9SDimitry Andric   ES.registerResourceManager(*this);
650e8d8bef9SDimitry Andric }
651e8d8bef9SDimitry Andric 
652e8d8bef9SDimitry Andric ObjectLinkingLayer::~ObjectLinkingLayer() {
653e8d8bef9SDimitry Andric   assert(Allocs.empty() && "Layer destroyed with resources still attached");
654e8d8bef9SDimitry Andric   getExecutionSession().deregisterResourceManager(*this);
655e8d8bef9SDimitry Andric }
656e8d8bef9SDimitry Andric 
657fe6060f1SDimitry Andric Error ObjectLinkingLayer::add(ResourceTrackerSP RT,
658fe6060f1SDimitry Andric                               std::unique_ptr<LinkGraph> G) {
659fe6060f1SDimitry Andric   auto &JD = RT->getJITDylib();
660fe6060f1SDimitry Andric   return JD.define(LinkGraphMaterializationUnit::Create(*this, std::move(G)),
661fe6060f1SDimitry Andric                    std::move(RT));
662fe6060f1SDimitry Andric }
663fe6060f1SDimitry Andric 
664e8d8bef9SDimitry Andric void ObjectLinkingLayer::emit(std::unique_ptr<MaterializationResponsibility> R,
6650b57cec5SDimitry Andric                               std::unique_ptr<MemoryBuffer> O) {
6660b57cec5SDimitry Andric   assert(O && "Object must not be null");
667fe6060f1SDimitry Andric   MemoryBufferRef ObjBuffer = O->getMemBufferRef();
668fe6060f1SDimitry Andric 
669e8d8bef9SDimitry Andric   auto Ctx = std::make_unique<ObjectLinkingLayerJITLinkContext>(
670e8d8bef9SDimitry Andric       *this, std::move(R), std::move(O));
671fe6060f1SDimitry Andric   if (auto G = createLinkGraphFromObject(ObjBuffer)) {
672fe6060f1SDimitry Andric     Ctx->notifyMaterializing(**G);
673e8d8bef9SDimitry Andric     link(std::move(*G), std::move(Ctx));
674fe6060f1SDimitry Andric   } else {
675e8d8bef9SDimitry Andric     Ctx->notifyFailed(G.takeError());
676e8d8bef9SDimitry Andric   }
677fe6060f1SDimitry Andric }
678e8d8bef9SDimitry Andric 
679e8d8bef9SDimitry Andric void ObjectLinkingLayer::emit(std::unique_ptr<MaterializationResponsibility> R,
680e8d8bef9SDimitry Andric                               std::unique_ptr<LinkGraph> G) {
681fe6060f1SDimitry Andric   auto Ctx = std::make_unique<ObjectLinkingLayerJITLinkContext>(
682fe6060f1SDimitry Andric       *this, std::move(R), nullptr);
683fe6060f1SDimitry Andric   Ctx->notifyMaterializing(*G);
684fe6060f1SDimitry Andric   link(std::move(G), std::move(Ctx));
6850b57cec5SDimitry Andric }
6860b57cec5SDimitry Andric 
6870b57cec5SDimitry Andric void ObjectLinkingLayer::modifyPassConfig(MaterializationResponsibility &MR,
688fe6060f1SDimitry Andric                                           LinkGraph &G,
6890b57cec5SDimitry Andric                                           PassConfiguration &PassConfig) {
6900b57cec5SDimitry Andric   for (auto &P : Plugins)
691fe6060f1SDimitry Andric     P->modifyPassConfig(MR, G, PassConfig);
6920b57cec5SDimitry Andric }
6930b57cec5SDimitry Andric 
6940b57cec5SDimitry Andric void ObjectLinkingLayer::notifyLoaded(MaterializationResponsibility &MR) {
6950b57cec5SDimitry Andric   for (auto &P : Plugins)
6960b57cec5SDimitry Andric     P->notifyLoaded(MR);
6970b57cec5SDimitry Andric }
6980b57cec5SDimitry Andric 
6990b57cec5SDimitry Andric Error ObjectLinkingLayer::notifyEmitted(MaterializationResponsibility &MR,
700349cc55cSDimitry Andric                                         FinalizedAlloc FA) {
7010b57cec5SDimitry Andric   Error Err = Error::success();
7020b57cec5SDimitry Andric   for (auto &P : Plugins)
7030b57cec5SDimitry Andric     Err = joinErrors(std::move(Err), P->notifyEmitted(MR));
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric   if (Err)
7060b57cec5SDimitry Andric     return Err;
7070b57cec5SDimitry Andric 
708e8d8bef9SDimitry Andric   return MR.withResourceKeyDo(
709349cc55cSDimitry Andric       [&](ResourceKey K) { Allocs[K].push_back(std::move(FA)); });
7100b57cec5SDimitry Andric }
7110b57cec5SDimitry Andric 
712bdd1243dSDimitry Andric Error ObjectLinkingLayer::handleRemoveResources(JITDylib &JD, ResourceKey K) {
7130b57cec5SDimitry Andric 
714349cc55cSDimitry Andric   {
7150b57cec5SDimitry Andric     Error Err = Error::success();
7160b57cec5SDimitry Andric     for (auto &P : Plugins)
717bdd1243dSDimitry Andric       Err = joinErrors(std::move(Err), P->notifyRemovingResources(JD, K));
718349cc55cSDimitry Andric     if (Err)
719349cc55cSDimitry Andric       return Err;
720349cc55cSDimitry Andric   }
7210b57cec5SDimitry Andric 
722349cc55cSDimitry Andric   std::vector<FinalizedAlloc> AllocsToRemove;
723e8d8bef9SDimitry Andric   getExecutionSession().runSessionLocked([&] {
724e8d8bef9SDimitry Andric     auto I = Allocs.find(K);
725e8d8bef9SDimitry Andric     if (I != Allocs.end()) {
726e8d8bef9SDimitry Andric       std::swap(AllocsToRemove, I->second);
727e8d8bef9SDimitry Andric       Allocs.erase(I);
7280b57cec5SDimitry Andric     }
729e8d8bef9SDimitry Andric   });
7300b57cec5SDimitry Andric 
731349cc55cSDimitry Andric   if (AllocsToRemove.empty())
732349cc55cSDimitry Andric     return Error::success();
7330b57cec5SDimitry Andric 
734349cc55cSDimitry Andric   return MemMgr.deallocate(std::move(AllocsToRemove));
7350b57cec5SDimitry Andric }
7360b57cec5SDimitry Andric 
737bdd1243dSDimitry Andric void ObjectLinkingLayer::handleTransferResources(JITDylib &JD,
738bdd1243dSDimitry Andric                                                  ResourceKey DstKey,
739e8d8bef9SDimitry Andric                                                  ResourceKey SrcKey) {
740e8d8bef9SDimitry Andric   auto I = Allocs.find(SrcKey);
741e8d8bef9SDimitry Andric   if (I != Allocs.end()) {
742e8d8bef9SDimitry Andric     auto &SrcAllocs = I->second;
743e8d8bef9SDimitry Andric     auto &DstAllocs = Allocs[DstKey];
744e8d8bef9SDimitry Andric     DstAllocs.reserve(DstAllocs.size() + SrcAllocs.size());
745e8d8bef9SDimitry Andric     for (auto &Alloc : SrcAllocs)
746e8d8bef9SDimitry Andric       DstAllocs.push_back(std::move(Alloc));
747e8d8bef9SDimitry Andric 
748e8d8bef9SDimitry Andric     // Erase SrcKey entry using value rather than iterator I: I may have been
749e8d8bef9SDimitry Andric     // invalidated when we looked up DstKey.
750e8d8bef9SDimitry Andric     Allocs.erase(SrcKey);
751e8d8bef9SDimitry Andric   }
752e8d8bef9SDimitry Andric 
753e8d8bef9SDimitry Andric   for (auto &P : Plugins)
754bdd1243dSDimitry Andric     P->notifyTransferringResources(JD, DstKey, SrcKey);
755e8d8bef9SDimitry Andric }
756e8d8bef9SDimitry Andric 
7570b57cec5SDimitry Andric EHFrameRegistrationPlugin::EHFrameRegistrationPlugin(
758e8d8bef9SDimitry Andric     ExecutionSession &ES, std::unique_ptr<EHFrameRegistrar> Registrar)
759e8d8bef9SDimitry Andric     : ES(ES), Registrar(std::move(Registrar)) {}
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric void EHFrameRegistrationPlugin::modifyPassConfig(
762fe6060f1SDimitry Andric     MaterializationResponsibility &MR, LinkGraph &G,
7630b57cec5SDimitry Andric     PassConfiguration &PassConfig) {
7640b57cec5SDimitry Andric 
7655ffd83dbSDimitry Andric   PassConfig.PostFixupPasses.push_back(createEHFrameRecorderPass(
76604eeddc0SDimitry Andric       G.getTargetTriple(), [this, &MR](ExecutorAddr Addr, size_t Size) {
7675ffd83dbSDimitry Andric         if (Addr) {
7685ffd83dbSDimitry Andric           std::lock_guard<std::mutex> Lock(EHFramePluginMutex);
7695ffd83dbSDimitry Andric           assert(!InProcessLinks.count(&MR) &&
7705ffd83dbSDimitry Andric                  "Link for MR already being tracked?");
7718bcb0991SDimitry Andric           InProcessLinks[&MR] = {Addr, Size};
7725ffd83dbSDimitry Andric         }
7730b57cec5SDimitry Andric       }));
7740b57cec5SDimitry Andric }
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric Error EHFrameRegistrationPlugin::notifyEmitted(
7770b57cec5SDimitry Andric     MaterializationResponsibility &MR) {
778e8d8bef9SDimitry Andric 
77904eeddc0SDimitry Andric   ExecutorAddrRange EmittedRange;
780e8d8bef9SDimitry Andric   {
7815ffd83dbSDimitry Andric     std::lock_guard<std::mutex> Lock(EHFramePluginMutex);
7820b57cec5SDimitry Andric 
7838bcb0991SDimitry Andric     auto EHFrameRangeItr = InProcessLinks.find(&MR);
7848bcb0991SDimitry Andric     if (EHFrameRangeItr == InProcessLinks.end())
7850b57cec5SDimitry Andric       return Error::success();
7860b57cec5SDimitry Andric 
787e8d8bef9SDimitry Andric     EmittedRange = EHFrameRangeItr->second;
78804eeddc0SDimitry Andric     assert(EmittedRange.Start && "eh-frame addr to register can not be null");
7898bcb0991SDimitry Andric     InProcessLinks.erase(EHFrameRangeItr);
7900b57cec5SDimitry Andric   }
7910b57cec5SDimitry Andric 
792e8d8bef9SDimitry Andric   if (auto Err = MR.withResourceKeyDo(
793e8d8bef9SDimitry Andric           [&](ResourceKey K) { EHFrameRanges[K].push_back(EmittedRange); }))
794e8d8bef9SDimitry Andric     return Err;
7955ffd83dbSDimitry Andric 
79604eeddc0SDimitry Andric   return Registrar->registerEHFrames(EmittedRange);
797e8d8bef9SDimitry Andric }
798e8d8bef9SDimitry Andric 
799e8d8bef9SDimitry Andric Error EHFrameRegistrationPlugin::notifyFailed(
800e8d8bef9SDimitry Andric     MaterializationResponsibility &MR) {
801e8d8bef9SDimitry Andric   std::lock_guard<std::mutex> Lock(EHFramePluginMutex);
802e8d8bef9SDimitry Andric   InProcessLinks.erase(&MR);
8030b57cec5SDimitry Andric   return Error::success();
8040b57cec5SDimitry Andric }
8050b57cec5SDimitry Andric 
806bdd1243dSDimitry Andric Error EHFrameRegistrationPlugin::notifyRemovingResources(JITDylib &JD,
807bdd1243dSDimitry Andric                                                          ResourceKey K) {
80804eeddc0SDimitry Andric   std::vector<ExecutorAddrRange> RangesToRemove;
8090b57cec5SDimitry Andric 
810e8d8bef9SDimitry Andric   ES.runSessionLocked([&] {
811e8d8bef9SDimitry Andric     auto I = EHFrameRanges.find(K);
812e8d8bef9SDimitry Andric     if (I != EHFrameRanges.end()) {
813e8d8bef9SDimitry Andric       RangesToRemove = std::move(I->second);
814e8d8bef9SDimitry Andric       EHFrameRanges.erase(I);
815e8d8bef9SDimitry Andric     }
816e8d8bef9SDimitry Andric   });
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric   Error Err = Error::success();
819e8d8bef9SDimitry Andric   while (!RangesToRemove.empty()) {
820e8d8bef9SDimitry Andric     auto RangeToRemove = RangesToRemove.back();
821e8d8bef9SDimitry Andric     RangesToRemove.pop_back();
82204eeddc0SDimitry Andric     assert(RangeToRemove.Start && "Untracked eh-frame range must not be null");
82304eeddc0SDimitry Andric     Err = joinErrors(std::move(Err),
82404eeddc0SDimitry Andric                      Registrar->deregisterEHFrames(RangeToRemove));
8250b57cec5SDimitry Andric   }
8260b57cec5SDimitry Andric 
8270b57cec5SDimitry Andric   return Err;
8280b57cec5SDimitry Andric }
8290b57cec5SDimitry Andric 
830e8d8bef9SDimitry Andric void EHFrameRegistrationPlugin::notifyTransferringResources(
831bdd1243dSDimitry Andric     JITDylib &JD, ResourceKey DstKey, ResourceKey SrcKey) {
832e8d8bef9SDimitry Andric   auto SI = EHFrameRanges.find(SrcKey);
833fe6060f1SDimitry Andric   if (SI == EHFrameRanges.end())
834fe6060f1SDimitry Andric     return;
835fe6060f1SDimitry Andric 
836fe6060f1SDimitry Andric   auto DI = EHFrameRanges.find(DstKey);
837fe6060f1SDimitry Andric   if (DI != EHFrameRanges.end()) {
838e8d8bef9SDimitry Andric     auto &SrcRanges = SI->second;
839fe6060f1SDimitry Andric     auto &DstRanges = DI->second;
840e8d8bef9SDimitry Andric     DstRanges.reserve(DstRanges.size() + SrcRanges.size());
841e8d8bef9SDimitry Andric     for (auto &SrcRange : SrcRanges)
842e8d8bef9SDimitry Andric       DstRanges.push_back(std::move(SrcRange));
843e8d8bef9SDimitry Andric     EHFrameRanges.erase(SI);
844fe6060f1SDimitry Andric   } else {
845fe6060f1SDimitry Andric     // We need to move SrcKey's ranges over without invalidating the SI
846fe6060f1SDimitry Andric     // iterator.
847fe6060f1SDimitry Andric     auto Tmp = std::move(SI->second);
848fe6060f1SDimitry Andric     EHFrameRanges.erase(SI);
849fe6060f1SDimitry Andric     EHFrameRanges[DstKey] = std::move(Tmp);
850e8d8bef9SDimitry Andric   }
851e8d8bef9SDimitry Andric }
852e8d8bef9SDimitry Andric 
8530b57cec5SDimitry Andric } // End namespace orc.
8540b57cec5SDimitry Andric } // End namespace llvm.
855