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