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