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 Error ExecutionSession::endSession() {
1864   LLVM_DEBUG(dbgs() << "Ending ExecutionSession " << this << "\n");
1865 
1866   std::vector<JITDylibSP> JITDylibsToClose = runSessionLocked([&] {
1867     SessionOpen = false;
1868     return std::move(JDs);
1869   });
1870 
1871   // TODO: notifiy platform? run static deinits?
1872 
1873   Error Err = Error::success();
1874   for (auto &JD : reverse(JITDylibsToClose))
1875     Err = joinErrors(std::move(Err), JD->clear());
1876 
1877   Err = joinErrors(std::move(Err), EPC->disconnect());
1878 
1879   return Err;
1880 }
1881 
1882 void ExecutionSession::registerResourceManager(ResourceManager &RM) {
1883   runSessionLocked([&] { ResourceManagers.push_back(&RM); });
1884 }
1885 
1886 void ExecutionSession::deregisterResourceManager(ResourceManager &RM) {
1887   runSessionLocked([&] {
1888     assert(!ResourceManagers.empty() && "No managers registered");
1889     if (ResourceManagers.back() == &RM)
1890       ResourceManagers.pop_back();
1891     else {
1892       auto I = llvm::find(ResourceManagers, &RM);
1893       assert(I != ResourceManagers.end() && "RM not registered");
1894       ResourceManagers.erase(I);
1895     }
1896   });
1897 }
1898 
1899 JITDylib *ExecutionSession::getJITDylibByName(StringRef Name) {
1900   return runSessionLocked([&, this]() -> JITDylib * {
1901     for (auto &JD : JDs)
1902       if (JD->getName() == Name)
1903         return JD.get();
1904     return nullptr;
1905   });
1906 }
1907 
1908 JITDylib &ExecutionSession::createBareJITDylib(std::string Name) {
1909   assert(!getJITDylibByName(Name) && "JITDylib with that name already exists");
1910   return runSessionLocked([&, this]() -> JITDylib & {
1911     JDs.push_back(new JITDylib(*this, std::move(Name)));
1912     return *JDs.back();
1913   });
1914 }
1915 
1916 Expected<JITDylib &> ExecutionSession::createJITDylib(std::string Name) {
1917   auto &JD = createBareJITDylib(Name);
1918   if (P)
1919     if (auto Err = P->setupJITDylib(JD))
1920       return std::move(Err);
1921   return JD;
1922 }
1923 
1924 Error ExecutionSession::removeJITDylib(JITDylib &JD) {
1925   // Keep JD alive throughout this routine, even if all other references
1926   // have been dropped.
1927   JITDylibSP JDKeepAlive = &JD;
1928 
1929   // Set JD to 'Closing' state and remove JD from the ExecutionSession.
1930   runSessionLocked([&] {
1931     assert(JD.State == JITDylib::Open && "JD already closed");
1932     JD.State = JITDylib::Closing;
1933     auto I = llvm::find(JDs, &JD);
1934     assert(I != JDs.end() && "JD does not appear in session JDs");
1935     JDs.erase(I);
1936   });
1937 
1938   // Clear the JITDylib. Hold on to any error while we clean up the
1939   // JITDylib members below.
1940   auto Err = JD.clear();
1941 
1942   // Notify the platform of the teardown.
1943   if (P)
1944     Err = joinErrors(std::move(Err), P->teardownJITDylib(JD));
1945 
1946   // Set JD to closed state. Clear remaining data structures.
1947   runSessionLocked([&] {
1948     assert(JD.State == JITDylib::Closing && "JD should be closing");
1949     JD.State = JITDylib::Closed;
1950     assert(JD.Symbols.empty() && "JD.Symbols is not empty after clear");
1951     assert(JD.UnmaterializedInfos.empty() &&
1952            "JD.UnmaterializedInfos is not empty after clear");
1953     assert(JD.MaterializingInfos.empty() &&
1954            "JD.MaterializingInfos is not empty after clear");
1955     assert(JD.TrackerSymbols.empty() &&
1956            "TrackerSymbols is not empty after clear");
1957     JD.DefGenerators.clear();
1958     JD.LinkOrder.clear();
1959   });
1960   return Err;
1961 }
1962 
1963 Expected<std::vector<JITDylibSP>>
1964 JITDylib::getDFSLinkOrder(ArrayRef<JITDylibSP> JDs) {
1965   if (JDs.empty())
1966     return std::vector<JITDylibSP>();
1967 
1968   auto &ES = JDs.front()->getExecutionSession();
1969   return ES.runSessionLocked([&]() -> Expected<std::vector<JITDylibSP>> {
1970     DenseSet<JITDylib *> Visited;
1971     std::vector<JITDylibSP> Result;
1972 
1973     for (auto &JD : JDs) {
1974 
1975       if (JD->State != Open)
1976         return make_error<StringError>(
1977             "Error building link order: " + JD->getName() + " is defunct",
1978             inconvertibleErrorCode());
1979       if (Visited.count(JD.get()))
1980         continue;
1981 
1982       SmallVector<JITDylibSP, 64> WorkStack;
1983       WorkStack.push_back(JD);
1984       Visited.insert(JD.get());
1985 
1986       while (!WorkStack.empty()) {
1987         Result.push_back(std::move(WorkStack.back()));
1988         WorkStack.pop_back();
1989 
1990         for (auto &KV : llvm::reverse(Result.back()->LinkOrder)) {
1991           auto &JD = *KV.first;
1992           if (Visited.count(&JD))
1993             continue;
1994           Visited.insert(&JD);
1995           WorkStack.push_back(&JD);
1996         }
1997       }
1998     }
1999     return Result;
2000   });
2001 }
2002 
2003 Expected<std::vector<JITDylibSP>>
2004 JITDylib::getReverseDFSLinkOrder(ArrayRef<JITDylibSP> JDs) {
2005   auto Result = getDFSLinkOrder(JDs);
2006   if (Result)
2007     std::reverse(Result->begin(), Result->end());
2008   return Result;
2009 }
2010 
2011 Expected<std::vector<JITDylibSP>> JITDylib::getDFSLinkOrder() {
2012   return getDFSLinkOrder({this});
2013 }
2014 
2015 Expected<std::vector<JITDylibSP>> JITDylib::getReverseDFSLinkOrder() {
2016   return getReverseDFSLinkOrder({this});
2017 }
2018 
2019 void ExecutionSession::lookupFlags(
2020     LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet,
2021     unique_function<void(Expected<SymbolFlagsMap>)> OnComplete) {
2022 
2023   OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
2024                           K, std::move(SearchOrder), std::move(LookupSet),
2025                           std::move(OnComplete)),
2026                       Error::success());
2027 }
2028 
2029 Expected<SymbolFlagsMap>
2030 ExecutionSession::lookupFlags(LookupKind K, JITDylibSearchOrder SearchOrder,
2031                               SymbolLookupSet LookupSet) {
2032 
2033   std::promise<MSVCPExpected<SymbolFlagsMap>> ResultP;
2034   OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
2035                           K, std::move(SearchOrder), std::move(LookupSet),
2036                           [&ResultP](Expected<SymbolFlagsMap> Result) {
2037                             ResultP.set_value(std::move(Result));
2038                           }),
2039                       Error::success());
2040 
2041   auto ResultF = ResultP.get_future();
2042   return ResultF.get();
2043 }
2044 
2045 void ExecutionSession::lookup(
2046     LookupKind K, const JITDylibSearchOrder &SearchOrder,
2047     SymbolLookupSet Symbols, SymbolState RequiredState,
2048     SymbolsResolvedCallback NotifyComplete,
2049     RegisterDependenciesFunction RegisterDependencies) {
2050 
2051   LLVM_DEBUG({
2052     runSessionLocked([&]() {
2053       dbgs() << "Looking up " << Symbols << " in " << SearchOrder
2054              << " (required state: " << RequiredState << ")\n";
2055     });
2056   });
2057 
2058   // lookup can be re-entered recursively if running on a single thread. Run any
2059   // outstanding MUs in case this query depends on them, otherwise this lookup
2060   // will starve waiting for a result from an MU that is stuck in the queue.
2061   dispatchOutstandingMUs();
2062 
2063   auto Unresolved = std::move(Symbols);
2064   auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
2065                                                      std::move(NotifyComplete));
2066 
2067   auto IPLS = std::make_unique<InProgressFullLookupState>(
2068       K, SearchOrder, std::move(Unresolved), RequiredState, std::move(Q),
2069       std::move(RegisterDependencies));
2070 
2071   OL_applyQueryPhase1(std::move(IPLS), Error::success());
2072 }
2073 
2074 Expected<SymbolMap>
2075 ExecutionSession::lookup(const JITDylibSearchOrder &SearchOrder,
2076                          SymbolLookupSet Symbols, LookupKind K,
2077                          SymbolState RequiredState,
2078                          RegisterDependenciesFunction RegisterDependencies) {
2079 #if LLVM_ENABLE_THREADS
2080   // In the threaded case we use promises to return the results.
2081   std::promise<SymbolMap> PromisedResult;
2082   Error ResolutionError = Error::success();
2083 
2084   auto NotifyComplete = [&](Expected<SymbolMap> R) {
2085     if (R)
2086       PromisedResult.set_value(std::move(*R));
2087     else {
2088       ErrorAsOutParameter _(&ResolutionError);
2089       ResolutionError = R.takeError();
2090       PromisedResult.set_value(SymbolMap());
2091     }
2092   };
2093 
2094 #else
2095   SymbolMap Result;
2096   Error ResolutionError = Error::success();
2097 
2098   auto NotifyComplete = [&](Expected<SymbolMap> R) {
2099     ErrorAsOutParameter _(&ResolutionError);
2100     if (R)
2101       Result = std::move(*R);
2102     else
2103       ResolutionError = R.takeError();
2104   };
2105 #endif
2106 
2107   // Perform the asynchronous lookup.
2108   lookup(K, SearchOrder, std::move(Symbols), RequiredState, NotifyComplete,
2109          RegisterDependencies);
2110 
2111 #if LLVM_ENABLE_THREADS
2112   auto ResultFuture = PromisedResult.get_future();
2113   auto Result = ResultFuture.get();
2114 
2115   if (ResolutionError)
2116     return std::move(ResolutionError);
2117 
2118   return std::move(Result);
2119 
2120 #else
2121   if (ResolutionError)
2122     return std::move(ResolutionError);
2123 
2124   return Result;
2125 #endif
2126 }
2127 
2128 Expected<JITEvaluatedSymbol>
2129 ExecutionSession::lookup(const JITDylibSearchOrder &SearchOrder,
2130                          SymbolStringPtr Name, SymbolState RequiredState) {
2131   SymbolLookupSet Names({Name});
2132 
2133   if (auto ResultMap = lookup(SearchOrder, std::move(Names), LookupKind::Static,
2134                               RequiredState, NoDependenciesToRegister)) {
2135     assert(ResultMap->size() == 1 && "Unexpected number of results");
2136     assert(ResultMap->count(Name) && "Missing result for symbol");
2137     return std::move(ResultMap->begin()->second);
2138   } else
2139     return ResultMap.takeError();
2140 }
2141 
2142 Expected<JITEvaluatedSymbol>
2143 ExecutionSession::lookup(ArrayRef<JITDylib *> SearchOrder, SymbolStringPtr Name,
2144                          SymbolState RequiredState) {
2145   return lookup(makeJITDylibSearchOrder(SearchOrder), Name, RequiredState);
2146 }
2147 
2148 Expected<JITEvaluatedSymbol>
2149 ExecutionSession::lookup(ArrayRef<JITDylib *> SearchOrder, StringRef Name,
2150                          SymbolState RequiredState) {
2151   return lookup(SearchOrder, intern(Name), RequiredState);
2152 }
2153 
2154 Error ExecutionSession::registerJITDispatchHandlers(
2155     JITDylib &JD, JITDispatchHandlerAssociationMap WFs) {
2156 
2157   auto TagAddrs = lookup({{&JD, JITDylibLookupFlags::MatchAllSymbols}},
2158                          SymbolLookupSet::fromMapKeys(
2159                              WFs, SymbolLookupFlags::WeaklyReferencedSymbol));
2160   if (!TagAddrs)
2161     return TagAddrs.takeError();
2162 
2163   // Associate tag addresses with implementations.
2164   std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
2165   for (auto &KV : *TagAddrs) {
2166     auto TagAddr = KV.second.getAddress();
2167     if (JITDispatchHandlers.count(TagAddr))
2168       return make_error<StringError>("Tag " + formatv("{0:x16}", TagAddr) +
2169                                          " (for " + *KV.first +
2170                                          ") already registered",
2171                                      inconvertibleErrorCode());
2172     auto I = WFs.find(KV.first);
2173     assert(I != WFs.end() && I->second &&
2174            "JITDispatchHandler implementation missing");
2175     JITDispatchHandlers[KV.second.getAddress()] =
2176         std::make_shared<JITDispatchHandlerFunction>(std::move(I->second));
2177     LLVM_DEBUG({
2178       dbgs() << "Associated function tag \"" << *KV.first << "\" ("
2179              << formatv("{0:x}", KV.second.getAddress()) << ") with handler\n";
2180     });
2181   }
2182   return Error::success();
2183 }
2184 
2185 void ExecutionSession::runJITDispatchHandler(
2186     SendResultFunction SendResult, JITTargetAddress HandlerFnTagAddr,
2187     ArrayRef<char> ArgBuffer) {
2188 
2189   std::shared_ptr<JITDispatchHandlerFunction> F;
2190   {
2191     std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
2192     auto I = JITDispatchHandlers.find(HandlerFnTagAddr);
2193     if (I != JITDispatchHandlers.end())
2194       F = I->second;
2195   }
2196 
2197   if (F)
2198     (*F)(std::move(SendResult), ArgBuffer.data(), ArgBuffer.size());
2199   else
2200     SendResult(shared::WrapperFunctionResult::createOutOfBandError(
2201         ("No function registered for tag " +
2202          formatv("{0:x16}", HandlerFnTagAddr))
2203             .str()));
2204 }
2205 
2206 void ExecutionSession::dump(raw_ostream &OS) {
2207   runSessionLocked([this, &OS]() {
2208     for (auto &JD : JDs)
2209       JD->dump(OS);
2210   });
2211 }
2212 
2213 void ExecutionSession::dispatchOutstandingMUs() {
2214   LLVM_DEBUG(dbgs() << "Dispatching MaterializationUnits...\n");
2215   while (true) {
2216     Optional<std::pair<std::unique_ptr<MaterializationUnit>,
2217                        std::unique_ptr<MaterializationResponsibility>>>
2218         JMU;
2219 
2220     {
2221       std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2222       if (!OutstandingMUs.empty()) {
2223         JMU.emplace(std::move(OutstandingMUs.back()));
2224         OutstandingMUs.pop_back();
2225       }
2226     }
2227 
2228     if (!JMU)
2229       break;
2230 
2231     assert(JMU->first && "No MU?");
2232     LLVM_DEBUG(dbgs() << "  Dispatching \"" << JMU->first->getName() << "\"\n");
2233     dispatchTask(std::make_unique<MaterializationTask>(std::move(JMU->first),
2234                                                        std::move(JMU->second)));
2235   }
2236   LLVM_DEBUG(dbgs() << "Done dispatching MaterializationUnits.\n");
2237 }
2238 
2239 Error ExecutionSession::removeResourceTracker(ResourceTracker &RT) {
2240   LLVM_DEBUG({
2241     dbgs() << "In " << RT.getJITDylib().getName() << " removing tracker "
2242            << formatv("{0:x}", RT.getKeyUnsafe()) << "\n";
2243   });
2244   std::vector<ResourceManager *> CurrentResourceManagers;
2245 
2246   JITDylib::AsynchronousSymbolQuerySet QueriesToFail;
2247   std::shared_ptr<SymbolDependenceMap> FailedSymbols;
2248 
2249   runSessionLocked([&] {
2250     CurrentResourceManagers = ResourceManagers;
2251     RT.makeDefunct();
2252     std::tie(QueriesToFail, FailedSymbols) = RT.getJITDylib().removeTracker(RT);
2253   });
2254 
2255   Error Err = Error::success();
2256 
2257   for (auto *L : reverse(CurrentResourceManagers))
2258     Err =
2259         joinErrors(std::move(Err), L->handleRemoveResources(RT.getKeyUnsafe()));
2260 
2261   for (auto &Q : QueriesToFail)
2262     Q->handleFailed(make_error<FailedToMaterialize>(FailedSymbols));
2263 
2264   return Err;
2265 }
2266 
2267 void ExecutionSession::transferResourceTracker(ResourceTracker &DstRT,
2268                                                ResourceTracker &SrcRT) {
2269   LLVM_DEBUG({
2270     dbgs() << "In " << SrcRT.getJITDylib().getName()
2271            << " transfering resources from tracker "
2272            << formatv("{0:x}", SrcRT.getKeyUnsafe()) << " to tracker "
2273            << formatv("{0:x}", DstRT.getKeyUnsafe()) << "\n";
2274   });
2275 
2276   // No-op transfers are allowed and do not invalidate the source.
2277   if (&DstRT == &SrcRT)
2278     return;
2279 
2280   assert(&DstRT.getJITDylib() == &SrcRT.getJITDylib() &&
2281          "Can't transfer resources between JITDylibs");
2282   runSessionLocked([&]() {
2283     SrcRT.makeDefunct();
2284     auto &JD = DstRT.getJITDylib();
2285     JD.transferTracker(DstRT, SrcRT);
2286     for (auto *L : reverse(ResourceManagers))
2287       L->handleTransferResources(DstRT.getKeyUnsafe(), SrcRT.getKeyUnsafe());
2288   });
2289 }
2290 
2291 void ExecutionSession::destroyResourceTracker(ResourceTracker &RT) {
2292   runSessionLocked([&]() {
2293     LLVM_DEBUG({
2294       dbgs() << "In " << RT.getJITDylib().getName() << " destroying tracker "
2295              << formatv("{0:x}", RT.getKeyUnsafe()) << "\n";
2296     });
2297     if (!RT.isDefunct())
2298       transferResourceTracker(*RT.getJITDylib().getDefaultResourceTracker(),
2299                               RT);
2300   });
2301 }
2302 
2303 Error ExecutionSession::IL_updateCandidatesFor(
2304     JITDylib &JD, JITDylibLookupFlags JDLookupFlags,
2305     SymbolLookupSet &Candidates, SymbolLookupSet *NonCandidates) {
2306   return Candidates.forEachWithRemoval(
2307       [&](const SymbolStringPtr &Name,
2308           SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
2309         /// Search for the symbol. If not found then continue without
2310         /// removal.
2311         auto SymI = JD.Symbols.find(Name);
2312         if (SymI == JD.Symbols.end())
2313           return false;
2314 
2315         // If this is a non-exported symbol and we're matching exported
2316         // symbols only then remove this symbol from the candidates list.
2317         //
2318         // If we're tracking non-candidates then add this to the non-candidate
2319         // list.
2320         if (!SymI->second.getFlags().isExported() &&
2321             JDLookupFlags == JITDylibLookupFlags::MatchExportedSymbolsOnly) {
2322           if (NonCandidates)
2323             NonCandidates->add(Name, SymLookupFlags);
2324           return true;
2325         }
2326 
2327         // If we match against a materialization-side-effects only symbol
2328         // then make sure it is weakly-referenced. Otherwise bail out with
2329         // an error.
2330         // FIXME: Use a "materialization-side-effects-only symbols must be
2331         // weakly referenced" specific error here to reduce confusion.
2332         if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2333             SymLookupFlags != SymbolLookupFlags::WeaklyReferencedSymbol)
2334           return make_error<SymbolsNotFound>(getSymbolStringPool(),
2335                                              SymbolNameVector({Name}));
2336 
2337         // If we matched against this symbol but it is in the error state
2338         // then bail out and treat it as a failure to materialize.
2339         if (SymI->second.getFlags().hasError()) {
2340           auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2341           (*FailedSymbolsMap)[&JD] = {Name};
2342           return make_error<FailedToMaterialize>(std::move(FailedSymbolsMap));
2343         }
2344 
2345         // Otherwise this is a match. Remove it from the candidate set.
2346         return true;
2347       });
2348 }
2349 
2350 void ExecutionSession::OL_applyQueryPhase1(
2351     std::unique_ptr<InProgressLookupState> IPLS, Error Err) {
2352 
2353   LLVM_DEBUG({
2354     dbgs() << "Entering OL_applyQueryPhase1:\n"
2355            << "  Lookup kind: " << IPLS->K << "\n"
2356            << "  Search order: " << IPLS->SearchOrder
2357            << ", Current index = " << IPLS->CurSearchOrderIndex
2358            << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2359            << "  Lookup set: " << IPLS->LookupSet << "\n"
2360            << "  Definition generator candidates: "
2361            << IPLS->DefGeneratorCandidates << "\n"
2362            << "  Definition generator non-candidates: "
2363            << IPLS->DefGeneratorNonCandidates << "\n";
2364   });
2365 
2366   // FIXME: We should attach the query as we go: This provides a result in a
2367   // single pass in the common case where all symbols have already reached the
2368   // required state. The query could be detached again in the 'fail' method on
2369   // IPLS. Phase 2 would be reduced to collecting and dispatching the MUs.
2370 
2371   while (IPLS->CurSearchOrderIndex != IPLS->SearchOrder.size()) {
2372 
2373     // If we've been handed an error or received one back from a generator then
2374     // fail the query. We don't need to unlink: At this stage the query hasn't
2375     // actually been lodged.
2376     if (Err)
2377       return IPLS->fail(std::move(Err));
2378 
2379     // Get the next JITDylib and lookup flags.
2380     auto &KV = IPLS->SearchOrder[IPLS->CurSearchOrderIndex];
2381     auto &JD = *KV.first;
2382     auto JDLookupFlags = KV.second;
2383 
2384     LLVM_DEBUG({
2385       dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2386              << ") with lookup set " << IPLS->LookupSet << ":\n";
2387     });
2388 
2389     // If we've just reached a new JITDylib then perform some setup.
2390     if (IPLS->NewJITDylib) {
2391 
2392       // Acquire the generator lock for this JITDylib.
2393       IPLS->GeneratorLock = std::unique_lock<std::mutex>(JD.GeneratorsMutex);
2394 
2395       // Add any non-candidates from the last JITDylib (if any) back on to the
2396       // list of definition candidates for this JITDylib, reset definition
2397       // non-candiates to the empty set.
2398       SymbolLookupSet Tmp;
2399       std::swap(IPLS->DefGeneratorNonCandidates, Tmp);
2400       IPLS->DefGeneratorCandidates.append(std::move(Tmp));
2401 
2402       LLVM_DEBUG({
2403         dbgs() << "  First time visiting " << JD.getName()
2404                << ", resetting candidate sets and building generator stack\n";
2405       });
2406 
2407       // Build the definition generator stack for this JITDylib.
2408       runSessionLocked([&] {
2409         IPLS->CurDefGeneratorStack.reserve(JD.DefGenerators.size());
2410         for (auto &DG : reverse(JD.DefGenerators))
2411           IPLS->CurDefGeneratorStack.push_back(DG);
2412       });
2413 
2414       // Flag that we've done our initialization.
2415       IPLS->NewJITDylib = false;
2416     }
2417 
2418     // Remove any generation candidates that are already defined (and match) in
2419     // this JITDylib.
2420     runSessionLocked([&] {
2421       // Update the list of candidates (and non-candidates) for definition
2422       // generation.
2423       LLVM_DEBUG(dbgs() << "  Updating candidate set...\n");
2424       Err = IL_updateCandidatesFor(
2425           JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2426           JD.DefGenerators.empty() ? nullptr
2427                                    : &IPLS->DefGeneratorNonCandidates);
2428       LLVM_DEBUG({
2429         dbgs() << "    Remaining candidates = " << IPLS->DefGeneratorCandidates
2430                << "\n";
2431       });
2432     });
2433 
2434     // If we encountered an error while filtering generation candidates then
2435     // bail out.
2436     if (Err)
2437       return IPLS->fail(std::move(Err));
2438 
2439     /// Apply any definition generators on the stack.
2440     LLVM_DEBUG({
2441       if (IPLS->CurDefGeneratorStack.empty())
2442         LLVM_DEBUG(dbgs() << "  No generators to run for this JITDylib.\n");
2443       else if (IPLS->DefGeneratorCandidates.empty())
2444         LLVM_DEBUG(dbgs() << "  No candidates to generate.\n");
2445       else
2446         dbgs() << "  Running " << IPLS->CurDefGeneratorStack.size()
2447                << " remaining generators for "
2448                << IPLS->DefGeneratorCandidates.size() << " candidates\n";
2449     });
2450     while (!IPLS->CurDefGeneratorStack.empty() &&
2451            !IPLS->DefGeneratorCandidates.empty()) {
2452       auto DG = IPLS->CurDefGeneratorStack.back().lock();
2453       IPLS->CurDefGeneratorStack.pop_back();
2454 
2455       if (!DG)
2456         return IPLS->fail(make_error<StringError>(
2457             "DefinitionGenerator removed while lookup in progress",
2458             inconvertibleErrorCode()));
2459 
2460       auto K = IPLS->K;
2461       auto &LookupSet = IPLS->DefGeneratorCandidates;
2462 
2463       // Run the generator. If the generator takes ownership of QA then this
2464       // will break the loop.
2465       {
2466         LLVM_DEBUG(dbgs() << "  Attempting to generate " << LookupSet << "\n");
2467         LookupState LS(std::move(IPLS));
2468         Err = DG->tryToGenerate(LS, K, JD, JDLookupFlags, LookupSet);
2469         IPLS = std::move(LS.IPLS);
2470       }
2471 
2472       // If there was an error then fail the query.
2473       if (Err) {
2474         LLVM_DEBUG({
2475           dbgs() << "  Error attempting to generate " << LookupSet << "\n";
2476         });
2477         assert(IPLS && "LS cannot be retained if error is returned");
2478         return IPLS->fail(std::move(Err));
2479       }
2480 
2481       // Otherwise if QA was captured then break the loop.
2482       if (!IPLS) {
2483         LLVM_DEBUG(
2484             { dbgs() << "  LookupState captured. Exiting phase1 for now.\n"; });
2485         return;
2486       }
2487 
2488       // Otherwise if we're continuing around the loop then update candidates
2489       // for the next round.
2490       runSessionLocked([&] {
2491         LLVM_DEBUG(dbgs() << "  Updating candidate set post-generation\n");
2492         Err = IL_updateCandidatesFor(
2493             JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2494             JD.DefGenerators.empty() ? nullptr
2495                                      : &IPLS->DefGeneratorNonCandidates);
2496       });
2497 
2498       // If updating candidates failed then fail the query.
2499       if (Err) {
2500         LLVM_DEBUG(dbgs() << "  Error encountered while updating candidates\n");
2501         return IPLS->fail(std::move(Err));
2502       }
2503     }
2504 
2505     if (IPLS->DefGeneratorCandidates.empty() &&
2506         IPLS->DefGeneratorNonCandidates.empty()) {
2507       // Early out if there are no remaining symbols.
2508       LLVM_DEBUG(dbgs() << "All symbols matched.\n");
2509       IPLS->CurSearchOrderIndex = IPLS->SearchOrder.size();
2510       break;
2511     } else {
2512       // If we get here then we've moved on to the next JITDylib with candidates
2513       // remaining.
2514       LLVM_DEBUG(dbgs() << "Phase 1 moving to next JITDylib.\n");
2515       ++IPLS->CurSearchOrderIndex;
2516       IPLS->NewJITDylib = true;
2517     }
2518   }
2519 
2520   // Remove any weakly referenced candidates that could not be found/generated.
2521   IPLS->DefGeneratorCandidates.remove_if(
2522       [](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2523         return SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol;
2524       });
2525 
2526   // If we get here then we've finished searching all JITDylibs.
2527   // If we matched all symbols then move to phase 2, otherwise fail the query
2528   // with a SymbolsNotFound error.
2529   if (IPLS->DefGeneratorCandidates.empty()) {
2530     LLVM_DEBUG(dbgs() << "Phase 1 succeeded.\n");
2531     IPLS->complete(std::move(IPLS));
2532   } else {
2533     LLVM_DEBUG(dbgs() << "Phase 1 failed with unresolved symbols.\n");
2534     IPLS->fail(make_error<SymbolsNotFound>(
2535         getSymbolStringPool(), IPLS->DefGeneratorCandidates.getSymbolNames()));
2536   }
2537 }
2538 
2539 void ExecutionSession::OL_completeLookup(
2540     std::unique_ptr<InProgressLookupState> IPLS,
2541     std::shared_ptr<AsynchronousSymbolQuery> Q,
2542     RegisterDependenciesFunction RegisterDependencies) {
2543 
2544   LLVM_DEBUG({
2545     dbgs() << "Entering OL_completeLookup:\n"
2546            << "  Lookup kind: " << IPLS->K << "\n"
2547            << "  Search order: " << IPLS->SearchOrder
2548            << ", Current index = " << IPLS->CurSearchOrderIndex
2549            << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2550            << "  Lookup set: " << IPLS->LookupSet << "\n"
2551            << "  Definition generator candidates: "
2552            << IPLS->DefGeneratorCandidates << "\n"
2553            << "  Definition generator non-candidates: "
2554            << IPLS->DefGeneratorNonCandidates << "\n";
2555   });
2556 
2557   bool QueryComplete = false;
2558   DenseMap<JITDylib *, JITDylib::UnmaterializedInfosList> CollectedUMIs;
2559 
2560   auto LodgingErr = runSessionLocked([&]() -> Error {
2561     for (auto &KV : IPLS->SearchOrder) {
2562       auto &JD = *KV.first;
2563       auto JDLookupFlags = KV.second;
2564       LLVM_DEBUG({
2565         dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2566                << ") with lookup set " << IPLS->LookupSet << ":\n";
2567       });
2568 
2569       auto Err = IPLS->LookupSet.forEachWithRemoval(
2570           [&](const SymbolStringPtr &Name,
2571               SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
2572             LLVM_DEBUG({
2573               dbgs() << "  Attempting to match \"" << Name << "\" ("
2574                      << SymLookupFlags << ")... ";
2575             });
2576 
2577             /// Search for the symbol. If not found then continue without
2578             /// removal.
2579             auto SymI = JD.Symbols.find(Name);
2580             if (SymI == JD.Symbols.end()) {
2581               LLVM_DEBUG(dbgs() << "skipping: not present\n");
2582               return false;
2583             }
2584 
2585             // If this is a non-exported symbol and we're matching exported
2586             // symbols only then skip this symbol without removal.
2587             if (!SymI->second.getFlags().isExported() &&
2588                 JDLookupFlags ==
2589                     JITDylibLookupFlags::MatchExportedSymbolsOnly) {
2590               LLVM_DEBUG(dbgs() << "skipping: not exported\n");
2591               return false;
2592             }
2593 
2594             // If we match against a materialization-side-effects only symbol
2595             // then make sure it is weakly-referenced. Otherwise bail out with
2596             // an error.
2597             // FIXME: Use a "materialization-side-effects-only symbols must be
2598             // weakly referenced" specific error here to reduce confusion.
2599             if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2600                 SymLookupFlags != SymbolLookupFlags::WeaklyReferencedSymbol) {
2601               LLVM_DEBUG({
2602                 dbgs() << "error: "
2603                           "required, but symbol is has-side-effects-only\n";
2604               });
2605               return make_error<SymbolsNotFound>(getSymbolStringPool(),
2606                                                  SymbolNameVector({Name}));
2607             }
2608 
2609             // If we matched against this symbol but it is in the error state
2610             // then bail out and treat it as a failure to materialize.
2611             if (SymI->second.getFlags().hasError()) {
2612               LLVM_DEBUG(dbgs() << "error: symbol is in error state\n");
2613               auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2614               (*FailedSymbolsMap)[&JD] = {Name};
2615               return make_error<FailedToMaterialize>(
2616                   std::move(FailedSymbolsMap));
2617             }
2618 
2619             // Otherwise this is a match.
2620 
2621             // If this symbol is already in the requried state then notify the
2622             // query, remove the symbol and continue.
2623             if (SymI->second.getState() >= Q->getRequiredState()) {
2624               LLVM_DEBUG(dbgs()
2625                          << "matched, symbol already in required state\n");
2626               Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
2627               return true;
2628             }
2629 
2630             // Otherwise this symbol does not yet meet the required state. Check
2631             // whether it has a materializer attached, and if so prepare to run
2632             // it.
2633             if (SymI->second.hasMaterializerAttached()) {
2634               assert(SymI->second.getAddress() == 0 &&
2635                      "Symbol not resolved but already has address?");
2636               auto UMII = JD.UnmaterializedInfos.find(Name);
2637               assert(UMII != JD.UnmaterializedInfos.end() &&
2638                      "Lazy symbol should have UnmaterializedInfo");
2639 
2640               auto UMI = UMII->second;
2641               assert(UMI->MU && "Materializer should not be null");
2642               assert(UMI->RT && "Tracker should not be null");
2643               LLVM_DEBUG({
2644                 dbgs() << "matched, preparing to dispatch MU@" << UMI->MU.get()
2645                        << " (" << UMI->MU->getName() << ")\n";
2646               });
2647 
2648               // Move all symbols associated with this MaterializationUnit into
2649               // materializing state.
2650               for (auto &KV : UMI->MU->getSymbols()) {
2651                 auto SymK = JD.Symbols.find(KV.first);
2652                 assert(SymK != JD.Symbols.end() &&
2653                        "No entry for symbol covered by MaterializationUnit");
2654                 SymK->second.setMaterializerAttached(false);
2655                 SymK->second.setState(SymbolState::Materializing);
2656                 JD.UnmaterializedInfos.erase(KV.first);
2657               }
2658 
2659               // Add MU to the list of MaterializationUnits to be materialized.
2660               CollectedUMIs[&JD].push_back(std::move(UMI));
2661             } else
2662               LLVM_DEBUG(dbgs() << "matched, registering query");
2663 
2664             // Add the query to the PendingQueries list and continue, deleting
2665             // the element from the lookup set.
2666             assert(SymI->second.getState() != SymbolState::NeverSearched &&
2667                    SymI->second.getState() != SymbolState::Ready &&
2668                    "By this line the symbol should be materializing");
2669             auto &MI = JD.MaterializingInfos[Name];
2670             MI.addQuery(Q);
2671             Q->addQueryDependence(JD, Name);
2672 
2673             return true;
2674           });
2675 
2676       // Handle failure.
2677       if (Err) {
2678 
2679         LLVM_DEBUG({
2680           dbgs() << "Lookup failed. Detaching query and replacing MUs.\n";
2681         });
2682 
2683         // Detach the query.
2684         Q->detach();
2685 
2686         // Replace the MUs.
2687         for (auto &KV : CollectedUMIs) {
2688           auto &JD = *KV.first;
2689           for (auto &UMI : KV.second)
2690             for (auto &KV2 : UMI->MU->getSymbols()) {
2691               assert(!JD.UnmaterializedInfos.count(KV2.first) &&
2692                      "Unexpected materializer in map");
2693               auto SymI = JD.Symbols.find(KV2.first);
2694               assert(SymI != JD.Symbols.end() && "Missing symbol entry");
2695               assert(SymI->second.getState() == SymbolState::Materializing &&
2696                      "Can not replace symbol that is not materializing");
2697               assert(!SymI->second.hasMaterializerAttached() &&
2698                      "MaterializerAttached flag should not be set");
2699               SymI->second.setMaterializerAttached(true);
2700               JD.UnmaterializedInfos[KV2.first] = UMI;
2701             }
2702         }
2703 
2704         return Err;
2705       }
2706     }
2707 
2708     LLVM_DEBUG(dbgs() << "Stripping unmatched weakly-referenced symbols\n");
2709     IPLS->LookupSet.forEachWithRemoval(
2710         [&](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2711           if (SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol) {
2712             Q->dropSymbol(Name);
2713             return true;
2714           } else
2715             return false;
2716         });
2717 
2718     if (!IPLS->LookupSet.empty()) {
2719       LLVM_DEBUG(dbgs() << "Failing due to unresolved symbols\n");
2720       return make_error<SymbolsNotFound>(getSymbolStringPool(),
2721                                          IPLS->LookupSet.getSymbolNames());
2722     }
2723 
2724     // Record whether the query completed.
2725     QueryComplete = Q->isComplete();
2726 
2727     LLVM_DEBUG({
2728       dbgs() << "Query successfully "
2729              << (QueryComplete ? "completed" : "lodged") << "\n";
2730     });
2731 
2732     // Move the collected MUs to the OutstandingMUs list.
2733     if (!CollectedUMIs.empty()) {
2734       std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2735 
2736       LLVM_DEBUG(dbgs() << "Adding MUs to dispatch:\n");
2737       for (auto &KV : CollectedUMIs) {
2738         LLVM_DEBUG({
2739           auto &JD = *KV.first;
2740           dbgs() << "  For " << JD.getName() << ": Adding " << KV.second.size()
2741                  << " MUs.\n";
2742         });
2743         for (auto &UMI : KV.second) {
2744           auto MR = createMaterializationResponsibility(
2745               *UMI->RT, std::move(UMI->MU->SymbolFlags),
2746               std::move(UMI->MU->InitSymbol));
2747           OutstandingMUs.push_back(
2748               std::make_pair(std::move(UMI->MU), std::move(MR)));
2749         }
2750       }
2751     } else
2752       LLVM_DEBUG(dbgs() << "No MUs to dispatch.\n");
2753 
2754     if (RegisterDependencies && !Q->QueryRegistrations.empty()) {
2755       LLVM_DEBUG(dbgs() << "Registering dependencies\n");
2756       RegisterDependencies(Q->QueryRegistrations);
2757     } else
2758       LLVM_DEBUG(dbgs() << "No dependencies to register\n");
2759 
2760     return Error::success();
2761   });
2762 
2763   if (LodgingErr) {
2764     LLVM_DEBUG(dbgs() << "Failing query\n");
2765     Q->detach();
2766     Q->handleFailed(std::move(LodgingErr));
2767     return;
2768   }
2769 
2770   if (QueryComplete) {
2771     LLVM_DEBUG(dbgs() << "Completing query\n");
2772     Q->handleComplete(*this);
2773   }
2774 
2775   dispatchOutstandingMUs();
2776 }
2777 
2778 void ExecutionSession::OL_completeLookupFlags(
2779     std::unique_ptr<InProgressLookupState> IPLS,
2780     unique_function<void(Expected<SymbolFlagsMap>)> OnComplete) {
2781 
2782   auto Result = runSessionLocked([&]() -> Expected<SymbolFlagsMap> {
2783     LLVM_DEBUG({
2784       dbgs() << "Entering OL_completeLookupFlags:\n"
2785              << "  Lookup kind: " << IPLS->K << "\n"
2786              << "  Search order: " << IPLS->SearchOrder
2787              << ", Current index = " << IPLS->CurSearchOrderIndex
2788              << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2789              << "  Lookup set: " << IPLS->LookupSet << "\n"
2790              << "  Definition generator candidates: "
2791              << IPLS->DefGeneratorCandidates << "\n"
2792              << "  Definition generator non-candidates: "
2793              << IPLS->DefGeneratorNonCandidates << "\n";
2794     });
2795 
2796     SymbolFlagsMap Result;
2797 
2798     // Attempt to find flags for each symbol.
2799     for (auto &KV : IPLS->SearchOrder) {
2800       auto &JD = *KV.first;
2801       auto JDLookupFlags = KV.second;
2802       LLVM_DEBUG({
2803         dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2804                << ") with lookup set " << IPLS->LookupSet << ":\n";
2805       });
2806 
2807       IPLS->LookupSet.forEachWithRemoval([&](const SymbolStringPtr &Name,
2808                                              SymbolLookupFlags SymLookupFlags) {
2809         LLVM_DEBUG({
2810           dbgs() << "  Attempting to match \"" << Name << "\" ("
2811                  << SymLookupFlags << ")... ";
2812         });
2813 
2814         // Search for the symbol. If not found then continue without removing
2815         // from the lookup set.
2816         auto SymI = JD.Symbols.find(Name);
2817         if (SymI == JD.Symbols.end()) {
2818           LLVM_DEBUG(dbgs() << "skipping: not present\n");
2819           return false;
2820         }
2821 
2822         // If this is a non-exported symbol then it doesn't match. Skip it.
2823         if (!SymI->second.getFlags().isExported() &&
2824             JDLookupFlags == JITDylibLookupFlags::MatchExportedSymbolsOnly) {
2825           LLVM_DEBUG(dbgs() << "skipping: not exported\n");
2826           return false;
2827         }
2828 
2829         LLVM_DEBUG({
2830           dbgs() << "matched, \"" << Name << "\" -> " << SymI->second.getFlags()
2831                  << "\n";
2832         });
2833         Result[Name] = SymI->second.getFlags();
2834         return true;
2835       });
2836     }
2837 
2838     // Remove any weakly referenced symbols that haven't been resolved.
2839     IPLS->LookupSet.remove_if(
2840         [](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2841           return SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol;
2842         });
2843 
2844     if (!IPLS->LookupSet.empty()) {
2845       LLVM_DEBUG(dbgs() << "Failing due to unresolved symbols\n");
2846       return make_error<SymbolsNotFound>(getSymbolStringPool(),
2847                                          IPLS->LookupSet.getSymbolNames());
2848     }
2849 
2850     LLVM_DEBUG(dbgs() << "Succeded, result = " << Result << "\n");
2851     return Result;
2852   });
2853 
2854   // Run the callback on the result.
2855   LLVM_DEBUG(dbgs() << "Sending result to handler.\n");
2856   OnComplete(std::move(Result));
2857 }
2858 
2859 void ExecutionSession::OL_destroyMaterializationResponsibility(
2860     MaterializationResponsibility &MR) {
2861 
2862   assert(MR.SymbolFlags.empty() &&
2863          "All symbols should have been explicitly materialized or failed");
2864   MR.JD.unlinkMaterializationResponsibility(MR);
2865 }
2866 
2867 SymbolNameSet ExecutionSession::OL_getRequestedSymbols(
2868     const MaterializationResponsibility &MR) {
2869   return MR.JD.getRequestedSymbols(MR.SymbolFlags);
2870 }
2871 
2872 Error ExecutionSession::OL_notifyResolved(MaterializationResponsibility &MR,
2873                                           const SymbolMap &Symbols) {
2874   LLVM_DEBUG({
2875     dbgs() << "In " << MR.JD.getName() << " resolving " << Symbols << "\n";
2876   });
2877 #ifndef NDEBUG
2878   for (auto &KV : Symbols) {
2879     auto WeakFlags = JITSymbolFlags::Weak | JITSymbolFlags::Common;
2880     auto I = MR.SymbolFlags.find(KV.first);
2881     assert(I != MR.SymbolFlags.end() &&
2882            "Resolving symbol outside this responsibility set");
2883     assert(!I->second.hasMaterializationSideEffectsOnly() &&
2884            "Can't resolve materialization-side-effects-only symbol");
2885     assert((KV.second.getFlags() & ~WeakFlags) == (I->second & ~WeakFlags) &&
2886            "Resolving symbol with incorrect flags");
2887   }
2888 #endif
2889 
2890   return MR.JD.resolve(MR, Symbols);
2891 }
2892 
2893 Error ExecutionSession::OL_notifyEmitted(MaterializationResponsibility &MR) {
2894   LLVM_DEBUG({
2895     dbgs() << "In " << MR.JD.getName() << " emitting " << MR.SymbolFlags
2896            << "\n";
2897   });
2898 
2899   if (auto Err = MR.JD.emit(MR, MR.SymbolFlags))
2900     return Err;
2901 
2902   MR.SymbolFlags.clear();
2903   return Error::success();
2904 }
2905 
2906 Error ExecutionSession::OL_defineMaterializing(
2907     MaterializationResponsibility &MR, SymbolFlagsMap NewSymbolFlags) {
2908 
2909   LLVM_DEBUG({
2910     dbgs() << "In " << MR.JD.getName() << " defining materializing symbols "
2911            << NewSymbolFlags << "\n";
2912   });
2913   if (auto AcceptedDefs =
2914           MR.JD.defineMaterializing(std::move(NewSymbolFlags))) {
2915     // Add all newly accepted symbols to this responsibility object.
2916     for (auto &KV : *AcceptedDefs)
2917       MR.SymbolFlags.insert(KV);
2918     return Error::success();
2919   } else
2920     return AcceptedDefs.takeError();
2921 }
2922 
2923 void ExecutionSession::OL_notifyFailed(MaterializationResponsibility &MR) {
2924 
2925   LLVM_DEBUG({
2926     dbgs() << "In " << MR.JD.getName() << " failing materialization for "
2927            << MR.SymbolFlags << "\n";
2928   });
2929 
2930   JITDylib::FailedSymbolsWorklist Worklist;
2931 
2932   for (auto &KV : MR.SymbolFlags)
2933     Worklist.push_back(std::make_pair(&MR.JD, KV.first));
2934   MR.SymbolFlags.clear();
2935 
2936   if (Worklist.empty())
2937     return;
2938 
2939   JITDylib::AsynchronousSymbolQuerySet FailedQueries;
2940   std::shared_ptr<SymbolDependenceMap> FailedSymbols;
2941 
2942   runSessionLocked([&]() {
2943     // If the tracker is defunct then there's nothing to do here.
2944     if (MR.RT->isDefunct())
2945       return;
2946 
2947     std::tie(FailedQueries, FailedSymbols) =
2948         JITDylib::failSymbols(std::move(Worklist));
2949   });
2950 
2951   for (auto &Q : FailedQueries)
2952     Q->handleFailed(make_error<FailedToMaterialize>(FailedSymbols));
2953 }
2954 
2955 Error ExecutionSession::OL_replace(MaterializationResponsibility &MR,
2956                                    std::unique_ptr<MaterializationUnit> MU) {
2957   for (auto &KV : MU->getSymbols()) {
2958     assert(MR.SymbolFlags.count(KV.first) &&
2959            "Replacing definition outside this responsibility set");
2960     MR.SymbolFlags.erase(KV.first);
2961   }
2962 
2963   if (MU->getInitializerSymbol() == MR.InitSymbol)
2964     MR.InitSymbol = nullptr;
2965 
2966   LLVM_DEBUG(MR.JD.getExecutionSession().runSessionLocked([&]() {
2967     dbgs() << "In " << MR.JD.getName() << " replacing symbols with " << *MU
2968            << "\n";
2969   }););
2970 
2971   return MR.JD.replace(MR, std::move(MU));
2972 }
2973 
2974 Expected<std::unique_ptr<MaterializationResponsibility>>
2975 ExecutionSession::OL_delegate(MaterializationResponsibility &MR,
2976                               const SymbolNameSet &Symbols) {
2977 
2978   SymbolStringPtr DelegatedInitSymbol;
2979   SymbolFlagsMap DelegatedFlags;
2980 
2981   for (auto &Name : Symbols) {
2982     auto I = MR.SymbolFlags.find(Name);
2983     assert(I != MR.SymbolFlags.end() &&
2984            "Symbol is not tracked by this MaterializationResponsibility "
2985            "instance");
2986 
2987     DelegatedFlags[Name] = std::move(I->second);
2988     if (Name == MR.InitSymbol)
2989       std::swap(MR.InitSymbol, DelegatedInitSymbol);
2990 
2991     MR.SymbolFlags.erase(I);
2992   }
2993 
2994   return MR.JD.delegate(MR, std::move(DelegatedFlags),
2995                         std::move(DelegatedInitSymbol));
2996 }
2997 
2998 void ExecutionSession::OL_addDependencies(
2999     MaterializationResponsibility &MR, const SymbolStringPtr &Name,
3000     const SymbolDependenceMap &Dependencies) {
3001   LLVM_DEBUG({
3002     dbgs() << "Adding dependencies for " << Name << ": " << Dependencies
3003            << "\n";
3004   });
3005   assert(MR.SymbolFlags.count(Name) &&
3006          "Symbol not covered by this MaterializationResponsibility instance");
3007   MR.JD.addDependencies(Name, Dependencies);
3008 }
3009 
3010 void ExecutionSession::OL_addDependenciesForAll(
3011     MaterializationResponsibility &MR,
3012     const SymbolDependenceMap &Dependencies) {
3013   LLVM_DEBUG({
3014     dbgs() << "Adding dependencies for all symbols in " << MR.SymbolFlags << ": "
3015            << Dependencies << "\n";
3016   });
3017   for (auto &KV : MR.SymbolFlags)
3018     MR.JD.addDependencies(KV.first, Dependencies);
3019 }
3020 
3021 #ifndef NDEBUG
3022 void ExecutionSession::dumpDispatchInfo(Task &T) {
3023   runSessionLocked([&]() {
3024     dbgs() << "Dispatching: ";
3025     T.printDescription(dbgs());
3026     dbgs() << "\n";
3027   });
3028 }
3029 #endif // NDEBUG
3030 
3031 } // End namespace orc.
3032 } // End namespace llvm.
3033