Core.cpp 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068
  1. //===--- Core.cpp - Core ORC APIs (MaterializationUnit, JITDylib, etc.) ---===//
  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/Core.h"
  9. #include "llvm/ADT/STLExtras.h"
  10. #include "llvm/Config/llvm-config.h"
  11. #include "llvm/ExecutionEngine/Orc/DebugUtils.h"
  12. #include "llvm/ExecutionEngine/Orc/Shared/OrcError.h"
  13. #include "llvm/Support/FormatVariadic.h"
  14. #include "llvm/Support/MSVCErrorWorkarounds.h"
  15. #include <condition_variable>
  16. #include <future>
  17. #include <optional>
  18. #define DEBUG_TYPE "orc"
  19. namespace llvm {
  20. namespace orc {
  21. char ResourceTrackerDefunct::ID = 0;
  22. char FailedToMaterialize::ID = 0;
  23. char SymbolsNotFound::ID = 0;
  24. char SymbolsCouldNotBeRemoved::ID = 0;
  25. char MissingSymbolDefinitions::ID = 0;
  26. char UnexpectedSymbolDefinitions::ID = 0;
  27. char MaterializationTask::ID = 0;
  28. RegisterDependenciesFunction NoDependenciesToRegister =
  29. RegisterDependenciesFunction();
  30. void MaterializationUnit::anchor() {}
  31. ResourceTracker::ResourceTracker(JITDylibSP JD) {
  32. assert((reinterpret_cast<uintptr_t>(JD.get()) & 0x1) == 0 &&
  33. "JITDylib must be two byte aligned");
  34. JD->Retain();
  35. JDAndFlag.store(reinterpret_cast<uintptr_t>(JD.get()));
  36. }
  37. ResourceTracker::~ResourceTracker() {
  38. getJITDylib().getExecutionSession().destroyResourceTracker(*this);
  39. getJITDylib().Release();
  40. }
  41. Error ResourceTracker::remove() {
  42. return getJITDylib().getExecutionSession().removeResourceTracker(*this);
  43. }
  44. void ResourceTracker::transferTo(ResourceTracker &DstRT) {
  45. getJITDylib().getExecutionSession().transferResourceTracker(DstRT, *this);
  46. }
  47. void ResourceTracker::makeDefunct() {
  48. uintptr_t Val = JDAndFlag.load();
  49. Val |= 0x1U;
  50. JDAndFlag.store(Val);
  51. }
  52. ResourceManager::~ResourceManager() = default;
  53. ResourceTrackerDefunct::ResourceTrackerDefunct(ResourceTrackerSP RT)
  54. : RT(std::move(RT)) {}
  55. std::error_code ResourceTrackerDefunct::convertToErrorCode() const {
  56. return orcError(OrcErrorCode::UnknownORCError);
  57. }
  58. void ResourceTrackerDefunct::log(raw_ostream &OS) const {
  59. OS << "Resource tracker " << (void *)RT.get() << " became defunct";
  60. }
  61. FailedToMaterialize::FailedToMaterialize(
  62. std::shared_ptr<SymbolStringPool> SSP,
  63. std::shared_ptr<SymbolDependenceMap> Symbols)
  64. : SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
  65. assert(this->SSP && "String pool cannot be null");
  66. assert(!this->Symbols->empty() && "Can not fail to resolve an empty set");
  67. // FIXME: Use a new dep-map type for FailedToMaterialize errors so that we
  68. // don't have to manually retain/release.
  69. for (auto &KV : *this->Symbols)
  70. KV.first->Retain();
  71. }
  72. FailedToMaterialize::~FailedToMaterialize() {
  73. for (auto &KV : *Symbols)
  74. KV.first->Release();
  75. }
  76. std::error_code FailedToMaterialize::convertToErrorCode() const {
  77. return orcError(OrcErrorCode::UnknownORCError);
  78. }
  79. void FailedToMaterialize::log(raw_ostream &OS) const {
  80. OS << "Failed to materialize symbols: " << *Symbols;
  81. }
  82. SymbolsNotFound::SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
  83. SymbolNameSet Symbols)
  84. : SSP(std::move(SSP)) {
  85. for (auto &Sym : Symbols)
  86. this->Symbols.push_back(Sym);
  87. assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
  88. }
  89. SymbolsNotFound::SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
  90. SymbolNameVector Symbols)
  91. : SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
  92. assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
  93. }
  94. std::error_code SymbolsNotFound::convertToErrorCode() const {
  95. return orcError(OrcErrorCode::UnknownORCError);
  96. }
  97. void SymbolsNotFound::log(raw_ostream &OS) const {
  98. OS << "Symbols not found: " << Symbols;
  99. }
  100. SymbolsCouldNotBeRemoved::SymbolsCouldNotBeRemoved(
  101. std::shared_ptr<SymbolStringPool> SSP, SymbolNameSet Symbols)
  102. : SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
  103. assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
  104. }
  105. std::error_code SymbolsCouldNotBeRemoved::convertToErrorCode() const {
  106. return orcError(OrcErrorCode::UnknownORCError);
  107. }
  108. void SymbolsCouldNotBeRemoved::log(raw_ostream &OS) const {
  109. OS << "Symbols could not be removed: " << Symbols;
  110. }
  111. std::error_code MissingSymbolDefinitions::convertToErrorCode() const {
  112. return orcError(OrcErrorCode::MissingSymbolDefinitions);
  113. }
  114. void MissingSymbolDefinitions::log(raw_ostream &OS) const {
  115. OS << "Missing definitions in module " << ModuleName
  116. << ": " << Symbols;
  117. }
  118. std::error_code UnexpectedSymbolDefinitions::convertToErrorCode() const {
  119. return orcError(OrcErrorCode::UnexpectedSymbolDefinitions);
  120. }
  121. void UnexpectedSymbolDefinitions::log(raw_ostream &OS) const {
  122. OS << "Unexpected definitions in module " << ModuleName
  123. << ": " << Symbols;
  124. }
  125. AsynchronousSymbolQuery::AsynchronousSymbolQuery(
  126. const SymbolLookupSet &Symbols, SymbolState RequiredState,
  127. SymbolsResolvedCallback NotifyComplete)
  128. : NotifyComplete(std::move(NotifyComplete)), RequiredState(RequiredState) {
  129. assert(RequiredState >= SymbolState::Resolved &&
  130. "Cannot query for a symbols that have not reached the resolve state "
  131. "yet");
  132. OutstandingSymbolsCount = Symbols.size();
  133. for (auto &KV : Symbols)
  134. ResolvedSymbols[KV.first] = nullptr;
  135. }
  136. void AsynchronousSymbolQuery::notifySymbolMetRequiredState(
  137. const SymbolStringPtr &Name, JITEvaluatedSymbol Sym) {
  138. auto I = ResolvedSymbols.find(Name);
  139. assert(I != ResolvedSymbols.end() &&
  140. "Resolving symbol outside the requested set");
  141. assert(I->second.getAddress() == 0 && "Redundantly resolving symbol Name");
  142. // If this is a materialization-side-effects-only symbol then drop it,
  143. // otherwise update its map entry with its resolved address.
  144. if (Sym.getFlags().hasMaterializationSideEffectsOnly())
  145. ResolvedSymbols.erase(I);
  146. else
  147. I->second = std::move(Sym);
  148. --OutstandingSymbolsCount;
  149. }
  150. void AsynchronousSymbolQuery::handleComplete(ExecutionSession &ES) {
  151. assert(OutstandingSymbolsCount == 0 &&
  152. "Symbols remain, handleComplete called prematurely");
  153. class RunQueryCompleteTask : public Task {
  154. public:
  155. RunQueryCompleteTask(SymbolMap ResolvedSymbols,
  156. SymbolsResolvedCallback NotifyComplete)
  157. : ResolvedSymbols(std::move(ResolvedSymbols)),
  158. NotifyComplete(std::move(NotifyComplete)) {}
  159. void printDescription(raw_ostream &OS) override {
  160. OS << "Execute query complete callback for " << ResolvedSymbols;
  161. }
  162. void run() override { NotifyComplete(std::move(ResolvedSymbols)); }
  163. private:
  164. SymbolMap ResolvedSymbols;
  165. SymbolsResolvedCallback NotifyComplete;
  166. };
  167. auto T = std::make_unique<RunQueryCompleteTask>(std::move(ResolvedSymbols),
  168. std::move(NotifyComplete));
  169. NotifyComplete = SymbolsResolvedCallback();
  170. ES.dispatchTask(std::move(T));
  171. }
  172. void AsynchronousSymbolQuery::handleFailed(Error Err) {
  173. assert(QueryRegistrations.empty() && ResolvedSymbols.empty() &&
  174. OutstandingSymbolsCount == 0 &&
  175. "Query should already have been abandoned");
  176. NotifyComplete(std::move(Err));
  177. NotifyComplete = SymbolsResolvedCallback();
  178. }
  179. void AsynchronousSymbolQuery::addQueryDependence(JITDylib &JD,
  180. SymbolStringPtr Name) {
  181. bool Added = QueryRegistrations[&JD].insert(std::move(Name)).second;
  182. (void)Added;
  183. assert(Added && "Duplicate dependence notification?");
  184. }
  185. void AsynchronousSymbolQuery::removeQueryDependence(
  186. JITDylib &JD, const SymbolStringPtr &Name) {
  187. auto QRI = QueryRegistrations.find(&JD);
  188. assert(QRI != QueryRegistrations.end() &&
  189. "No dependencies registered for JD");
  190. assert(QRI->second.count(Name) && "No dependency on Name in JD");
  191. QRI->second.erase(Name);
  192. if (QRI->second.empty())
  193. QueryRegistrations.erase(QRI);
  194. }
  195. void AsynchronousSymbolQuery::dropSymbol(const SymbolStringPtr &Name) {
  196. auto I = ResolvedSymbols.find(Name);
  197. assert(I != ResolvedSymbols.end() &&
  198. "Redundant removal of weakly-referenced symbol");
  199. ResolvedSymbols.erase(I);
  200. --OutstandingSymbolsCount;
  201. }
  202. void AsynchronousSymbolQuery::detach() {
  203. ResolvedSymbols.clear();
  204. OutstandingSymbolsCount = 0;
  205. for (auto &KV : QueryRegistrations)
  206. KV.first->detachQueryHelper(*this, KV.second);
  207. QueryRegistrations.clear();
  208. }
  209. AbsoluteSymbolsMaterializationUnit::AbsoluteSymbolsMaterializationUnit(
  210. SymbolMap Symbols)
  211. : MaterializationUnit(extractFlags(Symbols)), Symbols(std::move(Symbols)) {}
  212. StringRef AbsoluteSymbolsMaterializationUnit::getName() const {
  213. return "<Absolute Symbols>";
  214. }
  215. void AbsoluteSymbolsMaterializationUnit::materialize(
  216. std::unique_ptr<MaterializationResponsibility> R) {
  217. // Even though these are just absolute symbols we need to check for failure
  218. // to resolve/emit: the tracker for these symbols may have been removed while
  219. // the materialization was in flight (e.g. due to a failure in some action
  220. // triggered by the queries attached to the resolution/emission of these
  221. // symbols).
  222. if (auto Err = R->notifyResolved(Symbols)) {
  223. R->getExecutionSession().reportError(std::move(Err));
  224. R->failMaterialization();
  225. return;
  226. }
  227. if (auto Err = R->notifyEmitted()) {
  228. R->getExecutionSession().reportError(std::move(Err));
  229. R->failMaterialization();
  230. return;
  231. }
  232. }
  233. void AbsoluteSymbolsMaterializationUnit::discard(const JITDylib &JD,
  234. const SymbolStringPtr &Name) {
  235. assert(Symbols.count(Name) && "Symbol is not part of this MU");
  236. Symbols.erase(Name);
  237. }
  238. MaterializationUnit::Interface
  239. AbsoluteSymbolsMaterializationUnit::extractFlags(const SymbolMap &Symbols) {
  240. SymbolFlagsMap Flags;
  241. for (const auto &KV : Symbols)
  242. Flags[KV.first] = KV.second.getFlags();
  243. return MaterializationUnit::Interface(std::move(Flags), nullptr);
  244. }
  245. ReExportsMaterializationUnit::ReExportsMaterializationUnit(
  246. JITDylib *SourceJD, JITDylibLookupFlags SourceJDLookupFlags,
  247. SymbolAliasMap Aliases)
  248. : MaterializationUnit(extractFlags(Aliases)), SourceJD(SourceJD),
  249. SourceJDLookupFlags(SourceJDLookupFlags), Aliases(std::move(Aliases)) {}
  250. StringRef ReExportsMaterializationUnit::getName() const {
  251. return "<Reexports>";
  252. }
  253. void ReExportsMaterializationUnit::materialize(
  254. std::unique_ptr<MaterializationResponsibility> R) {
  255. auto &ES = R->getTargetJITDylib().getExecutionSession();
  256. JITDylib &TgtJD = R->getTargetJITDylib();
  257. JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD;
  258. // Find the set of requested aliases and aliasees. Return any unrequested
  259. // aliases back to the JITDylib so as to not prematurely materialize any
  260. // aliasees.
  261. auto RequestedSymbols = R->getRequestedSymbols();
  262. SymbolAliasMap RequestedAliases;
  263. for (auto &Name : RequestedSymbols) {
  264. auto I = Aliases.find(Name);
  265. assert(I != Aliases.end() && "Symbol not found in aliases map?");
  266. RequestedAliases[Name] = std::move(I->second);
  267. Aliases.erase(I);
  268. }
  269. LLVM_DEBUG({
  270. ES.runSessionLocked([&]() {
  271. dbgs() << "materializing reexports: target = " << TgtJD.getName()
  272. << ", source = " << SrcJD.getName() << " " << RequestedAliases
  273. << "\n";
  274. });
  275. });
  276. if (!Aliases.empty()) {
  277. auto Err = SourceJD ? R->replace(reexports(*SourceJD, std::move(Aliases),
  278. SourceJDLookupFlags))
  279. : R->replace(symbolAliases(std::move(Aliases)));
  280. if (Err) {
  281. // FIXME: Should this be reported / treated as failure to materialize?
  282. // Or should this be treated as a sanctioned bailing-out?
  283. ES.reportError(std::move(Err));
  284. R->failMaterialization();
  285. return;
  286. }
  287. }
  288. // The OnResolveInfo struct will hold the aliases and responsibilty for each
  289. // query in the list.
  290. struct OnResolveInfo {
  291. OnResolveInfo(std::unique_ptr<MaterializationResponsibility> R,
  292. SymbolAliasMap Aliases)
  293. : R(std::move(R)), Aliases(std::move(Aliases)) {}
  294. std::unique_ptr<MaterializationResponsibility> R;
  295. SymbolAliasMap Aliases;
  296. };
  297. // Build a list of queries to issue. In each round we build a query for the
  298. // largest set of aliases that we can resolve without encountering a chain of
  299. // aliases (e.g. Foo -> Bar, Bar -> Baz). Such a chain would deadlock as the
  300. // query would be waiting on a symbol that it itself had to resolve. Creating
  301. // a new query for each link in such a chain eliminates the possibility of
  302. // deadlock. In practice chains are likely to be rare, and this algorithm will
  303. // usually result in a single query to issue.
  304. std::vector<std::pair<SymbolLookupSet, std::shared_ptr<OnResolveInfo>>>
  305. QueryInfos;
  306. while (!RequestedAliases.empty()) {
  307. SymbolNameSet ResponsibilitySymbols;
  308. SymbolLookupSet QuerySymbols;
  309. SymbolAliasMap QueryAliases;
  310. // Collect as many aliases as we can without including a chain.
  311. for (auto &KV : RequestedAliases) {
  312. // Chain detected. Skip this symbol for this round.
  313. if (&SrcJD == &TgtJD && (QueryAliases.count(KV.second.Aliasee) ||
  314. RequestedAliases.count(KV.second.Aliasee)))
  315. continue;
  316. ResponsibilitySymbols.insert(KV.first);
  317. QuerySymbols.add(KV.second.Aliasee,
  318. KV.second.AliasFlags.hasMaterializationSideEffectsOnly()
  319. ? SymbolLookupFlags::WeaklyReferencedSymbol
  320. : SymbolLookupFlags::RequiredSymbol);
  321. QueryAliases[KV.first] = std::move(KV.second);
  322. }
  323. // Remove the aliases collected this round from the RequestedAliases map.
  324. for (auto &KV : QueryAliases)
  325. RequestedAliases.erase(KV.first);
  326. assert(!QuerySymbols.empty() && "Alias cycle detected!");
  327. auto NewR = R->delegate(ResponsibilitySymbols);
  328. if (!NewR) {
  329. ES.reportError(NewR.takeError());
  330. R->failMaterialization();
  331. return;
  332. }
  333. auto QueryInfo = std::make_shared<OnResolveInfo>(std::move(*NewR),
  334. std::move(QueryAliases));
  335. QueryInfos.push_back(
  336. make_pair(std::move(QuerySymbols), std::move(QueryInfo)));
  337. }
  338. // Issue the queries.
  339. while (!QueryInfos.empty()) {
  340. auto QuerySymbols = std::move(QueryInfos.back().first);
  341. auto QueryInfo = std::move(QueryInfos.back().second);
  342. QueryInfos.pop_back();
  343. auto RegisterDependencies = [QueryInfo,
  344. &SrcJD](const SymbolDependenceMap &Deps) {
  345. // If there were no materializing symbols, just bail out.
  346. if (Deps.empty())
  347. return;
  348. // Otherwise the only deps should be on SrcJD.
  349. assert(Deps.size() == 1 && Deps.count(&SrcJD) &&
  350. "Unexpected dependencies for reexports");
  351. auto &SrcJDDeps = Deps.find(&SrcJD)->second;
  352. SymbolDependenceMap PerAliasDepsMap;
  353. auto &PerAliasDeps = PerAliasDepsMap[&SrcJD];
  354. for (auto &KV : QueryInfo->Aliases)
  355. if (SrcJDDeps.count(KV.second.Aliasee)) {
  356. PerAliasDeps = {KV.second.Aliasee};
  357. QueryInfo->R->addDependencies(KV.first, PerAliasDepsMap);
  358. }
  359. };
  360. auto OnComplete = [QueryInfo](Expected<SymbolMap> Result) {
  361. auto &ES = QueryInfo->R->getTargetJITDylib().getExecutionSession();
  362. if (Result) {
  363. SymbolMap ResolutionMap;
  364. for (auto &KV : QueryInfo->Aliases) {
  365. assert((KV.second.AliasFlags.hasMaterializationSideEffectsOnly() ||
  366. Result->count(KV.second.Aliasee)) &&
  367. "Result map missing entry?");
  368. // Don't try to resolve materialization-side-effects-only symbols.
  369. if (KV.second.AliasFlags.hasMaterializationSideEffectsOnly())
  370. continue;
  371. ResolutionMap[KV.first] = JITEvaluatedSymbol(
  372. (*Result)[KV.second.Aliasee].getAddress(), KV.second.AliasFlags);
  373. }
  374. if (auto Err = QueryInfo->R->notifyResolved(ResolutionMap)) {
  375. ES.reportError(std::move(Err));
  376. QueryInfo->R->failMaterialization();
  377. return;
  378. }
  379. if (auto Err = QueryInfo->R->notifyEmitted()) {
  380. ES.reportError(std::move(Err));
  381. QueryInfo->R->failMaterialization();
  382. return;
  383. }
  384. } else {
  385. ES.reportError(Result.takeError());
  386. QueryInfo->R->failMaterialization();
  387. }
  388. };
  389. ES.lookup(LookupKind::Static,
  390. JITDylibSearchOrder({{&SrcJD, SourceJDLookupFlags}}),
  391. QuerySymbols, SymbolState::Resolved, std::move(OnComplete),
  392. std::move(RegisterDependencies));
  393. }
  394. }
  395. void ReExportsMaterializationUnit::discard(const JITDylib &JD,
  396. const SymbolStringPtr &Name) {
  397. assert(Aliases.count(Name) &&
  398. "Symbol not covered by this MaterializationUnit");
  399. Aliases.erase(Name);
  400. }
  401. MaterializationUnit::Interface
  402. ReExportsMaterializationUnit::extractFlags(const SymbolAliasMap &Aliases) {
  403. SymbolFlagsMap SymbolFlags;
  404. for (auto &KV : Aliases)
  405. SymbolFlags[KV.first] = KV.second.AliasFlags;
  406. return MaterializationUnit::Interface(std::move(SymbolFlags), nullptr);
  407. }
  408. Expected<SymbolAliasMap> buildSimpleReexportsAliasMap(JITDylib &SourceJD,
  409. SymbolNameSet Symbols) {
  410. SymbolLookupSet LookupSet(Symbols);
  411. auto Flags = SourceJD.getExecutionSession().lookupFlags(
  412. LookupKind::Static, {{&SourceJD, JITDylibLookupFlags::MatchAllSymbols}},
  413. SymbolLookupSet(std::move(Symbols)));
  414. if (!Flags)
  415. return Flags.takeError();
  416. SymbolAliasMap Result;
  417. for (auto &Name : Symbols) {
  418. assert(Flags->count(Name) && "Missing entry in flags map");
  419. Result[Name] = SymbolAliasMapEntry(Name, (*Flags)[Name]);
  420. }
  421. return Result;
  422. }
  423. class InProgressLookupState {
  424. public:
  425. // FIXME: Reduce the number of SymbolStringPtrs here. See
  426. // https://github.com/llvm/llvm-project/issues/55576.
  427. InProgressLookupState(LookupKind K, JITDylibSearchOrder SearchOrder,
  428. SymbolLookupSet LookupSet, SymbolState RequiredState)
  429. : K(K), SearchOrder(std::move(SearchOrder)),
  430. LookupSet(std::move(LookupSet)), RequiredState(RequiredState) {
  431. DefGeneratorCandidates = this->LookupSet;
  432. }
  433. virtual ~InProgressLookupState() = default;
  434. virtual void complete(std::unique_ptr<InProgressLookupState> IPLS) = 0;
  435. virtual void fail(Error Err) = 0;
  436. LookupKind K;
  437. JITDylibSearchOrder SearchOrder;
  438. SymbolLookupSet LookupSet;
  439. SymbolState RequiredState;
  440. std::unique_lock<std::mutex> GeneratorLock;
  441. size_t CurSearchOrderIndex = 0;
  442. bool NewJITDylib = true;
  443. SymbolLookupSet DefGeneratorCandidates;
  444. SymbolLookupSet DefGeneratorNonCandidates;
  445. std::vector<std::weak_ptr<DefinitionGenerator>> CurDefGeneratorStack;
  446. };
  447. class InProgressLookupFlagsState : public InProgressLookupState {
  448. public:
  449. InProgressLookupFlagsState(
  450. LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet,
  451. unique_function<void(Expected<SymbolFlagsMap>)> OnComplete)
  452. : InProgressLookupState(K, std::move(SearchOrder), std::move(LookupSet),
  453. SymbolState::NeverSearched),
  454. OnComplete(std::move(OnComplete)) {}
  455. void complete(std::unique_ptr<InProgressLookupState> IPLS) override {
  456. GeneratorLock = {}; // Unlock and release.
  457. auto &ES = SearchOrder.front().first->getExecutionSession();
  458. ES.OL_completeLookupFlags(std::move(IPLS), std::move(OnComplete));
  459. }
  460. void fail(Error Err) override {
  461. GeneratorLock = {}; // Unlock and release.
  462. OnComplete(std::move(Err));
  463. }
  464. private:
  465. unique_function<void(Expected<SymbolFlagsMap>)> OnComplete;
  466. };
  467. class InProgressFullLookupState : public InProgressLookupState {
  468. public:
  469. InProgressFullLookupState(LookupKind K, JITDylibSearchOrder SearchOrder,
  470. SymbolLookupSet LookupSet,
  471. SymbolState RequiredState,
  472. std::shared_ptr<AsynchronousSymbolQuery> Q,
  473. RegisterDependenciesFunction RegisterDependencies)
  474. : InProgressLookupState(K, std::move(SearchOrder), std::move(LookupSet),
  475. RequiredState),
  476. Q(std::move(Q)), RegisterDependencies(std::move(RegisterDependencies)) {
  477. }
  478. void complete(std::unique_ptr<InProgressLookupState> IPLS) override {
  479. GeneratorLock = {}; // Unlock and release.
  480. auto &ES = SearchOrder.front().first->getExecutionSession();
  481. ES.OL_completeLookup(std::move(IPLS), std::move(Q),
  482. std::move(RegisterDependencies));
  483. }
  484. void fail(Error Err) override {
  485. GeneratorLock = {};
  486. Q->detach();
  487. Q->handleFailed(std::move(Err));
  488. }
  489. private:
  490. std::shared_ptr<AsynchronousSymbolQuery> Q;
  491. RegisterDependenciesFunction RegisterDependencies;
  492. };
  493. ReexportsGenerator::ReexportsGenerator(JITDylib &SourceJD,
  494. JITDylibLookupFlags SourceJDLookupFlags,
  495. SymbolPredicate Allow)
  496. : SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
  497. Allow(std::move(Allow)) {}
  498. Error ReexportsGenerator::tryToGenerate(LookupState &LS, LookupKind K,
  499. JITDylib &JD,
  500. JITDylibLookupFlags JDLookupFlags,
  501. const SymbolLookupSet &LookupSet) {
  502. assert(&JD != &SourceJD && "Cannot re-export from the same dylib");
  503. // Use lookupFlags to find the subset of symbols that match our lookup.
  504. auto Flags = JD.getExecutionSession().lookupFlags(
  505. K, {{&SourceJD, JDLookupFlags}}, LookupSet);
  506. if (!Flags)
  507. return Flags.takeError();
  508. // Create an alias map.
  509. orc::SymbolAliasMap AliasMap;
  510. for (auto &KV : *Flags)
  511. if (!Allow || Allow(KV.first))
  512. AliasMap[KV.first] = SymbolAliasMapEntry(KV.first, KV.second);
  513. if (AliasMap.empty())
  514. return Error::success();
  515. // Define the re-exports.
  516. return JD.define(reexports(SourceJD, AliasMap, SourceJDLookupFlags));
  517. }
  518. LookupState::LookupState(std::unique_ptr<InProgressLookupState> IPLS)
  519. : IPLS(std::move(IPLS)) {}
  520. void LookupState::reset(InProgressLookupState *IPLS) { this->IPLS.reset(IPLS); }
  521. LookupState::LookupState() = default;
  522. LookupState::LookupState(LookupState &&) = default;
  523. LookupState &LookupState::operator=(LookupState &&) = default;
  524. LookupState::~LookupState() = default;
  525. void LookupState::continueLookup(Error Err) {
  526. assert(IPLS && "Cannot call continueLookup on empty LookupState");
  527. auto &ES = IPLS->SearchOrder.begin()->first->getExecutionSession();
  528. ES.OL_applyQueryPhase1(std::move(IPLS), std::move(Err));
  529. }
  530. DefinitionGenerator::~DefinitionGenerator() = default;
  531. JITDylib::~JITDylib() {
  532. LLVM_DEBUG(dbgs() << "Destroying JITDylib " << getName() << "\n");
  533. }
  534. Error JITDylib::clear() {
  535. std::vector<ResourceTrackerSP> TrackersToRemove;
  536. ES.runSessionLocked([&]() {
  537. assert(State != Closed && "JD is defunct");
  538. for (auto &KV : TrackerSymbols)
  539. TrackersToRemove.push_back(KV.first);
  540. TrackersToRemove.push_back(getDefaultResourceTracker());
  541. });
  542. Error Err = Error::success();
  543. for (auto &RT : TrackersToRemove)
  544. Err = joinErrors(std::move(Err), RT->remove());
  545. return Err;
  546. }
  547. ResourceTrackerSP JITDylib::getDefaultResourceTracker() {
  548. return ES.runSessionLocked([this] {
  549. assert(State != Closed && "JD is defunct");
  550. if (!DefaultTracker)
  551. DefaultTracker = new ResourceTracker(this);
  552. return DefaultTracker;
  553. });
  554. }
  555. ResourceTrackerSP JITDylib::createResourceTracker() {
  556. return ES.runSessionLocked([this] {
  557. assert(State == Open && "JD is defunct");
  558. ResourceTrackerSP RT = new ResourceTracker(this);
  559. return RT;
  560. });
  561. }
  562. void JITDylib::removeGenerator(DefinitionGenerator &G) {
  563. ES.runSessionLocked([&] {
  564. assert(State == Open && "JD is defunct");
  565. auto I = llvm::find_if(DefGenerators,
  566. [&](const std::shared_ptr<DefinitionGenerator> &H) {
  567. return H.get() == &G;
  568. });
  569. assert(I != DefGenerators.end() && "Generator not found");
  570. DefGenerators.erase(I);
  571. });
  572. }
  573. Expected<SymbolFlagsMap>
  574. JITDylib::defineMaterializing(SymbolFlagsMap SymbolFlags) {
  575. return ES.runSessionLocked([&]() -> Expected<SymbolFlagsMap> {
  576. std::vector<SymbolTable::iterator> AddedSyms;
  577. std::vector<SymbolFlagsMap::iterator> RejectedWeakDefs;
  578. for (auto SFItr = SymbolFlags.begin(), SFEnd = SymbolFlags.end();
  579. SFItr != SFEnd; ++SFItr) {
  580. auto &Name = SFItr->first;
  581. auto &Flags = SFItr->second;
  582. auto EntryItr = Symbols.find(Name);
  583. // If the entry already exists...
  584. if (EntryItr != Symbols.end()) {
  585. // If this is a strong definition then error out.
  586. if (!Flags.isWeak()) {
  587. // Remove any symbols already added.
  588. for (auto &SI : AddedSyms)
  589. Symbols.erase(SI);
  590. // FIXME: Return all duplicates.
  591. return make_error<DuplicateDefinition>(std::string(*Name));
  592. }
  593. // Otherwise just make a note to discard this symbol after the loop.
  594. RejectedWeakDefs.push_back(SFItr);
  595. continue;
  596. } else
  597. EntryItr =
  598. Symbols.insert(std::make_pair(Name, SymbolTableEntry(Flags))).first;
  599. AddedSyms.push_back(EntryItr);
  600. EntryItr->second.setState(SymbolState::Materializing);
  601. }
  602. // Remove any rejected weak definitions from the SymbolFlags map.
  603. while (!RejectedWeakDefs.empty()) {
  604. SymbolFlags.erase(RejectedWeakDefs.back());
  605. RejectedWeakDefs.pop_back();
  606. }
  607. return SymbolFlags;
  608. });
  609. }
  610. Error JITDylib::replace(MaterializationResponsibility &FromMR,
  611. std::unique_ptr<MaterializationUnit> MU) {
  612. assert(MU != nullptr && "Can not replace with a null MaterializationUnit");
  613. std::unique_ptr<MaterializationUnit> MustRunMU;
  614. std::unique_ptr<MaterializationResponsibility> MustRunMR;
  615. auto Err =
  616. ES.runSessionLocked([&, this]() -> Error {
  617. if (FromMR.RT->isDefunct())
  618. return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
  619. #ifndef NDEBUG
  620. for (auto &KV : MU->getSymbols()) {
  621. auto SymI = Symbols.find(KV.first);
  622. assert(SymI != Symbols.end() && "Replacing unknown symbol");
  623. assert(SymI->second.getState() == SymbolState::Materializing &&
  624. "Can not replace a symbol that ha is not materializing");
  625. assert(!SymI->second.hasMaterializerAttached() &&
  626. "Symbol should not have materializer attached already");
  627. assert(UnmaterializedInfos.count(KV.first) == 0 &&
  628. "Symbol being replaced should have no UnmaterializedInfo");
  629. }
  630. #endif // NDEBUG
  631. // If the tracker is defunct we need to bail out immediately.
  632. // If any symbol has pending queries against it then we need to
  633. // materialize MU immediately.
  634. for (auto &KV : MU->getSymbols()) {
  635. auto MII = MaterializingInfos.find(KV.first);
  636. if (MII != MaterializingInfos.end()) {
  637. if (MII->second.hasQueriesPending()) {
  638. MustRunMR = ES.createMaterializationResponsibility(
  639. *FromMR.RT, std::move(MU->SymbolFlags),
  640. std::move(MU->InitSymbol));
  641. MustRunMU = std::move(MU);
  642. return Error::success();
  643. }
  644. }
  645. }
  646. // Otherwise, make MU responsible for all the symbols.
  647. auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU),
  648. FromMR.RT.get());
  649. for (auto &KV : UMI->MU->getSymbols()) {
  650. auto SymI = Symbols.find(KV.first);
  651. assert(SymI->second.getState() == SymbolState::Materializing &&
  652. "Can not replace a symbol that is not materializing");
  653. assert(!SymI->second.hasMaterializerAttached() &&
  654. "Can not replace a symbol that has a materializer attached");
  655. assert(UnmaterializedInfos.count(KV.first) == 0 &&
  656. "Unexpected materializer entry in map");
  657. SymI->second.setAddress(SymI->second.getAddress());
  658. SymI->second.setMaterializerAttached(true);
  659. auto &UMIEntry = UnmaterializedInfos[KV.first];
  660. assert((!UMIEntry || !UMIEntry->MU) &&
  661. "Replacing symbol with materializer still attached");
  662. UMIEntry = UMI;
  663. }
  664. return Error::success();
  665. });
  666. if (Err)
  667. return Err;
  668. if (MustRunMU) {
  669. assert(MustRunMR && "MustRunMU set implies MustRunMR set");
  670. ES.dispatchTask(std::make_unique<MaterializationTask>(
  671. std::move(MustRunMU), std::move(MustRunMR)));
  672. } else {
  673. assert(!MustRunMR && "MustRunMU unset implies MustRunMR unset");
  674. }
  675. return Error::success();
  676. }
  677. Expected<std::unique_ptr<MaterializationResponsibility>>
  678. JITDylib::delegate(MaterializationResponsibility &FromMR,
  679. SymbolFlagsMap SymbolFlags, SymbolStringPtr InitSymbol) {
  680. return ES.runSessionLocked(
  681. [&]() -> Expected<std::unique_ptr<MaterializationResponsibility>> {
  682. if (FromMR.RT->isDefunct())
  683. return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
  684. return ES.createMaterializationResponsibility(
  685. *FromMR.RT, std::move(SymbolFlags), std::move(InitSymbol));
  686. });
  687. }
  688. SymbolNameSet
  689. JITDylib::getRequestedSymbols(const SymbolFlagsMap &SymbolFlags) const {
  690. return ES.runSessionLocked([&]() {
  691. SymbolNameSet RequestedSymbols;
  692. for (auto &KV : SymbolFlags) {
  693. assert(Symbols.count(KV.first) && "JITDylib does not cover this symbol?");
  694. assert(Symbols.find(KV.first)->second.getState() !=
  695. SymbolState::NeverSearched &&
  696. Symbols.find(KV.first)->second.getState() != SymbolState::Ready &&
  697. "getRequestedSymbols can only be called for symbols that have "
  698. "started materializing");
  699. auto I = MaterializingInfos.find(KV.first);
  700. if (I == MaterializingInfos.end())
  701. continue;
  702. if (I->second.hasQueriesPending())
  703. RequestedSymbols.insert(KV.first);
  704. }
  705. return RequestedSymbols;
  706. });
  707. }
  708. void JITDylib::addDependencies(const SymbolStringPtr &Name,
  709. const SymbolDependenceMap &Dependencies) {
  710. ES.runSessionLocked([&]() {
  711. assert(Symbols.count(Name) && "Name not in symbol table");
  712. assert(Symbols[Name].getState() < SymbolState::Emitted &&
  713. "Can not add dependencies for a symbol that is not materializing");
  714. LLVM_DEBUG({
  715. dbgs() << "In " << getName() << " adding dependencies for " << *Name
  716. << ": " << Dependencies << "\n";
  717. });
  718. // If Name is already in an error state then just bail out.
  719. if (Symbols[Name].getFlags().hasError())
  720. return;
  721. auto &MI = MaterializingInfos[Name];
  722. assert(Symbols[Name].getState() != SymbolState::Emitted &&
  723. "Can not add dependencies to an emitted symbol");
  724. bool DependsOnSymbolInErrorState = false;
  725. // Register dependencies, record whether any depenendency is in the error
  726. // state.
  727. for (auto &KV : Dependencies) {
  728. assert(KV.first && "Null JITDylib in dependency?");
  729. auto &OtherJITDylib = *KV.first;
  730. auto &DepsOnOtherJITDylib = MI.UnemittedDependencies[&OtherJITDylib];
  731. for (auto &OtherSymbol : KV.second) {
  732. // Check the sym entry for the dependency.
  733. auto OtherSymI = OtherJITDylib.Symbols.find(OtherSymbol);
  734. // Assert that this symbol exists and has not reached the ready state
  735. // already.
  736. assert(OtherSymI != OtherJITDylib.Symbols.end() &&
  737. "Dependency on unknown symbol");
  738. auto &OtherSymEntry = OtherSymI->second;
  739. // If the other symbol is already in the Ready state then there's no
  740. // dependency to add.
  741. if (OtherSymEntry.getState() == SymbolState::Ready)
  742. continue;
  743. // If the dependency is in an error state then note this and continue,
  744. // we will move this symbol to the error state below.
  745. if (OtherSymEntry.getFlags().hasError()) {
  746. DependsOnSymbolInErrorState = true;
  747. continue;
  748. }
  749. // If the dependency was not in the error state then add it to
  750. // our list of dependencies.
  751. auto &OtherMI = OtherJITDylib.MaterializingInfos[OtherSymbol];
  752. if (OtherSymEntry.getState() == SymbolState::Emitted)
  753. transferEmittedNodeDependencies(MI, Name, OtherMI);
  754. else if (&OtherJITDylib != this || OtherSymbol != Name) {
  755. OtherMI.Dependants[this].insert(Name);
  756. DepsOnOtherJITDylib.insert(OtherSymbol);
  757. }
  758. }
  759. if (DepsOnOtherJITDylib.empty())
  760. MI.UnemittedDependencies.erase(&OtherJITDylib);
  761. }
  762. // If this symbol dependended on any symbols in the error state then move
  763. // this symbol to the error state too.
  764. if (DependsOnSymbolInErrorState)
  765. Symbols[Name].setFlags(Symbols[Name].getFlags() |
  766. JITSymbolFlags::HasError);
  767. });
  768. }
  769. Error JITDylib::resolve(MaterializationResponsibility &MR,
  770. const SymbolMap &Resolved) {
  771. AsynchronousSymbolQuerySet CompletedQueries;
  772. if (auto Err = ES.runSessionLocked([&, this]() -> Error {
  773. if (MR.RT->isDefunct())
  774. return make_error<ResourceTrackerDefunct>(MR.RT);
  775. if (State != Open)
  776. return make_error<StringError>("JITDylib " + getName() +
  777. " is defunct",
  778. inconvertibleErrorCode());
  779. struct WorklistEntry {
  780. SymbolTable::iterator SymI;
  781. JITEvaluatedSymbol ResolvedSym;
  782. };
  783. SymbolNameSet SymbolsInErrorState;
  784. std::vector<WorklistEntry> Worklist;
  785. Worklist.reserve(Resolved.size());
  786. // Build worklist and check for any symbols in the error state.
  787. for (const auto &KV : Resolved) {
  788. assert(!KV.second.getFlags().hasError() &&
  789. "Resolution result can not have error flag set");
  790. auto SymI = Symbols.find(KV.first);
  791. assert(SymI != Symbols.end() && "Symbol not found");
  792. assert(!SymI->second.hasMaterializerAttached() &&
  793. "Resolving symbol with materializer attached?");
  794. assert(SymI->second.getState() == SymbolState::Materializing &&
  795. "Symbol should be materializing");
  796. assert(SymI->second.getAddress() == 0 &&
  797. "Symbol has already been resolved");
  798. if (SymI->second.getFlags().hasError())
  799. SymbolsInErrorState.insert(KV.first);
  800. else {
  801. auto Flags = KV.second.getFlags();
  802. Flags &= ~JITSymbolFlags::Common;
  803. assert(Flags ==
  804. (SymI->second.getFlags() & ~JITSymbolFlags::Common) &&
  805. "Resolved flags should match the declared flags");
  806. Worklist.push_back(
  807. {SymI, JITEvaluatedSymbol(KV.second.getAddress(), Flags)});
  808. }
  809. }
  810. // If any symbols were in the error state then bail out.
  811. if (!SymbolsInErrorState.empty()) {
  812. auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
  813. (*FailedSymbolsDepMap)[this] = std::move(SymbolsInErrorState);
  814. return make_error<FailedToMaterialize>(
  815. getExecutionSession().getSymbolStringPool(),
  816. std::move(FailedSymbolsDepMap));
  817. }
  818. while (!Worklist.empty()) {
  819. auto SymI = Worklist.back().SymI;
  820. auto ResolvedSym = Worklist.back().ResolvedSym;
  821. Worklist.pop_back();
  822. auto &Name = SymI->first;
  823. // Resolved symbols can not be weak: discard the weak flag.
  824. JITSymbolFlags ResolvedFlags = ResolvedSym.getFlags();
  825. SymI->second.setAddress(ResolvedSym.getAddress());
  826. SymI->second.setFlags(ResolvedFlags);
  827. SymI->second.setState(SymbolState::Resolved);
  828. auto MII = MaterializingInfos.find(Name);
  829. if (MII == MaterializingInfos.end())
  830. continue;
  831. auto &MI = MII->second;
  832. for (auto &Q : MI.takeQueriesMeeting(SymbolState::Resolved)) {
  833. Q->notifySymbolMetRequiredState(Name, ResolvedSym);
  834. Q->removeQueryDependence(*this, Name);
  835. if (Q->isComplete())
  836. CompletedQueries.insert(std::move(Q));
  837. }
  838. }
  839. return Error::success();
  840. }))
  841. return Err;
  842. // Otherwise notify all the completed queries.
  843. for (auto &Q : CompletedQueries) {
  844. assert(Q->isComplete() && "Q not completed");
  845. Q->handleComplete(ES);
  846. }
  847. return Error::success();
  848. }
  849. Error JITDylib::emit(MaterializationResponsibility &MR,
  850. const SymbolFlagsMap &Emitted) {
  851. AsynchronousSymbolQuerySet CompletedQueries;
  852. DenseMap<JITDylib *, SymbolNameVector> ReadySymbols;
  853. if (auto Err = ES.runSessionLocked([&, this]() -> Error {
  854. if (MR.RT->isDefunct())
  855. return make_error<ResourceTrackerDefunct>(MR.RT);
  856. if (State != Open)
  857. return make_error<StringError>("JITDylib " + getName() +
  858. " is defunct",
  859. inconvertibleErrorCode());
  860. SymbolNameSet SymbolsInErrorState;
  861. std::vector<SymbolTable::iterator> Worklist;
  862. // Scan to build worklist, record any symbols in the erorr state.
  863. for (const auto &KV : Emitted) {
  864. auto &Name = KV.first;
  865. auto SymI = Symbols.find(Name);
  866. assert(SymI != Symbols.end() && "No symbol table entry for Name");
  867. if (SymI->second.getFlags().hasError())
  868. SymbolsInErrorState.insert(Name);
  869. else
  870. Worklist.push_back(SymI);
  871. }
  872. // If any symbols were in the error state then bail out.
  873. if (!SymbolsInErrorState.empty()) {
  874. auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
  875. (*FailedSymbolsDepMap)[this] = std::move(SymbolsInErrorState);
  876. return make_error<FailedToMaterialize>(
  877. getExecutionSession().getSymbolStringPool(),
  878. std::move(FailedSymbolsDepMap));
  879. }
  880. // Otherwise update dependencies and move to the emitted state.
  881. while (!Worklist.empty()) {
  882. auto SymI = Worklist.back();
  883. Worklist.pop_back();
  884. auto &Name = SymI->first;
  885. auto &SymEntry = SymI->second;
  886. // Move symbol to the emitted state.
  887. assert(((SymEntry.getFlags().hasMaterializationSideEffectsOnly() &&
  888. SymEntry.getState() == SymbolState::Materializing) ||
  889. SymEntry.getState() == SymbolState::Resolved) &&
  890. "Emitting from state other than Resolved");
  891. SymEntry.setState(SymbolState::Emitted);
  892. auto MII = MaterializingInfos.find(Name);
  893. // If this symbol has no MaterializingInfo then it's trivially ready.
  894. // Update its state and continue.
  895. if (MII == MaterializingInfos.end()) {
  896. SymEntry.setState(SymbolState::Ready);
  897. continue;
  898. }
  899. auto &MI = MII->second;
  900. // For each dependant, transfer this node's emitted dependencies to
  901. // it. If the dependant node is ready (i.e. has no unemitted
  902. // dependencies) then notify any pending queries.
  903. for (auto &KV : MI.Dependants) {
  904. auto &DependantJD = *KV.first;
  905. auto &DependantJDReadySymbols = ReadySymbols[&DependantJD];
  906. for (auto &DependantName : KV.second) {
  907. auto DependantMII =
  908. DependantJD.MaterializingInfos.find(DependantName);
  909. assert(DependantMII != DependantJD.MaterializingInfos.end() &&
  910. "Dependant should have MaterializingInfo");
  911. auto &DependantMI = DependantMII->second;
  912. // Remove the dependant's dependency on this node.
  913. assert(DependantMI.UnemittedDependencies.count(this) &&
  914. "Dependant does not have an unemitted dependencies record "
  915. "for "
  916. "this JITDylib");
  917. assert(DependantMI.UnemittedDependencies[this].count(Name) &&
  918. "Dependant does not count this symbol as a dependency?");
  919. DependantMI.UnemittedDependencies[this].erase(Name);
  920. if (DependantMI.UnemittedDependencies[this].empty())
  921. DependantMI.UnemittedDependencies.erase(this);
  922. // Transfer unemitted dependencies from this node to the
  923. // dependant.
  924. DependantJD.transferEmittedNodeDependencies(DependantMI,
  925. DependantName, MI);
  926. auto DependantSymI = DependantJD.Symbols.find(DependantName);
  927. assert(DependantSymI != DependantJD.Symbols.end() &&
  928. "Dependant has no entry in the Symbols table");
  929. auto &DependantSymEntry = DependantSymI->second;
  930. // If the dependant is emitted and this node was the last of its
  931. // unemitted dependencies then the dependant node is now ready, so
  932. // notify any pending queries on the dependant node.
  933. if (DependantSymEntry.getState() == SymbolState::Emitted &&
  934. DependantMI.UnemittedDependencies.empty()) {
  935. assert(DependantMI.Dependants.empty() &&
  936. "Dependants should be empty by now");
  937. // Since this dependant is now ready, we erase its
  938. // MaterializingInfo and update its materializing state.
  939. DependantSymEntry.setState(SymbolState::Ready);
  940. DependantJDReadySymbols.push_back(DependantName);
  941. for (auto &Q :
  942. DependantMI.takeQueriesMeeting(SymbolState::Ready)) {
  943. Q->notifySymbolMetRequiredState(
  944. DependantName, DependantSymI->second.getSymbol());
  945. if (Q->isComplete())
  946. CompletedQueries.insert(Q);
  947. Q->removeQueryDependence(DependantJD, DependantName);
  948. }
  949. DependantJD.MaterializingInfos.erase(DependantMII);
  950. }
  951. }
  952. }
  953. auto &ThisJDReadySymbols = ReadySymbols[this];
  954. MI.Dependants.clear();
  955. if (MI.UnemittedDependencies.empty()) {
  956. SymI->second.setState(SymbolState::Ready);
  957. ThisJDReadySymbols.push_back(Name);
  958. for (auto &Q : MI.takeQueriesMeeting(SymbolState::Ready)) {
  959. Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
  960. if (Q->isComplete())
  961. CompletedQueries.insert(Q);
  962. Q->removeQueryDependence(*this, Name);
  963. }
  964. MaterializingInfos.erase(MII);
  965. }
  966. }
  967. return Error::success();
  968. }))
  969. return Err;
  970. // Otherwise notify all the completed queries.
  971. for (auto &Q : CompletedQueries) {
  972. assert(Q->isComplete() && "Q is not complete");
  973. Q->handleComplete(ES);
  974. }
  975. return Error::success();
  976. }
  977. void JITDylib::unlinkMaterializationResponsibility(
  978. MaterializationResponsibility &MR) {
  979. ES.runSessionLocked([&]() {
  980. auto I = TrackerMRs.find(MR.RT.get());
  981. assert(I != TrackerMRs.end() && "No MRs in TrackerMRs list for RT");
  982. assert(I->second.count(&MR) && "MR not in TrackerMRs list for RT");
  983. I->second.erase(&MR);
  984. if (I->second.empty())
  985. TrackerMRs.erase(MR.RT.get());
  986. });
  987. }
  988. std::pair<JITDylib::AsynchronousSymbolQuerySet,
  989. std::shared_ptr<SymbolDependenceMap>>
  990. JITDylib::failSymbols(FailedSymbolsWorklist Worklist) {
  991. AsynchronousSymbolQuerySet FailedQueries;
  992. auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
  993. while (!Worklist.empty()) {
  994. assert(Worklist.back().first && "Failed JITDylib can not be null");
  995. auto &JD = *Worklist.back().first;
  996. auto Name = std::move(Worklist.back().second);
  997. Worklist.pop_back();
  998. (*FailedSymbolsMap)[&JD].insert(Name);
  999. // Look up the symbol to fail.
  1000. auto SymI = JD.Symbols.find(Name);
  1001. // It's possible that this symbol has already been removed, e.g. if a
  1002. // materialization failure happens concurrently with a ResourceTracker or
  1003. // JITDylib removal. In that case we can safely skip this symbol and
  1004. // continue.
  1005. if (SymI == JD.Symbols.end())
  1006. continue;
  1007. auto &Sym = SymI->second;
  1008. // Move the symbol into the error state.
  1009. // Note that this may be redundant: The symbol might already have been
  1010. // moved to this state in response to the failure of a dependence.
  1011. Sym.setFlags(Sym.getFlags() | JITSymbolFlags::HasError);
  1012. // FIXME: Come up with a sane mapping of state to
  1013. // presence-of-MaterializingInfo so that we can assert presence / absence
  1014. // here, rather than testing it.
  1015. auto MII = JD.MaterializingInfos.find(Name);
  1016. if (MII == JD.MaterializingInfos.end())
  1017. continue;
  1018. auto &MI = MII->second;
  1019. // Move all dependants to the error state and disconnect from them.
  1020. for (auto &KV : MI.Dependants) {
  1021. auto &DependantJD = *KV.first;
  1022. for (auto &DependantName : KV.second) {
  1023. assert(DependantJD.Symbols.count(DependantName) &&
  1024. "No symbol table entry for DependantName");
  1025. auto &DependantSym = DependantJD.Symbols[DependantName];
  1026. DependantSym.setFlags(DependantSym.getFlags() |
  1027. JITSymbolFlags::HasError);
  1028. assert(DependantJD.MaterializingInfos.count(DependantName) &&
  1029. "No MaterializingInfo for dependant");
  1030. auto &DependantMI = DependantJD.MaterializingInfos[DependantName];
  1031. auto UnemittedDepI = DependantMI.UnemittedDependencies.find(&JD);
  1032. assert(UnemittedDepI != DependantMI.UnemittedDependencies.end() &&
  1033. "No UnemittedDependencies entry for this JITDylib");
  1034. assert(UnemittedDepI->second.count(Name) &&
  1035. "No UnemittedDependencies entry for this symbol");
  1036. UnemittedDepI->second.erase(Name);
  1037. if (UnemittedDepI->second.empty())
  1038. DependantMI.UnemittedDependencies.erase(UnemittedDepI);
  1039. // If this symbol is already in the emitted state then we need to
  1040. // take responsibility for failing its queries, so add it to the
  1041. // worklist.
  1042. if (DependantSym.getState() == SymbolState::Emitted) {
  1043. assert(DependantMI.Dependants.empty() &&
  1044. "Emitted symbol should not have dependants");
  1045. Worklist.push_back(std::make_pair(&DependantJD, DependantName));
  1046. }
  1047. }
  1048. }
  1049. MI.Dependants.clear();
  1050. // Disconnect from all unemitted depenencies.
  1051. for (auto &KV : MI.UnemittedDependencies) {
  1052. auto &UnemittedDepJD = *KV.first;
  1053. for (auto &UnemittedDepName : KV.second) {
  1054. auto UnemittedDepMII =
  1055. UnemittedDepJD.MaterializingInfos.find(UnemittedDepName);
  1056. assert(UnemittedDepMII != UnemittedDepJD.MaterializingInfos.end() &&
  1057. "Missing MII for unemitted dependency");
  1058. assert(UnemittedDepMII->second.Dependants.count(&JD) &&
  1059. "JD not listed as a dependant of unemitted dependency");
  1060. assert(UnemittedDepMII->second.Dependants[&JD].count(Name) &&
  1061. "Name is not listed as a dependant of unemitted dependency");
  1062. UnemittedDepMII->second.Dependants[&JD].erase(Name);
  1063. if (UnemittedDepMII->second.Dependants[&JD].empty())
  1064. UnemittedDepMII->second.Dependants.erase(&JD);
  1065. }
  1066. }
  1067. MI.UnemittedDependencies.clear();
  1068. // Collect queries to be failed for this MII.
  1069. AsynchronousSymbolQueryList ToDetach;
  1070. for (auto &Q : MII->second.pendingQueries()) {
  1071. // Add the query to the list to be failed and detach it.
  1072. FailedQueries.insert(Q);
  1073. ToDetach.push_back(Q);
  1074. }
  1075. for (auto &Q : ToDetach)
  1076. Q->detach();
  1077. assert(MI.Dependants.empty() &&
  1078. "Can not delete MaterializingInfo with dependants still attached");
  1079. assert(MI.UnemittedDependencies.empty() &&
  1080. "Can not delete MaterializingInfo with unemitted dependencies "
  1081. "still attached");
  1082. assert(!MI.hasQueriesPending() &&
  1083. "Can not delete MaterializingInfo with queries pending");
  1084. JD.MaterializingInfos.erase(MII);
  1085. }
  1086. return std::make_pair(std::move(FailedQueries), std::move(FailedSymbolsMap));
  1087. }
  1088. void JITDylib::setLinkOrder(JITDylibSearchOrder NewLinkOrder,
  1089. bool LinkAgainstThisJITDylibFirst) {
  1090. ES.runSessionLocked([&]() {
  1091. assert(State == Open && "JD is defunct");
  1092. if (LinkAgainstThisJITDylibFirst) {
  1093. LinkOrder.clear();
  1094. if (NewLinkOrder.empty() || NewLinkOrder.front().first != this)
  1095. LinkOrder.push_back(
  1096. std::make_pair(this, JITDylibLookupFlags::MatchAllSymbols));
  1097. llvm::append_range(LinkOrder, NewLinkOrder);
  1098. } else
  1099. LinkOrder = std::move(NewLinkOrder);
  1100. });
  1101. }
  1102. void JITDylib::addToLinkOrder(JITDylib &JD, JITDylibLookupFlags JDLookupFlags) {
  1103. ES.runSessionLocked([&]() { LinkOrder.push_back({&JD, JDLookupFlags}); });
  1104. }
  1105. void JITDylib::replaceInLinkOrder(JITDylib &OldJD, JITDylib &NewJD,
  1106. JITDylibLookupFlags JDLookupFlags) {
  1107. ES.runSessionLocked([&]() {
  1108. assert(State == Open && "JD is defunct");
  1109. for (auto &KV : LinkOrder)
  1110. if (KV.first == &OldJD) {
  1111. KV = {&NewJD, JDLookupFlags};
  1112. break;
  1113. }
  1114. });
  1115. }
  1116. void JITDylib::removeFromLinkOrder(JITDylib &JD) {
  1117. ES.runSessionLocked([&]() {
  1118. assert(State == Open && "JD is defunct");
  1119. auto I = llvm::find_if(LinkOrder,
  1120. [&](const JITDylibSearchOrder::value_type &KV) {
  1121. return KV.first == &JD;
  1122. });
  1123. if (I != LinkOrder.end())
  1124. LinkOrder.erase(I);
  1125. });
  1126. }
  1127. Error JITDylib::remove(const SymbolNameSet &Names) {
  1128. return ES.runSessionLocked([&]() -> Error {
  1129. assert(State == Open && "JD is defunct");
  1130. using SymbolMaterializerItrPair =
  1131. std::pair<SymbolTable::iterator, UnmaterializedInfosMap::iterator>;
  1132. std::vector<SymbolMaterializerItrPair> SymbolsToRemove;
  1133. SymbolNameSet Missing;
  1134. SymbolNameSet Materializing;
  1135. for (auto &Name : Names) {
  1136. auto I = Symbols.find(Name);
  1137. // Note symbol missing.
  1138. if (I == Symbols.end()) {
  1139. Missing.insert(Name);
  1140. continue;
  1141. }
  1142. // Note symbol materializing.
  1143. if (I->second.getState() != SymbolState::NeverSearched &&
  1144. I->second.getState() != SymbolState::Ready) {
  1145. Materializing.insert(Name);
  1146. continue;
  1147. }
  1148. auto UMII = I->second.hasMaterializerAttached()
  1149. ? UnmaterializedInfos.find(Name)
  1150. : UnmaterializedInfos.end();
  1151. SymbolsToRemove.push_back(std::make_pair(I, UMII));
  1152. }
  1153. // If any of the symbols are not defined, return an error.
  1154. if (!Missing.empty())
  1155. return make_error<SymbolsNotFound>(ES.getSymbolStringPool(),
  1156. std::move(Missing));
  1157. // If any of the symbols are currently materializing, return an error.
  1158. if (!Materializing.empty())
  1159. return make_error<SymbolsCouldNotBeRemoved>(ES.getSymbolStringPool(),
  1160. std::move(Materializing));
  1161. // Remove the symbols.
  1162. for (auto &SymbolMaterializerItrPair : SymbolsToRemove) {
  1163. auto UMII = SymbolMaterializerItrPair.second;
  1164. // If there is a materializer attached, call discard.
  1165. if (UMII != UnmaterializedInfos.end()) {
  1166. UMII->second->MU->doDiscard(*this, UMII->first);
  1167. UnmaterializedInfos.erase(UMII);
  1168. }
  1169. auto SymI = SymbolMaterializerItrPair.first;
  1170. Symbols.erase(SymI);
  1171. }
  1172. return Error::success();
  1173. });
  1174. }
  1175. void JITDylib::dump(raw_ostream &OS) {
  1176. ES.runSessionLocked([&, this]() {
  1177. OS << "JITDylib \"" << getName() << "\" (ES: "
  1178. << format("0x%016" PRIx64, reinterpret_cast<uintptr_t>(&ES))
  1179. << ", State = ";
  1180. switch (State) {
  1181. case Open:
  1182. OS << "Open";
  1183. break;
  1184. case Closing:
  1185. OS << "Closing";
  1186. break;
  1187. case Closed:
  1188. OS << "Closed";
  1189. break;
  1190. }
  1191. OS << ")\n";
  1192. if (State == Closed)
  1193. return;
  1194. OS << "Link order: " << LinkOrder << "\n"
  1195. << "Symbol table:\n";
  1196. for (auto &KV : Symbols) {
  1197. OS << " \"" << *KV.first << "\": ";
  1198. if (auto Addr = KV.second.getAddress())
  1199. OS << format("0x%016" PRIx64, Addr);
  1200. else
  1201. OS << "<not resolved> ";
  1202. OS << " " << KV.second.getFlags() << " " << KV.second.getState();
  1203. if (KV.second.hasMaterializerAttached()) {
  1204. OS << " (Materializer ";
  1205. auto I = UnmaterializedInfos.find(KV.first);
  1206. assert(I != UnmaterializedInfos.end() &&
  1207. "Lazy symbol should have UnmaterializedInfo");
  1208. OS << I->second->MU.get() << ", " << I->second->MU->getName() << ")\n";
  1209. } else
  1210. OS << "\n";
  1211. }
  1212. if (!MaterializingInfos.empty())
  1213. OS << " MaterializingInfos entries:\n";
  1214. for (auto &KV : MaterializingInfos) {
  1215. OS << " \"" << *KV.first << "\":\n"
  1216. << " " << KV.second.pendingQueries().size()
  1217. << " pending queries: { ";
  1218. for (const auto &Q : KV.second.pendingQueries())
  1219. OS << Q.get() << " (" << Q->getRequiredState() << ") ";
  1220. OS << "}\n Dependants:\n";
  1221. for (auto &KV2 : KV.second.Dependants)
  1222. OS << " " << KV2.first->getName() << ": " << KV2.second << "\n";
  1223. OS << " Unemitted Dependencies:\n";
  1224. for (auto &KV2 : KV.second.UnemittedDependencies)
  1225. OS << " " << KV2.first->getName() << ": " << KV2.second << "\n";
  1226. assert((Symbols[KV.first].getState() != SymbolState::Ready ||
  1227. !KV.second.pendingQueries().empty() ||
  1228. !KV.second.Dependants.empty() ||
  1229. !KV.second.UnemittedDependencies.empty()) &&
  1230. "Stale materializing info entry");
  1231. }
  1232. });
  1233. }
  1234. void JITDylib::MaterializingInfo::addQuery(
  1235. std::shared_ptr<AsynchronousSymbolQuery> Q) {
  1236. auto I = llvm::lower_bound(
  1237. llvm::reverse(PendingQueries), Q->getRequiredState(),
  1238. [](const std::shared_ptr<AsynchronousSymbolQuery> &V, SymbolState S) {
  1239. return V->getRequiredState() <= S;
  1240. });
  1241. PendingQueries.insert(I.base(), std::move(Q));
  1242. }
  1243. void JITDylib::MaterializingInfo::removeQuery(
  1244. const AsynchronousSymbolQuery &Q) {
  1245. // FIXME: Implement 'find_as' for shared_ptr<T>/T*.
  1246. auto I = llvm::find_if(
  1247. PendingQueries, [&Q](const std::shared_ptr<AsynchronousSymbolQuery> &V) {
  1248. return V.get() == &Q;
  1249. });
  1250. assert(I != PendingQueries.end() &&
  1251. "Query is not attached to this MaterializingInfo");
  1252. PendingQueries.erase(I);
  1253. }
  1254. JITDylib::AsynchronousSymbolQueryList
  1255. JITDylib::MaterializingInfo::takeQueriesMeeting(SymbolState RequiredState) {
  1256. AsynchronousSymbolQueryList Result;
  1257. while (!PendingQueries.empty()) {
  1258. if (PendingQueries.back()->getRequiredState() > RequiredState)
  1259. break;
  1260. Result.push_back(std::move(PendingQueries.back()));
  1261. PendingQueries.pop_back();
  1262. }
  1263. return Result;
  1264. }
  1265. JITDylib::JITDylib(ExecutionSession &ES, std::string Name)
  1266. : JITLinkDylib(std::move(Name)), ES(ES) {
  1267. LinkOrder.push_back({this, JITDylibLookupFlags::MatchAllSymbols});
  1268. }
  1269. std::pair<JITDylib::AsynchronousSymbolQuerySet,
  1270. std::shared_ptr<SymbolDependenceMap>>
  1271. JITDylib::removeTracker(ResourceTracker &RT) {
  1272. // Note: Should be called under the session lock.
  1273. assert(State != Closed && "JD is defunct");
  1274. SymbolNameVector SymbolsToRemove;
  1275. std::vector<std::pair<JITDylib *, SymbolStringPtr>> SymbolsToFail;
  1276. if (&RT == DefaultTracker.get()) {
  1277. SymbolNameSet TrackedSymbols;
  1278. for (auto &KV : TrackerSymbols)
  1279. for (auto &Sym : KV.second)
  1280. TrackedSymbols.insert(Sym);
  1281. for (auto &KV : Symbols) {
  1282. auto &Sym = KV.first;
  1283. if (!TrackedSymbols.count(Sym))
  1284. SymbolsToRemove.push_back(Sym);
  1285. }
  1286. DefaultTracker.reset();
  1287. } else {
  1288. /// Check for a non-default tracker.
  1289. auto I = TrackerSymbols.find(&RT);
  1290. if (I != TrackerSymbols.end()) {
  1291. SymbolsToRemove = std::move(I->second);
  1292. TrackerSymbols.erase(I);
  1293. }
  1294. // ... if not found this tracker was already defunct. Nothing to do.
  1295. }
  1296. for (auto &Sym : SymbolsToRemove) {
  1297. assert(Symbols.count(Sym) && "Symbol not in symbol table");
  1298. // If there is a MaterializingInfo then collect any queries to fail.
  1299. auto MII = MaterializingInfos.find(Sym);
  1300. if (MII != MaterializingInfos.end())
  1301. SymbolsToFail.push_back({this, Sym});
  1302. }
  1303. AsynchronousSymbolQuerySet QueriesToFail;
  1304. auto Result = failSymbols(std::move(SymbolsToFail));
  1305. // Removed symbols should be taken out of the table altogether.
  1306. for (auto &Sym : SymbolsToRemove) {
  1307. auto I = Symbols.find(Sym);
  1308. assert(I != Symbols.end() && "Symbol not present in table");
  1309. // Remove Materializer if present.
  1310. if (I->second.hasMaterializerAttached()) {
  1311. // FIXME: Should this discard the symbols?
  1312. UnmaterializedInfos.erase(Sym);
  1313. } else {
  1314. assert(!UnmaterializedInfos.count(Sym) &&
  1315. "Symbol has materializer attached");
  1316. }
  1317. Symbols.erase(I);
  1318. }
  1319. return Result;
  1320. }
  1321. void JITDylib::transferTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT) {
  1322. assert(State != Closed && "JD is defunct");
  1323. assert(&DstRT != &SrcRT && "No-op transfers shouldn't call transferTracker");
  1324. assert(&DstRT.getJITDylib() == this && "DstRT is not for this JITDylib");
  1325. assert(&SrcRT.getJITDylib() == this && "SrcRT is not for this JITDylib");
  1326. // Update trackers for any not-yet materialized units.
  1327. for (auto &KV : UnmaterializedInfos) {
  1328. if (KV.second->RT == &SrcRT)
  1329. KV.second->RT = &DstRT;
  1330. }
  1331. // Update trackers for any active materialization responsibilities.
  1332. {
  1333. auto I = TrackerMRs.find(&SrcRT);
  1334. if (I != TrackerMRs.end()) {
  1335. auto &SrcMRs = I->second;
  1336. auto &DstMRs = TrackerMRs[&DstRT];
  1337. for (auto *MR : SrcMRs)
  1338. MR->RT = &DstRT;
  1339. if (DstMRs.empty())
  1340. DstMRs = std::move(SrcMRs);
  1341. else
  1342. for (auto *MR : SrcMRs)
  1343. DstMRs.insert(MR);
  1344. // Erase SrcRT entry in TrackerMRs. Use &SrcRT key rather than iterator I
  1345. // for this, since I may have been invalidated by 'TrackerMRs[&DstRT]'.
  1346. TrackerMRs.erase(&SrcRT);
  1347. }
  1348. }
  1349. // If we're transfering to the default tracker we just need to delete the
  1350. // tracked symbols for the source tracker.
  1351. if (&DstRT == DefaultTracker.get()) {
  1352. TrackerSymbols.erase(&SrcRT);
  1353. return;
  1354. }
  1355. // If we're transferring from the default tracker we need to find all
  1356. // currently untracked symbols.
  1357. if (&SrcRT == DefaultTracker.get()) {
  1358. assert(!TrackerSymbols.count(&SrcRT) &&
  1359. "Default tracker should not appear in TrackerSymbols");
  1360. SymbolNameVector SymbolsToTrack;
  1361. SymbolNameSet CurrentlyTrackedSymbols;
  1362. for (auto &KV : TrackerSymbols)
  1363. for (auto &Sym : KV.second)
  1364. CurrentlyTrackedSymbols.insert(Sym);
  1365. for (auto &KV : Symbols) {
  1366. auto &Sym = KV.first;
  1367. if (!CurrentlyTrackedSymbols.count(Sym))
  1368. SymbolsToTrack.push_back(Sym);
  1369. }
  1370. TrackerSymbols[&DstRT] = std::move(SymbolsToTrack);
  1371. return;
  1372. }
  1373. auto &DstTrackedSymbols = TrackerSymbols[&DstRT];
  1374. // Finally if neither SrtRT or DstRT are the default tracker then
  1375. // just append DstRT's tracked symbols to SrtRT's.
  1376. auto SI = TrackerSymbols.find(&SrcRT);
  1377. if (SI == TrackerSymbols.end())
  1378. return;
  1379. DstTrackedSymbols.reserve(DstTrackedSymbols.size() + SI->second.size());
  1380. for (auto &Sym : SI->second)
  1381. DstTrackedSymbols.push_back(std::move(Sym));
  1382. TrackerSymbols.erase(SI);
  1383. }
  1384. Error JITDylib::defineImpl(MaterializationUnit &MU) {
  1385. LLVM_DEBUG({ dbgs() << " " << MU.getSymbols() << "\n"; });
  1386. SymbolNameSet Duplicates;
  1387. std::vector<SymbolStringPtr> ExistingDefsOverridden;
  1388. std::vector<SymbolStringPtr> MUDefsOverridden;
  1389. for (const auto &KV : MU.getSymbols()) {
  1390. auto I = Symbols.find(KV.first);
  1391. if (I != Symbols.end()) {
  1392. if (KV.second.isStrong()) {
  1393. if (I->second.getFlags().isStrong() ||
  1394. I->second.getState() > SymbolState::NeverSearched)
  1395. Duplicates.insert(KV.first);
  1396. else {
  1397. assert(I->second.getState() == SymbolState::NeverSearched &&
  1398. "Overridden existing def should be in the never-searched "
  1399. "state");
  1400. ExistingDefsOverridden.push_back(KV.first);
  1401. }
  1402. } else
  1403. MUDefsOverridden.push_back(KV.first);
  1404. }
  1405. }
  1406. // If there were any duplicate definitions then bail out.
  1407. if (!Duplicates.empty()) {
  1408. LLVM_DEBUG(
  1409. { dbgs() << " Error: Duplicate symbols " << Duplicates << "\n"; });
  1410. return make_error<DuplicateDefinition>(std::string(**Duplicates.begin()));
  1411. }
  1412. // Discard any overridden defs in this MU.
  1413. LLVM_DEBUG({
  1414. if (!MUDefsOverridden.empty())
  1415. dbgs() << " Defs in this MU overridden: " << MUDefsOverridden << "\n";
  1416. });
  1417. for (auto &S : MUDefsOverridden)
  1418. MU.doDiscard(*this, S);
  1419. // Discard existing overridden defs.
  1420. LLVM_DEBUG({
  1421. if (!ExistingDefsOverridden.empty())
  1422. dbgs() << " Existing defs overridden by this MU: " << MUDefsOverridden
  1423. << "\n";
  1424. });
  1425. for (auto &S : ExistingDefsOverridden) {
  1426. auto UMII = UnmaterializedInfos.find(S);
  1427. assert(UMII != UnmaterializedInfos.end() &&
  1428. "Overridden existing def should have an UnmaterializedInfo");
  1429. UMII->second->MU->doDiscard(*this, S);
  1430. }
  1431. // Finally, add the defs from this MU.
  1432. for (auto &KV : MU.getSymbols()) {
  1433. auto &SymEntry = Symbols[KV.first];
  1434. SymEntry.setFlags(KV.second);
  1435. SymEntry.setState(SymbolState::NeverSearched);
  1436. SymEntry.setMaterializerAttached(true);
  1437. }
  1438. return Error::success();
  1439. }
  1440. void JITDylib::installMaterializationUnit(
  1441. std::unique_ptr<MaterializationUnit> MU, ResourceTracker &RT) {
  1442. /// defineImpl succeeded.
  1443. if (&RT != DefaultTracker.get()) {
  1444. auto &TS = TrackerSymbols[&RT];
  1445. TS.reserve(TS.size() + MU->getSymbols().size());
  1446. for (auto &KV : MU->getSymbols())
  1447. TS.push_back(KV.first);
  1448. }
  1449. auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU), &RT);
  1450. for (auto &KV : UMI->MU->getSymbols())
  1451. UnmaterializedInfos[KV.first] = UMI;
  1452. }
  1453. void JITDylib::detachQueryHelper(AsynchronousSymbolQuery &Q,
  1454. const SymbolNameSet &QuerySymbols) {
  1455. for (auto &QuerySymbol : QuerySymbols) {
  1456. assert(MaterializingInfos.count(QuerySymbol) &&
  1457. "QuerySymbol does not have MaterializingInfo");
  1458. auto &MI = MaterializingInfos[QuerySymbol];
  1459. MI.removeQuery(Q);
  1460. }
  1461. }
  1462. void JITDylib::transferEmittedNodeDependencies(
  1463. MaterializingInfo &DependantMI, const SymbolStringPtr &DependantName,
  1464. MaterializingInfo &EmittedMI) {
  1465. for (auto &KV : EmittedMI.UnemittedDependencies) {
  1466. auto &DependencyJD = *KV.first;
  1467. SymbolNameSet *UnemittedDependenciesOnDependencyJD = nullptr;
  1468. for (auto &DependencyName : KV.second) {
  1469. auto &DependencyMI = DependencyJD.MaterializingInfos[DependencyName];
  1470. // Do not add self dependencies.
  1471. if (&DependencyMI == &DependantMI)
  1472. continue;
  1473. // If we haven't looked up the dependencies for DependencyJD yet, do it
  1474. // now and cache the result.
  1475. if (!UnemittedDependenciesOnDependencyJD)
  1476. UnemittedDependenciesOnDependencyJD =
  1477. &DependantMI.UnemittedDependencies[&DependencyJD];
  1478. DependencyMI.Dependants[this].insert(DependantName);
  1479. UnemittedDependenciesOnDependencyJD->insert(DependencyName);
  1480. }
  1481. }
  1482. }
  1483. Platform::~Platform() = default;
  1484. Expected<DenseMap<JITDylib *, SymbolMap>> Platform::lookupInitSymbols(
  1485. ExecutionSession &ES,
  1486. const DenseMap<JITDylib *, SymbolLookupSet> &InitSyms) {
  1487. DenseMap<JITDylib *, SymbolMap> CompoundResult;
  1488. Error CompoundErr = Error::success();
  1489. std::mutex LookupMutex;
  1490. std::condition_variable CV;
  1491. uint64_t Count = InitSyms.size();
  1492. LLVM_DEBUG({
  1493. dbgs() << "Issuing init-symbol lookup:\n";
  1494. for (auto &KV : InitSyms)
  1495. dbgs() << " " << KV.first->getName() << ": " << KV.second << "\n";
  1496. });
  1497. for (auto &KV : InitSyms) {
  1498. auto *JD = KV.first;
  1499. auto Names = std::move(KV.second);
  1500. ES.lookup(
  1501. LookupKind::Static,
  1502. JITDylibSearchOrder({{JD, JITDylibLookupFlags::MatchAllSymbols}}),
  1503. std::move(Names), SymbolState::Ready,
  1504. [&, JD](Expected<SymbolMap> Result) {
  1505. {
  1506. std::lock_guard<std::mutex> Lock(LookupMutex);
  1507. --Count;
  1508. if (Result) {
  1509. assert(!CompoundResult.count(JD) &&
  1510. "Duplicate JITDylib in lookup?");
  1511. CompoundResult[JD] = std::move(*Result);
  1512. } else
  1513. CompoundErr =
  1514. joinErrors(std::move(CompoundErr), Result.takeError());
  1515. }
  1516. CV.notify_one();
  1517. },
  1518. NoDependenciesToRegister);
  1519. }
  1520. std::unique_lock<std::mutex> Lock(LookupMutex);
  1521. CV.wait(Lock, [&] { return Count == 0 || CompoundErr; });
  1522. if (CompoundErr)
  1523. return std::move(CompoundErr);
  1524. return std::move(CompoundResult);
  1525. }
  1526. void Platform::lookupInitSymbolsAsync(
  1527. unique_function<void(Error)> OnComplete, ExecutionSession &ES,
  1528. const DenseMap<JITDylib *, SymbolLookupSet> &InitSyms) {
  1529. class TriggerOnComplete {
  1530. public:
  1531. using OnCompleteFn = unique_function<void(Error)>;
  1532. TriggerOnComplete(OnCompleteFn OnComplete)
  1533. : OnComplete(std::move(OnComplete)) {}
  1534. ~TriggerOnComplete() { OnComplete(std::move(LookupResult)); }
  1535. void reportResult(Error Err) {
  1536. std::lock_guard<std::mutex> Lock(ResultMutex);
  1537. LookupResult = joinErrors(std::move(LookupResult), std::move(Err));
  1538. }
  1539. private:
  1540. std::mutex ResultMutex;
  1541. Error LookupResult{Error::success()};
  1542. OnCompleteFn OnComplete;
  1543. };
  1544. LLVM_DEBUG({
  1545. dbgs() << "Issuing init-symbol lookup:\n";
  1546. for (auto &KV : InitSyms)
  1547. dbgs() << " " << KV.first->getName() << ": " << KV.second << "\n";
  1548. });
  1549. auto TOC = std::make_shared<TriggerOnComplete>(std::move(OnComplete));
  1550. for (auto &KV : InitSyms) {
  1551. auto *JD = KV.first;
  1552. auto Names = std::move(KV.second);
  1553. ES.lookup(
  1554. LookupKind::Static,
  1555. JITDylibSearchOrder({{JD, JITDylibLookupFlags::MatchAllSymbols}}),
  1556. std::move(Names), SymbolState::Ready,
  1557. [TOC](Expected<SymbolMap> Result) {
  1558. TOC->reportResult(Result.takeError());
  1559. },
  1560. NoDependenciesToRegister);
  1561. }
  1562. }
  1563. void MaterializationTask::printDescription(raw_ostream &OS) {
  1564. OS << "Materialization task: " << MU->getName() << " in "
  1565. << MR->getTargetJITDylib().getName();
  1566. }
  1567. void MaterializationTask::run() { MU->materialize(std::move(MR)); }
  1568. ExecutionSession::ExecutionSession(std::unique_ptr<ExecutorProcessControl> EPC)
  1569. : EPC(std::move(EPC)) {
  1570. // Associated EPC and this.
  1571. this->EPC->ES = this;
  1572. }
  1573. ExecutionSession::~ExecutionSession() {
  1574. // You must call endSession prior to destroying the session.
  1575. assert(!SessionOpen &&
  1576. "Session still open. Did you forget to call endSession?");
  1577. }
  1578. Error ExecutionSession::endSession() {
  1579. LLVM_DEBUG(dbgs() << "Ending ExecutionSession " << this << "\n");
  1580. std::vector<JITDylibSP> JITDylibsToClose = runSessionLocked([&] {
  1581. SessionOpen = false;
  1582. return std::move(JDs);
  1583. });
  1584. // TODO: notifiy platform? run static deinits?
  1585. Error Err = Error::success();
  1586. for (auto &JD : reverse(JITDylibsToClose))
  1587. Err = joinErrors(std::move(Err), JD->clear());
  1588. Err = joinErrors(std::move(Err), EPC->disconnect());
  1589. return Err;
  1590. }
  1591. void ExecutionSession::registerResourceManager(ResourceManager &RM) {
  1592. runSessionLocked([&] { ResourceManagers.push_back(&RM); });
  1593. }
  1594. void ExecutionSession::deregisterResourceManager(ResourceManager &RM) {
  1595. runSessionLocked([&] {
  1596. assert(!ResourceManagers.empty() && "No managers registered");
  1597. if (ResourceManagers.back() == &RM)
  1598. ResourceManagers.pop_back();
  1599. else {
  1600. auto I = llvm::find(ResourceManagers, &RM);
  1601. assert(I != ResourceManagers.end() && "RM not registered");
  1602. ResourceManagers.erase(I);
  1603. }
  1604. });
  1605. }
  1606. JITDylib *ExecutionSession::getJITDylibByName(StringRef Name) {
  1607. return runSessionLocked([&, this]() -> JITDylib * {
  1608. for (auto &JD : JDs)
  1609. if (JD->getName() == Name)
  1610. return JD.get();
  1611. return nullptr;
  1612. });
  1613. }
  1614. JITDylib &ExecutionSession::createBareJITDylib(std::string Name) {
  1615. assert(!getJITDylibByName(Name) && "JITDylib with that name already exists");
  1616. return runSessionLocked([&, this]() -> JITDylib & {
  1617. JDs.push_back(new JITDylib(*this, std::move(Name)));
  1618. return *JDs.back();
  1619. });
  1620. }
  1621. Expected<JITDylib &> ExecutionSession::createJITDylib(std::string Name) {
  1622. auto &JD = createBareJITDylib(Name);
  1623. if (P)
  1624. if (auto Err = P->setupJITDylib(JD))
  1625. return std::move(Err);
  1626. return JD;
  1627. }
  1628. Error ExecutionSession::removeJITDylib(JITDylib &JD) {
  1629. // Keep JD alive throughout this routine, even if all other references
  1630. // have been dropped.
  1631. JITDylibSP JDKeepAlive = &JD;
  1632. // Set JD to 'Closing' state and remove JD from the ExecutionSession.
  1633. runSessionLocked([&] {
  1634. assert(JD.State == JITDylib::Open && "JD already closed");
  1635. JD.State = JITDylib::Closing;
  1636. auto I = llvm::find(JDs, &JD);
  1637. assert(I != JDs.end() && "JD does not appear in session JDs");
  1638. JDs.erase(I);
  1639. });
  1640. // Clear the JITDylib. Hold on to any error while we clean up the
  1641. // JITDylib members below.
  1642. auto Err = JD.clear();
  1643. // Notify the platform of the teardown.
  1644. if (P)
  1645. Err = joinErrors(std::move(Err), P->teardownJITDylib(JD));
  1646. // Set JD to closed state. Clear remaining data structures.
  1647. runSessionLocked([&] {
  1648. assert(JD.State == JITDylib::Closing && "JD should be closing");
  1649. JD.State = JITDylib::Closed;
  1650. assert(JD.Symbols.empty() && "JD.Symbols is not empty after clear");
  1651. assert(JD.UnmaterializedInfos.empty() &&
  1652. "JD.UnmaterializedInfos is not empty after clear");
  1653. assert(JD.MaterializingInfos.empty() &&
  1654. "JD.MaterializingInfos is not empty after clear");
  1655. assert(JD.TrackerSymbols.empty() &&
  1656. "TrackerSymbols is not empty after clear");
  1657. JD.DefGenerators.clear();
  1658. JD.LinkOrder.clear();
  1659. });
  1660. return Err;
  1661. }
  1662. Expected<std::vector<JITDylibSP>>
  1663. JITDylib::getDFSLinkOrder(ArrayRef<JITDylibSP> JDs) {
  1664. if (JDs.empty())
  1665. return std::vector<JITDylibSP>();
  1666. auto &ES = JDs.front()->getExecutionSession();
  1667. return ES.runSessionLocked([&]() -> Expected<std::vector<JITDylibSP>> {
  1668. DenseSet<JITDylib *> Visited;
  1669. std::vector<JITDylibSP> Result;
  1670. for (auto &JD : JDs) {
  1671. if (JD->State != Open)
  1672. return make_error<StringError>(
  1673. "Error building link order: " + JD->getName() + " is defunct",
  1674. inconvertibleErrorCode());
  1675. if (Visited.count(JD.get()))
  1676. continue;
  1677. SmallVector<JITDylibSP, 64> WorkStack;
  1678. WorkStack.push_back(JD);
  1679. Visited.insert(JD.get());
  1680. while (!WorkStack.empty()) {
  1681. Result.push_back(std::move(WorkStack.back()));
  1682. WorkStack.pop_back();
  1683. for (auto &KV : llvm::reverse(Result.back()->LinkOrder)) {
  1684. auto &JD = *KV.first;
  1685. if (!Visited.insert(&JD).second)
  1686. continue;
  1687. WorkStack.push_back(&JD);
  1688. }
  1689. }
  1690. }
  1691. return Result;
  1692. });
  1693. }
  1694. Expected<std::vector<JITDylibSP>>
  1695. JITDylib::getReverseDFSLinkOrder(ArrayRef<JITDylibSP> JDs) {
  1696. auto Result = getDFSLinkOrder(JDs);
  1697. if (Result)
  1698. std::reverse(Result->begin(), Result->end());
  1699. return Result;
  1700. }
  1701. Expected<std::vector<JITDylibSP>> JITDylib::getDFSLinkOrder() {
  1702. return getDFSLinkOrder({this});
  1703. }
  1704. Expected<std::vector<JITDylibSP>> JITDylib::getReverseDFSLinkOrder() {
  1705. return getReverseDFSLinkOrder({this});
  1706. }
  1707. void ExecutionSession::lookupFlags(
  1708. LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet,
  1709. unique_function<void(Expected<SymbolFlagsMap>)> OnComplete) {
  1710. OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
  1711. K, std::move(SearchOrder), std::move(LookupSet),
  1712. std::move(OnComplete)),
  1713. Error::success());
  1714. }
  1715. Expected<SymbolFlagsMap>
  1716. ExecutionSession::lookupFlags(LookupKind K, JITDylibSearchOrder SearchOrder,
  1717. SymbolLookupSet LookupSet) {
  1718. std::promise<MSVCPExpected<SymbolFlagsMap>> ResultP;
  1719. OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
  1720. K, std::move(SearchOrder), std::move(LookupSet),
  1721. [&ResultP](Expected<SymbolFlagsMap> Result) {
  1722. ResultP.set_value(std::move(Result));
  1723. }),
  1724. Error::success());
  1725. auto ResultF = ResultP.get_future();
  1726. return ResultF.get();
  1727. }
  1728. void ExecutionSession::lookup(
  1729. LookupKind K, const JITDylibSearchOrder &SearchOrder,
  1730. SymbolLookupSet Symbols, SymbolState RequiredState,
  1731. SymbolsResolvedCallback NotifyComplete,
  1732. RegisterDependenciesFunction RegisterDependencies) {
  1733. LLVM_DEBUG({
  1734. runSessionLocked([&]() {
  1735. dbgs() << "Looking up " << Symbols << " in " << SearchOrder
  1736. << " (required state: " << RequiredState << ")\n";
  1737. });
  1738. });
  1739. // lookup can be re-entered recursively if running on a single thread. Run any
  1740. // outstanding MUs in case this query depends on them, otherwise this lookup
  1741. // will starve waiting for a result from an MU that is stuck in the queue.
  1742. dispatchOutstandingMUs();
  1743. auto Unresolved = std::move(Symbols);
  1744. auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
  1745. std::move(NotifyComplete));
  1746. auto IPLS = std::make_unique<InProgressFullLookupState>(
  1747. K, SearchOrder, std::move(Unresolved), RequiredState, std::move(Q),
  1748. std::move(RegisterDependencies));
  1749. OL_applyQueryPhase1(std::move(IPLS), Error::success());
  1750. }
  1751. Expected<SymbolMap>
  1752. ExecutionSession::lookup(const JITDylibSearchOrder &SearchOrder,
  1753. SymbolLookupSet Symbols, LookupKind K,
  1754. SymbolState RequiredState,
  1755. RegisterDependenciesFunction RegisterDependencies) {
  1756. #if LLVM_ENABLE_THREADS
  1757. // In the threaded case we use promises to return the results.
  1758. std::promise<SymbolMap> PromisedResult;
  1759. Error ResolutionError = Error::success();
  1760. auto NotifyComplete = [&](Expected<SymbolMap> R) {
  1761. if (R)
  1762. PromisedResult.set_value(std::move(*R));
  1763. else {
  1764. ErrorAsOutParameter _(&ResolutionError);
  1765. ResolutionError = R.takeError();
  1766. PromisedResult.set_value(SymbolMap());
  1767. }
  1768. };
  1769. #else
  1770. SymbolMap Result;
  1771. Error ResolutionError = Error::success();
  1772. auto NotifyComplete = [&](Expected<SymbolMap> R) {
  1773. ErrorAsOutParameter _(&ResolutionError);
  1774. if (R)
  1775. Result = std::move(*R);
  1776. else
  1777. ResolutionError = R.takeError();
  1778. };
  1779. #endif
  1780. // Perform the asynchronous lookup.
  1781. lookup(K, SearchOrder, std::move(Symbols), RequiredState, NotifyComplete,
  1782. RegisterDependencies);
  1783. #if LLVM_ENABLE_THREADS
  1784. auto ResultFuture = PromisedResult.get_future();
  1785. auto Result = ResultFuture.get();
  1786. if (ResolutionError)
  1787. return std::move(ResolutionError);
  1788. return std::move(Result);
  1789. #else
  1790. if (ResolutionError)
  1791. return std::move(ResolutionError);
  1792. return Result;
  1793. #endif
  1794. }
  1795. Expected<JITEvaluatedSymbol>
  1796. ExecutionSession::lookup(const JITDylibSearchOrder &SearchOrder,
  1797. SymbolStringPtr Name, SymbolState RequiredState) {
  1798. SymbolLookupSet Names({Name});
  1799. if (auto ResultMap = lookup(SearchOrder, std::move(Names), LookupKind::Static,
  1800. RequiredState, NoDependenciesToRegister)) {
  1801. assert(ResultMap->size() == 1 && "Unexpected number of results");
  1802. assert(ResultMap->count(Name) && "Missing result for symbol");
  1803. return std::move(ResultMap->begin()->second);
  1804. } else
  1805. return ResultMap.takeError();
  1806. }
  1807. Expected<JITEvaluatedSymbol>
  1808. ExecutionSession::lookup(ArrayRef<JITDylib *> SearchOrder, SymbolStringPtr Name,
  1809. SymbolState RequiredState) {
  1810. return lookup(makeJITDylibSearchOrder(SearchOrder), Name, RequiredState);
  1811. }
  1812. Expected<JITEvaluatedSymbol>
  1813. ExecutionSession::lookup(ArrayRef<JITDylib *> SearchOrder, StringRef Name,
  1814. SymbolState RequiredState) {
  1815. return lookup(SearchOrder, intern(Name), RequiredState);
  1816. }
  1817. Error ExecutionSession::registerJITDispatchHandlers(
  1818. JITDylib &JD, JITDispatchHandlerAssociationMap WFs) {
  1819. auto TagAddrs = lookup({{&JD, JITDylibLookupFlags::MatchAllSymbols}},
  1820. SymbolLookupSet::fromMapKeys(
  1821. WFs, SymbolLookupFlags::WeaklyReferencedSymbol));
  1822. if (!TagAddrs)
  1823. return TagAddrs.takeError();
  1824. // Associate tag addresses with implementations.
  1825. std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
  1826. for (auto &KV : *TagAddrs) {
  1827. auto TagAddr = KV.second.getAddress();
  1828. if (JITDispatchHandlers.count(TagAddr))
  1829. return make_error<StringError>("Tag " + formatv("{0:x16}", TagAddr) +
  1830. " (for " + *KV.first +
  1831. ") already registered",
  1832. inconvertibleErrorCode());
  1833. auto I = WFs.find(KV.first);
  1834. assert(I != WFs.end() && I->second &&
  1835. "JITDispatchHandler implementation missing");
  1836. JITDispatchHandlers[KV.second.getAddress()] =
  1837. std::make_shared<JITDispatchHandlerFunction>(std::move(I->second));
  1838. LLVM_DEBUG({
  1839. dbgs() << "Associated function tag \"" << *KV.first << "\" ("
  1840. << formatv("{0:x}", KV.second.getAddress()) << ") with handler\n";
  1841. });
  1842. }
  1843. return Error::success();
  1844. }
  1845. void ExecutionSession::runJITDispatchHandler(
  1846. SendResultFunction SendResult, JITTargetAddress HandlerFnTagAddr,
  1847. ArrayRef<char> ArgBuffer) {
  1848. std::shared_ptr<JITDispatchHandlerFunction> F;
  1849. {
  1850. std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
  1851. auto I = JITDispatchHandlers.find(HandlerFnTagAddr);
  1852. if (I != JITDispatchHandlers.end())
  1853. F = I->second;
  1854. }
  1855. if (F)
  1856. (*F)(std::move(SendResult), ArgBuffer.data(), ArgBuffer.size());
  1857. else
  1858. SendResult(shared::WrapperFunctionResult::createOutOfBandError(
  1859. ("No function registered for tag " +
  1860. formatv("{0:x16}", HandlerFnTagAddr))
  1861. .str()));
  1862. }
  1863. void ExecutionSession::dump(raw_ostream &OS) {
  1864. runSessionLocked([this, &OS]() {
  1865. for (auto &JD : JDs)
  1866. JD->dump(OS);
  1867. });
  1868. }
  1869. void ExecutionSession::dispatchOutstandingMUs() {
  1870. LLVM_DEBUG(dbgs() << "Dispatching MaterializationUnits...\n");
  1871. while (true) {
  1872. std::optional<std::pair<std::unique_ptr<MaterializationUnit>,
  1873. std::unique_ptr<MaterializationResponsibility>>>
  1874. JMU;
  1875. {
  1876. std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
  1877. if (!OutstandingMUs.empty()) {
  1878. JMU.emplace(std::move(OutstandingMUs.back()));
  1879. OutstandingMUs.pop_back();
  1880. }
  1881. }
  1882. if (!JMU)
  1883. break;
  1884. assert(JMU->first && "No MU?");
  1885. LLVM_DEBUG(dbgs() << " Dispatching \"" << JMU->first->getName() << "\"\n");
  1886. dispatchTask(std::make_unique<MaterializationTask>(std::move(JMU->first),
  1887. std::move(JMU->second)));
  1888. }
  1889. LLVM_DEBUG(dbgs() << "Done dispatching MaterializationUnits.\n");
  1890. }
  1891. Error ExecutionSession::removeResourceTracker(ResourceTracker &RT) {
  1892. LLVM_DEBUG({
  1893. dbgs() << "In " << RT.getJITDylib().getName() << " removing tracker "
  1894. << formatv("{0:x}", RT.getKeyUnsafe()) << "\n";
  1895. });
  1896. std::vector<ResourceManager *> CurrentResourceManagers;
  1897. JITDylib::AsynchronousSymbolQuerySet QueriesToFail;
  1898. std::shared_ptr<SymbolDependenceMap> FailedSymbols;
  1899. runSessionLocked([&] {
  1900. CurrentResourceManagers = ResourceManagers;
  1901. RT.makeDefunct();
  1902. std::tie(QueriesToFail, FailedSymbols) = RT.getJITDylib().removeTracker(RT);
  1903. });
  1904. Error Err = Error::success();
  1905. auto &JD = RT.getJITDylib();
  1906. for (auto *L : reverse(CurrentResourceManagers))
  1907. Err = joinErrors(std::move(Err),
  1908. L->handleRemoveResources(JD, RT.getKeyUnsafe()));
  1909. for (auto &Q : QueriesToFail)
  1910. Q->handleFailed(
  1911. make_error<FailedToMaterialize>(getSymbolStringPool(), FailedSymbols));
  1912. return Err;
  1913. }
  1914. void ExecutionSession::transferResourceTracker(ResourceTracker &DstRT,
  1915. ResourceTracker &SrcRT) {
  1916. LLVM_DEBUG({
  1917. dbgs() << "In " << SrcRT.getJITDylib().getName()
  1918. << " transfering resources from tracker "
  1919. << formatv("{0:x}", SrcRT.getKeyUnsafe()) << " to tracker "
  1920. << formatv("{0:x}", DstRT.getKeyUnsafe()) << "\n";
  1921. });
  1922. // No-op transfers are allowed and do not invalidate the source.
  1923. if (&DstRT == &SrcRT)
  1924. return;
  1925. assert(&DstRT.getJITDylib() == &SrcRT.getJITDylib() &&
  1926. "Can't transfer resources between JITDylibs");
  1927. runSessionLocked([&]() {
  1928. SrcRT.makeDefunct();
  1929. auto &JD = DstRT.getJITDylib();
  1930. JD.transferTracker(DstRT, SrcRT);
  1931. for (auto *L : reverse(ResourceManagers))
  1932. L->handleTransferResources(JD, DstRT.getKeyUnsafe(),
  1933. SrcRT.getKeyUnsafe());
  1934. });
  1935. }
  1936. void ExecutionSession::destroyResourceTracker(ResourceTracker &RT) {
  1937. runSessionLocked([&]() {
  1938. LLVM_DEBUG({
  1939. dbgs() << "In " << RT.getJITDylib().getName() << " destroying tracker "
  1940. << formatv("{0:x}", RT.getKeyUnsafe()) << "\n";
  1941. });
  1942. if (!RT.isDefunct())
  1943. transferResourceTracker(*RT.getJITDylib().getDefaultResourceTracker(),
  1944. RT);
  1945. });
  1946. }
  1947. Error ExecutionSession::IL_updateCandidatesFor(
  1948. JITDylib &JD, JITDylibLookupFlags JDLookupFlags,
  1949. SymbolLookupSet &Candidates, SymbolLookupSet *NonCandidates) {
  1950. return Candidates.forEachWithRemoval(
  1951. [&](const SymbolStringPtr &Name,
  1952. SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
  1953. /// Search for the symbol. If not found then continue without
  1954. /// removal.
  1955. auto SymI = JD.Symbols.find(Name);
  1956. if (SymI == JD.Symbols.end())
  1957. return false;
  1958. // If this is a non-exported symbol and we're matching exported
  1959. // symbols only then remove this symbol from the candidates list.
  1960. //
  1961. // If we're tracking non-candidates then add this to the non-candidate
  1962. // list.
  1963. if (!SymI->second.getFlags().isExported() &&
  1964. JDLookupFlags == JITDylibLookupFlags::MatchExportedSymbolsOnly) {
  1965. if (NonCandidates)
  1966. NonCandidates->add(Name, SymLookupFlags);
  1967. return true;
  1968. }
  1969. // If we match against a materialization-side-effects only symbol
  1970. // then make sure it is weakly-referenced. Otherwise bail out with
  1971. // an error.
  1972. // FIXME: Use a "materialization-side-effects-only symbols must be
  1973. // weakly referenced" specific error here to reduce confusion.
  1974. if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
  1975. SymLookupFlags != SymbolLookupFlags::WeaklyReferencedSymbol)
  1976. return make_error<SymbolsNotFound>(getSymbolStringPool(),
  1977. SymbolNameVector({Name}));
  1978. // If we matched against this symbol but it is in the error state
  1979. // then bail out and treat it as a failure to materialize.
  1980. if (SymI->second.getFlags().hasError()) {
  1981. auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
  1982. (*FailedSymbolsMap)[&JD] = {Name};
  1983. return make_error<FailedToMaterialize>(getSymbolStringPool(),
  1984. std::move(FailedSymbolsMap));
  1985. }
  1986. // Otherwise this is a match. Remove it from the candidate set.
  1987. return true;
  1988. });
  1989. }
  1990. void ExecutionSession::OL_applyQueryPhase1(
  1991. std::unique_ptr<InProgressLookupState> IPLS, Error Err) {
  1992. LLVM_DEBUG({
  1993. dbgs() << "Entering OL_applyQueryPhase1:\n"
  1994. << " Lookup kind: " << IPLS->K << "\n"
  1995. << " Search order: " << IPLS->SearchOrder
  1996. << ", Current index = " << IPLS->CurSearchOrderIndex
  1997. << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
  1998. << " Lookup set: " << IPLS->LookupSet << "\n"
  1999. << " Definition generator candidates: "
  2000. << IPLS->DefGeneratorCandidates << "\n"
  2001. << " Definition generator non-candidates: "
  2002. << IPLS->DefGeneratorNonCandidates << "\n";
  2003. });
  2004. // FIXME: We should attach the query as we go: This provides a result in a
  2005. // single pass in the common case where all symbols have already reached the
  2006. // required state. The query could be detached again in the 'fail' method on
  2007. // IPLS. Phase 2 would be reduced to collecting and dispatching the MUs.
  2008. while (IPLS->CurSearchOrderIndex != IPLS->SearchOrder.size()) {
  2009. // If we've been handed an error or received one back from a generator then
  2010. // fail the query. We don't need to unlink: At this stage the query hasn't
  2011. // actually been lodged.
  2012. if (Err)
  2013. return IPLS->fail(std::move(Err));
  2014. // Get the next JITDylib and lookup flags.
  2015. auto &KV = IPLS->SearchOrder[IPLS->CurSearchOrderIndex];
  2016. auto &JD = *KV.first;
  2017. auto JDLookupFlags = KV.second;
  2018. LLVM_DEBUG({
  2019. dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
  2020. << ") with lookup set " << IPLS->LookupSet << ":\n";
  2021. });
  2022. // If we've just reached a new JITDylib then perform some setup.
  2023. if (IPLS->NewJITDylib) {
  2024. // Acquire the generator lock for this JITDylib.
  2025. IPLS->GeneratorLock = std::unique_lock<std::mutex>(JD.GeneratorsMutex);
  2026. // Add any non-candidates from the last JITDylib (if any) back on to the
  2027. // list of definition candidates for this JITDylib, reset definition
  2028. // non-candidates to the empty set.
  2029. SymbolLookupSet Tmp;
  2030. std::swap(IPLS->DefGeneratorNonCandidates, Tmp);
  2031. IPLS->DefGeneratorCandidates.append(std::move(Tmp));
  2032. LLVM_DEBUG({
  2033. dbgs() << " First time visiting " << JD.getName()
  2034. << ", resetting candidate sets and building generator stack\n";
  2035. });
  2036. // Build the definition generator stack for this JITDylib.
  2037. runSessionLocked([&] {
  2038. IPLS->CurDefGeneratorStack.reserve(JD.DefGenerators.size());
  2039. for (auto &DG : reverse(JD.DefGenerators))
  2040. IPLS->CurDefGeneratorStack.push_back(DG);
  2041. });
  2042. // Flag that we've done our initialization.
  2043. IPLS->NewJITDylib = false;
  2044. }
  2045. // Remove any generation candidates that are already defined (and match) in
  2046. // this JITDylib.
  2047. runSessionLocked([&] {
  2048. // Update the list of candidates (and non-candidates) for definition
  2049. // generation.
  2050. LLVM_DEBUG(dbgs() << " Updating candidate set...\n");
  2051. Err = IL_updateCandidatesFor(
  2052. JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
  2053. JD.DefGenerators.empty() ? nullptr
  2054. : &IPLS->DefGeneratorNonCandidates);
  2055. LLVM_DEBUG({
  2056. dbgs() << " Remaining candidates = " << IPLS->DefGeneratorCandidates
  2057. << "\n";
  2058. });
  2059. });
  2060. // If we encountered an error while filtering generation candidates then
  2061. // bail out.
  2062. if (Err)
  2063. return IPLS->fail(std::move(Err));
  2064. /// Apply any definition generators on the stack.
  2065. LLVM_DEBUG({
  2066. if (IPLS->CurDefGeneratorStack.empty())
  2067. LLVM_DEBUG(dbgs() << " No generators to run for this JITDylib.\n");
  2068. else if (IPLS->DefGeneratorCandidates.empty())
  2069. LLVM_DEBUG(dbgs() << " No candidates to generate.\n");
  2070. else
  2071. dbgs() << " Running " << IPLS->CurDefGeneratorStack.size()
  2072. << " remaining generators for "
  2073. << IPLS->DefGeneratorCandidates.size() << " candidates\n";
  2074. });
  2075. while (!IPLS->CurDefGeneratorStack.empty() &&
  2076. !IPLS->DefGeneratorCandidates.empty()) {
  2077. auto DG = IPLS->CurDefGeneratorStack.back().lock();
  2078. IPLS->CurDefGeneratorStack.pop_back();
  2079. if (!DG)
  2080. return IPLS->fail(make_error<StringError>(
  2081. "DefinitionGenerator removed while lookup in progress",
  2082. inconvertibleErrorCode()));
  2083. auto K = IPLS->K;
  2084. auto &LookupSet = IPLS->DefGeneratorCandidates;
  2085. // Run the generator. If the generator takes ownership of QA then this
  2086. // will break the loop.
  2087. {
  2088. LLVM_DEBUG(dbgs() << " Attempting to generate " << LookupSet << "\n");
  2089. LookupState LS(std::move(IPLS));
  2090. Err = DG->tryToGenerate(LS, K, JD, JDLookupFlags, LookupSet);
  2091. IPLS = std::move(LS.IPLS);
  2092. }
  2093. // If there was an error then fail the query.
  2094. if (Err) {
  2095. LLVM_DEBUG({
  2096. dbgs() << " Error attempting to generate " << LookupSet << "\n";
  2097. });
  2098. assert(IPLS && "LS cannot be retained if error is returned");
  2099. return IPLS->fail(std::move(Err));
  2100. }
  2101. // Otherwise if QA was captured then break the loop.
  2102. if (!IPLS) {
  2103. LLVM_DEBUG(
  2104. { dbgs() << " LookupState captured. Exiting phase1 for now.\n"; });
  2105. return;
  2106. }
  2107. // Otherwise if we're continuing around the loop then update candidates
  2108. // for the next round.
  2109. runSessionLocked([&] {
  2110. LLVM_DEBUG(dbgs() << " Updating candidate set post-generation\n");
  2111. Err = IL_updateCandidatesFor(
  2112. JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
  2113. JD.DefGenerators.empty() ? nullptr
  2114. : &IPLS->DefGeneratorNonCandidates);
  2115. });
  2116. // If updating candidates failed then fail the query.
  2117. if (Err) {
  2118. LLVM_DEBUG(dbgs() << " Error encountered while updating candidates\n");
  2119. return IPLS->fail(std::move(Err));
  2120. }
  2121. }
  2122. if (IPLS->DefGeneratorCandidates.empty() &&
  2123. IPLS->DefGeneratorNonCandidates.empty()) {
  2124. // Early out if there are no remaining symbols.
  2125. LLVM_DEBUG(dbgs() << "All symbols matched.\n");
  2126. IPLS->CurSearchOrderIndex = IPLS->SearchOrder.size();
  2127. break;
  2128. } else {
  2129. // If we get here then we've moved on to the next JITDylib with candidates
  2130. // remaining.
  2131. LLVM_DEBUG(dbgs() << "Phase 1 moving to next JITDylib.\n");
  2132. ++IPLS->CurSearchOrderIndex;
  2133. IPLS->NewJITDylib = true;
  2134. }
  2135. }
  2136. // Remove any weakly referenced candidates that could not be found/generated.
  2137. IPLS->DefGeneratorCandidates.remove_if(
  2138. [](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
  2139. return SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol;
  2140. });
  2141. // If we get here then we've finished searching all JITDylibs.
  2142. // If we matched all symbols then move to phase 2, otherwise fail the query
  2143. // with a SymbolsNotFound error.
  2144. if (IPLS->DefGeneratorCandidates.empty()) {
  2145. LLVM_DEBUG(dbgs() << "Phase 1 succeeded.\n");
  2146. IPLS->complete(std::move(IPLS));
  2147. } else {
  2148. LLVM_DEBUG(dbgs() << "Phase 1 failed with unresolved symbols.\n");
  2149. IPLS->fail(make_error<SymbolsNotFound>(
  2150. getSymbolStringPool(), IPLS->DefGeneratorCandidates.getSymbolNames()));
  2151. }
  2152. }
  2153. void ExecutionSession::OL_completeLookup(
  2154. std::unique_ptr<InProgressLookupState> IPLS,
  2155. std::shared_ptr<AsynchronousSymbolQuery> Q,
  2156. RegisterDependenciesFunction RegisterDependencies) {
  2157. LLVM_DEBUG({
  2158. dbgs() << "Entering OL_completeLookup:\n"
  2159. << " Lookup kind: " << IPLS->K << "\n"
  2160. << " Search order: " << IPLS->SearchOrder
  2161. << ", Current index = " << IPLS->CurSearchOrderIndex
  2162. << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
  2163. << " Lookup set: " << IPLS->LookupSet << "\n"
  2164. << " Definition generator candidates: "
  2165. << IPLS->DefGeneratorCandidates << "\n"
  2166. << " Definition generator non-candidates: "
  2167. << IPLS->DefGeneratorNonCandidates << "\n";
  2168. });
  2169. bool QueryComplete = false;
  2170. DenseMap<JITDylib *, JITDylib::UnmaterializedInfosList> CollectedUMIs;
  2171. auto LodgingErr = runSessionLocked([&]() -> Error {
  2172. for (auto &KV : IPLS->SearchOrder) {
  2173. auto &JD = *KV.first;
  2174. auto JDLookupFlags = KV.second;
  2175. LLVM_DEBUG({
  2176. dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
  2177. << ") with lookup set " << IPLS->LookupSet << ":\n";
  2178. });
  2179. auto Err = IPLS->LookupSet.forEachWithRemoval(
  2180. [&](const SymbolStringPtr &Name,
  2181. SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
  2182. LLVM_DEBUG({
  2183. dbgs() << " Attempting to match \"" << Name << "\" ("
  2184. << SymLookupFlags << ")... ";
  2185. });
  2186. /// Search for the symbol. If not found then continue without
  2187. /// removal.
  2188. auto SymI = JD.Symbols.find(Name);
  2189. if (SymI == JD.Symbols.end()) {
  2190. LLVM_DEBUG(dbgs() << "skipping: not present\n");
  2191. return false;
  2192. }
  2193. // If this is a non-exported symbol and we're matching exported
  2194. // symbols only then skip this symbol without removal.
  2195. if (!SymI->second.getFlags().isExported() &&
  2196. JDLookupFlags ==
  2197. JITDylibLookupFlags::MatchExportedSymbolsOnly) {
  2198. LLVM_DEBUG(dbgs() << "skipping: not exported\n");
  2199. return false;
  2200. }
  2201. // If we match against a materialization-side-effects only symbol
  2202. // then make sure it is weakly-referenced. Otherwise bail out with
  2203. // an error.
  2204. // FIXME: Use a "materialization-side-effects-only symbols must be
  2205. // weakly referenced" specific error here to reduce confusion.
  2206. if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
  2207. SymLookupFlags != SymbolLookupFlags::WeaklyReferencedSymbol) {
  2208. LLVM_DEBUG({
  2209. dbgs() << "error: "
  2210. "required, but symbol is has-side-effects-only\n";
  2211. });
  2212. return make_error<SymbolsNotFound>(getSymbolStringPool(),
  2213. SymbolNameVector({Name}));
  2214. }
  2215. // If we matched against this symbol but it is in the error state
  2216. // then bail out and treat it as a failure to materialize.
  2217. if (SymI->second.getFlags().hasError()) {
  2218. LLVM_DEBUG(dbgs() << "error: symbol is in error state\n");
  2219. auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
  2220. (*FailedSymbolsMap)[&JD] = {Name};
  2221. return make_error<FailedToMaterialize>(
  2222. getSymbolStringPool(), std::move(FailedSymbolsMap));
  2223. }
  2224. // Otherwise this is a match.
  2225. // If this symbol is already in the requried state then notify the
  2226. // query, remove the symbol and continue.
  2227. if (SymI->second.getState() >= Q->getRequiredState()) {
  2228. LLVM_DEBUG(dbgs()
  2229. << "matched, symbol already in required state\n");
  2230. Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
  2231. return true;
  2232. }
  2233. // Otherwise this symbol does not yet meet the required state. Check
  2234. // whether it has a materializer attached, and if so prepare to run
  2235. // it.
  2236. if (SymI->second.hasMaterializerAttached()) {
  2237. assert(SymI->second.getAddress() == 0 &&
  2238. "Symbol not resolved but already has address?");
  2239. auto UMII = JD.UnmaterializedInfos.find(Name);
  2240. assert(UMII != JD.UnmaterializedInfos.end() &&
  2241. "Lazy symbol should have UnmaterializedInfo");
  2242. auto UMI = UMII->second;
  2243. assert(UMI->MU && "Materializer should not be null");
  2244. assert(UMI->RT && "Tracker should not be null");
  2245. LLVM_DEBUG({
  2246. dbgs() << "matched, preparing to dispatch MU@" << UMI->MU.get()
  2247. << " (" << UMI->MU->getName() << ")\n";
  2248. });
  2249. // Move all symbols associated with this MaterializationUnit into
  2250. // materializing state.
  2251. for (auto &KV : UMI->MU->getSymbols()) {
  2252. auto SymK = JD.Symbols.find(KV.first);
  2253. assert(SymK != JD.Symbols.end() &&
  2254. "No entry for symbol covered by MaterializationUnit");
  2255. SymK->second.setMaterializerAttached(false);
  2256. SymK->second.setState(SymbolState::Materializing);
  2257. JD.UnmaterializedInfos.erase(KV.first);
  2258. }
  2259. // Add MU to the list of MaterializationUnits to be materialized.
  2260. CollectedUMIs[&JD].push_back(std::move(UMI));
  2261. } else
  2262. LLVM_DEBUG(dbgs() << "matched, registering query");
  2263. // Add the query to the PendingQueries list and continue, deleting
  2264. // the element from the lookup set.
  2265. assert(SymI->second.getState() != SymbolState::NeverSearched &&
  2266. SymI->second.getState() != SymbolState::Ready &&
  2267. "By this line the symbol should be materializing");
  2268. auto &MI = JD.MaterializingInfos[Name];
  2269. MI.addQuery(Q);
  2270. Q->addQueryDependence(JD, Name);
  2271. return true;
  2272. });
  2273. // Handle failure.
  2274. if (Err) {
  2275. LLVM_DEBUG({
  2276. dbgs() << "Lookup failed. Detaching query and replacing MUs.\n";
  2277. });
  2278. // Detach the query.
  2279. Q->detach();
  2280. // Replace the MUs.
  2281. for (auto &KV : CollectedUMIs) {
  2282. auto &JD = *KV.first;
  2283. for (auto &UMI : KV.second)
  2284. for (auto &KV2 : UMI->MU->getSymbols()) {
  2285. assert(!JD.UnmaterializedInfos.count(KV2.first) &&
  2286. "Unexpected materializer in map");
  2287. auto SymI = JD.Symbols.find(KV2.first);
  2288. assert(SymI != JD.Symbols.end() && "Missing symbol entry");
  2289. assert(SymI->second.getState() == SymbolState::Materializing &&
  2290. "Can not replace symbol that is not materializing");
  2291. assert(!SymI->second.hasMaterializerAttached() &&
  2292. "MaterializerAttached flag should not be set");
  2293. SymI->second.setMaterializerAttached(true);
  2294. JD.UnmaterializedInfos[KV2.first] = UMI;
  2295. }
  2296. }
  2297. return Err;
  2298. }
  2299. }
  2300. LLVM_DEBUG(dbgs() << "Stripping unmatched weakly-referenced symbols\n");
  2301. IPLS->LookupSet.forEachWithRemoval(
  2302. [&](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
  2303. if (SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol) {
  2304. Q->dropSymbol(Name);
  2305. return true;
  2306. } else
  2307. return false;
  2308. });
  2309. if (!IPLS->LookupSet.empty()) {
  2310. LLVM_DEBUG(dbgs() << "Failing due to unresolved symbols\n");
  2311. return make_error<SymbolsNotFound>(getSymbolStringPool(),
  2312. IPLS->LookupSet.getSymbolNames());
  2313. }
  2314. // Record whether the query completed.
  2315. QueryComplete = Q->isComplete();
  2316. LLVM_DEBUG({
  2317. dbgs() << "Query successfully "
  2318. << (QueryComplete ? "completed" : "lodged") << "\n";
  2319. });
  2320. // Move the collected MUs to the OutstandingMUs list.
  2321. if (!CollectedUMIs.empty()) {
  2322. std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
  2323. LLVM_DEBUG(dbgs() << "Adding MUs to dispatch:\n");
  2324. for (auto &KV : CollectedUMIs) {
  2325. LLVM_DEBUG({
  2326. auto &JD = *KV.first;
  2327. dbgs() << " For " << JD.getName() << ": Adding " << KV.second.size()
  2328. << " MUs.\n";
  2329. });
  2330. for (auto &UMI : KV.second) {
  2331. auto MR = createMaterializationResponsibility(
  2332. *UMI->RT, std::move(UMI->MU->SymbolFlags),
  2333. std::move(UMI->MU->InitSymbol));
  2334. OutstandingMUs.push_back(
  2335. std::make_pair(std::move(UMI->MU), std::move(MR)));
  2336. }
  2337. }
  2338. } else
  2339. LLVM_DEBUG(dbgs() << "No MUs to dispatch.\n");
  2340. if (RegisterDependencies && !Q->QueryRegistrations.empty()) {
  2341. LLVM_DEBUG(dbgs() << "Registering dependencies\n");
  2342. RegisterDependencies(Q->QueryRegistrations);
  2343. } else
  2344. LLVM_DEBUG(dbgs() << "No dependencies to register\n");
  2345. return Error::success();
  2346. });
  2347. if (LodgingErr) {
  2348. LLVM_DEBUG(dbgs() << "Failing query\n");
  2349. Q->detach();
  2350. Q->handleFailed(std::move(LodgingErr));
  2351. return;
  2352. }
  2353. if (QueryComplete) {
  2354. LLVM_DEBUG(dbgs() << "Completing query\n");
  2355. Q->handleComplete(*this);
  2356. }
  2357. dispatchOutstandingMUs();
  2358. }
  2359. void ExecutionSession::OL_completeLookupFlags(
  2360. std::unique_ptr<InProgressLookupState> IPLS,
  2361. unique_function<void(Expected<SymbolFlagsMap>)> OnComplete) {
  2362. auto Result = runSessionLocked([&]() -> Expected<SymbolFlagsMap> {
  2363. LLVM_DEBUG({
  2364. dbgs() << "Entering OL_completeLookupFlags:\n"
  2365. << " Lookup kind: " << IPLS->K << "\n"
  2366. << " Search order: " << IPLS->SearchOrder
  2367. << ", Current index = " << IPLS->CurSearchOrderIndex
  2368. << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
  2369. << " Lookup set: " << IPLS->LookupSet << "\n"
  2370. << " Definition generator candidates: "
  2371. << IPLS->DefGeneratorCandidates << "\n"
  2372. << " Definition generator non-candidates: "
  2373. << IPLS->DefGeneratorNonCandidates << "\n";
  2374. });
  2375. SymbolFlagsMap Result;
  2376. // Attempt to find flags for each symbol.
  2377. for (auto &KV : IPLS->SearchOrder) {
  2378. auto &JD = *KV.first;
  2379. auto JDLookupFlags = KV.second;
  2380. LLVM_DEBUG({
  2381. dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
  2382. << ") with lookup set " << IPLS->LookupSet << ":\n";
  2383. });
  2384. IPLS->LookupSet.forEachWithRemoval([&](const SymbolStringPtr &Name,
  2385. SymbolLookupFlags SymLookupFlags) {
  2386. LLVM_DEBUG({
  2387. dbgs() << " Attempting to match \"" << Name << "\" ("
  2388. << SymLookupFlags << ")... ";
  2389. });
  2390. // Search for the symbol. If not found then continue without removing
  2391. // from the lookup set.
  2392. auto SymI = JD.Symbols.find(Name);
  2393. if (SymI == JD.Symbols.end()) {
  2394. LLVM_DEBUG(dbgs() << "skipping: not present\n");
  2395. return false;
  2396. }
  2397. // If this is a non-exported symbol then it doesn't match. Skip it.
  2398. if (!SymI->second.getFlags().isExported() &&
  2399. JDLookupFlags == JITDylibLookupFlags::MatchExportedSymbolsOnly) {
  2400. LLVM_DEBUG(dbgs() << "skipping: not exported\n");
  2401. return false;
  2402. }
  2403. LLVM_DEBUG({
  2404. dbgs() << "matched, \"" << Name << "\" -> " << SymI->second.getFlags()
  2405. << "\n";
  2406. });
  2407. Result[Name] = SymI->second.getFlags();
  2408. return true;
  2409. });
  2410. }
  2411. // Remove any weakly referenced symbols that haven't been resolved.
  2412. IPLS->LookupSet.remove_if(
  2413. [](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
  2414. return SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol;
  2415. });
  2416. if (!IPLS->LookupSet.empty()) {
  2417. LLVM_DEBUG(dbgs() << "Failing due to unresolved symbols\n");
  2418. return make_error<SymbolsNotFound>(getSymbolStringPool(),
  2419. IPLS->LookupSet.getSymbolNames());
  2420. }
  2421. LLVM_DEBUG(dbgs() << "Succeded, result = " << Result << "\n");
  2422. return Result;
  2423. });
  2424. // Run the callback on the result.
  2425. LLVM_DEBUG(dbgs() << "Sending result to handler.\n");
  2426. OnComplete(std::move(Result));
  2427. }
  2428. void ExecutionSession::OL_destroyMaterializationResponsibility(
  2429. MaterializationResponsibility &MR) {
  2430. assert(MR.SymbolFlags.empty() &&
  2431. "All symbols should have been explicitly materialized or failed");
  2432. MR.JD.unlinkMaterializationResponsibility(MR);
  2433. }
  2434. SymbolNameSet ExecutionSession::OL_getRequestedSymbols(
  2435. const MaterializationResponsibility &MR) {
  2436. return MR.JD.getRequestedSymbols(MR.SymbolFlags);
  2437. }
  2438. Error ExecutionSession::OL_notifyResolved(MaterializationResponsibility &MR,
  2439. const SymbolMap &Symbols) {
  2440. LLVM_DEBUG({
  2441. dbgs() << "In " << MR.JD.getName() << " resolving " << Symbols << "\n";
  2442. });
  2443. #ifndef NDEBUG
  2444. for (auto &KV : Symbols) {
  2445. auto I = MR.SymbolFlags.find(KV.first);
  2446. assert(I != MR.SymbolFlags.end() &&
  2447. "Resolving symbol outside this responsibility set");
  2448. assert(!I->second.hasMaterializationSideEffectsOnly() &&
  2449. "Can't resolve materialization-side-effects-only symbol");
  2450. assert((KV.second.getFlags() & ~JITSymbolFlags::Common) ==
  2451. (I->second & ~JITSymbolFlags::Common) &&
  2452. "Resolving symbol with incorrect flags");
  2453. }
  2454. #endif
  2455. return MR.JD.resolve(MR, Symbols);
  2456. }
  2457. Error ExecutionSession::OL_notifyEmitted(MaterializationResponsibility &MR) {
  2458. LLVM_DEBUG({
  2459. dbgs() << "In " << MR.JD.getName() << " emitting " << MR.SymbolFlags
  2460. << "\n";
  2461. });
  2462. if (auto Err = MR.JD.emit(MR, MR.SymbolFlags))
  2463. return Err;
  2464. MR.SymbolFlags.clear();
  2465. return Error::success();
  2466. }
  2467. Error ExecutionSession::OL_defineMaterializing(
  2468. MaterializationResponsibility &MR, SymbolFlagsMap NewSymbolFlags) {
  2469. LLVM_DEBUG({
  2470. dbgs() << "In " << MR.JD.getName() << " defining materializing symbols "
  2471. << NewSymbolFlags << "\n";
  2472. });
  2473. if (auto AcceptedDefs =
  2474. MR.JD.defineMaterializing(std::move(NewSymbolFlags))) {
  2475. // Add all newly accepted symbols to this responsibility object.
  2476. for (auto &KV : *AcceptedDefs)
  2477. MR.SymbolFlags.insert(KV);
  2478. return Error::success();
  2479. } else
  2480. return AcceptedDefs.takeError();
  2481. }
  2482. void ExecutionSession::OL_notifyFailed(MaterializationResponsibility &MR) {
  2483. LLVM_DEBUG({
  2484. dbgs() << "In " << MR.JD.getName() << " failing materialization for "
  2485. << MR.SymbolFlags << "\n";
  2486. });
  2487. JITDylib::FailedSymbolsWorklist Worklist;
  2488. for (auto &KV : MR.SymbolFlags)
  2489. Worklist.push_back(std::make_pair(&MR.JD, KV.first));
  2490. MR.SymbolFlags.clear();
  2491. if (Worklist.empty())
  2492. return;
  2493. JITDylib::AsynchronousSymbolQuerySet FailedQueries;
  2494. std::shared_ptr<SymbolDependenceMap> FailedSymbols;
  2495. runSessionLocked([&]() {
  2496. // If the tracker is defunct then there's nothing to do here.
  2497. if (MR.RT->isDefunct())
  2498. return;
  2499. std::tie(FailedQueries, FailedSymbols) =
  2500. JITDylib::failSymbols(std::move(Worklist));
  2501. });
  2502. for (auto &Q : FailedQueries)
  2503. Q->handleFailed(
  2504. make_error<FailedToMaterialize>(getSymbolStringPool(), FailedSymbols));
  2505. }
  2506. Error ExecutionSession::OL_replace(MaterializationResponsibility &MR,
  2507. std::unique_ptr<MaterializationUnit> MU) {
  2508. for (auto &KV : MU->getSymbols()) {
  2509. assert(MR.SymbolFlags.count(KV.first) &&
  2510. "Replacing definition outside this responsibility set");
  2511. MR.SymbolFlags.erase(KV.first);
  2512. }
  2513. if (MU->getInitializerSymbol() == MR.InitSymbol)
  2514. MR.InitSymbol = nullptr;
  2515. LLVM_DEBUG(MR.JD.getExecutionSession().runSessionLocked([&]() {
  2516. dbgs() << "In " << MR.JD.getName() << " replacing symbols with " << *MU
  2517. << "\n";
  2518. }););
  2519. return MR.JD.replace(MR, std::move(MU));
  2520. }
  2521. Expected<std::unique_ptr<MaterializationResponsibility>>
  2522. ExecutionSession::OL_delegate(MaterializationResponsibility &MR,
  2523. const SymbolNameSet &Symbols) {
  2524. SymbolStringPtr DelegatedInitSymbol;
  2525. SymbolFlagsMap DelegatedFlags;
  2526. for (auto &Name : Symbols) {
  2527. auto I = MR.SymbolFlags.find(Name);
  2528. assert(I != MR.SymbolFlags.end() &&
  2529. "Symbol is not tracked by this MaterializationResponsibility "
  2530. "instance");
  2531. DelegatedFlags[Name] = std::move(I->second);
  2532. if (Name == MR.InitSymbol)
  2533. std::swap(MR.InitSymbol, DelegatedInitSymbol);
  2534. MR.SymbolFlags.erase(I);
  2535. }
  2536. return MR.JD.delegate(MR, std::move(DelegatedFlags),
  2537. std::move(DelegatedInitSymbol));
  2538. }
  2539. void ExecutionSession::OL_addDependencies(
  2540. MaterializationResponsibility &MR, const SymbolStringPtr &Name,
  2541. const SymbolDependenceMap &Dependencies) {
  2542. LLVM_DEBUG({
  2543. dbgs() << "Adding dependencies for " << Name << ": " << Dependencies
  2544. << "\n";
  2545. });
  2546. assert(MR.SymbolFlags.count(Name) &&
  2547. "Symbol not covered by this MaterializationResponsibility instance");
  2548. MR.JD.addDependencies(Name, Dependencies);
  2549. }
  2550. void ExecutionSession::OL_addDependenciesForAll(
  2551. MaterializationResponsibility &MR,
  2552. const SymbolDependenceMap &Dependencies) {
  2553. LLVM_DEBUG({
  2554. dbgs() << "Adding dependencies for all symbols in " << MR.SymbolFlags << ": "
  2555. << Dependencies << "\n";
  2556. });
  2557. for (auto &KV : MR.SymbolFlags)
  2558. MR.JD.addDependencies(KV.first, Dependencies);
  2559. }
  2560. #ifndef NDEBUG
  2561. void ExecutionSession::dumpDispatchInfo(Task &T) {
  2562. runSessionLocked([&]() {
  2563. dbgs() << "Dispatching: ";
  2564. T.printDescription(dbgs());
  2565. dbgs() << "\n";
  2566. });
  2567. }
  2568. #endif // NDEBUG
  2569. } // End namespace orc.
  2570. } // End namespace llvm.