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