ObjectLinkingLayer.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. //===------- ObjectLinkingLayer.cpp - JITLink backed ORC ObjectLayer ------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
  9. #include "llvm/ExecutionEngine/JITLink/EHFrameSupport.h"
  10. #include "llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h"
  11. #include "llvm/ExecutionEngine/Orc/ObjectFileInterface.h"
  12. #include "llvm/Support/MemoryBuffer.h"
  13. #include <string>
  14. #include <vector>
  15. #define DEBUG_TYPE "orc"
  16. using namespace llvm;
  17. using namespace llvm::jitlink;
  18. using namespace llvm::orc;
  19. namespace {
  20. class LinkGraphMaterializationUnit : public MaterializationUnit {
  21. public:
  22. static std::unique_ptr<LinkGraphMaterializationUnit>
  23. Create(ObjectLinkingLayer &ObjLinkingLayer, std::unique_ptr<LinkGraph> G) {
  24. auto LGI = scanLinkGraph(ObjLinkingLayer.getExecutionSession(), *G);
  25. return std::unique_ptr<LinkGraphMaterializationUnit>(
  26. new LinkGraphMaterializationUnit(ObjLinkingLayer, std::move(G),
  27. std::move(LGI)));
  28. }
  29. StringRef getName() const override { return G->getName(); }
  30. void materialize(std::unique_ptr<MaterializationResponsibility> MR) override {
  31. ObjLinkingLayer.emit(std::move(MR), std::move(G));
  32. }
  33. private:
  34. static Interface scanLinkGraph(ExecutionSession &ES, LinkGraph &G) {
  35. Interface LGI;
  36. for (auto *Sym : G.defined_symbols()) {
  37. // Skip local symbols.
  38. if (Sym->getScope() == Scope::Local)
  39. continue;
  40. assert(Sym->hasName() && "Anonymous non-local symbol?");
  41. JITSymbolFlags Flags;
  42. if (Sym->getScope() == Scope::Default)
  43. Flags |= JITSymbolFlags::Exported;
  44. if (Sym->isCallable())
  45. Flags |= JITSymbolFlags::Callable;
  46. LGI.SymbolFlags[ES.intern(Sym->getName())] = Flags;
  47. }
  48. if (hasInitializerSection(G))
  49. LGI.InitSymbol = makeInitSymbol(ES, G);
  50. return LGI;
  51. }
  52. static SymbolStringPtr makeInitSymbol(ExecutionSession &ES, LinkGraph &G) {
  53. std::string InitSymString;
  54. raw_string_ostream(InitSymString)
  55. << "$." << G.getName() << ".__inits" << Counter++;
  56. return ES.intern(InitSymString);
  57. }
  58. LinkGraphMaterializationUnit(ObjectLinkingLayer &ObjLinkingLayer,
  59. std::unique_ptr<LinkGraph> G, Interface LGI)
  60. : MaterializationUnit(std::move(LGI)), ObjLinkingLayer(ObjLinkingLayer),
  61. G(std::move(G)) {}
  62. void discard(const JITDylib &JD, const SymbolStringPtr &Name) override {
  63. for (auto *Sym : G->defined_symbols())
  64. if (Sym->getName() == *Name) {
  65. assert(Sym->getLinkage() == Linkage::Weak &&
  66. "Discarding non-weak definition");
  67. G->makeExternal(*Sym);
  68. break;
  69. }
  70. }
  71. ObjectLinkingLayer &ObjLinkingLayer;
  72. std::unique_ptr<LinkGraph> G;
  73. static std::atomic<uint64_t> Counter;
  74. };
  75. std::atomic<uint64_t> LinkGraphMaterializationUnit::Counter{0};
  76. } // end anonymous namespace
  77. namespace llvm {
  78. namespace orc {
  79. class ObjectLinkingLayerJITLinkContext final : public JITLinkContext {
  80. public:
  81. ObjectLinkingLayerJITLinkContext(
  82. ObjectLinkingLayer &Layer,
  83. std::unique_ptr<MaterializationResponsibility> MR,
  84. std::unique_ptr<MemoryBuffer> ObjBuffer)
  85. : JITLinkContext(&MR->getTargetJITDylib()), Layer(Layer),
  86. MR(std::move(MR)), ObjBuffer(std::move(ObjBuffer)) {}
  87. ~ObjectLinkingLayerJITLinkContext() {
  88. // If there is an object buffer return function then use it to
  89. // return ownership of the buffer.
  90. if (Layer.ReturnObjectBuffer && ObjBuffer)
  91. Layer.ReturnObjectBuffer(std::move(ObjBuffer));
  92. }
  93. JITLinkMemoryManager &getMemoryManager() override { return Layer.MemMgr; }
  94. void notifyMaterializing(LinkGraph &G) {
  95. for (auto &P : Layer.Plugins)
  96. P->notifyMaterializing(*MR, G, *this,
  97. ObjBuffer ? ObjBuffer->getMemBufferRef()
  98. : MemoryBufferRef());
  99. }
  100. void notifyFailed(Error Err) override {
  101. for (auto &P : Layer.Plugins)
  102. Err = joinErrors(std::move(Err), P->notifyFailed(*MR));
  103. Layer.getExecutionSession().reportError(std::move(Err));
  104. MR->failMaterialization();
  105. }
  106. void lookup(const LookupMap &Symbols,
  107. std::unique_ptr<JITLinkAsyncLookupContinuation> LC) override {
  108. JITDylibSearchOrder LinkOrder;
  109. MR->getTargetJITDylib().withLinkOrderDo(
  110. [&](const JITDylibSearchOrder &LO) { LinkOrder = LO; });
  111. auto &ES = Layer.getExecutionSession();
  112. SymbolLookupSet LookupSet;
  113. for (auto &KV : Symbols) {
  114. orc::SymbolLookupFlags LookupFlags;
  115. switch (KV.second) {
  116. case jitlink::SymbolLookupFlags::RequiredSymbol:
  117. LookupFlags = orc::SymbolLookupFlags::RequiredSymbol;
  118. break;
  119. case jitlink::SymbolLookupFlags::WeaklyReferencedSymbol:
  120. LookupFlags = orc::SymbolLookupFlags::WeaklyReferencedSymbol;
  121. break;
  122. }
  123. LookupSet.add(ES.intern(KV.first), LookupFlags);
  124. }
  125. // OnResolve -- De-intern the symbols and pass the result to the linker.
  126. auto OnResolve = [LookupContinuation =
  127. std::move(LC)](Expected<SymbolMap> Result) mutable {
  128. if (!Result)
  129. LookupContinuation->run(Result.takeError());
  130. else {
  131. AsyncLookupResult LR;
  132. for (auto &KV : *Result)
  133. LR[*KV.first] = KV.second;
  134. LookupContinuation->run(std::move(LR));
  135. }
  136. };
  137. for (auto &KV : InternalNamedSymbolDeps) {
  138. SymbolDependenceMap InternalDeps;
  139. InternalDeps[&MR->getTargetJITDylib()] = std::move(KV.second);
  140. MR->addDependencies(KV.first, InternalDeps);
  141. }
  142. ES.lookup(LookupKind::Static, LinkOrder, std::move(LookupSet),
  143. SymbolState::Resolved, std::move(OnResolve),
  144. [this](const SymbolDependenceMap &Deps) {
  145. registerDependencies(Deps);
  146. });
  147. }
  148. Error notifyResolved(LinkGraph &G) override {
  149. auto &ES = Layer.getExecutionSession();
  150. SymbolFlagsMap ExtraSymbolsToClaim;
  151. bool AutoClaim = Layer.AutoClaimObjectSymbols;
  152. SymbolMap InternedResult;
  153. for (auto *Sym : G.defined_symbols())
  154. if (Sym->hasName() && Sym->getScope() != Scope::Local) {
  155. auto InternedName = ES.intern(Sym->getName());
  156. JITSymbolFlags Flags;
  157. if (Sym->isCallable())
  158. Flags |= JITSymbolFlags::Callable;
  159. if (Sym->getScope() == Scope::Default)
  160. Flags |= JITSymbolFlags::Exported;
  161. if (Sym->getLinkage() == Linkage::Weak)
  162. Flags |= JITSymbolFlags::Weak;
  163. InternedResult[InternedName] =
  164. JITEvaluatedSymbol(Sym->getAddress().getValue(), Flags);
  165. if (AutoClaim && !MR->getSymbols().count(InternedName)) {
  166. assert(!ExtraSymbolsToClaim.count(InternedName) &&
  167. "Duplicate symbol to claim?");
  168. ExtraSymbolsToClaim[InternedName] = Flags;
  169. }
  170. }
  171. for (auto *Sym : G.absolute_symbols())
  172. if (Sym->hasName() && Sym->getScope() != Scope::Local) {
  173. auto InternedName = ES.intern(Sym->getName());
  174. JITSymbolFlags Flags;
  175. if (Sym->isCallable())
  176. Flags |= JITSymbolFlags::Callable;
  177. if (Sym->getScope() == Scope::Default)
  178. Flags |= JITSymbolFlags::Exported;
  179. if (Sym->getLinkage() == Linkage::Weak)
  180. Flags |= JITSymbolFlags::Weak;
  181. InternedResult[InternedName] =
  182. JITEvaluatedSymbol(Sym->getAddress().getValue(), Flags);
  183. if (AutoClaim && !MR->getSymbols().count(InternedName)) {
  184. assert(!ExtraSymbolsToClaim.count(InternedName) &&
  185. "Duplicate symbol to claim?");
  186. ExtraSymbolsToClaim[InternedName] = Flags;
  187. }
  188. }
  189. if (!ExtraSymbolsToClaim.empty())
  190. if (auto Err = MR->defineMaterializing(ExtraSymbolsToClaim))
  191. return Err;
  192. {
  193. // Check that InternedResult matches up with MR->getSymbols(), overriding
  194. // flags if requested.
  195. // This guards against faulty transformations / compilers / object caches.
  196. // First check that there aren't any missing symbols.
  197. size_t NumMaterializationSideEffectsOnlySymbols = 0;
  198. SymbolNameVector ExtraSymbols;
  199. SymbolNameVector MissingSymbols;
  200. for (auto &KV : MR->getSymbols()) {
  201. auto I = InternedResult.find(KV.first);
  202. // If this is a materialization-side-effects only symbol then bump
  203. // the counter and make sure it's *not* defined, otherwise make
  204. // sure that it is defined.
  205. if (KV.second.hasMaterializationSideEffectsOnly()) {
  206. ++NumMaterializationSideEffectsOnlySymbols;
  207. if (I != InternedResult.end())
  208. ExtraSymbols.push_back(KV.first);
  209. continue;
  210. } else if (I == InternedResult.end())
  211. MissingSymbols.push_back(KV.first);
  212. else if (Layer.OverrideObjectFlags)
  213. I->second.setFlags(KV.second);
  214. }
  215. // If there were missing symbols then report the error.
  216. if (!MissingSymbols.empty())
  217. return make_error<MissingSymbolDefinitions>(
  218. Layer.getExecutionSession().getSymbolStringPool(), G.getName(),
  219. std::move(MissingSymbols));
  220. // If there are more definitions than expected, add them to the
  221. // ExtraSymbols vector.
  222. if (InternedResult.size() >
  223. MR->getSymbols().size() - NumMaterializationSideEffectsOnlySymbols) {
  224. for (auto &KV : InternedResult)
  225. if (!MR->getSymbols().count(KV.first))
  226. ExtraSymbols.push_back(KV.first);
  227. }
  228. // If there were extra definitions then report the error.
  229. if (!ExtraSymbols.empty())
  230. return make_error<UnexpectedSymbolDefinitions>(
  231. Layer.getExecutionSession().getSymbolStringPool(), G.getName(),
  232. std::move(ExtraSymbols));
  233. }
  234. if (auto Err = MR->notifyResolved(InternedResult))
  235. return Err;
  236. Layer.notifyLoaded(*MR);
  237. return Error::success();
  238. }
  239. void notifyFinalized(JITLinkMemoryManager::FinalizedAlloc A) override {
  240. if (auto Err = Layer.notifyEmitted(*MR, std::move(A))) {
  241. Layer.getExecutionSession().reportError(std::move(Err));
  242. MR->failMaterialization();
  243. return;
  244. }
  245. if (auto Err = MR->notifyEmitted()) {
  246. Layer.getExecutionSession().reportError(std::move(Err));
  247. MR->failMaterialization();
  248. }
  249. }
  250. LinkGraphPassFunction getMarkLivePass(const Triple &TT) const override {
  251. return [this](LinkGraph &G) { return markResponsibilitySymbolsLive(G); };
  252. }
  253. Error modifyPassConfig(LinkGraph &LG, PassConfiguration &Config) override {
  254. // Add passes to mark duplicate defs as should-discard, and to walk the
  255. // link graph to build the symbol dependence graph.
  256. Config.PrePrunePasses.push_back([this](LinkGraph &G) {
  257. return claimOrExternalizeWeakAndCommonSymbols(G);
  258. });
  259. Layer.modifyPassConfig(*MR, LG, Config);
  260. Config.PostPrunePasses.push_back(
  261. [this](LinkGraph &G) { return computeNamedSymbolDependencies(G); });
  262. return Error::success();
  263. }
  264. private:
  265. // Symbol name dependencies:
  266. // Internal: Defined in this graph.
  267. // External: Defined externally.
  268. struct BlockSymbolDependencies {
  269. SymbolNameSet Internal, External;
  270. };
  271. // Lazily populated map of blocks to BlockSymbolDependencies values.
  272. class BlockDependenciesMap {
  273. public:
  274. BlockDependenciesMap(ExecutionSession &ES,
  275. DenseMap<const Block *, DenseSet<Block *>> BlockDeps)
  276. : ES(ES), BlockDeps(std::move(BlockDeps)) {}
  277. const BlockSymbolDependencies &operator[](const Block &B) {
  278. // Check the cache first.
  279. auto I = BlockTransitiveDepsCache.find(&B);
  280. if (I != BlockTransitiveDepsCache.end())
  281. return I->second;
  282. // No value. Populate the cache.
  283. BlockSymbolDependencies BTDCacheVal;
  284. auto BDI = BlockDeps.find(&B);
  285. assert(BDI != BlockDeps.end() && "No block dependencies");
  286. for (auto *BDep : BDI->second) {
  287. auto &BID = getBlockImmediateDeps(*BDep);
  288. for (auto &ExternalDep : BID.External)
  289. BTDCacheVal.External.insert(ExternalDep);
  290. for (auto &InternalDep : BID.Internal)
  291. BTDCacheVal.Internal.insert(InternalDep);
  292. }
  293. return BlockTransitiveDepsCache
  294. .insert(std::make_pair(&B, std::move(BTDCacheVal)))
  295. .first->second;
  296. }
  297. SymbolStringPtr &getInternedName(Symbol &Sym) {
  298. auto I = NameCache.find(&Sym);
  299. if (I != NameCache.end())
  300. return I->second;
  301. return NameCache.insert(std::make_pair(&Sym, ES.intern(Sym.getName())))
  302. .first->second;
  303. }
  304. private:
  305. BlockSymbolDependencies &getBlockImmediateDeps(Block &B) {
  306. // Check the cache first.
  307. auto I = BlockImmediateDepsCache.find(&B);
  308. if (I != BlockImmediateDepsCache.end())
  309. return I->second;
  310. BlockSymbolDependencies BIDCacheVal;
  311. for (auto &E : B.edges()) {
  312. auto &Tgt = E.getTarget();
  313. if (Tgt.getScope() != Scope::Local) {
  314. if (Tgt.isExternal())
  315. BIDCacheVal.External.insert(getInternedName(Tgt));
  316. else
  317. BIDCacheVal.Internal.insert(getInternedName(Tgt));
  318. }
  319. }
  320. return BlockImmediateDepsCache
  321. .insert(std::make_pair(&B, std::move(BIDCacheVal)))
  322. .first->second;
  323. }
  324. ExecutionSession &ES;
  325. DenseMap<const Block *, DenseSet<Block *>> BlockDeps;
  326. DenseMap<const Symbol *, SymbolStringPtr> NameCache;
  327. DenseMap<const Block *, BlockSymbolDependencies> BlockImmediateDepsCache;
  328. DenseMap<const Block *, BlockSymbolDependencies> BlockTransitiveDepsCache;
  329. };
  330. Error claimOrExternalizeWeakAndCommonSymbols(LinkGraph &G) {
  331. auto &ES = Layer.getExecutionSession();
  332. SymbolFlagsMap NewSymbolsToClaim;
  333. std::vector<std::pair<SymbolStringPtr, Symbol *>> NameToSym;
  334. auto ProcessSymbol = [&](Symbol *Sym) {
  335. if (Sym->hasName() && Sym->getLinkage() == Linkage::Weak &&
  336. Sym->getScope() != Scope::Local) {
  337. auto Name = ES.intern(Sym->getName());
  338. if (!MR->getSymbols().count(ES.intern(Sym->getName()))) {
  339. JITSymbolFlags SF = JITSymbolFlags::Weak;
  340. if (Sym->getScope() == Scope::Default)
  341. SF |= JITSymbolFlags::Exported;
  342. NewSymbolsToClaim[Name] = SF;
  343. NameToSym.push_back(std::make_pair(std::move(Name), Sym));
  344. }
  345. }
  346. };
  347. for (auto *Sym : G.defined_symbols())
  348. ProcessSymbol(Sym);
  349. for (auto *Sym : G.absolute_symbols())
  350. ProcessSymbol(Sym);
  351. // Attempt to claim all weak defs that we're not already responsible for.
  352. // This cannot fail -- any clashes will just result in rejection of our
  353. // claim, at which point we'll externalize that symbol.
  354. cantFail(MR->defineMaterializing(std::move(NewSymbolsToClaim)));
  355. // Walk the list of symbols that we just tried to claim. Symbols that we're
  356. // responsible for are marked live. Symbols that we're not responsible for
  357. // are turned into external references.
  358. for (auto &KV : NameToSym) {
  359. if (MR->getSymbols().count(KV.first))
  360. KV.second->setLive(true);
  361. else
  362. G.makeExternal(*KV.second);
  363. }
  364. return Error::success();
  365. }
  366. Error markResponsibilitySymbolsLive(LinkGraph &G) const {
  367. auto &ES = Layer.getExecutionSession();
  368. for (auto *Sym : G.defined_symbols())
  369. if (Sym->hasName() && MR->getSymbols().count(ES.intern(Sym->getName())))
  370. Sym->setLive(true);
  371. return Error::success();
  372. }
  373. Error computeNamedSymbolDependencies(LinkGraph &G) {
  374. auto &ES = MR->getTargetJITDylib().getExecutionSession();
  375. auto BlockDeps = computeBlockNonLocalDeps(G);
  376. // Compute dependencies for symbols defined in the JITLink graph.
  377. for (auto *Sym : G.defined_symbols()) {
  378. // Skip local symbols: we do not track dependencies for these.
  379. if (Sym->getScope() == Scope::Local)
  380. continue;
  381. assert(Sym->hasName() &&
  382. "Defined non-local jitlink::Symbol should have a name");
  383. auto &SymDeps = BlockDeps[Sym->getBlock()];
  384. if (SymDeps.External.empty() && SymDeps.Internal.empty())
  385. continue;
  386. auto SymName = ES.intern(Sym->getName());
  387. if (!SymDeps.External.empty())
  388. ExternalNamedSymbolDeps[SymName] = SymDeps.External;
  389. if (!SymDeps.Internal.empty())
  390. InternalNamedSymbolDeps[SymName] = SymDeps.Internal;
  391. }
  392. for (auto &P : Layer.Plugins) {
  393. auto SynthDeps = P->getSyntheticSymbolDependencies(*MR);
  394. if (SynthDeps.empty())
  395. continue;
  396. DenseSet<Block *> BlockVisited;
  397. for (auto &KV : SynthDeps) {
  398. auto &Name = KV.first;
  399. auto &DepsForName = KV.second;
  400. for (auto *Sym : DepsForName) {
  401. if (Sym->getScope() == Scope::Local) {
  402. auto &BDeps = BlockDeps[Sym->getBlock()];
  403. for (auto &S : BDeps.Internal)
  404. InternalNamedSymbolDeps[Name].insert(S);
  405. for (auto &S : BDeps.External)
  406. ExternalNamedSymbolDeps[Name].insert(S);
  407. } else {
  408. if (Sym->isExternal())
  409. ExternalNamedSymbolDeps[Name].insert(
  410. BlockDeps.getInternedName(*Sym));
  411. else
  412. InternalNamedSymbolDeps[Name].insert(
  413. BlockDeps.getInternedName(*Sym));
  414. }
  415. }
  416. }
  417. }
  418. return Error::success();
  419. }
  420. BlockDependenciesMap computeBlockNonLocalDeps(LinkGraph &G) {
  421. // First calculate the reachable-via-non-local-symbol blocks for each block.
  422. struct BlockInfo {
  423. DenseSet<Block *> Dependencies;
  424. DenseSet<Block *> Dependants;
  425. bool DependenciesChanged = true;
  426. };
  427. DenseMap<Block *, BlockInfo> BlockInfos;
  428. SmallVector<Block *> WorkList;
  429. // Pre-allocate map entries. This prevents any iterator/reference
  430. // invalidation in the next loop.
  431. for (auto *B : G.blocks())
  432. (void)BlockInfos[B];
  433. // Build initial worklist, record block dependencies/dependants and
  434. // non-local symbol dependencies.
  435. for (auto *B : G.blocks()) {
  436. auto &BI = BlockInfos[B];
  437. for (auto &E : B->edges()) {
  438. if (E.getTarget().getScope() == Scope::Local &&
  439. !E.getTarget().isAbsolute()) {
  440. auto &TgtB = E.getTarget().getBlock();
  441. if (&TgtB != B) {
  442. BI.Dependencies.insert(&TgtB);
  443. BlockInfos[&TgtB].Dependants.insert(B);
  444. }
  445. }
  446. }
  447. // If this node has both dependants and dependencies then add it to the
  448. // worklist to propagate the dependencies to the dependants.
  449. if (!BI.Dependants.empty() && !BI.Dependencies.empty())
  450. WorkList.push_back(B);
  451. }
  452. // Propagate block-level dependencies through the block-dependence graph.
  453. while (!WorkList.empty()) {
  454. auto *B = WorkList.pop_back_val();
  455. auto &BI = BlockInfos[B];
  456. assert(BI.DependenciesChanged &&
  457. "Block in worklist has unchanged dependencies");
  458. BI.DependenciesChanged = false;
  459. for (auto *Dependant : BI.Dependants) {
  460. auto &DependantBI = BlockInfos[Dependant];
  461. for (auto *Dependency : BI.Dependencies) {
  462. if (Dependant != Dependency &&
  463. DependantBI.Dependencies.insert(Dependency).second)
  464. if (!DependantBI.DependenciesChanged) {
  465. DependantBI.DependenciesChanged = true;
  466. WorkList.push_back(Dependant);
  467. }
  468. }
  469. }
  470. }
  471. DenseMap<const Block *, DenseSet<Block *>> BlockDeps;
  472. for (auto &KV : BlockInfos)
  473. BlockDeps[KV.first] = std::move(KV.second.Dependencies);
  474. return BlockDependenciesMap(Layer.getExecutionSession(),
  475. std::move(BlockDeps));
  476. }
  477. void registerDependencies(const SymbolDependenceMap &QueryDeps) {
  478. for (auto &NamedDepsEntry : ExternalNamedSymbolDeps) {
  479. auto &Name = NamedDepsEntry.first;
  480. auto &NameDeps = NamedDepsEntry.second;
  481. SymbolDependenceMap SymbolDeps;
  482. for (const auto &QueryDepsEntry : QueryDeps) {
  483. JITDylib &SourceJD = *QueryDepsEntry.first;
  484. const SymbolNameSet &Symbols = QueryDepsEntry.second;
  485. auto &DepsForJD = SymbolDeps[&SourceJD];
  486. for (const auto &S : Symbols)
  487. if (NameDeps.count(S))
  488. DepsForJD.insert(S);
  489. if (DepsForJD.empty())
  490. SymbolDeps.erase(&SourceJD);
  491. }
  492. MR->addDependencies(Name, SymbolDeps);
  493. }
  494. }
  495. ObjectLinkingLayer &Layer;
  496. std::unique_ptr<MaterializationResponsibility> MR;
  497. std::unique_ptr<MemoryBuffer> ObjBuffer;
  498. DenseMap<SymbolStringPtr, SymbolNameSet> ExternalNamedSymbolDeps;
  499. DenseMap<SymbolStringPtr, SymbolNameSet> InternalNamedSymbolDeps;
  500. };
  501. ObjectLinkingLayer::Plugin::~Plugin() = default;
  502. char ObjectLinkingLayer::ID;
  503. using BaseT = RTTIExtends<ObjectLinkingLayer, ObjectLayer>;
  504. ObjectLinkingLayer::ObjectLinkingLayer(ExecutionSession &ES)
  505. : BaseT(ES), MemMgr(ES.getExecutorProcessControl().getMemMgr()) {
  506. ES.registerResourceManager(*this);
  507. }
  508. ObjectLinkingLayer::ObjectLinkingLayer(ExecutionSession &ES,
  509. JITLinkMemoryManager &MemMgr)
  510. : BaseT(ES), MemMgr(MemMgr) {
  511. ES.registerResourceManager(*this);
  512. }
  513. ObjectLinkingLayer::ObjectLinkingLayer(
  514. ExecutionSession &ES, std::unique_ptr<JITLinkMemoryManager> MemMgr)
  515. : BaseT(ES), MemMgr(*MemMgr), MemMgrOwnership(std::move(MemMgr)) {
  516. ES.registerResourceManager(*this);
  517. }
  518. ObjectLinkingLayer::~ObjectLinkingLayer() {
  519. assert(Allocs.empty() && "Layer destroyed with resources still attached");
  520. getExecutionSession().deregisterResourceManager(*this);
  521. }
  522. Error ObjectLinkingLayer::add(ResourceTrackerSP RT,
  523. std::unique_ptr<LinkGraph> G) {
  524. auto &JD = RT->getJITDylib();
  525. return JD.define(LinkGraphMaterializationUnit::Create(*this, std::move(G)),
  526. std::move(RT));
  527. }
  528. void ObjectLinkingLayer::emit(std::unique_ptr<MaterializationResponsibility> R,
  529. std::unique_ptr<MemoryBuffer> O) {
  530. assert(O && "Object must not be null");
  531. MemoryBufferRef ObjBuffer = O->getMemBufferRef();
  532. auto Ctx = std::make_unique<ObjectLinkingLayerJITLinkContext>(
  533. *this, std::move(R), std::move(O));
  534. if (auto G = createLinkGraphFromObject(ObjBuffer)) {
  535. Ctx->notifyMaterializing(**G);
  536. link(std::move(*G), std::move(Ctx));
  537. } else {
  538. Ctx->notifyFailed(G.takeError());
  539. }
  540. }
  541. void ObjectLinkingLayer::emit(std::unique_ptr<MaterializationResponsibility> R,
  542. std::unique_ptr<LinkGraph> G) {
  543. auto Ctx = std::make_unique<ObjectLinkingLayerJITLinkContext>(
  544. *this, std::move(R), nullptr);
  545. Ctx->notifyMaterializing(*G);
  546. link(std::move(G), std::move(Ctx));
  547. }
  548. void ObjectLinkingLayer::modifyPassConfig(MaterializationResponsibility &MR,
  549. LinkGraph &G,
  550. PassConfiguration &PassConfig) {
  551. for (auto &P : Plugins)
  552. P->modifyPassConfig(MR, G, PassConfig);
  553. }
  554. void ObjectLinkingLayer::notifyLoaded(MaterializationResponsibility &MR) {
  555. for (auto &P : Plugins)
  556. P->notifyLoaded(MR);
  557. }
  558. Error ObjectLinkingLayer::notifyEmitted(MaterializationResponsibility &MR,
  559. FinalizedAlloc FA) {
  560. Error Err = Error::success();
  561. for (auto &P : Plugins)
  562. Err = joinErrors(std::move(Err), P->notifyEmitted(MR));
  563. if (Err)
  564. return Err;
  565. return MR.withResourceKeyDo(
  566. [&](ResourceKey K) { Allocs[K].push_back(std::move(FA)); });
  567. }
  568. Error ObjectLinkingLayer::handleRemoveResources(JITDylib &JD, ResourceKey K) {
  569. {
  570. Error Err = Error::success();
  571. for (auto &P : Plugins)
  572. Err = joinErrors(std::move(Err), P->notifyRemovingResources(JD, K));
  573. if (Err)
  574. return Err;
  575. }
  576. std::vector<FinalizedAlloc> AllocsToRemove;
  577. getExecutionSession().runSessionLocked([&] {
  578. auto I = Allocs.find(K);
  579. if (I != Allocs.end()) {
  580. std::swap(AllocsToRemove, I->second);
  581. Allocs.erase(I);
  582. }
  583. });
  584. if (AllocsToRemove.empty())
  585. return Error::success();
  586. return MemMgr.deallocate(std::move(AllocsToRemove));
  587. }
  588. void ObjectLinkingLayer::handleTransferResources(JITDylib &JD,
  589. ResourceKey DstKey,
  590. ResourceKey SrcKey) {
  591. auto I = Allocs.find(SrcKey);
  592. if (I != Allocs.end()) {
  593. auto &SrcAllocs = I->second;
  594. auto &DstAllocs = Allocs[DstKey];
  595. DstAllocs.reserve(DstAllocs.size() + SrcAllocs.size());
  596. for (auto &Alloc : SrcAllocs)
  597. DstAllocs.push_back(std::move(Alloc));
  598. // Erase SrcKey entry using value rather than iterator I: I may have been
  599. // invalidated when we looked up DstKey.
  600. Allocs.erase(SrcKey);
  601. }
  602. for (auto &P : Plugins)
  603. P->notifyTransferringResources(JD, DstKey, SrcKey);
  604. }
  605. EHFrameRegistrationPlugin::EHFrameRegistrationPlugin(
  606. ExecutionSession &ES, std::unique_ptr<EHFrameRegistrar> Registrar)
  607. : ES(ES), Registrar(std::move(Registrar)) {}
  608. void EHFrameRegistrationPlugin::modifyPassConfig(
  609. MaterializationResponsibility &MR, LinkGraph &G,
  610. PassConfiguration &PassConfig) {
  611. PassConfig.PostFixupPasses.push_back(createEHFrameRecorderPass(
  612. G.getTargetTriple(), [this, &MR](ExecutorAddr Addr, size_t Size) {
  613. if (Addr) {
  614. std::lock_guard<std::mutex> Lock(EHFramePluginMutex);
  615. assert(!InProcessLinks.count(&MR) &&
  616. "Link for MR already being tracked?");
  617. InProcessLinks[&MR] = {Addr, Size};
  618. }
  619. }));
  620. }
  621. Error EHFrameRegistrationPlugin::notifyEmitted(
  622. MaterializationResponsibility &MR) {
  623. ExecutorAddrRange EmittedRange;
  624. {
  625. std::lock_guard<std::mutex> Lock(EHFramePluginMutex);
  626. auto EHFrameRangeItr = InProcessLinks.find(&MR);
  627. if (EHFrameRangeItr == InProcessLinks.end())
  628. return Error::success();
  629. EmittedRange = EHFrameRangeItr->second;
  630. assert(EmittedRange.Start && "eh-frame addr to register can not be null");
  631. InProcessLinks.erase(EHFrameRangeItr);
  632. }
  633. if (auto Err = MR.withResourceKeyDo(
  634. [&](ResourceKey K) { EHFrameRanges[K].push_back(EmittedRange); }))
  635. return Err;
  636. return Registrar->registerEHFrames(EmittedRange);
  637. }
  638. Error EHFrameRegistrationPlugin::notifyFailed(
  639. MaterializationResponsibility &MR) {
  640. std::lock_guard<std::mutex> Lock(EHFramePluginMutex);
  641. InProcessLinks.erase(&MR);
  642. return Error::success();
  643. }
  644. Error EHFrameRegistrationPlugin::notifyRemovingResources(JITDylib &JD,
  645. ResourceKey K) {
  646. std::vector<ExecutorAddrRange> RangesToRemove;
  647. ES.runSessionLocked([&] {
  648. auto I = EHFrameRanges.find(K);
  649. if (I != EHFrameRanges.end()) {
  650. RangesToRemove = std::move(I->second);
  651. EHFrameRanges.erase(I);
  652. }
  653. });
  654. Error Err = Error::success();
  655. while (!RangesToRemove.empty()) {
  656. auto RangeToRemove = RangesToRemove.back();
  657. RangesToRemove.pop_back();
  658. assert(RangeToRemove.Start && "Untracked eh-frame range must not be null");
  659. Err = joinErrors(std::move(Err),
  660. Registrar->deregisterEHFrames(RangeToRemove));
  661. }
  662. return Err;
  663. }
  664. void EHFrameRegistrationPlugin::notifyTransferringResources(
  665. JITDylib &JD, ResourceKey DstKey, ResourceKey SrcKey) {
  666. auto SI = EHFrameRanges.find(SrcKey);
  667. if (SI == EHFrameRanges.end())
  668. return;
  669. auto DI = EHFrameRanges.find(DstKey);
  670. if (DI != EHFrameRanges.end()) {
  671. auto &SrcRanges = SI->second;
  672. auto &DstRanges = DI->second;
  673. DstRanges.reserve(DstRanges.size() + SrcRanges.size());
  674. for (auto &SrcRange : SrcRanges)
  675. DstRanges.push_back(std::move(SrcRange));
  676. EHFrameRanges.erase(SI);
  677. } else {
  678. // We need to move SrcKey's ranges over without invalidating the SI
  679. // iterator.
  680. auto Tmp = std::move(SI->second);
  681. EHFrameRanges.erase(SI);
  682. EHFrameRanges[DstKey] = std::move(Tmp);
  683. }
  684. }
  685. } // End namespace orc.
  686. } // End namespace llvm.