ObjectLinkingLayer.cpp 28 KB

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