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