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