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