LLVM 21.0.0git
Core.cpp
Go to the documentation of this file.
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
10
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/Config/llvm-config.h"
18
19#include <condition_variable>
20#include <future>
21#include <optional>
22
23#define DEBUG_TYPE "orc"
24
25namespace llvm {
26namespace orc {
27
30char SymbolsNotFound::ID = 0;
36char LookupTask::ID = 0;
37
40
41void MaterializationUnit::anchor() {}
42
44 assert((reinterpret_cast<uintptr_t>(JD.get()) & 0x1) == 0 &&
45 "JITDylib must be two byte aligned");
46 JD->Retain();
47 JDAndFlag.store(reinterpret_cast<uintptr_t>(JD.get()));
48}
49
51 getJITDylib().getExecutionSession().destroyResourceTracker(*this);
53}
54
56 return getJITDylib().getExecutionSession().removeResourceTracker(*this);
57}
58
60 getJITDylib().getExecutionSession().transferResourceTracker(DstRT, *this);
61}
62
63void ResourceTracker::makeDefunct() {
64 uintptr_t Val = JDAndFlag.load();
65 Val |= 0x1U;
66 JDAndFlag.store(Val);
67}
68
70
72 : RT(std::move(RT)) {}
73
76}
77
79 OS << "Resource tracker " << (void *)RT.get() << " became defunct";
80}
81
83 std::shared_ptr<SymbolStringPool> SSP,
84 std::shared_ptr<SymbolDependenceMap> Symbols)
85 : SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
86 assert(this->SSP && "String pool cannot be null");
87 assert(!this->Symbols->empty() && "Can not fail to resolve an empty set");
88
89 // FIXME: Use a new dep-map type for FailedToMaterialize errors so that we
90 // don't have to manually retain/release.
91 for (auto &[JD, Syms] : *this->Symbols)
92 JD->Retain();
93}
94
96 for (auto &[JD, Syms] : *Symbols)
97 JD->Release();
98}
99
102}
103
105 OS << "Failed to materialize symbols: " << *Symbols;
106}
107
109 std::shared_ptr<SymbolStringPool> SSP, JITDylibSP JD,
110 SymbolNameSet FailedSymbols, SymbolDependenceMap BadDeps,
111 std::string Explanation)
112 : SSP(std::move(SSP)), JD(std::move(JD)),
113 FailedSymbols(std::move(FailedSymbols)), BadDeps(std::move(BadDeps)),
114 Explanation(std::move(Explanation)) {}
115
118}
119
121 OS << "In " << JD->getName() << ", failed to materialize " << FailedSymbols
122 << ", due to unsatisfied dependencies " << BadDeps;
123 if (!Explanation.empty())
124 OS << " (" << Explanation << ")";
125}
126
127SymbolsNotFound::SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
128 SymbolNameSet Symbols)
129 : SSP(std::move(SSP)) {
130 for (auto &Sym : Symbols)
131 this->Symbols.push_back(Sym);
132 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
133}
134
135SymbolsNotFound::SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
136 SymbolNameVector Symbols)
137 : SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
138 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
139}
140
141std::error_code SymbolsNotFound::convertToErrorCode() const {
143}
144
146 OS << "Symbols not found: " << Symbols;
147}
148
150 std::shared_ptr<SymbolStringPool> SSP, SymbolNameSet Symbols)
151 : SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
152 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
153}
154
157}
158
160 OS << "Symbols could not be removed: " << Symbols;
161}
162
165}
166
168 OS << "Missing definitions in module " << ModuleName
169 << ": " << Symbols;
170}
171
174}
175
177 OS << "Unexpected definitions in module " << ModuleName
178 << ": " << Symbols;
179}
180
182 JD->getExecutionSession().lookup(
185 [OnComplete = std::move(OnComplete)
186#ifndef NDEBUG
187 ,
188 Name = this->Name // Captured for the assert below only.
189#endif // NDEBUG
190 ](Expected<SymbolMap> Result) mutable {
191 if (Result) {
192 assert(Result->size() == 1 && "Unexpected number of results");
193 assert(Result->count(Name) &&
194 "Result does not contain expected symbol");
195 OnComplete(Result->begin()->second);
196 } else
197 OnComplete(Result.takeError());
198 },
200}
201
203 const SymbolLookupSet &Symbols, SymbolState RequiredState,
204 SymbolsResolvedCallback NotifyComplete)
205 : NotifyComplete(std::move(NotifyComplete)), RequiredState(RequiredState) {
206 assert(RequiredState >= SymbolState::Resolved &&
207 "Cannot query for a symbols that have not reached the resolve state "
208 "yet");
209
210 OutstandingSymbolsCount = Symbols.size();
211
212 for (auto &[Name, Flags] : Symbols)
213 ResolvedSymbols[Name] = ExecutorSymbolDef();
214}
215
218 auto I = ResolvedSymbols.find(Name);
219 assert(I != ResolvedSymbols.end() &&
220 "Resolving symbol outside the requested set");
221 assert(I->second == ExecutorSymbolDef() &&
222 "Redundantly resolving symbol Name");
223
224 // If this is a materialization-side-effects-only symbol then drop it,
225 // otherwise update its map entry with its resolved address.
226 if (Sym.getFlags().hasMaterializationSideEffectsOnly())
227 ResolvedSymbols.erase(I);
228 else
229 I->second = std::move(Sym);
230 --OutstandingSymbolsCount;
231}
232
233void AsynchronousSymbolQuery::handleComplete(ExecutionSession &ES) {
234 assert(OutstandingSymbolsCount == 0 &&
235 "Symbols remain, handleComplete called prematurely");
236
237 class RunQueryCompleteTask : public Task {
238 public:
239 RunQueryCompleteTask(SymbolMap ResolvedSymbols,
240 SymbolsResolvedCallback NotifyComplete)
241 : ResolvedSymbols(std::move(ResolvedSymbols)),
242 NotifyComplete(std::move(NotifyComplete)) {}
243 void printDescription(raw_ostream &OS) override {
244 OS << "Execute query complete callback for " << ResolvedSymbols;
245 }
246 void run() override { NotifyComplete(std::move(ResolvedSymbols)); }
247
248 private:
249 SymbolMap ResolvedSymbols;
250 SymbolsResolvedCallback NotifyComplete;
251 };
252
253 auto T = std::make_unique<RunQueryCompleteTask>(std::move(ResolvedSymbols),
254 std::move(NotifyComplete));
255 NotifyComplete = SymbolsResolvedCallback();
256 ES.dispatchTask(std::move(T));
257}
258
259void AsynchronousSymbolQuery::handleFailed(Error Err) {
260 assert(QueryRegistrations.empty() && ResolvedSymbols.empty() &&
261 OutstandingSymbolsCount == 0 &&
262 "Query should already have been abandoned");
263 NotifyComplete(std::move(Err));
264 NotifyComplete = SymbolsResolvedCallback();
265}
266
267void AsynchronousSymbolQuery::addQueryDependence(JITDylib &JD,
268 SymbolStringPtr Name) {
269 bool Added = QueryRegistrations[&JD].insert(std::move(Name)).second;
270 (void)Added;
271 assert(Added && "Duplicate dependence notification?");
272}
273
274void AsynchronousSymbolQuery::removeQueryDependence(
275 JITDylib &JD, const SymbolStringPtr &Name) {
276 auto QRI = QueryRegistrations.find(&JD);
277 assert(QRI != QueryRegistrations.end() &&
278 "No dependencies registered for JD");
279 assert(QRI->second.count(Name) && "No dependency on Name in JD");
280 QRI->second.erase(Name);
281 if (QRI->second.empty())
282 QueryRegistrations.erase(QRI);
283}
284
285void AsynchronousSymbolQuery::dropSymbol(const SymbolStringPtr &Name) {
286 auto I = ResolvedSymbols.find(Name);
287 assert(I != ResolvedSymbols.end() &&
288 "Redundant removal of weakly-referenced symbol");
289 ResolvedSymbols.erase(I);
290 --OutstandingSymbolsCount;
291}
292
293void AsynchronousSymbolQuery::detach() {
294 ResolvedSymbols.clear();
295 OutstandingSymbolsCount = 0;
296 for (auto &[JD, Syms] : QueryRegistrations)
297 JD->detachQueryHelper(*this, Syms);
298 QueryRegistrations.clear();
299}
300
302 JITDylib *SourceJD, JITDylibLookupFlags SourceJDLookupFlags,
303 SymbolAliasMap Aliases)
304 : MaterializationUnit(extractFlags(Aliases)), SourceJD(SourceJD),
305 SourceJDLookupFlags(SourceJDLookupFlags), Aliases(std::move(Aliases)) {}
306
308 return "<Reexports>";
309}
310
311void ReExportsMaterializationUnit::materialize(
312 std::unique_ptr<MaterializationResponsibility> R) {
313
314 auto &ES = R->getTargetJITDylib().getExecutionSession();
315 JITDylib &TgtJD = R->getTargetJITDylib();
316 JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD;
317
318 // Find the set of requested aliases and aliasees. Return any unrequested
319 // aliases back to the JITDylib so as to not prematurely materialize any
320 // aliasees.
321 auto RequestedSymbols = R->getRequestedSymbols();
322 SymbolAliasMap RequestedAliases;
323
324 for (auto &Name : RequestedSymbols) {
325 auto I = Aliases.find(Name);
326 assert(I != Aliases.end() && "Symbol not found in aliases map?");
327 RequestedAliases[Name] = std::move(I->second);
328 Aliases.erase(I);
329 }
330
331 LLVM_DEBUG({
332 ES.runSessionLocked([&]() {
333 dbgs() << "materializing reexports: target = " << TgtJD.getName()
334 << ", source = " << SrcJD.getName() << " " << RequestedAliases
335 << "\n";
336 });
337 });
338
339 if (!Aliases.empty()) {
340 auto Err = SourceJD ? R->replace(reexports(*SourceJD, std::move(Aliases),
341 SourceJDLookupFlags))
342 : R->replace(symbolAliases(std::move(Aliases)));
343
344 if (Err) {
345 // FIXME: Should this be reported / treated as failure to materialize?
346 // Or should this be treated as a sanctioned bailing-out?
347 ES.reportError(std::move(Err));
348 R->failMaterialization();
349 return;
350 }
351 }
352
353 // The OnResolveInfo struct will hold the aliases and responsibility for each
354 // query in the list.
355 struct OnResolveInfo {
356 OnResolveInfo(std::unique_ptr<MaterializationResponsibility> R,
357 SymbolAliasMap Aliases)
358 : R(std::move(R)), Aliases(std::move(Aliases)) {}
359
360 std::unique_ptr<MaterializationResponsibility> R;
361 SymbolAliasMap Aliases;
362 std::vector<SymbolDependenceGroup> SDGs;
363 };
364
365 // Build a list of queries to issue. In each round we build a query for the
366 // largest set of aliases that we can resolve without encountering a chain of
367 // aliases (e.g. Foo -> Bar, Bar -> Baz). Such a chain would deadlock as the
368 // query would be waiting on a symbol that it itself had to resolve. Creating
369 // a new query for each link in such a chain eliminates the possibility of
370 // deadlock. In practice chains are likely to be rare, and this algorithm will
371 // usually result in a single query to issue.
372
373 std::vector<std::pair<SymbolLookupSet, std::shared_ptr<OnResolveInfo>>>
374 QueryInfos;
375 while (!RequestedAliases.empty()) {
376 SymbolNameSet ResponsibilitySymbols;
377 SymbolLookupSet QuerySymbols;
378 SymbolAliasMap QueryAliases;
379
380 // Collect as many aliases as we can without including a chain.
381 for (auto &KV : RequestedAliases) {
382 // Chain detected. Skip this symbol for this round.
383 if (&SrcJD == &TgtJD && (QueryAliases.count(KV.second.Aliasee) ||
384 RequestedAliases.count(KV.second.Aliasee)))
385 continue;
386
387 ResponsibilitySymbols.insert(KV.first);
388 QuerySymbols.add(KV.second.Aliasee,
389 KV.second.AliasFlags.hasMaterializationSideEffectsOnly()
392 QueryAliases[KV.first] = std::move(KV.second);
393 }
394
395 // Remove the aliases collected this round from the RequestedAliases map.
396 for (auto &KV : QueryAliases)
397 RequestedAliases.erase(KV.first);
398
399 assert(!QuerySymbols.empty() && "Alias cycle detected!");
400
401 auto NewR = R->delegate(ResponsibilitySymbols);
402 if (!NewR) {
403 ES.reportError(NewR.takeError());
404 R->failMaterialization();
405 return;
406 }
407
408 auto QueryInfo = std::make_shared<OnResolveInfo>(std::move(*NewR),
409 std::move(QueryAliases));
410 QueryInfos.push_back(
411 make_pair(std::move(QuerySymbols), std::move(QueryInfo)));
412 }
413
414 // Issue the queries.
415 while (!QueryInfos.empty()) {
416 auto QuerySymbols = std::move(QueryInfos.back().first);
417 auto QueryInfo = std::move(QueryInfos.back().second);
418
419 QueryInfos.pop_back();
420
421 auto RegisterDependencies = [QueryInfo,
422 &SrcJD](const SymbolDependenceMap &Deps) {
423 // If there were no materializing symbols, just bail out.
424 if (Deps.empty())
425 return;
426
427 // Otherwise the only deps should be on SrcJD.
428 assert(Deps.size() == 1 && Deps.count(&SrcJD) &&
429 "Unexpected dependencies for reexports");
430
431 auto &SrcJDDeps = Deps.find(&SrcJD)->second;
432
433 for (auto &[Alias, AliasInfo] : QueryInfo->Aliases)
434 if (SrcJDDeps.count(AliasInfo.Aliasee))
435 QueryInfo->SDGs.push_back({{Alias}, {{&SrcJD, {AliasInfo.Aliasee}}}});
436 };
437
438 auto OnComplete = [QueryInfo](Expected<SymbolMap> Result) {
439 auto &ES = QueryInfo->R->getTargetJITDylib().getExecutionSession();
440 if (Result) {
441 SymbolMap ResolutionMap;
442 for (auto &KV : QueryInfo->Aliases) {
443 assert((KV.second.AliasFlags.hasMaterializationSideEffectsOnly() ||
444 Result->count(KV.second.Aliasee)) &&
445 "Result map missing entry?");
446 // Don't try to resolve materialization-side-effects-only symbols.
447 if (KV.second.AliasFlags.hasMaterializationSideEffectsOnly())
448 continue;
449
450 ResolutionMap[KV.first] = {(*Result)[KV.second.Aliasee].getAddress(),
451 KV.second.AliasFlags};
452 }
453 if (auto Err = QueryInfo->R->notifyResolved(ResolutionMap)) {
454 ES.reportError(std::move(Err));
455 QueryInfo->R->failMaterialization();
456 return;
457 }
458 if (auto Err = QueryInfo->R->notifyEmitted(QueryInfo->SDGs)) {
459 ES.reportError(std::move(Err));
460 QueryInfo->R->failMaterialization();
461 return;
462 }
463 } else {
464 ES.reportError(Result.takeError());
465 QueryInfo->R->failMaterialization();
466 }
467 };
468
470 JITDylibSearchOrder({{&SrcJD, SourceJDLookupFlags}}),
471 QuerySymbols, SymbolState::Resolved, std::move(OnComplete),
472 std::move(RegisterDependencies));
473 }
474}
475
476void ReExportsMaterializationUnit::discard(const JITDylib &JD,
477 const SymbolStringPtr &Name) {
478 assert(Aliases.count(Name) &&
479 "Symbol not covered by this MaterializationUnit");
480 Aliases.erase(Name);
481}
482
483MaterializationUnit::Interface
484ReExportsMaterializationUnit::extractFlags(const SymbolAliasMap &Aliases) {
486 for (auto &KV : Aliases)
487 SymbolFlags[KV.first] = KV.second.AliasFlags;
488
489 return MaterializationUnit::Interface(std::move(SymbolFlags), nullptr);
490}
491
493 SymbolNameSet Symbols) {
494 SymbolLookupSet LookupSet(Symbols);
495 auto Flags = SourceJD.getExecutionSession().lookupFlags(
497 SymbolLookupSet(std::move(Symbols)));
498
499 if (!Flags)
500 return Flags.takeError();
501
503 for (auto &Name : Symbols) {
504 assert(Flags->count(Name) && "Missing entry in flags map");
505 Result[Name] = SymbolAliasMapEntry(Name, (*Flags)[Name]);
506 }
507
508 return Result;
509}
510
512public:
513 // FIXME: Reduce the number of SymbolStringPtrs here. See
514 // https://github.com/llvm/llvm-project/issues/55576.
515
521 }
522 virtual ~InProgressLookupState() = default;
523 virtual void complete(std::unique_ptr<InProgressLookupState> IPLS) = 0;
524 virtual void fail(Error Err) = 0;
525
530
532 bool NewJITDylib = true;
535
536 enum {
537 NotInGenerator, // Not currently using a generator.
538 ResumedForGenerator, // Resumed after being auto-suspended before generator.
539 InGenerator // Currently using generator.
541 std::vector<std::weak_ptr<DefinitionGenerator>> CurDefGeneratorStack;
542};
543
545public:
551 OnComplete(std::move(OnComplete)) {}
552
553 void complete(std::unique_ptr<InProgressLookupState> IPLS) override {
554 auto &ES = SearchOrder.front().first->getExecutionSession();
555 ES.OL_completeLookupFlags(std::move(IPLS), std::move(OnComplete));
556 }
557
558 void fail(Error Err) override { OnComplete(std::move(Err)); }
559
560private:
562};
563
565public:
569 std::shared_ptr<AsynchronousSymbolQuery> Q,
570 RegisterDependenciesFunction RegisterDependencies)
573 Q(std::move(Q)), RegisterDependencies(std::move(RegisterDependencies)) {
574 }
575
576 void complete(std::unique_ptr<InProgressLookupState> IPLS) override {
577 auto &ES = SearchOrder.front().first->getExecutionSession();
578 ES.OL_completeLookup(std::move(IPLS), std::move(Q),
579 std::move(RegisterDependencies));
580 }
581
582 void fail(Error Err) override {
583 Q->detach();
584 Q->handleFailed(std::move(Err));
585 }
586
587private:
588 std::shared_ptr<AsynchronousSymbolQuery> Q;
589 RegisterDependenciesFunction RegisterDependencies;
590};
591
593 JITDylibLookupFlags SourceJDLookupFlags,
594 SymbolPredicate Allow)
595 : SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
596 Allow(std::move(Allow)) {}
597
599 JITDylib &JD,
600 JITDylibLookupFlags JDLookupFlags,
601 const SymbolLookupSet &LookupSet) {
602 assert(&JD != &SourceJD && "Cannot re-export from the same dylib");
603
604 // Use lookupFlags to find the subset of symbols that match our lookup.
605 auto Flags = JD.getExecutionSession().lookupFlags(
606 K, {{&SourceJD, JDLookupFlags}}, LookupSet);
607 if (!Flags)
608 return Flags.takeError();
609
610 // Create an alias map.
611 orc::SymbolAliasMap AliasMap;
612 for (auto &KV : *Flags)
613 if (!Allow || Allow(KV.first))
614 AliasMap[KV.first] = SymbolAliasMapEntry(KV.first, KV.second);
615
616 if (AliasMap.empty())
617 return Error::success();
618
619 // Define the re-exports.
620 return JD.define(reexports(SourceJD, AliasMap, SourceJDLookupFlags));
621}
622
623LookupState::LookupState(std::unique_ptr<InProgressLookupState> IPLS)
624 : IPLS(std::move(IPLS)) {}
625
626void LookupState::reset(InProgressLookupState *IPLS) { this->IPLS.reset(IPLS); }
627
628LookupState::LookupState() = default;
629LookupState::LookupState(LookupState &&) = default;
630LookupState &LookupState::operator=(LookupState &&) = default;
631LookupState::~LookupState() = default;
632
634 assert(IPLS && "Cannot call continueLookup on empty LookupState");
635 auto &ES = IPLS->SearchOrder.begin()->first->getExecutionSession();
636 ES.OL_applyQueryPhase1(std::move(IPLS), std::move(Err));
637}
638
640 std::deque<LookupState> LookupsToFail;
641 {
642 std::lock_guard<std::mutex> Lock(M);
643 std::swap(PendingLookups, LookupsToFail);
644 InUse = false;
645 }
646
647 for (auto &LS : LookupsToFail)
648 LS.continueLookup(make_error<StringError>(
649 "Query waiting on DefinitionGenerator that was destroyed",
651}
652
654 LLVM_DEBUG(dbgs() << "Destroying JITDylib " << getName() << "\n");
655}
656
658 std::vector<ResourceTrackerSP> TrackersToRemove;
659 ES.runSessionLocked([&]() {
660 assert(State != Closed && "JD is defunct");
661 for (auto &KV : TrackerSymbols)
662 TrackersToRemove.push_back(KV.first);
663 TrackersToRemove.push_back(getDefaultResourceTracker());
664 });
665
666 Error Err = Error::success();
667 for (auto &RT : TrackersToRemove)
668 Err = joinErrors(std::move(Err), RT->remove());
669 return Err;
670}
671
673 return ES.runSessionLocked([this] {
674 assert(State != Closed && "JD is defunct");
675 if (!DefaultTracker)
676 DefaultTracker = new ResourceTracker(this);
677 return DefaultTracker;
678 });
679}
680
682 return ES.runSessionLocked([this] {
683 assert(State == Open && "JD is defunct");
684 ResourceTrackerSP RT = new ResourceTracker(this);
685 return RT;
686 });
687}
688
690 // DefGenerator moved into TmpDG to ensure that it's destroyed outside the
691 // session lock (since it may have to send errors to pending queries).
692 std::shared_ptr<DefinitionGenerator> TmpDG;
693
694 ES.runSessionLocked([&] {
695 assert(State == Open && "JD is defunct");
696 auto I = llvm::find_if(DefGenerators,
697 [&](const std::shared_ptr<DefinitionGenerator> &H) {
698 return H.get() == &G;
699 });
700 assert(I != DefGenerators.end() && "Generator not found");
701 TmpDG = std::move(*I);
702 DefGenerators.erase(I);
703 });
704}
705
707JITDylib::defineMaterializing(MaterializationResponsibility &FromMR,
708 SymbolFlagsMap SymbolFlags) {
709
710 return ES.runSessionLocked([&]() -> Expected<SymbolFlagsMap> {
711 if (FromMR.RT->isDefunct())
712 return make_error<ResourceTrackerDefunct>(FromMR.RT);
713
714 std::vector<NonOwningSymbolStringPtr> AddedSyms;
715 std::vector<NonOwningSymbolStringPtr> RejectedWeakDefs;
716
717 for (auto SFItr = SymbolFlags.begin(), SFEnd = SymbolFlags.end();
718 SFItr != SFEnd; ++SFItr) {
719
720 auto &Name = SFItr->first;
721 auto &Flags = SFItr->second;
722
723 auto EntryItr = Symbols.find(Name);
724
725 // If the entry already exists...
726 if (EntryItr != Symbols.end()) {
727
728 // If this is a strong definition then error out.
729 if (!Flags.isWeak()) {
730 // Remove any symbols already added.
731 for (auto &S : AddedSyms)
732 Symbols.erase(Symbols.find_as(S));
733
734 // FIXME: Return all duplicates.
735 return make_error<DuplicateDefinition>(std::string(*Name));
736 }
737
738 // Otherwise just make a note to discard this symbol after the loop.
739 RejectedWeakDefs.push_back(NonOwningSymbolStringPtr(Name));
740 continue;
741 } else
742 EntryItr =
743 Symbols.insert(std::make_pair(Name, SymbolTableEntry(Flags))).first;
744
745 AddedSyms.push_back(NonOwningSymbolStringPtr(Name));
746 EntryItr->second.setState(SymbolState::Materializing);
747 }
748
749 // Remove any rejected weak definitions from the SymbolFlags map.
750 while (!RejectedWeakDefs.empty()) {
751 SymbolFlags.erase(SymbolFlags.find_as(RejectedWeakDefs.back()));
752 RejectedWeakDefs.pop_back();
753 }
754
755 return SymbolFlags;
756 });
757}
758
759Error JITDylib::replace(MaterializationResponsibility &FromMR,
760 std::unique_ptr<MaterializationUnit> MU) {
761 assert(MU != nullptr && "Can not replace with a null MaterializationUnit");
762 std::unique_ptr<MaterializationUnit> MustRunMU;
763 std::unique_ptr<MaterializationResponsibility> MustRunMR;
764
765 auto Err =
766 ES.runSessionLocked([&, this]() -> Error {
767 if (FromMR.RT->isDefunct())
768 return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
769
770#ifndef NDEBUG
771 for (auto &KV : MU->getSymbols()) {
772 auto SymI = Symbols.find(KV.first);
773 assert(SymI != Symbols.end() && "Replacing unknown symbol");
774 assert(SymI->second.getState() == SymbolState::Materializing &&
775 "Can not replace a symbol that ha is not materializing");
776 assert(!SymI->second.hasMaterializerAttached() &&
777 "Symbol should not have materializer attached already");
778 assert(UnmaterializedInfos.count(KV.first) == 0 &&
779 "Symbol being replaced should have no UnmaterializedInfo");
780 }
781#endif // NDEBUG
782
783 // If the tracker is defunct we need to bail out immediately.
784
785 // If any symbol has pending queries against it then we need to
786 // materialize MU immediately.
787 for (auto &KV : MU->getSymbols()) {
788 auto MII = MaterializingInfos.find(KV.first);
789 if (MII != MaterializingInfos.end()) {
790 if (MII->second.hasQueriesPending()) {
791 MustRunMR = ES.createMaterializationResponsibility(
792 *FromMR.RT, std::move(MU->SymbolFlags),
793 std::move(MU->InitSymbol));
794 MustRunMU = std::move(MU);
795 return Error::success();
796 }
797 }
798 }
799
800 // Otherwise, make MU responsible for all the symbols.
801 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU),
802 FromMR.RT.get());
803 for (auto &KV : UMI->MU->getSymbols()) {
804 auto SymI = Symbols.find(KV.first);
805 assert(SymI->second.getState() == SymbolState::Materializing &&
806 "Can not replace a symbol that is not materializing");
807 assert(!SymI->second.hasMaterializerAttached() &&
808 "Can not replace a symbol that has a materializer attached");
809 assert(UnmaterializedInfos.count(KV.first) == 0 &&
810 "Unexpected materializer entry in map");
811 SymI->second.setAddress(SymI->second.getAddress());
812 SymI->second.setMaterializerAttached(true);
813
814 auto &UMIEntry = UnmaterializedInfos[KV.first];
815 assert((!UMIEntry || !UMIEntry->MU) &&
816 "Replacing symbol with materializer still attached");
817 UMIEntry = UMI;
818 }
819
820 return Error::success();
821 });
822
823 if (Err)
824 return Err;
825
826 if (MustRunMU) {
827 assert(MustRunMR && "MustRunMU set implies MustRunMR set");
828 ES.dispatchTask(std::make_unique<MaterializationTask>(
829 std::move(MustRunMU), std::move(MustRunMR)));
830 } else {
831 assert(!MustRunMR && "MustRunMU unset implies MustRunMR unset");
832 }
833
834 return Error::success();
835}
836
837Expected<std::unique_ptr<MaterializationResponsibility>>
838JITDylib::delegate(MaterializationResponsibility &FromMR,
839 SymbolFlagsMap SymbolFlags, SymbolStringPtr InitSymbol) {
840
841 return ES.runSessionLocked(
842 [&]() -> Expected<std::unique_ptr<MaterializationResponsibility>> {
843 if (FromMR.RT->isDefunct())
844 return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
845
846 return ES.createMaterializationResponsibility(
847 *FromMR.RT, std::move(SymbolFlags), std::move(InitSymbol));
848 });
849}
850
852JITDylib::getRequestedSymbols(const SymbolFlagsMap &SymbolFlags) const {
853 return ES.runSessionLocked([&]() {
854 SymbolNameSet RequestedSymbols;
855
856 for (auto &KV : SymbolFlags) {
857 assert(Symbols.count(KV.first) && "JITDylib does not cover this symbol?");
858 assert(Symbols.find(KV.first)->second.getState() !=
859 SymbolState::NeverSearched &&
860 Symbols.find(KV.first)->second.getState() != SymbolState::Ready &&
861 "getRequestedSymbols can only be called for symbols that have "
862 "started materializing");
863 auto I = MaterializingInfos.find(KV.first);
864 if (I == MaterializingInfos.end())
865 continue;
866
867 if (I->second.hasQueriesPending())
868 RequestedSymbols.insert(KV.first);
869 }
870
871 return RequestedSymbols;
872 });
873}
874
875Error JITDylib::resolve(MaterializationResponsibility &MR,
876 const SymbolMap &Resolved) {
877 AsynchronousSymbolQuerySet CompletedQueries;
878
879 if (auto Err = ES.runSessionLocked([&, this]() -> Error {
880 if (MR.RT->isDefunct())
881 return make_error<ResourceTrackerDefunct>(MR.RT);
882
883 if (State != Open)
884 return make_error<StringError>("JITDylib " + getName() +
885 " is defunct",
886 inconvertibleErrorCode());
887
888 struct WorklistEntry {
889 SymbolTable::iterator SymI;
890 ExecutorSymbolDef ResolvedSym;
891 };
892
893 SymbolNameSet SymbolsInErrorState;
894 std::vector<WorklistEntry> Worklist;
895 Worklist.reserve(Resolved.size());
896
897 // Build worklist and check for any symbols in the error state.
898 for (const auto &KV : Resolved) {
899
900 assert(!KV.second.getFlags().hasError() &&
901 "Resolution result can not have error flag set");
902
903 auto SymI = Symbols.find(KV.first);
904
905 assert(SymI != Symbols.end() && "Symbol not found");
906 assert(!SymI->second.hasMaterializerAttached() &&
907 "Resolving symbol with materializer attached?");
908 assert(SymI->second.getState() == SymbolState::Materializing &&
909 "Symbol should be materializing");
910 assert(SymI->second.getAddress() == ExecutorAddr() &&
911 "Symbol has already been resolved");
912
913 if (SymI->second.getFlags().hasError())
914 SymbolsInErrorState.insert(KV.first);
915 else {
916 if (SymI->second.getFlags() & JITSymbolFlags::Common) {
917 [[maybe_unused]] auto WeakOrCommon =
918 JITSymbolFlags::Weak | JITSymbolFlags::Common;
919 assert((KV.second.getFlags() & WeakOrCommon) &&
920 "Common symbols must be resolved as common or weak");
921 assert((KV.second.getFlags() & ~WeakOrCommon) ==
922 (SymI->second.getFlags() & ~JITSymbolFlags::Common) &&
923 "Resolving symbol with incorrect flags");
924
925 } else
926 assert(KV.second.getFlags() == SymI->second.getFlags() &&
927 "Resolved flags should match the declared flags");
928
929 Worklist.push_back(
930 {SymI, {KV.second.getAddress(), SymI->second.getFlags()}});
931 }
932 }
933
934 // If any symbols were in the error state then bail out.
935 if (!SymbolsInErrorState.empty()) {
936 auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
937 (*FailedSymbolsDepMap)[this] = std::move(SymbolsInErrorState);
938 return make_error<FailedToMaterialize>(
939 getExecutionSession().getSymbolStringPool(),
940 std::move(FailedSymbolsDepMap));
941 }
942
943 while (!Worklist.empty()) {
944 auto SymI = Worklist.back().SymI;
945 auto ResolvedSym = Worklist.back().ResolvedSym;
946 Worklist.pop_back();
947
948 auto &Name = SymI->first;
949
950 // Resolved symbols can not be weak: discard the weak flag.
951 JITSymbolFlags ResolvedFlags = ResolvedSym.getFlags();
952 SymI->second.setAddress(ResolvedSym.getAddress());
953 SymI->second.setFlags(ResolvedFlags);
954 SymI->second.setState(SymbolState::Resolved);
955
956 auto MII = MaterializingInfos.find(Name);
957 if (MII == MaterializingInfos.end())
958 continue;
959
960 auto &MI = MII->second;
961 for (auto &Q : MI.takeQueriesMeeting(SymbolState::Resolved)) {
962 Q->notifySymbolMetRequiredState(Name, ResolvedSym);
963 if (Q->isComplete())
964 CompletedQueries.insert(std::move(Q));
965 }
966 }
967
968 return Error::success();
969 }))
970 return Err;
971
972 // Otherwise notify all the completed queries.
973 for (auto &Q : CompletedQueries) {
974 assert(Q->isComplete() && "Q not completed");
975 Q->handleComplete(ES);
976 }
977
978 return Error::success();
979}
980
981void JITDylib::unlinkMaterializationResponsibility(
982 MaterializationResponsibility &MR) {
983 ES.runSessionLocked([&]() {
984 auto I = TrackerMRs.find(MR.RT.get());
985 assert(I != TrackerMRs.end() && "No MRs in TrackerMRs list for RT");
986 assert(I->second.count(&MR) && "MR not in TrackerMRs list for RT");
987 I->second.erase(&MR);
988 if (I->second.empty())
989 TrackerMRs.erase(MR.RT.get());
990 });
991}
992
993void JITDylib::shrinkMaterializationInfoMemory() {
994 // DenseMap::erase never shrinks its storage; use clear to heuristically free
995 // memory since we may have long-lived JDs after linking is done.
996
997 if (UnmaterializedInfos.empty())
998 UnmaterializedInfos.clear();
999
1000 if (MaterializingInfos.empty())
1001 MaterializingInfos.clear();
1002}
1003
1004void JITDylib::setLinkOrder(JITDylibSearchOrder NewLinkOrder,
1005 bool LinkAgainstThisJITDylibFirst) {
1006 ES.runSessionLocked([&]() {
1007 assert(State == Open && "JD is defunct");
1008 if (LinkAgainstThisJITDylibFirst) {
1009 LinkOrder.clear();
1010 if (NewLinkOrder.empty() || NewLinkOrder.front().first != this)
1011 LinkOrder.push_back(
1012 std::make_pair(this, JITDylibLookupFlags::MatchAllSymbols));
1013 llvm::append_range(LinkOrder, NewLinkOrder);
1014 } else
1015 LinkOrder = std::move(NewLinkOrder);
1016 });
1017}
1018
1019void JITDylib::addToLinkOrder(const JITDylibSearchOrder &NewLinks) {
1020 ES.runSessionLocked([&]() {
1021 for (auto &KV : NewLinks) {
1022 // Skip elements of NewLinks that are already in the link order.
1023 if (llvm::is_contained(LinkOrder, KV))
1024 continue;
1025
1026 LinkOrder.push_back(std::move(KV));
1027 }
1028 });
1029}
1030
1031void JITDylib::addToLinkOrder(JITDylib &JD, JITDylibLookupFlags JDLookupFlags) {
1032 ES.runSessionLocked([&]() { LinkOrder.push_back({&JD, JDLookupFlags}); });
1033}
1034
1035void JITDylib::replaceInLinkOrder(JITDylib &OldJD, JITDylib &NewJD,
1036 JITDylibLookupFlags JDLookupFlags) {
1037 ES.runSessionLocked([&]() {
1038 assert(State == Open && "JD is defunct");
1039 for (auto &KV : LinkOrder)
1040 if (KV.first == &OldJD) {
1041 KV = {&NewJD, JDLookupFlags};
1042 break;
1043 }
1044 });
1045}
1046
1047void JITDylib::removeFromLinkOrder(JITDylib &JD) {
1048 ES.runSessionLocked([&]() {
1049 assert(State == Open && "JD is defunct");
1050 auto I = llvm::find_if(LinkOrder,
1051 [&](const JITDylibSearchOrder::value_type &KV) {
1052 return KV.first == &JD;
1053 });
1054 if (I != LinkOrder.end())
1055 LinkOrder.erase(I);
1056 });
1057}
1058
1059Error JITDylib::remove(const SymbolNameSet &Names) {
1060 return ES.runSessionLocked([&]() -> Error {
1061 assert(State == Open && "JD is defunct");
1062 using SymbolMaterializerItrPair =
1063 std::pair<SymbolTable::iterator, UnmaterializedInfosMap::iterator>;
1064 std::vector<SymbolMaterializerItrPair> SymbolsToRemove;
1065 SymbolNameSet Missing;
1067
1068 for (auto &Name : Names) {
1069 auto I = Symbols.find(Name);
1070
1071 // Note symbol missing.
1072 if (I == Symbols.end()) {
1073 Missing.insert(Name);
1074 continue;
1075 }
1076
1077 // Note symbol materializing.
1078 if (I->second.getState() != SymbolState::NeverSearched &&
1079 I->second.getState() != SymbolState::Ready) {
1080 Materializing.insert(Name);
1081 continue;
1082 }
1083
1084 auto UMII = I->second.hasMaterializerAttached()
1085 ? UnmaterializedInfos.find(Name)
1086 : UnmaterializedInfos.end();
1087 SymbolsToRemove.push_back(std::make_pair(I, UMII));
1088 }
1089
1090 // If any of the symbols are not defined, return an error.
1091 if (!Missing.empty())
1092 return make_error<SymbolsNotFound>(ES.getSymbolStringPool(),
1093 std::move(Missing));
1094
1095 // If any of the symbols are currently materializing, return an error.
1096 if (!Materializing.empty())
1097 return make_error<SymbolsCouldNotBeRemoved>(ES.getSymbolStringPool(),
1098 std::move(Materializing));
1099
1100 // Remove the symbols.
1101 for (auto &SymbolMaterializerItrPair : SymbolsToRemove) {
1102 auto UMII = SymbolMaterializerItrPair.second;
1103
1104 // If there is a materializer attached, call discard.
1105 if (UMII != UnmaterializedInfos.end()) {
1106 UMII->second->MU->doDiscard(*this, UMII->first);
1107 UnmaterializedInfos.erase(UMII);
1108 }
1109
1110 auto SymI = SymbolMaterializerItrPair.first;
1111 Symbols.erase(SymI);
1112 }
1113
1114 shrinkMaterializationInfoMemory();
1115
1116 return Error::success();
1117 });
1118}
1119
1120void JITDylib::dump(raw_ostream &OS) {
1121 ES.runSessionLocked([&, this]() {
1122 OS << "JITDylib \"" << getName() << "\" (ES: "
1123 << format("0x%016" PRIx64, reinterpret_cast<uintptr_t>(&ES))
1124 << ", State = ";
1125 switch (State) {
1126 case Open:
1127 OS << "Open";
1128 break;
1129 case Closing:
1130 OS << "Closing";
1131 break;
1132 case Closed:
1133 OS << "Closed";
1134 break;
1135 }
1136 OS << ")\n";
1137 if (State == Closed)
1138 return;
1139 OS << "Link order: " << LinkOrder << "\n"
1140 << "Symbol table:\n";
1141
1142 // Sort symbols so we get a deterministic order and can check them in tests.
1143 std::vector<std::pair<SymbolStringPtr, SymbolTableEntry *>> SymbolsSorted;
1144 for (auto &KV : Symbols)
1145 SymbolsSorted.emplace_back(KV.first, &KV.second);
1146 std::sort(SymbolsSorted.begin(), SymbolsSorted.end(),
1147 [](const auto &L, const auto &R) { return *L.first < *R.first; });
1148
1149 for (auto &KV : SymbolsSorted) {
1150 OS << " \"" << *KV.first << "\": ";
1151 if (auto Addr = KV.second->getAddress())
1152 OS << Addr;
1153 else
1154 OS << "<not resolved> ";
1155
1156 OS << " " << KV.second->getFlags() << " " << KV.second->getState();
1157
1158 if (KV.second->hasMaterializerAttached()) {
1159 OS << " (Materializer ";
1160 auto I = UnmaterializedInfos.find(KV.first);
1161 assert(I != UnmaterializedInfos.end() &&
1162 "Lazy symbol should have UnmaterializedInfo");
1163 OS << I->second->MU.get() << ", " << I->second->MU->getName() << ")\n";
1164 } else
1165 OS << "\n";
1166 }
1167
1168 if (!MaterializingInfos.empty())
1169 OS << " MaterializingInfos entries:\n";
1170 for (auto &KV : MaterializingInfos) {
1171 OS << " \"" << *KV.first << "\":\n"
1172 << " " << KV.second.pendingQueries().size()
1173 << " pending queries: { ";
1174 for (const auto &Q : KV.second.pendingQueries())
1175 OS << Q.get() << " (" << Q->getRequiredState() << ") ";
1176 OS << "}\n Defining EDU: ";
1177 if (KV.second.DefiningEDU) {
1178 OS << KV.second.DefiningEDU.get() << " { ";
1179 for (auto &[Name, Flags] : KV.second.DefiningEDU->Symbols)
1180 OS << Name << " ";
1181 OS << "}\n";
1182 OS << " Dependencies:\n";
1183 if (!KV.second.DefiningEDU->Dependencies.empty()) {
1184 for (auto &[DepJD, Deps] : KV.second.DefiningEDU->Dependencies) {
1185 OS << " " << DepJD->getName() << ": [ ";
1186 for (auto &Dep : Deps)
1187 OS << Dep << " ";
1188 OS << "]\n";
1189 }
1190 } else
1191 OS << " none\n";
1192 } else
1193 OS << "none\n";
1194 OS << " Dependant EDUs:\n";
1195 if (!KV.second.DependantEDUs.empty()) {
1196 for (auto &DependantEDU : KV.second.DependantEDUs) {
1197 OS << " " << DependantEDU << ": "
1198 << DependantEDU->JD->getName() << " { ";
1199 for (auto &[Name, Flags] : DependantEDU->Symbols)
1200 OS << Name << " ";
1201 OS << "}\n";
1202 }
1203 } else
1204 OS << " none\n";
1205 assert((Symbols[KV.first].getState() != SymbolState::Ready ||
1206 (KV.second.pendingQueries().empty() && !KV.second.DefiningEDU &&
1207 !KV.second.DependantEDUs.empty())) &&
1208 "Stale materializing info entry");
1209 }
1210 });
1211}
1212
1213void JITDylib::MaterializingInfo::addQuery(
1214 std::shared_ptr<AsynchronousSymbolQuery> Q) {
1215
1216 auto I = llvm::lower_bound(
1217 llvm::reverse(PendingQueries), Q->getRequiredState(),
1218 [](const std::shared_ptr<AsynchronousSymbolQuery> &V, SymbolState S) {
1219 return V->getRequiredState() <= S;
1220 });
1221 PendingQueries.insert(I.base(), std::move(Q));
1222}
1223
1224void JITDylib::MaterializingInfo::removeQuery(
1225 const AsynchronousSymbolQuery &Q) {
1226 // FIXME: Implement 'find_as' for shared_ptr<T>/T*.
1227 auto I = llvm::find_if(
1228 PendingQueries, [&Q](const std::shared_ptr<AsynchronousSymbolQuery> &V) {
1229 return V.get() == &Q;
1230 });
1231 if (I != PendingQueries.end())
1232 PendingQueries.erase(I);
1233}
1234
1235JITDylib::AsynchronousSymbolQueryList
1236JITDylib::MaterializingInfo::takeQueriesMeeting(SymbolState RequiredState) {
1237 AsynchronousSymbolQueryList Result;
1238 while (!PendingQueries.empty()) {
1239 if (PendingQueries.back()->getRequiredState() > RequiredState)
1240 break;
1241
1242 Result.push_back(std::move(PendingQueries.back()));
1243 PendingQueries.pop_back();
1244 }
1245
1246 return Result;
1247}
1248
1249JITDylib::JITDylib(ExecutionSession &ES, std::string Name)
1250 : JITLinkDylib(std::move(Name)), ES(ES) {
1251 LinkOrder.push_back({this, JITDylibLookupFlags::MatchAllSymbols});
1252}
1253
1254JITDylib::RemoveTrackerResult JITDylib::IL_removeTracker(ResourceTracker &RT) {
1255 // Note: Should be called under the session lock.
1256 assert(State != Closed && "JD is defunct");
1257
1258 SymbolNameVector SymbolsToRemove;
1259 SymbolNameVector SymbolsToFail;
1260
1261 if (&RT == DefaultTracker.get()) {
1262 SymbolNameSet TrackedSymbols;
1263 for (auto &KV : TrackerSymbols)
1264 for (auto &Sym : KV.second)
1265 TrackedSymbols.insert(Sym);
1266
1267 for (auto &KV : Symbols) {
1268 auto &Sym = KV.first;
1269 if (!TrackedSymbols.count(Sym))
1270 SymbolsToRemove.push_back(Sym);
1271 }
1272
1273 DefaultTracker.reset();
1274 } else {
1275 /// Check for a non-default tracker.
1276 auto I = TrackerSymbols.find(&RT);
1277 if (I != TrackerSymbols.end()) {
1278 SymbolsToRemove = std::move(I->second);
1279 TrackerSymbols.erase(I);
1280 }
1281 // ... if not found this tracker was already defunct. Nothing to do.
1282 }
1283
1284 for (auto &Sym : SymbolsToRemove) {
1285 assert(Symbols.count(Sym) && "Symbol not in symbol table");
1286
1287 // If there is a MaterializingInfo then collect any queries to fail.
1288 auto MII = MaterializingInfos.find(Sym);
1289 if (MII != MaterializingInfos.end())
1290 SymbolsToFail.push_back(Sym);
1291 }
1292
1293 auto [QueriesToFail, FailedSymbols] =
1294 ES.IL_failSymbols(*this, std::move(SymbolsToFail));
1295
1296 std::vector<std::unique_ptr<MaterializationUnit>> DefunctMUs;
1297
1298 // Removed symbols should be taken out of the table altogether.
1299 for (auto &Sym : SymbolsToRemove) {
1300 auto I = Symbols.find(Sym);
1301 assert(I != Symbols.end() && "Symbol not present in table");
1302
1303 // Remove Materializer if present.
1304 if (I->second.hasMaterializerAttached()) {
1305 // FIXME: Should this discard the symbols?
1306 auto J = UnmaterializedInfos.find(Sym);
1307 assert(J != UnmaterializedInfos.end() &&
1308 "Symbol table indicates MU present, but no UMI record");
1309 if (J->second->MU)
1310 DefunctMUs.push_back(std::move(J->second->MU));
1311 UnmaterializedInfos.erase(J);
1312 } else {
1313 assert(!UnmaterializedInfos.count(Sym) &&
1314 "Symbol has materializer attached");
1315 }
1316
1317 Symbols.erase(I);
1318 }
1319
1320 shrinkMaterializationInfoMemory();
1321
1322 return {std::move(QueriesToFail), std::move(FailedSymbols),
1323 std::move(DefunctMUs)};
1324}
1325
1326void JITDylib::transferTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT) {
1327 assert(State != Closed && "JD is defunct");
1328 assert(&DstRT != &SrcRT && "No-op transfers shouldn't call transferTracker");
1329 assert(&DstRT.getJITDylib() == this && "DstRT is not for this JITDylib");
1330 assert(&SrcRT.getJITDylib() == this && "SrcRT is not for this JITDylib");
1331
1332 // Update trackers for any not-yet materialized units.
1333 for (auto &KV : UnmaterializedInfos) {
1334 if (KV.second->RT == &SrcRT)
1335 KV.second->RT = &DstRT;
1336 }
1337
1338 // Update trackers for any active materialization responsibilities.
1339 {
1340 auto I = TrackerMRs.find(&SrcRT);
1341 if (I != TrackerMRs.end()) {
1342 auto &SrcMRs = I->second;
1343 auto &DstMRs = TrackerMRs[&DstRT];
1344 for (auto *MR : SrcMRs)
1345 MR->RT = &DstRT;
1346 if (DstMRs.empty())
1347 DstMRs = std::move(SrcMRs);
1348 else
1349 for (auto *MR : SrcMRs)
1350 DstMRs.insert(MR);
1351 // Erase SrcRT entry in TrackerMRs. Use &SrcRT key rather than iterator I
1352 // for this, since I may have been invalidated by 'TrackerMRs[&DstRT]'.
1353 TrackerMRs.erase(&SrcRT);
1354 }
1355 }
1356
1357 // If we're transfering to the default tracker we just need to delete the
1358 // tracked symbols for the source tracker.
1359 if (&DstRT == DefaultTracker.get()) {
1360 TrackerSymbols.erase(&SrcRT);
1361 return;
1362 }
1363
1364 // If we're transferring from the default tracker we need to find all
1365 // currently untracked symbols.
1366 if (&SrcRT == DefaultTracker.get()) {
1367 assert(!TrackerSymbols.count(&SrcRT) &&
1368 "Default tracker should not appear in TrackerSymbols");
1369
1370 SymbolNameVector SymbolsToTrack;
1371
1372 SymbolNameSet CurrentlyTrackedSymbols;
1373 for (auto &KV : TrackerSymbols)
1374 for (auto &Sym : KV.second)
1375 CurrentlyTrackedSymbols.insert(Sym);
1376
1377 for (auto &KV : Symbols) {
1378 auto &Sym = KV.first;
1379 if (!CurrentlyTrackedSymbols.count(Sym))
1380 SymbolsToTrack.push_back(Sym);
1381 }
1382
1383 TrackerSymbols[&DstRT] = std::move(SymbolsToTrack);
1384 return;
1385 }
1386
1387 auto &DstTrackedSymbols = TrackerSymbols[&DstRT];
1388
1389 // Finally if neither SrtRT or DstRT are the default tracker then
1390 // just append DstRT's tracked symbols to SrtRT's.
1391 auto SI = TrackerSymbols.find(&SrcRT);
1392 if (SI == TrackerSymbols.end())
1393 return;
1394
1395 DstTrackedSymbols.reserve(DstTrackedSymbols.size() + SI->second.size());
1396 for (auto &Sym : SI->second)
1397 DstTrackedSymbols.push_back(std::move(Sym));
1398 TrackerSymbols.erase(SI);
1399}
1400
1401Error JITDylib::defineImpl(MaterializationUnit &MU) {
1402 LLVM_DEBUG({ dbgs() << " " << MU.getSymbols() << "\n"; });
1403
1404 SymbolNameSet Duplicates;
1405 std::vector<SymbolStringPtr> ExistingDefsOverridden;
1406 std::vector<SymbolStringPtr> MUDefsOverridden;
1407
1408 for (const auto &KV : MU.getSymbols()) {
1409 auto I = Symbols.find(KV.first);
1410
1411 if (I != Symbols.end()) {
1412 if (KV.second.isStrong()) {
1413 if (I->second.getFlags().isStrong() ||
1414 I->second.getState() > SymbolState::NeverSearched)
1415 Duplicates.insert(KV.first);
1416 else {
1417 assert(I->second.getState() == SymbolState::NeverSearched &&
1418 "Overridden existing def should be in the never-searched "
1419 "state");
1420 ExistingDefsOverridden.push_back(KV.first);
1421 }
1422 } else
1423 MUDefsOverridden.push_back(KV.first);
1424 }
1425 }
1426
1427 // If there were any duplicate definitions then bail out.
1428 if (!Duplicates.empty()) {
1429 LLVM_DEBUG(
1430 { dbgs() << " Error: Duplicate symbols " << Duplicates << "\n"; });
1431 return make_error<DuplicateDefinition>(std::string(**Duplicates.begin()));
1432 }
1433
1434 // Discard any overridden defs in this MU.
1435 LLVM_DEBUG({
1436 if (!MUDefsOverridden.empty())
1437 dbgs() << " Defs in this MU overridden: " << MUDefsOverridden << "\n";
1438 });
1439 for (auto &S : MUDefsOverridden)
1440 MU.doDiscard(*this, S);
1441
1442 // Discard existing overridden defs.
1443 LLVM_DEBUG({
1444 if (!ExistingDefsOverridden.empty())
1445 dbgs() << " Existing defs overridden by this MU: " << MUDefsOverridden
1446 << "\n";
1447 });
1448 for (auto &S : ExistingDefsOverridden) {
1449
1450 auto UMII = UnmaterializedInfos.find(S);
1451 assert(UMII != UnmaterializedInfos.end() &&
1452 "Overridden existing def should have an UnmaterializedInfo");
1453 UMII->second->MU->doDiscard(*this, S);
1454 }
1455
1456 // Finally, add the defs from this MU.
1457 for (auto &KV : MU.getSymbols()) {
1458 auto &SymEntry = Symbols[KV.first];
1459 SymEntry.setFlags(KV.second);
1460 SymEntry.setState(SymbolState::NeverSearched);
1461 SymEntry.setMaterializerAttached(true);
1462 }
1463
1464 return Error::success();
1465}
1466
1467void JITDylib::installMaterializationUnit(
1468 std::unique_ptr<MaterializationUnit> MU, ResourceTracker &RT) {
1469
1470 /// defineImpl succeeded.
1471 if (&RT != DefaultTracker.get()) {
1472 auto &TS = TrackerSymbols[&RT];
1473 TS.reserve(TS.size() + MU->getSymbols().size());
1474 for (auto &KV : MU->getSymbols())
1475 TS.push_back(KV.first);
1476 }
1477
1478 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU), &RT);
1479 for (auto &KV : UMI->MU->getSymbols())
1480 UnmaterializedInfos[KV.first] = UMI;
1481}
1482
1483void JITDylib::detachQueryHelper(AsynchronousSymbolQuery &Q,
1484 const SymbolNameSet &QuerySymbols) {
1485 for (auto &QuerySymbol : QuerySymbols) {
1486 auto MII = MaterializingInfos.find(QuerySymbol);
1487 if (MII != MaterializingInfos.end())
1488 MII->second.removeQuery(Q);
1489 }
1490}
1491
1492Platform::~Platform() = default;
1493
1495 ExecutionSession &ES,
1496 const DenseMap<JITDylib *, SymbolLookupSet> &InitSyms) {
1497
1498 DenseMap<JITDylib *, SymbolMap> CompoundResult;
1499 Error CompoundErr = Error::success();
1500 std::mutex LookupMutex;
1501 std::condition_variable CV;
1502 uint64_t Count = InitSyms.size();
1503
1504 LLVM_DEBUG({
1505 dbgs() << "Issuing init-symbol lookup:\n";
1506 for (auto &KV : InitSyms)
1507 dbgs() << " " << KV.first->getName() << ": " << KV.second << "\n";
1508 });
1509
1510 for (auto &KV : InitSyms) {
1511 auto *JD = KV.first;
1512 auto Names = std::move(KV.second);
1513 ES.lookup(
1516 std::move(Names), SymbolState::Ready,
1517 [&, JD](Expected<SymbolMap> Result) {
1518 {
1519 std::lock_guard<std::mutex> Lock(LookupMutex);
1520 --Count;
1521 if (Result) {
1522 assert(!CompoundResult.count(JD) &&
1523 "Duplicate JITDylib in lookup?");
1524 CompoundResult[JD] = std::move(*Result);
1525 } else
1526 CompoundErr =
1527 joinErrors(std::move(CompoundErr), Result.takeError());
1528 }
1529 CV.notify_one();
1530 },
1532 }
1533
1534 std::unique_lock<std::mutex> Lock(LookupMutex);
1535 CV.wait(Lock, [&] { return Count == 0 || CompoundErr; });
1536
1537 if (CompoundErr)
1538 return std::move(CompoundErr);
1539
1540 return std::move(CompoundResult);
1541}
1542
1544 unique_function<void(Error)> OnComplete, ExecutionSession &ES,
1545 const DenseMap<JITDylib *, SymbolLookupSet> &InitSyms) {
1546
1547 class TriggerOnComplete {
1548 public:
1549 using OnCompleteFn = unique_function<void(Error)>;
1550 TriggerOnComplete(OnCompleteFn OnComplete)
1551 : OnComplete(std::move(OnComplete)) {}
1552 ~TriggerOnComplete() { OnComplete(std::move(LookupResult)); }
1553 void reportResult(Error Err) {
1554 std::lock_guard<std::mutex> Lock(ResultMutex);
1555 LookupResult = joinErrors(std::move(LookupResult), std::move(Err));
1556 }
1557
1558 private:
1559 std::mutex ResultMutex;
1560 Error LookupResult{Error::success()};
1561 OnCompleteFn OnComplete;
1562 };
1563
1564 LLVM_DEBUG({
1565 dbgs() << "Issuing init-symbol lookup:\n";
1566 for (auto &KV : InitSyms)
1567 dbgs() << " " << KV.first->getName() << ": " << KV.second << "\n";
1568 });
1569
1570 auto TOC = std::make_shared<TriggerOnComplete>(std::move(OnComplete));
1571
1572 for (auto &KV : InitSyms) {
1573 auto *JD = KV.first;
1574 auto Names = std::move(KV.second);
1575 ES.lookup(
1578 std::move(Names), SymbolState::Ready,
1580 TOC->reportResult(Result.takeError());
1581 },
1583 }
1584}
1585
1587 // If this task wasn't run then fail materialization.
1588 if (MR)
1589 MR->failMaterialization();
1590}
1591
1593 OS << "Materialization task: " << MU->getName() << " in "
1594 << MR->getTargetJITDylib().getName();
1595}
1596
1598 assert(MU && "MU should not be null");
1599 assert(MR && "MR should not be null");
1600 MU->materialize(std::move(MR));
1601}
1602
1603void LookupTask::printDescription(raw_ostream &OS) { OS << "Lookup task"; }
1604
1606
1607ExecutionSession::ExecutionSession(std::unique_ptr<ExecutorProcessControl> EPC)
1608 : EPC(std::move(EPC)) {
1609 // Associated EPC and this.
1610 this->EPC->ES = this;
1611}
1612
1614 // You must call endSession prior to destroying the session.
1615 assert(!SessionOpen &&
1616 "Session still open. Did you forget to call endSession?");
1617}
1618
1620 LLVM_DEBUG(dbgs() << "Ending ExecutionSession " << this << "\n");
1621
1622 auto JDsToRemove = runSessionLocked([&] {
1623
1624#ifdef EXPENSIVE_CHECKS
1625 verifySessionState("Entering ExecutionSession::endSession");
1626#endif
1627
1628 SessionOpen = false;
1629 return JDs;
1630 });
1631
1632 std::reverse(JDsToRemove.begin(), JDsToRemove.end());
1633
1634 auto Err = removeJITDylibs(std::move(JDsToRemove));
1635
1636 Err = joinErrors(std::move(Err), EPC->disconnect());
1637
1638 return Err;
1639}
1640
1642 runSessionLocked([&] { ResourceManagers.push_back(&RM); });
1643}
1644
1646 runSessionLocked([&] {
1647 assert(!ResourceManagers.empty() && "No managers registered");
1648 if (ResourceManagers.back() == &RM)
1649 ResourceManagers.pop_back();
1650 else {
1651 auto I = llvm::find(ResourceManagers, &RM);
1652 assert(I != ResourceManagers.end() && "RM not registered");
1653 ResourceManagers.erase(I);
1654 }
1655 });
1656}
1657
1659 return runSessionLocked([&, this]() -> JITDylib * {
1660 for (auto &JD : JDs)
1661 if (JD->getName() == Name)
1662 return JD.get();
1663 return nullptr;
1664 });
1665}
1666
1668 assert(!getJITDylibByName(Name) && "JITDylib with that name already exists");
1669 return runSessionLocked([&, this]() -> JITDylib & {
1670 assert(SessionOpen && "Cannot create JITDylib after session is closed");
1671 JDs.push_back(new JITDylib(*this, std::move(Name)));
1672 return *JDs.back();
1673 });
1674}
1675
1677 auto &JD = createBareJITDylib(Name);
1678 if (P)
1679 if (auto Err = P->setupJITDylib(JD))
1680 return std::move(Err);
1681 return JD;
1682}
1683
1684Error ExecutionSession::removeJITDylibs(std::vector<JITDylibSP> JDsToRemove) {
1685 // Set JD to 'Closing' state and remove JD from the ExecutionSession.
1686 runSessionLocked([&] {
1687 for (auto &JD : JDsToRemove) {
1688 assert(JD->State == JITDylib::Open && "JD already closed");
1689 JD->State = JITDylib::Closing;
1690 auto I = llvm::find(JDs, JD);
1691 assert(I != JDs.end() && "JD does not appear in session JDs");
1692 JDs.erase(I);
1693 }
1694 });
1695
1696 // Clear JITDylibs and notify the platform.
1697 Error Err = Error::success();
1698 for (auto JD : JDsToRemove) {
1699 Err = joinErrors(std::move(Err), JD->clear());
1700 if (P)
1701 Err = joinErrors(std::move(Err), P->teardownJITDylib(*JD));
1702 }
1703
1704 // Set JD to closed state. Clear remaining data structures.
1705 runSessionLocked([&] {
1706 for (auto &JD : JDsToRemove) {
1707 assert(JD->State == JITDylib::Closing && "JD should be closing");
1708 JD->State = JITDylib::Closed;
1709 assert(JD->Symbols.empty() && "JD.Symbols is not empty after clear");
1710 assert(JD->UnmaterializedInfos.empty() &&
1711 "JD.UnmaterializedInfos is not empty after clear");
1712 assert(JD->MaterializingInfos.empty() &&
1713 "JD.MaterializingInfos is not empty after clear");
1714 assert(JD->TrackerSymbols.empty() &&
1715 "TrackerSymbols is not empty after clear");
1716 JD->DefGenerators.clear();
1717 JD->LinkOrder.clear();
1718 }
1719 });
1720
1721 return Err;
1722}
1723
1726 if (JDs.empty())
1727 return std::vector<JITDylibSP>();
1728
1729 auto &ES = JDs.front()->getExecutionSession();
1730 return ES.runSessionLocked([&]() -> Expected<std::vector<JITDylibSP>> {
1731 DenseSet<JITDylib *> Visited;
1732 std::vector<JITDylibSP> Result;
1733
1734 for (auto &JD : JDs) {
1735
1736 if (JD->State != Open)
1737 return make_error<StringError>(
1738 "Error building link order: " + JD->getName() + " is defunct",
1740 if (Visited.count(JD.get()))
1741 continue;
1742
1744 WorkStack.push_back(JD);
1745 Visited.insert(JD.get());
1746
1747 while (!WorkStack.empty()) {
1748 Result.push_back(std::move(WorkStack.back()));
1749 WorkStack.pop_back();
1750
1751 for (auto &KV : llvm::reverse(Result.back()->LinkOrder)) {
1752 auto &JD = *KV.first;
1753 if (!Visited.insert(&JD).second)
1754 continue;
1755 WorkStack.push_back(&JD);
1756 }
1757 }
1758 }
1759 return Result;
1760 });
1761}
1762
1765 auto Result = getDFSLinkOrder(JDs);
1766 if (Result)
1767 std::reverse(Result->begin(), Result->end());
1768 return Result;
1769}
1770
1772 return getDFSLinkOrder({this});
1773}
1774
1776 return getReverseDFSLinkOrder({this});
1777}
1778
1780 LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet,
1781 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete) {
1782
1783 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1784 K, std::move(SearchOrder), std::move(LookupSet),
1785 std::move(OnComplete)),
1786 Error::success());
1787}
1788
1791 SymbolLookupSet LookupSet) {
1792
1793 std::promise<MSVCPExpected<SymbolFlagsMap>> ResultP;
1794 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1795 K, std::move(SearchOrder), std::move(LookupSet),
1796 [&ResultP](Expected<SymbolFlagsMap> Result) {
1797 ResultP.set_value(std::move(Result));
1798 }),
1799 Error::success());
1800
1801 auto ResultF = ResultP.get_future();
1802 return ResultF.get();
1803}
1804
1806 LookupKind K, const JITDylibSearchOrder &SearchOrder,
1807 SymbolLookupSet Symbols, SymbolState RequiredState,
1808 SymbolsResolvedCallback NotifyComplete,
1809 RegisterDependenciesFunction RegisterDependencies) {
1810
1811 LLVM_DEBUG({
1812 runSessionLocked([&]() {
1813 dbgs() << "Looking up " << Symbols << " in " << SearchOrder
1814 << " (required state: " << RequiredState << ")\n";
1815 });
1816 });
1817
1818 // lookup can be re-entered recursively if running on a single thread. Run any
1819 // outstanding MUs in case this query depends on them, otherwise this lookup
1820 // will starve waiting for a result from an MU that is stuck in the queue.
1821 dispatchOutstandingMUs();
1822
1823 auto Unresolved = std::move(Symbols);
1824 auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
1825 std::move(NotifyComplete));
1826
1827 auto IPLS = std::make_unique<InProgressFullLookupState>(
1828 K, SearchOrder, std::move(Unresolved), RequiredState, std::move(Q),
1829 std::move(RegisterDependencies));
1830
1831 OL_applyQueryPhase1(std::move(IPLS), Error::success());
1832}
1833
1836 SymbolLookupSet Symbols, LookupKind K,
1837 SymbolState RequiredState,
1838 RegisterDependenciesFunction RegisterDependencies) {
1839#if LLVM_ENABLE_THREADS
1840 // In the threaded case we use promises to return the results.
1841 std::promise<MSVCPExpected<SymbolMap>> PromisedResult;
1842
1843 auto NotifyComplete = [&](Expected<SymbolMap> R) {
1844 PromisedResult.set_value(std::move(R));
1845 };
1846
1847#else
1849 Error ResolutionError = Error::success();
1850
1851 auto NotifyComplete = [&](Expected<SymbolMap> R) {
1852 ErrorAsOutParameter _(ResolutionError);
1853 if (R)
1854 Result = std::move(*R);
1855 else
1856 ResolutionError = R.takeError();
1857 };
1858#endif
1859
1860 // Perform the asynchronous lookup.
1861 lookup(K, SearchOrder, std::move(Symbols), RequiredState,
1862 std::move(NotifyComplete), RegisterDependencies);
1863
1864#if LLVM_ENABLE_THREADS
1865 return PromisedResult.get_future().get();
1866#else
1867 if (ResolutionError)
1868 return std::move(ResolutionError);
1869
1870 return Result;
1871#endif
1872}
1873
1876 SymbolStringPtr Name, SymbolState RequiredState) {
1877 SymbolLookupSet Names({Name});
1878
1879 if (auto ResultMap = lookup(SearchOrder, std::move(Names), LookupKind::Static,
1880 RequiredState, NoDependenciesToRegister)) {
1881 assert(ResultMap->size() == 1 && "Unexpected number of results");
1882 assert(ResultMap->count(Name) && "Missing result for symbol");
1883 return std::move(ResultMap->begin()->second);
1884 } else
1885 return ResultMap.takeError();
1886}
1887
1890 SymbolState RequiredState) {
1891 return lookup(makeJITDylibSearchOrder(SearchOrder), Name, RequiredState);
1892}
1893
1896 SymbolState RequiredState) {
1897 return lookup(SearchOrder, intern(Name), RequiredState);
1898}
1899
1902
1903 auto TagSyms = lookup({{&JD, JITDylibLookupFlags::MatchAllSymbols}},
1906 if (!TagSyms)
1907 return TagSyms.takeError();
1908
1909 // Associate tag addresses with implementations.
1910 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1911
1912 // Check that no tags are being overwritten.
1913 for (auto &[TagName, TagSym] : *TagSyms) {
1914 auto TagAddr = TagSym.getAddress();
1915 if (JITDispatchHandlers.count(TagAddr))
1916 return make_error<StringError>("Tag " + formatv("{0:x}", TagAddr) +
1917 " (for " + *TagName +
1918 ") already registered",
1920 }
1921
1922 // At this point we're guaranteed to succeed. Install the handlers.
1923 for (auto &[TagName, TagSym] : *TagSyms) {
1924 auto TagAddr = TagSym.getAddress();
1925 auto I = WFs.find(TagName);
1926 assert(I != WFs.end() && I->second &&
1927 "JITDispatchHandler implementation missing");
1928 JITDispatchHandlers[TagAddr] =
1929 std::make_shared<JITDispatchHandlerFunction>(std::move(I->second));
1930 LLVM_DEBUG({
1931 dbgs() << "Associated function tag \"" << *TagName << "\" ("
1932 << formatv("{0:x}", TagAddr) << ") with handler\n";
1933 });
1934 }
1935
1936 return Error::success();
1937}
1938
1940 ExecutorAddr HandlerFnTagAddr,
1941 ArrayRef<char> ArgBuffer) {
1942
1943 std::shared_ptr<JITDispatchHandlerFunction> F;
1944 {
1945 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1946 auto I = JITDispatchHandlers.find(HandlerFnTagAddr);
1947 if (I != JITDispatchHandlers.end())
1948 F = I->second;
1949 }
1950
1951 if (F)
1952 (*F)(std::move(SendResult), ArgBuffer.data(), ArgBuffer.size());
1953 else
1955 ("No function registered for tag " +
1956 formatv("{0:x16}", HandlerFnTagAddr))
1957 .str()));
1958}
1959
1961 runSessionLocked([this, &OS]() {
1962 for (auto &JD : JDs)
1963 JD->dump(OS);
1964 });
1965}
1966
1967#ifdef EXPENSIVE_CHECKS
1968bool ExecutionSession::verifySessionState(Twine Phase) {
1969 return runSessionLocked([&]() {
1970 bool AllOk = true;
1971
1972 // We'll collect these and verify them later to avoid redundant checks.
1974
1975 for (auto &JD : JDs) {
1976
1977 auto LogFailure = [&]() -> raw_fd_ostream & {
1978 auto &Stream = errs();
1979 if (AllOk)
1980 Stream << "ERROR: Bad ExecutionSession state detected " << Phase
1981 << "\n";
1982 Stream << " In JITDylib " << JD->getName() << ", ";
1983 AllOk = false;
1984 return Stream;
1985 };
1986
1987 if (JD->State != JITDylib::Open) {
1988 LogFailure()
1989 << "state is not Open, but JD is in ExecutionSession list.";
1990 }
1991
1992 // Check symbol table.
1993 // 1. If the entry state isn't resolved then check that no address has
1994 // been set.
1995 // 2. Check that if the hasMaterializerAttached flag is set then there is
1996 // an UnmaterializedInfo entry, and vice-versa.
1997 for (auto &[Sym, Entry] : JD->Symbols) {
1998 // Check that unresolved symbols have null addresses.
1999 if (Entry.getState() < SymbolState::Resolved) {
2000 if (Entry.getAddress()) {
2001 LogFailure() << "symbol " << Sym << " has state "
2002 << Entry.getState()
2003 << " (not-yet-resolved) but non-null address "
2004 << Entry.getAddress() << ".\n";
2005 }
2006 }
2007
2008 // Check that the hasMaterializerAttached flag is correct.
2009 auto UMIItr = JD->UnmaterializedInfos.find(Sym);
2010 if (Entry.hasMaterializerAttached()) {
2011 if (UMIItr == JD->UnmaterializedInfos.end()) {
2012 LogFailure() << "symbol " << Sym
2013 << " entry claims materializer attached, but "
2014 "UnmaterializedInfos has no corresponding entry.\n";
2015 }
2016 } else if (UMIItr != JD->UnmaterializedInfos.end()) {
2017 LogFailure()
2018 << "symbol " << Sym
2019 << " entry claims no materializer attached, but "
2020 "UnmaterializedInfos has an unexpected entry for it.\n";
2021 }
2022 }
2023
2024 // Check that every UnmaterializedInfo entry has a corresponding entry
2025 // in the Symbols table.
2026 for (auto &[Sym, UMI] : JD->UnmaterializedInfos) {
2027 auto SymItr = JD->Symbols.find(Sym);
2028 if (SymItr == JD->Symbols.end()) {
2029 LogFailure()
2030 << "symbol " << Sym
2031 << " has UnmaterializedInfos entry, but no Symbols entry.\n";
2032 }
2033 }
2034
2035 // Check consistency of the MaterializingInfos table.
2036 for (auto &[Sym, MII] : JD->MaterializingInfos) {
2037
2038 auto SymItr = JD->Symbols.find(Sym);
2039 if (SymItr == JD->Symbols.end()) {
2040 // If there's no Symbols entry for this MaterializingInfos entry then
2041 // report that.
2042 LogFailure()
2043 << "symbol " << Sym
2044 << " has MaterializingInfos entry, but no Symbols entry.\n";
2045 } else {
2046 // Otherwise check consistency between Symbols and MaterializingInfos.
2047
2048 // Ready symbols should not have MaterializingInfos.
2049 if (SymItr->second.getState() == SymbolState::Ready) {
2050 LogFailure()
2051 << "symbol " << Sym
2052 << " is in Ready state, should not have MaterializingInfo.\n";
2053 }
2054
2055 // Pending queries should be for subsequent states.
2056 auto CurState = static_cast<SymbolState>(
2057 static_cast<std::underlying_type_t<SymbolState>>(
2058 SymItr->second.getState()) + 1);
2059 for (auto &Q : MII.PendingQueries) {
2060 if (Q->getRequiredState() != CurState) {
2061 if (Q->getRequiredState() > CurState)
2062 CurState = Q->getRequiredState();
2063 else
2064 LogFailure() << "symbol " << Sym
2065 << " has stale or misordered queries.\n";
2066 }
2067 }
2068
2069 // If there's a DefiningEDU then check that...
2070 // 1. The JD matches.
2071 // 2. The symbol is in the EDU's Symbols map.
2072 // 3. The symbol table entry is in the Emitted state.
2073 if (MII.DefiningEDU) {
2074
2075 EDUsToCheck.insert(MII.DefiningEDU.get());
2076
2077 if (MII.DefiningEDU->JD != JD.get()) {
2078 LogFailure() << "symbol " << Sym
2079 << " has DefiningEDU with incorrect JD"
2080 << (llvm::is_contained(JDs, MII.DefiningEDU->JD)
2081 ? " (JD not currently in ExecutionSession"
2082 : "")
2083 << "\n";
2084 }
2085
2086 if (SymItr->second.getState() != SymbolState::Emitted) {
2087 LogFailure()
2088 << "symbol " << Sym
2089 << " has DefiningEDU, but is not in Emitted state.\n";
2090 }
2091 }
2092
2093 // Check that JDs for any DependantEDUs are also in the session --
2094 // that guarantees that we'll also visit them during this loop.
2095 for (auto &DepEDU : MII.DependantEDUs) {
2096 if (!llvm::is_contained(JDs, DepEDU->JD)) {
2097 LogFailure() << "symbol " << Sym << " has DependantEDU "
2098 << (void *)DepEDU << " with JD (" << DepEDU->JD
2099 << ") that isn't in ExecutionSession.\n";
2100 }
2101 }
2102 }
2103 }
2104 }
2105
2106 // Check EDUs.
2107 for (auto *EDU : EDUsToCheck) {
2108 assert(EDU->JD->State == JITDylib::Open && "EDU->JD is not Open");
2109
2110 auto LogFailure = [&]() -> raw_fd_ostream & {
2111 AllOk = false;
2112 auto &Stream = errs();
2113 Stream << "In EDU defining " << EDU->JD->getName() << ": { ";
2114 for (auto &[Sym, Flags] : EDU->Symbols)
2115 Stream << Sym << " ";
2116 Stream << "}, ";
2117 return Stream;
2118 };
2119
2120 if (EDU->Symbols.empty())
2121 LogFailure() << "no symbols defined.\n";
2122 else {
2123 for (auto &[Sym, Flags] : EDU->Symbols) {
2124 if (!Sym)
2125 LogFailure() << "null symbol defined.\n";
2126 else {
2127 if (!EDU->JD->Symbols.count(SymbolStringPtr(Sym))) {
2128 LogFailure() << "symbol " << Sym
2129 << " isn't present in JD's symbol table.\n";
2130 }
2131 }
2132 }
2133 }
2134
2135 for (auto &[DepJD, Symbols] : EDU->Dependencies) {
2136 if (!llvm::is_contained(JDs, DepJD)) {
2137 LogFailure() << "dependant symbols listed for JD that isn't in "
2138 "ExecutionSession.\n";
2139 } else {
2140 for (auto &DepSym : Symbols) {
2141 if (!DepJD->Symbols.count(SymbolStringPtr(DepSym))) {
2142 LogFailure()
2143 << "dependant symbol " << DepSym
2144 << " does not appear in symbol table for dependant JD "
2145 << DepJD->getName() << ".\n";
2146 }
2147 }
2148 }
2149 }
2150 }
2151
2152 return AllOk;
2153 });
2154}
2155#endif // EXPENSIVE_CHECKS
2156
2157void ExecutionSession::dispatchOutstandingMUs() {
2158 LLVM_DEBUG(dbgs() << "Dispatching MaterializationUnits...\n");
2159 while (true) {
2160 std::optional<std::pair<std::unique_ptr<MaterializationUnit>,
2161 std::unique_ptr<MaterializationResponsibility>>>
2162 JMU;
2163
2164 {
2165 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2166 if (!OutstandingMUs.empty()) {
2167 JMU.emplace(std::move(OutstandingMUs.back()));
2168 OutstandingMUs.pop_back();
2169 }
2170 }
2171
2172 if (!JMU)
2173 break;
2174
2175 assert(JMU->first && "No MU?");
2176 LLVM_DEBUG(dbgs() << " Dispatching \"" << JMU->first->getName() << "\"\n");
2177 dispatchTask(std::make_unique<MaterializationTask>(std::move(JMU->first),
2178 std::move(JMU->second)));
2179 }
2180 LLVM_DEBUG(dbgs() << "Done dispatching MaterializationUnits.\n");
2181}
2182
2183Error ExecutionSession::removeResourceTracker(ResourceTracker &RT) {
2184 LLVM_DEBUG({
2185 dbgs() << "In " << RT.getJITDylib().getName() << " removing tracker "
2186 << formatv("{0:x}", RT.getKeyUnsafe()) << "\n";
2187 });
2188 std::vector<ResourceManager *> CurrentResourceManagers;
2189
2190 JITDylib::RemoveTrackerResult R;
2191
2192 runSessionLocked([&] {
2193 CurrentResourceManagers = ResourceManagers;
2194 RT.makeDefunct();
2195 R = RT.getJITDylib().IL_removeTracker(RT);
2196 });
2197
2198 // Release any defunct MaterializationUnits.
2199 R.DefunctMUs.clear();
2200
2201 Error Err = Error::success();
2202
2203 auto &JD = RT.getJITDylib();
2204 for (auto *L : reverse(CurrentResourceManagers))
2205 Err = joinErrors(std::move(Err),
2206 L->handleRemoveResources(JD, RT.getKeyUnsafe()));
2207
2208 for (auto &Q : R.QueriesToFail)
2209 Q->handleFailed(make_error<FailedToMaterialize>(getSymbolStringPool(),
2210 R.FailedSymbols));
2211
2212 return Err;
2213}
2214
2215void ExecutionSession::transferResourceTracker(ResourceTracker &DstRT,
2216 ResourceTracker &SrcRT) {
2217 LLVM_DEBUG({
2218 dbgs() << "In " << SrcRT.getJITDylib().getName()
2219 << " transfering resources from tracker "
2220 << formatv("{0:x}", SrcRT.getKeyUnsafe()) << " to tracker "
2221 << formatv("{0:x}", DstRT.getKeyUnsafe()) << "\n";
2222 });
2223
2224 // No-op transfers are allowed and do not invalidate the source.
2225 if (&DstRT == &SrcRT)
2226 return;
2227
2228 assert(&DstRT.getJITDylib() == &SrcRT.getJITDylib() &&
2229 "Can't transfer resources between JITDylibs");
2230 runSessionLocked([&]() {
2231 SrcRT.makeDefunct();
2232 auto &JD = DstRT.getJITDylib();
2233 JD.transferTracker(DstRT, SrcRT);
2234 for (auto *L : reverse(ResourceManagers))
2235 L->handleTransferResources(JD, DstRT.getKeyUnsafe(),
2236 SrcRT.getKeyUnsafe());
2237 });
2238}
2239
2240void ExecutionSession::destroyResourceTracker(ResourceTracker &RT) {
2241 runSessionLocked([&]() {
2242 LLVM_DEBUG({
2243 dbgs() << "In " << RT.getJITDylib().getName() << " destroying tracker "
2244 << formatv("{0:x}", RT.getKeyUnsafe()) << "\n";
2245 });
2246 if (!RT.isDefunct())
2247 transferResourceTracker(*RT.getJITDylib().getDefaultResourceTracker(),
2248 RT);
2249 });
2250}
2251
2252Error ExecutionSession::IL_updateCandidatesFor(
2253 JITDylib &JD, JITDylibLookupFlags JDLookupFlags,
2254 SymbolLookupSet &Candidates, SymbolLookupSet *NonCandidates) {
2255 return Candidates.forEachWithRemoval(
2256 [&](const SymbolStringPtr &Name,
2257 SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
2258 /// Search for the symbol. If not found then continue without
2259 /// removal.
2260 auto SymI = JD.Symbols.find(Name);
2261 if (SymI == JD.Symbols.end())
2262 return false;
2263
2264 // If this is a non-exported symbol and we're matching exported
2265 // symbols only then remove this symbol from the candidates list.
2266 //
2267 // If we're tracking non-candidates then add this to the non-candidate
2268 // list.
2269 if (!SymI->second.getFlags().isExported() &&
2271 if (NonCandidates)
2272 NonCandidates->add(Name, SymLookupFlags);
2273 return true;
2274 }
2275
2276 // If we match against a materialization-side-effects only symbol
2277 // then make sure it is weakly-referenced. Otherwise bail out with
2278 // an error.
2279 // FIXME: Use a "materialization-side-effects-only symbols must be
2280 // weakly referenced" specific error here to reduce confusion.
2281 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2283 return make_error<SymbolsNotFound>(getSymbolStringPool(),
2285
2286 // If we matched against this symbol but it is in the error state
2287 // then bail out and treat it as a failure to materialize.
2288 if (SymI->second.getFlags().hasError()) {
2289 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2290 (*FailedSymbolsMap)[&JD] = {Name};
2291 return make_error<FailedToMaterialize>(getSymbolStringPool(),
2292 std::move(FailedSymbolsMap));
2293 }
2294
2295 // Otherwise this is a match. Remove it from the candidate set.
2296 return true;
2297 });
2298}
2299
2300void ExecutionSession::OL_resumeLookupAfterGeneration(
2301 InProgressLookupState &IPLS) {
2302
2304 "Should not be called for not-in-generator lookups");
2306
2308
2309 if (auto DG = IPLS.CurDefGeneratorStack.back().lock()) {
2310 IPLS.CurDefGeneratorStack.pop_back();
2311 std::lock_guard<std::mutex> Lock(DG->M);
2312
2313 // If there are no pending lookups then mark the generator as free and
2314 // return.
2315 if (DG->PendingLookups.empty()) {
2316 DG->InUse = false;
2317 return;
2318 }
2319
2320 // Otherwise resume the next lookup.
2321 LS = std::move(DG->PendingLookups.front());
2322 DG->PendingLookups.pop_front();
2323 }
2324
2325 if (LS.IPLS) {
2327 dispatchTask(std::make_unique<LookupTask>(std::move(LS)));
2328 }
2329}
2330
2331void ExecutionSession::OL_applyQueryPhase1(
2332 std::unique_ptr<InProgressLookupState> IPLS, Error Err) {
2333
2334 LLVM_DEBUG({
2335 dbgs() << "Entering OL_applyQueryPhase1:\n"
2336 << " Lookup kind: " << IPLS->K << "\n"
2337 << " Search order: " << IPLS->SearchOrder
2338 << ", Current index = " << IPLS->CurSearchOrderIndex
2339 << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2340 << " Lookup set: " << IPLS->LookupSet << "\n"
2341 << " Definition generator candidates: "
2342 << IPLS->DefGeneratorCandidates << "\n"
2343 << " Definition generator non-candidates: "
2344 << IPLS->DefGeneratorNonCandidates << "\n";
2345 });
2346
2347 if (IPLS->GenState == InProgressLookupState::InGenerator)
2348 OL_resumeLookupAfterGeneration(*IPLS);
2349
2350 assert(IPLS->GenState != InProgressLookupState::InGenerator &&
2351 "Lookup should not be in InGenerator state here");
2352
2353 // FIXME: We should attach the query as we go: This provides a result in a
2354 // single pass in the common case where all symbols have already reached the
2355 // required state. The query could be detached again in the 'fail' method on
2356 // IPLS. Phase 2 would be reduced to collecting and dispatching the MUs.
2357
2358 while (IPLS->CurSearchOrderIndex != IPLS->SearchOrder.size()) {
2359
2360 // If we've been handed an error or received one back from a generator then
2361 // fail the query. We don't need to unlink: At this stage the query hasn't
2362 // actually been lodged.
2363 if (Err)
2364 return IPLS->fail(std::move(Err));
2365
2366 // Get the next JITDylib and lookup flags.
2367 auto &KV = IPLS->SearchOrder[IPLS->CurSearchOrderIndex];
2368 auto &JD = *KV.first;
2369 auto JDLookupFlags = KV.second;
2370
2371 LLVM_DEBUG({
2372 dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2373 << ") with lookup set " << IPLS->LookupSet << ":\n";
2374 });
2375
2376 // If we've just reached a new JITDylib then perform some setup.
2377 if (IPLS->NewJITDylib) {
2378 // Add any non-candidates from the last JITDylib (if any) back on to the
2379 // list of definition candidates for this JITDylib, reset definition
2380 // non-candidates to the empty set.
2381 SymbolLookupSet Tmp;
2382 std::swap(IPLS->DefGeneratorNonCandidates, Tmp);
2383 IPLS->DefGeneratorCandidates.append(std::move(Tmp));
2384
2385 LLVM_DEBUG({
2386 dbgs() << " First time visiting " << JD.getName()
2387 << ", resetting candidate sets and building generator stack\n";
2388 });
2389
2390 // Build the definition generator stack for this JITDylib.
2391 runSessionLocked([&] {
2392 IPLS->CurDefGeneratorStack.reserve(JD.DefGenerators.size());
2393 for (auto &DG : reverse(JD.DefGenerators))
2394 IPLS->CurDefGeneratorStack.push_back(DG);
2395 });
2396
2397 // Flag that we've done our initialization.
2398 IPLS->NewJITDylib = false;
2399 }
2400
2401 // Remove any generation candidates that are already defined (and match) in
2402 // this JITDylib.
2403 runSessionLocked([&] {
2404 // Update the list of candidates (and non-candidates) for definition
2405 // generation.
2406 LLVM_DEBUG(dbgs() << " Updating candidate set...\n");
2407 Err = IL_updateCandidatesFor(
2408 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2409 JD.DefGenerators.empty() ? nullptr
2410 : &IPLS->DefGeneratorNonCandidates);
2411 LLVM_DEBUG({
2412 dbgs() << " Remaining candidates = " << IPLS->DefGeneratorCandidates
2413 << "\n";
2414 });
2415
2416 // If this lookup was resumed after auto-suspension but all candidates
2417 // have already been generated (by some previous call to the generator)
2418 // treat the lookup as if it had completed generation.
2419 if (IPLS->GenState == InProgressLookupState::ResumedForGenerator &&
2420 IPLS->DefGeneratorCandidates.empty())
2421 OL_resumeLookupAfterGeneration(*IPLS);
2422 });
2423
2424 // If we encountered an error while filtering generation candidates then
2425 // bail out.
2426 if (Err)
2427 return IPLS->fail(std::move(Err));
2428
2429 /// Apply any definition generators on the stack.
2430 LLVM_DEBUG({
2431 if (IPLS->CurDefGeneratorStack.empty())
2432 LLVM_DEBUG(dbgs() << " No generators to run for this JITDylib.\n");
2433 else if (IPLS->DefGeneratorCandidates.empty())
2434 LLVM_DEBUG(dbgs() << " No candidates to generate.\n");
2435 else
2436 dbgs() << " Running " << IPLS->CurDefGeneratorStack.size()
2437 << " remaining generators for "
2438 << IPLS->DefGeneratorCandidates.size() << " candidates\n";
2439 });
2440 while (!IPLS->CurDefGeneratorStack.empty() &&
2441 !IPLS->DefGeneratorCandidates.empty()) {
2442 auto DG = IPLS->CurDefGeneratorStack.back().lock();
2443
2444 if (!DG)
2445 return IPLS->fail(make_error<StringError>(
2446 "DefinitionGenerator removed while lookup in progress",
2448
2449 // At this point the lookup is in either the NotInGenerator state, or in
2450 // the ResumedForGenerator state.
2451 // If this lookup is in the NotInGenerator state then check whether the
2452 // generator is in use. If the generator is not in use then move the
2453 // lookup to the InGenerator state and continue. If the generator is
2454 // already in use then just add this lookup to the pending lookups list
2455 // and bail out.
2456 // If this lookup is in the ResumedForGenerator state then just move it
2457 // to InGenerator and continue.
2458 if (IPLS->GenState == InProgressLookupState::NotInGenerator) {
2459 std::lock_guard<std::mutex> Lock(DG->M);
2460 if (DG->InUse) {
2461 DG->PendingLookups.push_back(std::move(IPLS));
2462 return;
2463 }
2464 DG->InUse = true;
2465 }
2466
2467 IPLS->GenState = InProgressLookupState::InGenerator;
2468
2469 auto K = IPLS->K;
2470 auto &LookupSet = IPLS->DefGeneratorCandidates;
2471
2472 // Run the generator. If the generator takes ownership of QA then this
2473 // will break the loop.
2474 {
2475 LLVM_DEBUG(dbgs() << " Attempting to generate " << LookupSet << "\n");
2476 LookupState LS(std::move(IPLS));
2477 Err = DG->tryToGenerate(LS, K, JD, JDLookupFlags, LookupSet);
2478 IPLS = std::move(LS.IPLS);
2479 }
2480
2481 // If the lookup returned then pop the generator stack and unblock the
2482 // next lookup on this generator (if any).
2483 if (IPLS)
2484 OL_resumeLookupAfterGeneration(*IPLS);
2485
2486 // If there was an error then fail the query.
2487 if (Err) {
2488 LLVM_DEBUG({
2489 dbgs() << " Error attempting to generate " << LookupSet << "\n";
2490 });
2491 assert(IPLS && "LS cannot be retained if error is returned");
2492 return IPLS->fail(std::move(Err));
2493 }
2494
2495 // Otherwise if QA was captured then break the loop.
2496 if (!IPLS) {
2497 LLVM_DEBUG(
2498 { dbgs() << " LookupState captured. Exiting phase1 for now.\n"; });
2499 return;
2500 }
2501
2502 // Otherwise if we're continuing around the loop then update candidates
2503 // for the next round.
2504 runSessionLocked([&] {
2505 LLVM_DEBUG(dbgs() << " Updating candidate set post-generation\n");
2506 Err = IL_updateCandidatesFor(
2507 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2508 JD.DefGenerators.empty() ? nullptr
2509 : &IPLS->DefGeneratorNonCandidates);
2510 });
2511
2512 // If updating candidates failed then fail the query.
2513 if (Err) {
2514 LLVM_DEBUG(dbgs() << " Error encountered while updating candidates\n");
2515 return IPLS->fail(std::move(Err));
2516 }
2517 }
2518
2519 if (IPLS->DefGeneratorCandidates.empty() &&
2520 IPLS->DefGeneratorNonCandidates.empty()) {
2521 // Early out if there are no remaining symbols.
2522 LLVM_DEBUG(dbgs() << "All symbols matched.\n");
2523 IPLS->CurSearchOrderIndex = IPLS->SearchOrder.size();
2524 break;
2525 } else {
2526 // If we get here then we've moved on to the next JITDylib with candidates
2527 // remaining.
2528 LLVM_DEBUG(dbgs() << "Phase 1 moving to next JITDylib.\n");
2529 ++IPLS->CurSearchOrderIndex;
2530 IPLS->NewJITDylib = true;
2531 }
2532 }
2533
2534 // Remove any weakly referenced candidates that could not be found/generated.
2535 IPLS->DefGeneratorCandidates.remove_if(
2536 [](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2537 return SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol;
2538 });
2539
2540 // If we get here then we've finished searching all JITDylibs.
2541 // If we matched all symbols then move to phase 2, otherwise fail the query
2542 // with a SymbolsNotFound error.
2543 if (IPLS->DefGeneratorCandidates.empty()) {
2544 LLVM_DEBUG(dbgs() << "Phase 1 succeeded.\n");
2545 IPLS->complete(std::move(IPLS));
2546 } else {
2547 LLVM_DEBUG(dbgs() << "Phase 1 failed with unresolved symbols.\n");
2548 IPLS->fail(make_error<SymbolsNotFound>(
2549 getSymbolStringPool(), IPLS->DefGeneratorCandidates.getSymbolNames()));
2550 }
2551}
2552
2553void ExecutionSession::OL_completeLookup(
2554 std::unique_ptr<InProgressLookupState> IPLS,
2555 std::shared_ptr<AsynchronousSymbolQuery> Q,
2556 RegisterDependenciesFunction RegisterDependencies) {
2557
2558 LLVM_DEBUG({
2559 dbgs() << "Entering OL_completeLookup:\n"
2560 << " Lookup kind: " << IPLS->K << "\n"
2561 << " Search order: " << IPLS->SearchOrder
2562 << ", Current index = " << IPLS->CurSearchOrderIndex
2563 << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2564 << " Lookup set: " << IPLS->LookupSet << "\n"
2565 << " Definition generator candidates: "
2566 << IPLS->DefGeneratorCandidates << "\n"
2567 << " Definition generator non-candidates: "
2568 << IPLS->DefGeneratorNonCandidates << "\n";
2569 });
2570
2571 bool QueryComplete = false;
2572 DenseMap<JITDylib *, JITDylib::UnmaterializedInfosList> CollectedUMIs;
2573
2574 auto LodgingErr = runSessionLocked([&]() -> Error {
2575 for (auto &KV : IPLS->SearchOrder) {
2576 auto &JD = *KV.first;
2577 auto JDLookupFlags = KV.second;
2578 LLVM_DEBUG({
2579 dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2580 << ") with lookup set " << IPLS->LookupSet << ":\n";
2581 });
2582
2583 auto Err = IPLS->LookupSet.forEachWithRemoval(
2584 [&](const SymbolStringPtr &Name,
2585 SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
2586 LLVM_DEBUG({
2587 dbgs() << " Attempting to match \"" << Name << "\" ("
2588 << SymLookupFlags << ")... ";
2589 });
2590
2591 /// Search for the symbol. If not found then continue without
2592 /// removal.
2593 auto SymI = JD.Symbols.find(Name);
2594 if (SymI == JD.Symbols.end()) {
2595 LLVM_DEBUG(dbgs() << "skipping: not present\n");
2596 return false;
2597 }
2598
2599 // If this is a non-exported symbol and we're matching exported
2600 // symbols only then skip this symbol without removal.
2601 if (!SymI->second.getFlags().isExported() &&
2602 JDLookupFlags ==
2604 LLVM_DEBUG(dbgs() << "skipping: not exported\n");
2605 return false;
2606 }
2607
2608 // If we match against a materialization-side-effects only symbol
2609 // then make sure it is weakly-referenced. Otherwise bail out with
2610 // an error.
2611 // FIXME: Use a "materialization-side-effects-only symbols must be
2612 // weakly referenced" specific error here to reduce confusion.
2613 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2615 LLVM_DEBUG({
2616 dbgs() << "error: "
2617 "required, but symbol is has-side-effects-only\n";
2618 });
2619 return make_error<SymbolsNotFound>(getSymbolStringPool(),
2621 }
2622
2623 // If we matched against this symbol but it is in the error state
2624 // then bail out and treat it as a failure to materialize.
2625 if (SymI->second.getFlags().hasError()) {
2626 LLVM_DEBUG(dbgs() << "error: symbol is in error state\n");
2627 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2628 (*FailedSymbolsMap)[&JD] = {Name};
2629 return make_error<FailedToMaterialize>(
2630 getSymbolStringPool(), std::move(FailedSymbolsMap));
2631 }
2632
2633 // Otherwise this is a match.
2634
2635 // If this symbol is already in the required state then notify the
2636 // query, remove the symbol and continue.
2637 if (SymI->second.getState() >= Q->getRequiredState()) {
2639 << "matched, symbol already in required state\n");
2640 Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
2641
2642 // If this symbol is in anything other than the Ready state then
2643 // we need to track the dependence.
2644 if (SymI->second.getState() != SymbolState::Ready)
2645 Q->addQueryDependence(JD, Name);
2646
2647 return true;
2648 }
2649
2650 // Otherwise this symbol does not yet meet the required state. Check
2651 // whether it has a materializer attached, and if so prepare to run
2652 // it.
2653 if (SymI->second.hasMaterializerAttached()) {
2654 assert(SymI->second.getAddress() == ExecutorAddr() &&
2655 "Symbol not resolved but already has address?");
2656 auto UMII = JD.UnmaterializedInfos.find(Name);
2657 assert(UMII != JD.UnmaterializedInfos.end() &&
2658 "Lazy symbol should have UnmaterializedInfo");
2659
2660 auto UMI = UMII->second;
2661 assert(UMI->MU && "Materializer should not be null");
2662 assert(UMI->RT && "Tracker should not be null");
2663 LLVM_DEBUG({
2664 dbgs() << "matched, preparing to dispatch MU@" << UMI->MU.get()
2665 << " (" << UMI->MU->getName() << ")\n";
2666 });
2667
2668 // Move all symbols associated with this MaterializationUnit into
2669 // materializing state.
2670 for (auto &KV : UMI->MU->getSymbols()) {
2671 auto SymK = JD.Symbols.find(KV.first);
2672 assert(SymK != JD.Symbols.end() &&
2673 "No entry for symbol covered by MaterializationUnit");
2674 SymK->second.setMaterializerAttached(false);
2675 SymK->second.setState(SymbolState::Materializing);
2676 JD.UnmaterializedInfos.erase(KV.first);
2677 }
2678
2679 // Add MU to the list of MaterializationUnits to be materialized.
2680 CollectedUMIs[&JD].push_back(std::move(UMI));
2681 } else
2682 LLVM_DEBUG(dbgs() << "matched, registering query");
2683
2684 // Add the query to the PendingQueries list and continue, deleting
2685 // the element from the lookup set.
2686 assert(SymI->second.getState() != SymbolState::NeverSearched &&
2687 SymI->second.getState() != SymbolState::Ready &&
2688 "By this line the symbol should be materializing");
2689 auto &MI = JD.MaterializingInfos[Name];
2690 MI.addQuery(Q);
2691 Q->addQueryDependence(JD, Name);
2692
2693 return true;
2694 });
2695
2696 JD.shrinkMaterializationInfoMemory();
2697
2698 // Handle failure.
2699 if (Err) {
2700
2701 LLVM_DEBUG({
2702 dbgs() << "Lookup failed. Detaching query and replacing MUs.\n";
2703 });
2704
2705 // Detach the query.
2706 Q->detach();
2707
2708 // Replace the MUs.
2709 for (auto &KV : CollectedUMIs) {
2710 auto &JD = *KV.first;
2711 for (auto &UMI : KV.second)
2712 for (auto &KV2 : UMI->MU->getSymbols()) {
2713 assert(!JD.UnmaterializedInfos.count(KV2.first) &&
2714 "Unexpected materializer in map");
2715 auto SymI = JD.Symbols.find(KV2.first);
2716 assert(SymI != JD.Symbols.end() && "Missing symbol entry");
2717 assert(SymI->second.getState() == SymbolState::Materializing &&
2718 "Can not replace symbol that is not materializing");
2719 assert(!SymI->second.hasMaterializerAttached() &&
2720 "MaterializerAttached flag should not be set");
2721 SymI->second.setMaterializerAttached(true);
2722 JD.UnmaterializedInfos[KV2.first] = UMI;
2723 }
2724 }
2725
2726 return Err;
2727 }
2728 }
2729
2730 LLVM_DEBUG(dbgs() << "Stripping unmatched weakly-referenced symbols\n");
2731 IPLS->LookupSet.forEachWithRemoval(
2732 [&](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2733 if (SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol) {
2734 Q->dropSymbol(Name);
2735 return true;
2736 } else
2737 return false;
2738 });
2739
2740 if (!IPLS->LookupSet.empty()) {
2741 LLVM_DEBUG(dbgs() << "Failing due to unresolved symbols\n");
2742 return make_error<SymbolsNotFound>(getSymbolStringPool(),
2743 IPLS->LookupSet.getSymbolNames());
2744 }
2745
2746 // Record whether the query completed.
2747 QueryComplete = Q->isComplete();
2748
2749 LLVM_DEBUG({
2750 dbgs() << "Query successfully "
2751 << (QueryComplete ? "completed" : "lodged") << "\n";
2752 });
2753
2754 // Move the collected MUs to the OutstandingMUs list.
2755 if (!CollectedUMIs.empty()) {
2756 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2757
2758 LLVM_DEBUG(dbgs() << "Adding MUs to dispatch:\n");
2759 for (auto &KV : CollectedUMIs) {
2760 LLVM_DEBUG({
2761 auto &JD = *KV.first;
2762 dbgs() << " For " << JD.getName() << ": Adding " << KV.second.size()
2763 << " MUs.\n";
2764 });
2765 for (auto &UMI : KV.second) {
2766 auto MR = createMaterializationResponsibility(
2767 *UMI->RT, std::move(UMI->MU->SymbolFlags),
2768 std::move(UMI->MU->InitSymbol));
2769 OutstandingMUs.push_back(
2770 std::make_pair(std::move(UMI->MU), std::move(MR)));
2771 }
2772 }
2773 } else
2774 LLVM_DEBUG(dbgs() << "No MUs to dispatch.\n");
2775
2776 if (RegisterDependencies && !Q->QueryRegistrations.empty()) {
2777 LLVM_DEBUG(dbgs() << "Registering dependencies\n");
2778 RegisterDependencies(Q->QueryRegistrations);
2779 } else
2780 LLVM_DEBUG(dbgs() << "No dependencies to register\n");
2781
2782 return Error::success();
2783 });
2784
2785 if (LodgingErr) {
2786 LLVM_DEBUG(dbgs() << "Failing query\n");
2787 Q->detach();
2788 Q->handleFailed(std::move(LodgingErr));
2789 return;
2790 }
2791
2792 if (QueryComplete) {
2793 LLVM_DEBUG(dbgs() << "Completing query\n");
2794 Q->handleComplete(*this);
2795 }
2796
2797 dispatchOutstandingMUs();
2798}
2799
2800void ExecutionSession::OL_completeLookupFlags(
2801 std::unique_ptr<InProgressLookupState> IPLS,
2802 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete) {
2803
2804 auto Result = runSessionLocked([&]() -> Expected<SymbolFlagsMap> {
2805 LLVM_DEBUG({
2806 dbgs() << "Entering OL_completeLookupFlags:\n"
2807 << " Lookup kind: " << IPLS->K << "\n"
2808 << " Search order: " << IPLS->SearchOrder
2809 << ", Current index = " << IPLS->CurSearchOrderIndex
2810 << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2811 << " Lookup set: " << IPLS->LookupSet << "\n"
2812 << " Definition generator candidates: "
2813 << IPLS->DefGeneratorCandidates << "\n"
2814 << " Definition generator non-candidates: "
2815 << IPLS->DefGeneratorNonCandidates << "\n";
2816 });
2817
2819
2820 // Attempt to find flags for each symbol.
2821 for (auto &KV : IPLS->SearchOrder) {
2822 auto &JD = *KV.first;
2823 auto JDLookupFlags = KV.second;
2824 LLVM_DEBUG({
2825 dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2826 << ") with lookup set " << IPLS->LookupSet << ":\n";
2827 });
2828
2829 IPLS->LookupSet.forEachWithRemoval([&](const SymbolStringPtr &Name,
2830 SymbolLookupFlags SymLookupFlags) {
2831 LLVM_DEBUG({
2832 dbgs() << " Attempting to match \"" << Name << "\" ("
2833 << SymLookupFlags << ")... ";
2834 });
2835
2836 // Search for the symbol. If not found then continue without removing
2837 // from the lookup set.
2838 auto SymI = JD.Symbols.find(Name);
2839 if (SymI == JD.Symbols.end()) {
2840 LLVM_DEBUG(dbgs() << "skipping: not present\n");
2841 return false;
2842 }
2843
2844 // If this is a non-exported symbol then it doesn't match. Skip it.
2845 if (!SymI->second.getFlags().isExported() &&
2847 LLVM_DEBUG(dbgs() << "skipping: not exported\n");
2848 return false;
2849 }
2850
2851 LLVM_DEBUG({
2852 dbgs() << "matched, \"" << Name << "\" -> " << SymI->second.getFlags()
2853 << "\n";
2854 });
2855 Result[Name] = SymI->second.getFlags();
2856 return true;
2857 });
2858 }
2859
2860 // Remove any weakly referenced symbols that haven't been resolved.
2861 IPLS->LookupSet.remove_if(
2862 [](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2863 return SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol;
2864 });
2865
2866 if (!IPLS->LookupSet.empty()) {
2867 LLVM_DEBUG(dbgs() << "Failing due to unresolved symbols\n");
2868 return make_error<SymbolsNotFound>(getSymbolStringPool(),
2869 IPLS->LookupSet.getSymbolNames());
2870 }
2871
2872 LLVM_DEBUG(dbgs() << "Succeded, result = " << Result << "\n");
2873 return Result;
2874 });
2875
2876 // Run the callback on the result.
2877 LLVM_DEBUG(dbgs() << "Sending result to handler.\n");
2878 OnComplete(std::move(Result));
2879}
2880
2881void ExecutionSession::OL_destroyMaterializationResponsibility(
2882 MaterializationResponsibility &MR) {
2883
2884 assert(MR.SymbolFlags.empty() &&
2885 "All symbols should have been explicitly materialized or failed");
2886 MR.JD.unlinkMaterializationResponsibility(MR);
2887}
2888
2889SymbolNameSet ExecutionSession::OL_getRequestedSymbols(
2890 const MaterializationResponsibility &MR) {
2891 return MR.JD.getRequestedSymbols(MR.SymbolFlags);
2892}
2893
2894Error ExecutionSession::OL_notifyResolved(MaterializationResponsibility &MR,
2895 const SymbolMap &Symbols) {
2896 LLVM_DEBUG({
2897 dbgs() << "In " << MR.JD.getName() << " resolving " << Symbols << "\n";
2898 });
2899#ifndef NDEBUG
2900 for (auto &KV : Symbols) {
2901 auto I = MR.SymbolFlags.find(KV.first);
2902 assert(I != MR.SymbolFlags.end() &&
2903 "Resolving symbol outside this responsibility set");
2904 assert(!I->second.hasMaterializationSideEffectsOnly() &&
2905 "Can't resolve materialization-side-effects-only symbol");
2906 if (I->second & JITSymbolFlags::Common) {
2907 auto WeakOrCommon = JITSymbolFlags::Weak | JITSymbolFlags::Common;
2908 assert((KV.second.getFlags() & WeakOrCommon) &&
2909 "Common symbols must be resolved as common or weak");
2910 assert((KV.second.getFlags() & ~WeakOrCommon) ==
2911 (I->second & ~JITSymbolFlags::Common) &&
2912 "Resolving symbol with incorrect flags");
2913 } else
2914 assert(KV.second.getFlags() == I->second &&
2915 "Resolving symbol with incorrect flags");
2916 }
2917#endif
2918
2919 return MR.JD.resolve(MR, Symbols);
2920}
2921
2922template <typename HandleNewDepFn>
2923void ExecutionSession::propagateExtraEmitDeps(
2924 std::deque<JITDylib::EmissionDepUnit *> Worklist, EDUInfosMap &EDUInfos,
2925 HandleNewDepFn HandleNewDep) {
2926
2927 // Iterate to a fixed-point to propagate extra-emit dependencies through the
2928 // EDU graph.
2929 while (!Worklist.empty()) {
2930 auto &EDU = *Worklist.front();
2931 Worklist.pop_front();
2932
2933 assert(EDUInfos.count(&EDU) && "No info entry for EDU");
2934 auto &EDUInfo = EDUInfos[&EDU];
2935
2936 // Propagate new dependencies to users.
2937 for (auto *UserEDU : EDUInfo.IntraEmitUsers) {
2938
2939 // UserEDUInfo only present if UserEDU has its own users.
2940 JITDylib::EmissionDepUnitInfo *UserEDUInfo = nullptr;
2941 {
2942 auto UserEDUInfoItr = EDUInfos.find(UserEDU);
2943 if (UserEDUInfoItr != EDUInfos.end())
2944 UserEDUInfo = &UserEDUInfoItr->second;
2945 }
2946
2947 for (auto &[DepJD, Deps] : EDUInfo.NewDeps) {
2948 auto &UserEDUDepsForJD = UserEDU->Dependencies[DepJD];
2949 DenseSet<NonOwningSymbolStringPtr> *UserEDUNewDepsForJD = nullptr;
2950 for (auto Dep : Deps) {
2951 if (UserEDUDepsForJD.insert(Dep).second) {
2952 HandleNewDep(*UserEDU, *DepJD, Dep);
2953 if (UserEDUInfo) {
2954 if (!UserEDUNewDepsForJD) {
2955 // If UserEDU has no new deps then it's not in the worklist
2956 // yet, so add it.
2957 if (UserEDUInfo->NewDeps.empty())
2958 Worklist.push_back(UserEDU);
2959 UserEDUNewDepsForJD = &UserEDUInfo->NewDeps[DepJD];
2960 }
2961 // Add (DepJD, Dep) to NewDeps.
2962 UserEDUNewDepsForJD->insert(Dep);
2963 }
2964 }
2965 }
2966 }
2967 }
2968
2969 EDUInfo.NewDeps.clear();
2970 }
2971}
2972
2973// Note: This method modifies the emitted set.
2974ExecutionSession::EDUInfosMap ExecutionSession::simplifyDepGroups(
2975 MaterializationResponsibility &MR,
2976 ArrayRef<SymbolDependenceGroup> EmittedDeps) {
2977
2978 auto &TargetJD = MR.getTargetJITDylib();
2979
2980 // 1. Build initial EmissionDepUnit -> EmissionDepUnitInfo and
2981 // Symbol -> EmissionDepUnit mappings.
2982 DenseMap<JITDylib::EmissionDepUnit *, JITDylib::EmissionDepUnitInfo> EDUInfos;
2983 EDUInfos.reserve(EmittedDeps.size());
2984 DenseMap<NonOwningSymbolStringPtr, JITDylib::EmissionDepUnit *> EDUForSymbol;
2985 for (auto &DG : EmittedDeps) {
2986 assert(!DG.Symbols.empty() && "DepGroup does not cover any symbols");
2987
2988 // Skip empty EDUs.
2989 if (DG.Dependencies.empty())
2990 continue;
2991
2992 auto TmpEDU = std::make_shared<JITDylib::EmissionDepUnit>(TargetJD);
2993 auto &EDUInfo = EDUInfos[TmpEDU.get()];
2994 EDUInfo.EDU = std::move(TmpEDU);
2995 for (const auto &Symbol : DG.Symbols) {
2996 NonOwningSymbolStringPtr NonOwningSymbol(Symbol);
2997 assert(!EDUForSymbol.count(NonOwningSymbol) &&
2998 "Symbol should not appear in more than one SymbolDependenceGroup");
2999 assert(MR.getSymbols().count(Symbol) &&
3000 "Symbol in DepGroups not in the emitted set");
3001 auto NewlyEmittedItr = MR.getSymbols().find(Symbol);
3002 EDUInfo.EDU->Symbols[NonOwningSymbol] = NewlyEmittedItr->second;
3003 EDUForSymbol[NonOwningSymbol] = EDUInfo.EDU.get();
3004 }
3005 }
3006
3007 // 2. Build a "residual" EDU to cover all symbols that have no dependencies.
3008 {
3009 DenseMap<NonOwningSymbolStringPtr, JITSymbolFlags> ResidualSymbolFlags;
3010 for (auto &[Sym, Flags] : MR.getSymbols()) {
3011 if (!EDUForSymbol.count(NonOwningSymbolStringPtr(Sym)))
3012 ResidualSymbolFlags[NonOwningSymbolStringPtr(Sym)] = Flags;
3013 }
3014 if (!ResidualSymbolFlags.empty()) {
3015 auto ResidualEDU = std::make_shared<JITDylib::EmissionDepUnit>(TargetJD);
3016 ResidualEDU->Symbols = std::move(ResidualSymbolFlags);
3017 auto &ResidualEDUInfo = EDUInfos[ResidualEDU.get()];
3018 ResidualEDUInfo.EDU = std::move(ResidualEDU);
3019
3020 // If the residual EDU is the only one then bail out early.
3021 if (EDUInfos.size() == 1)
3022 return EDUInfos;
3023
3024 // Otherwise add the residual EDU to the EDUForSymbol map.
3025 for (auto &[Sym, Flags] : ResidualEDUInfo.EDU->Symbols)
3026 EDUForSymbol[Sym] = ResidualEDUInfo.EDU.get();
3027 }
3028 }
3029
3030#ifndef NDEBUG
3031 assert(EDUForSymbol.size() == MR.getSymbols().size() &&
3032 "MR symbols not fully covered by EDUs?");
3033 for (auto &[Sym, Flags] : MR.getSymbols()) {
3034 assert(EDUForSymbol.count(NonOwningSymbolStringPtr(Sym)) &&
3035 "Sym in MR not covered by EDU");
3036 }
3037#endif // NDEBUG
3038
3039 // 3. Use the DepGroups array to build a graph of dependencies between
3040 // EmissionDepUnits in this finalization. We want to remove these
3041 // intra-finalization uses, propagating dependencies on symbols outside
3042 // this finalization. Add EDUs to the worklist.
3043 for (auto &DG : EmittedDeps) {
3044
3045 // Skip SymbolDependenceGroups with no dependencies.
3046 if (DG.Dependencies.empty())
3047 continue;
3048
3049 assert(EDUForSymbol.count(NonOwningSymbolStringPtr(*DG.Symbols.begin())) &&
3050 "No EDU for DG");
3051 auto &EDU =
3052 *EDUForSymbol.find(NonOwningSymbolStringPtr(*DG.Symbols.begin()))
3053 ->second;
3054
3055 for (auto &[DepJD, Deps] : DG.Dependencies) {
3056 DenseSet<NonOwningSymbolStringPtr> NewDepsForJD;
3057
3058 assert(!Deps.empty() && "Dependence set for DepJD is empty");
3059
3060 if (DepJD != &TargetJD) {
3061 // DepJD is some other JITDylib.There can't be any intra-finalization
3062 // edges here, so just skip.
3063 for (auto &Dep : Deps)
3064 NewDepsForJD.insert(NonOwningSymbolStringPtr(Dep));
3065 } else {
3066 // DepJD is the Target JITDylib. Check for intra-finaliztaion edges,
3067 // skipping any and recording the intra-finalization use instead.
3068 for (auto &Dep : Deps) {
3069 NonOwningSymbolStringPtr NonOwningDep(Dep);
3070 auto I = EDUForSymbol.find(NonOwningDep);
3071 if (I == EDUForSymbol.end()) {
3072 if (!MR.getSymbols().count(Dep))
3073 NewDepsForJD.insert(NonOwningDep);
3074 continue;
3075 }
3076
3077 if (I->second != &EDU)
3078 EDUInfos[I->second].IntraEmitUsers.insert(&EDU);
3079 }
3080 }
3081
3082 if (!NewDepsForJD.empty())
3083 EDU.Dependencies[DepJD] = std::move(NewDepsForJD);
3084 }
3085 }
3086
3087 // 4. Build the worklist.
3088 std::deque<JITDylib::EmissionDepUnit *> Worklist;
3089 for (auto &[EDU, EDUInfo] : EDUInfos) {
3090 // If this EDU has extra-finalization dependencies and intra-finalization
3091 // users then add it to the worklist.
3092 if (!EDU->Dependencies.empty()) {
3093 auto I = EDUInfos.find(EDU);
3094 if (I != EDUInfos.end()) {
3095 auto &EDUInfo = I->second;
3096 if (!EDUInfo.IntraEmitUsers.empty()) {
3097 EDUInfo.NewDeps = EDU->Dependencies;
3098 Worklist.push_back(EDU);
3099 }
3100 }
3101 }
3102 }
3103
3104 // 4. Propagate dependencies through the EDU graph.
3105 propagateExtraEmitDeps(
3106 Worklist, EDUInfos,
3107 [](JITDylib::EmissionDepUnit &, JITDylib &, NonOwningSymbolStringPtr) {});
3108
3109 return EDUInfos;
3110}
3111
3112void ExecutionSession::IL_makeEDUReady(
3113 std::shared_ptr<JITDylib::EmissionDepUnit> EDU,
3114 JITDylib::AsynchronousSymbolQuerySet &Queries) {
3115
3116 // The symbols for this EDU are ready.
3117 auto &JD = *EDU->JD;
3118
3119 for (auto &[Sym, Flags] : EDU->Symbols) {
3120 assert(JD.Symbols.count(SymbolStringPtr(Sym)) &&
3121 "JD does not have an entry for Sym");
3122 auto &Entry = JD.Symbols[SymbolStringPtr(Sym)];
3123
3124 assert(((Entry.getFlags().hasMaterializationSideEffectsOnly() &&
3125 Entry.getState() == SymbolState::Materializing) ||
3126 Entry.getState() == SymbolState::Resolved ||
3127 Entry.getState() == SymbolState::Emitted) &&
3128 "Emitting from state other than Resolved");
3129
3130 Entry.setState(SymbolState::Ready);
3131
3132 auto MII = JD.MaterializingInfos.find(SymbolStringPtr(Sym));
3133
3134 // Check for pending queries.
3135 if (MII == JD.MaterializingInfos.end())
3136 continue;
3137 auto &MI = MII->second;
3138
3139 for (auto &Q : MI.takeQueriesMeeting(SymbolState::Ready)) {
3140 Q->notifySymbolMetRequiredState(SymbolStringPtr(Sym), Entry.getSymbol());
3141 if (Q->isComplete())
3142 Queries.insert(Q);
3143 Q->removeQueryDependence(JD, SymbolStringPtr(Sym));
3144 }
3145
3146 JD.MaterializingInfos.erase(MII);
3147 }
3148
3149 JD.shrinkMaterializationInfoMemory();
3150}
3151
3152void ExecutionSession::IL_makeEDUEmitted(
3153 std::shared_ptr<JITDylib::EmissionDepUnit> EDU,
3154 JITDylib::AsynchronousSymbolQuerySet &Queries) {
3155
3156 // The symbols for this EDU are emitted, but not ready.
3157 auto &JD = *EDU->JD;
3158
3159 for (auto &[Sym, Flags] : EDU->Symbols) {
3160 assert(JD.Symbols.count(SymbolStringPtr(Sym)) &&
3161 "JD does not have an entry for Sym");
3162 auto &Entry = JD.Symbols[SymbolStringPtr(Sym)];
3163
3164 assert(((Entry.getFlags().hasMaterializationSideEffectsOnly() &&
3165 Entry.getState() == SymbolState::Materializing) ||
3166 Entry.getState() == SymbolState::Resolved ||
3167 Entry.getState() == SymbolState::Emitted) &&
3168 "Emitting from state other than Resolved");
3169
3170 if (Entry.getState() == SymbolState::Emitted) {
3171 // This was already emitted, so we can skip the rest of this loop.
3172#ifndef NDEBUG
3173 for (auto &[Sym, Flags] : EDU->Symbols) {
3174 assert(JD.Symbols.count(SymbolStringPtr(Sym)) &&
3175 "JD does not have an entry for Sym");
3176 auto &Entry = JD.Symbols[SymbolStringPtr(Sym)];
3177 assert(Entry.getState() == SymbolState::Emitted &&
3178 "Symbols for EDU in inconsistent state");
3179 assert(JD.MaterializingInfos.count(SymbolStringPtr(Sym)) &&
3180 "Emitted symbol has no MI");
3181 auto MI = JD.MaterializingInfos[SymbolStringPtr(Sym)];
3182 assert(MI.takeQueriesMeeting(SymbolState::Emitted).empty() &&
3183 "Already-emitted symbol has waiting-on-emitted queries");
3184 }
3185#endif // NDEBUG
3186 break;
3187 }
3188
3189 Entry.setState(SymbolState::Emitted);
3190 auto &MI = JD.MaterializingInfos[SymbolStringPtr(Sym)];
3191 MI.DefiningEDU = EDU;
3192
3193 for (auto &Q : MI.takeQueriesMeeting(SymbolState::Emitted)) {
3194 Q->notifySymbolMetRequiredState(SymbolStringPtr(Sym), Entry.getSymbol());
3195 if (Q->isComplete())
3196 Queries.insert(Q);
3197 }
3198 }
3199
3200 for (auto &[DepJD, Deps] : EDU->Dependencies) {
3201 for (auto &Dep : Deps)
3202 DepJD->MaterializingInfos[SymbolStringPtr(Dep)].DependantEDUs.insert(
3203 EDU.get());
3204 }
3205}
3206
3207/// Removes the given dependence from EDU. If EDU's dependence set becomes
3208/// empty then this function adds an entry for it to the EDUInfos map.
3209/// Returns true if a new EDUInfosMap entry is added.
3210bool ExecutionSession::IL_removeEDUDependence(JITDylib::EmissionDepUnit &EDU,
3211 JITDylib &DepJD,
3212 NonOwningSymbolStringPtr DepSym,
3213 EDUInfosMap &EDUInfos) {
3214 assert(EDU.Dependencies.count(&DepJD) &&
3215 "JD does not appear in Dependencies of DependantEDU");
3216 assert(EDU.Dependencies[&DepJD].count(DepSym) &&
3217 "Symbol does not appear in Dependencies of DependantEDU");
3218 auto &JDDeps = EDU.Dependencies[&DepJD];
3219 JDDeps.erase(DepSym);
3220 if (JDDeps.empty()) {
3221 EDU.Dependencies.erase(&DepJD);
3222 if (EDU.Dependencies.empty()) {
3223 // If the dependencies set has become empty then EDU _may_ be ready
3224 // (we won't know for sure until we've propagated the extra-emit deps).
3225 // Create an EDUInfo for it (if it doesn't have one already) so that
3226 // it'll be visited after propagation.
3227 auto &DepEDUInfo = EDUInfos[&EDU];
3228 if (!DepEDUInfo.EDU) {
3229 assert(EDU.JD->Symbols.count(
3230 SymbolStringPtr(EDU.Symbols.begin()->first)) &&
3231 "Missing symbol entry for first symbol in EDU");
3232 auto DepEDUFirstMI = EDU.JD->MaterializingInfos.find(
3233 SymbolStringPtr(EDU.Symbols.begin()->first));
3234 assert(DepEDUFirstMI != EDU.JD->MaterializingInfos.end() &&
3235 "Missing MI for first symbol in DependantEDU");
3236 DepEDUInfo.EDU = DepEDUFirstMI->second.DefiningEDU;
3237 return true;
3238 }
3239 }
3240 }
3241 return false;
3242}
3243
3244Error ExecutionSession::makeJDClosedError(JITDylib::EmissionDepUnit &EDU,
3245 JITDylib &ClosedJD) {
3246 SymbolNameSet FailedSymbols;
3247 for (auto &[Sym, Flags] : EDU.Symbols)
3248 FailedSymbols.insert(SymbolStringPtr(Sym));
3249 SymbolDependenceMap BadDeps;
3250 for (auto &Dep : EDU.Dependencies[&ClosedJD])
3251 BadDeps[&ClosedJD].insert(SymbolStringPtr(Dep));
3252 return make_error<UnsatisfiedSymbolDependencies>(
3253 ClosedJD.getExecutionSession().getSymbolStringPool(), EDU.JD,
3254 std::move(FailedSymbols), std::move(BadDeps),
3255 ClosedJD.getName() + " is closed");
3256}
3257
3258Error ExecutionSession::makeUnsatisfiedDepsError(JITDylib::EmissionDepUnit &EDU,
3259 JITDylib &BadJD,
3260 SymbolNameSet BadDeps) {
3261 SymbolNameSet FailedSymbols;
3262 for (auto &[Sym, Flags] : EDU.Symbols)
3263 FailedSymbols.insert(SymbolStringPtr(Sym));
3264 SymbolDependenceMap BadDepsMap;
3265 BadDepsMap[&BadJD] = std::move(BadDeps);
3266 return make_error<UnsatisfiedSymbolDependencies>(
3267 BadJD.getExecutionSession().getSymbolStringPool(), &BadJD,
3268 std::move(FailedSymbols), std::move(BadDepsMap),
3269 "dependencies removed or in error state");
3270}
3271
3272Expected<JITDylib::AsynchronousSymbolQuerySet>
3273ExecutionSession::IL_emit(MaterializationResponsibility &MR,
3274 EDUInfosMap EDUInfos) {
3275
3276 if (MR.RT->isDefunct())
3277 return make_error<ResourceTrackerDefunct>(MR.RT);
3278
3279 auto &TargetJD = MR.getTargetJITDylib();
3280 if (TargetJD.State != JITDylib::Open)
3281 return make_error<StringError>("JITDylib " + TargetJD.getName() +
3282 " is defunct",
3284#ifdef EXPENSIVE_CHECKS
3285 verifySessionState("entering ExecutionSession::IL_emit");
3286#endif
3287
3288 // Walk all EDUs:
3289 // 1. Verifying that dependencies are available (not removed or in the error
3290 // state.
3291 // 2. Removing any dependencies that are already Ready.
3292 // 3. Lifting any EDUs for Emitted symbols into the EDUInfos map.
3293 // 4. Finding any dependant EDUs and lifting them into the EDUInfos map.
3294 std::deque<JITDylib::EmissionDepUnit *> Worklist;
3295 for (auto &[EDU, _] : EDUInfos)
3296 Worklist.push_back(EDU);
3297
3298 for (auto *EDU : Worklist) {
3299 auto *EDUInfo = &EDUInfos[EDU];
3300
3301 SmallVector<JITDylib *> DepJDsToRemove;
3302 for (auto &[DepJD, Deps] : EDU->Dependencies) {
3303 if (DepJD->State != JITDylib::Open)
3304 return makeJDClosedError(*EDU, *DepJD);
3305
3306 SymbolNameSet BadDeps;
3307 SmallVector<NonOwningSymbolStringPtr> DepsToRemove;
3308 for (auto &Dep : Deps) {
3309 auto DepEntryItr = DepJD->Symbols.find(SymbolStringPtr(Dep));
3310
3311 // If this dep has been removed or moved to the error state then add it
3312 // to the bad deps set. We aggregate these bad deps for more
3313 // comprehensive error messages.
3314 if (DepEntryItr == DepJD->Symbols.end() ||
3315 DepEntryItr->second.getFlags().hasError()) {
3316 BadDeps.insert(SymbolStringPtr(Dep));
3317 continue;
3318 }
3319
3320 // If this dep isn't emitted yet then just add it to the NewDeps set to
3321 // be propagated.
3322 auto &DepEntry = DepEntryItr->second;
3323 if (DepEntry.getState() < SymbolState::Emitted) {
3324 EDUInfo->NewDeps[DepJD].insert(Dep);
3325 continue;
3326 }
3327
3328 // This dep has been emitted, so add it to the list to be removed from
3329 // EDU.
3330 DepsToRemove.push_back(Dep);
3331
3332 // If Dep is Ready then there's nothing further to do.
3333 if (DepEntry.getState() == SymbolState::Ready) {
3334 assert(!DepJD->MaterializingInfos.count(SymbolStringPtr(Dep)) &&
3335 "Unexpected MaterializationInfo attached to ready symbol");
3336 continue;
3337 }
3338
3339 // If we get here then Dep is Emitted. We need to look up its defining
3340 // EDU and add this EDU to the defining EDU's list of users (this means
3341 // creating an EDUInfos entry if the defining EDU doesn't have one
3342 // already).
3343 assert(DepJD->MaterializingInfos.count(SymbolStringPtr(Dep)) &&
3344 "Expected MaterializationInfo for emitted dependency");
3345 auto &DepMI = DepJD->MaterializingInfos[SymbolStringPtr(Dep)];
3346 assert(DepMI.DefiningEDU &&
3347 "Emitted symbol does not have a defining EDU");
3348 assert(DepMI.DependantEDUs.empty() &&
3349 "Already-emitted symbol has dependant EDUs?");
3350 auto &DepEDUInfo = EDUInfos[DepMI.DefiningEDU.get()];
3351 if (!DepEDUInfo.EDU) {
3352 // No EDUInfo yet -- build initial entry, and reset the EDUInfo
3353 // pointer, which we will have invalidated.
3354 EDUInfo = &EDUInfos[EDU];
3355 DepEDUInfo.EDU = DepMI.DefiningEDU;
3356 for (auto &[DepDepJD, DepDeps] : DepEDUInfo.EDU->Dependencies) {
3357 if (DepDepJD == &TargetJD) {
3358 for (auto &DepDep : DepDeps)
3359 if (!MR.getSymbols().count(SymbolStringPtr(DepDep)))
3360 DepEDUInfo.NewDeps[DepDepJD].insert(DepDep);
3361 } else
3362 DepEDUInfo.NewDeps[DepDepJD] = DepDeps;
3363 }
3364 }
3365 DepEDUInfo.IntraEmitUsers.insert(EDU);
3366 }
3367
3368 // Some dependencies were removed or in an error state -- error out.
3369 if (!BadDeps.empty())
3370 return makeUnsatisfiedDepsError(*EDU, *DepJD, std::move(BadDeps));
3371
3372 // Remove the emitted / ready deps from DepJD.
3373 for (auto &Dep : DepsToRemove)
3374 Deps.erase(Dep);
3375
3376 // If there are no further deps in DepJD then flag it for removal too.
3377 if (Deps.empty())
3378 DepJDsToRemove.push_back(DepJD);
3379 }
3380
3381 // Remove any JDs whose dependence sets have become empty.
3382 for (auto &DepJD : DepJDsToRemove) {
3383 assert(EDU->Dependencies.count(DepJD) &&
3384 "Trying to remove non-existent dep entries");
3385 EDU->Dependencies.erase(DepJD);
3386 }
3387
3388 // Now look for users of this EDU.
3389 for (auto &[Sym, Flags] : EDU->Symbols) {
3390 assert(TargetJD.Symbols.count(SymbolStringPtr(Sym)) &&
3391 "Sym not present in symbol table");
3392 assert((TargetJD.Symbols[SymbolStringPtr(Sym)].getState() ==
3394 TargetJD.Symbols[SymbolStringPtr(Sym)]
3395 .getFlags()
3396 .hasMaterializationSideEffectsOnly()) &&
3397 "Emitting symbol not in the resolved state");
3398 assert(!TargetJD.Symbols[SymbolStringPtr(Sym)].getFlags().hasError() &&
3399 "Symbol is already in an error state");
3400
3401 auto MII = TargetJD.MaterializingInfos.find(SymbolStringPtr(Sym));
3402 if (MII == TargetJD.MaterializingInfos.end() ||
3403 MII->second.DependantEDUs.empty())
3404 continue;
3405
3406 for (auto &DependantEDU : MII->second.DependantEDUs) {
3407 if (IL_removeEDUDependence(*DependantEDU, TargetJD, Sym, EDUInfos))
3408 EDUInfo = &EDUInfos[EDU];
3409 EDUInfo->IntraEmitUsers.insert(DependantEDU);
3410 }
3411 MII->second.DependantEDUs.clear();
3412 }
3413 }
3414
3415 Worklist.clear();
3416 for (auto &[EDU, EDUInfo] : EDUInfos) {
3417 if (!EDUInfo.IntraEmitUsers.empty() && !EDU->Dependencies.empty()) {
3418 if (EDUInfo.NewDeps.empty())
3419 EDUInfo.NewDeps = EDU->Dependencies;
3420 Worklist.push_back(EDU);
3421 }
3422 }
3423
3424 propagateExtraEmitDeps(
3425 Worklist, EDUInfos,
3426 [](JITDylib::EmissionDepUnit &EDU, JITDylib &JD,
3427 NonOwningSymbolStringPtr Sym) {
3428 JD.MaterializingInfos[SymbolStringPtr(Sym)].DependantEDUs.insert(&EDU);
3429 });
3430
3431 JITDylib::AsynchronousSymbolQuerySet CompletedQueries;
3432
3433 // Extract completed queries and lodge not-yet-ready EDUs in the
3434 // session.
3435 for (auto &[EDU, EDUInfo] : EDUInfos) {
3436 if (EDU->Dependencies.empty())
3437 IL_makeEDUReady(std::move(EDUInfo.EDU), CompletedQueries);
3438 else
3439 IL_makeEDUEmitted(std::move(EDUInfo.EDU), CompletedQueries);
3440 }
3441
3442#ifdef EXPENSIVE_CHECKS
3443 verifySessionState("exiting ExecutionSession::IL_emit");
3444#endif
3445
3446 return std::move(CompletedQueries);
3447}
3448
3449Error ExecutionSession::OL_notifyEmitted(
3450 MaterializationResponsibility &MR,
3451 ArrayRef<SymbolDependenceGroup> DepGroups) {
3452 LLVM_DEBUG({
3453 dbgs() << "In " << MR.JD.getName() << " emitting " << MR.SymbolFlags
3454 << "\n";
3455 if (!DepGroups.empty()) {
3456 dbgs() << " Initial dependencies:\n";
3457 for (auto &SDG : DepGroups) {
3458 dbgs() << " Symbols: " << SDG.Symbols
3459 << ", Dependencies: " << SDG.Dependencies << "\n";
3460 }
3461 }
3462 });
3463
3464#ifndef NDEBUG
3465 SymbolNameSet Visited;
3466 for (auto &DG : DepGroups) {
3467 for (auto &Sym : DG.Symbols) {
3468 assert(MR.SymbolFlags.count(Sym) &&
3469 "DG contains dependence for symbol outside this MR");
3470 assert(Visited.insert(Sym).second &&
3471 "DG contains duplicate entries for Name");
3472 }
3473 }
3474#endif // NDEBUG
3475
3476 auto EDUInfos = simplifyDepGroups(MR, DepGroups);
3477
3478 LLVM_DEBUG({
3479 dbgs() << " Simplified dependencies:\n";
3480 for (auto &[EDU, EDUInfo] : EDUInfos) {
3481 dbgs() << " Symbols: { ";
3482 for (auto &[Sym, Flags] : EDU->Symbols)
3483 dbgs() << Sym << " ";
3484 dbgs() << "}, Dependencies: { ";
3485 for (auto &[DepJD, Deps] : EDU->Dependencies) {
3486 dbgs() << "(" << DepJD->getName() << ", { ";
3487 for (auto &Dep : Deps)
3488 dbgs() << Dep << " ";
3489 dbgs() << "}) ";
3490 }
3491 dbgs() << "}\n";
3492 }
3493 });
3494
3495 auto CompletedQueries =
3496 runSessionLocked([&]() { return IL_emit(MR, EDUInfos); });
3497
3498 // On error bail out.
3499 if (!CompletedQueries)
3500 return CompletedQueries.takeError();
3501
3502 MR.SymbolFlags.clear();
3503
3504 // Otherwise notify all the completed queries.
3505 for (auto &Q : *CompletedQueries) {
3506 assert(Q->isComplete() && "Q is not complete");
3507 Q->handleComplete(*this);
3508 }
3509
3510 return Error::success();
3511}
3512
3513Error ExecutionSession::OL_defineMaterializing(
3514 MaterializationResponsibility &MR, SymbolFlagsMap NewSymbolFlags) {
3515
3516 LLVM_DEBUG({
3517 dbgs() << "In " << MR.JD.getName() << " defining materializing symbols "
3518 << NewSymbolFlags << "\n";
3519 });
3520 if (auto AcceptedDefs =
3521 MR.JD.defineMaterializing(MR, std::move(NewSymbolFlags))) {
3522 // Add all newly accepted symbols to this responsibility object.
3523 for (auto &KV : *AcceptedDefs)
3524 MR.SymbolFlags.insert(KV);
3525 return Error::success();
3526 } else
3527 return AcceptedDefs.takeError();
3528}
3529
3530std::pair<JITDylib::AsynchronousSymbolQuerySet,
3531 std::shared_ptr<SymbolDependenceMap>>
3532ExecutionSession::IL_failSymbols(JITDylib &JD,
3533 const SymbolNameVector &SymbolsToFail) {
3534
3535#ifdef EXPENSIVE_CHECKS
3536 verifySessionState("entering ExecutionSession::IL_failSymbols");
3537#endif
3538
3539 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3540 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
3541 auto ExtractFailedQueries = [&](JITDylib::MaterializingInfo &MI) {
3542 JITDylib::AsynchronousSymbolQueryList ToDetach;
3543 for (auto &Q : MI.pendingQueries()) {
3544 // Add the query to the list to be failed and detach it.
3545 FailedQueries.insert(Q);
3546 ToDetach.push_back(Q);
3547 }
3548 for (auto &Q : ToDetach)
3549 Q->detach();
3550 assert(!MI.hasQueriesPending() && "Queries still pending after detach");
3551 };
3552
3553 for (auto &Name : SymbolsToFail) {
3554 (*FailedSymbolsMap)[&JD].insert(Name);
3555
3556 // Look up the symbol to fail.
3557 auto SymI = JD.Symbols.find(Name);
3558
3559 // FIXME: Revisit this. We should be able to assert sequencing between
3560 // ResourceTracker removal and symbol failure.
3561 //
3562 // It's possible that this symbol has already been removed, e.g. if a
3563 // materialization failure happens concurrently with a ResourceTracker or
3564 // JITDylib removal. In that case we can safely skip this symbol and
3565 // continue.
3566 if (SymI == JD.Symbols.end())
3567 continue;
3568 auto &Sym = SymI->second;
3569
3570 // If the symbol is already in the error state then we must have visited
3571 // it earlier.
3572 if (Sym.getFlags().hasError()) {
3573 assert(!JD.MaterializingInfos.count(Name) &&
3574 "Symbol in error state still has MaterializingInfo");
3575 continue;
3576 }
3577
3578 // Move the symbol into the error state.
3579 Sym.setFlags(Sym.getFlags() | JITSymbolFlags::HasError);
3580
3581 // FIXME: Come up with a sane mapping of state to
3582 // presence-of-MaterializingInfo so that we can assert presence / absence
3583 // here, rather than testing it.
3584 auto MII = JD.MaterializingInfos.find(Name);
3585 if (MII == JD.MaterializingInfos.end())
3586 continue;
3587
3588 auto &MI = MII->second;
3589
3590 // Collect queries to be failed for this MII.
3591 ExtractFailedQueries(MI);
3592
3593 if (MI.DefiningEDU) {
3594 // If there is a DefiningEDU for this symbol then remove this
3595 // symbol from it.
3596 assert(MI.DependantEDUs.empty() &&
3597 "Symbol with DefiningEDU should not have DependantEDUs");
3598 assert(Sym.getState() >= SymbolState::Emitted &&
3599 "Symbol has EDU, should have been emitted");
3600 assert(MI.DefiningEDU->Symbols.count(NonOwningSymbolStringPtr(Name)) &&
3601 "Symbol does not appear in its DefiningEDU");
3602 MI.DefiningEDU->Symbols.erase(NonOwningSymbolStringPtr(Name));
3603
3604 // Remove this EDU from the dependants lists of its dependencies.
3605 for (auto &[DepJD, DepSyms] : MI.DefiningEDU->Dependencies) {
3606 for (auto DepSym : DepSyms) {
3607 assert(DepJD->Symbols.count(SymbolStringPtr(DepSym)) &&
3608 "DepSym not in DepJD");
3609 assert(DepJD->MaterializingInfos.count(SymbolStringPtr(DepSym)) &&
3610 "DepSym has not MaterializingInfo");
3611 auto &SymMI = DepJD->MaterializingInfos[SymbolStringPtr(DepSym)];
3612 assert(SymMI.DependantEDUs.count(MI.DefiningEDU.get()) &&
3613 "DefiningEDU missing from DependantEDUs list of dependency");
3614 SymMI.DependantEDUs.erase(MI.DefiningEDU.get());
3615 }
3616 }
3617
3618 MI.DefiningEDU = nullptr;
3619 } else {
3620 // Otherwise if there are any EDUs waiting on this symbol then move
3621 // those symbols to the error state too, and deregister them from the
3622 // symbols that they depend on.
3623 // Note: We use a copy of DependantEDUs here since we'll be removing
3624 // from the original set as we go.
3625 for (auto &DependantEDU : MI.DependantEDUs) {
3626
3627 // Remove DependantEDU from all of its users DependantEDUs lists.
3628 for (auto &[DepJD, DepSyms] : DependantEDU->Dependencies) {
3629 for (auto DepSym : DepSyms) {
3630 // Skip self-reference to avoid invalidating the MI.DependantEDUs
3631 // map. We'll clear this later.
3632 if (DepJD == &JD && DepSym == Name)
3633 continue;
3634 assert(DepJD->Symbols.count(SymbolStringPtr(DepSym)) &&
3635 "DepSym not in DepJD?");
3636 assert(DepJD->MaterializingInfos.count(SymbolStringPtr(DepSym)) &&
3637 "DependantEDU not registered with symbol it depends on");
3638 auto &SymMI = DepJD->MaterializingInfos[SymbolStringPtr(DepSym)];
3639 assert(SymMI.DependantEDUs.count(DependantEDU) &&
3640 "DependantEDU missing from DependantEDUs list");
3641 SymMI.DependantEDUs.erase(DependantEDU);
3642 }
3643 }
3644
3645 // Move any symbols defined by DependantEDU into the error state and
3646 // fail any queries waiting on them.
3647 auto &DepJD = *DependantEDU->JD;
3648 auto DepEDUSymbols = std::move(DependantEDU->Symbols);
3649 for (auto &[DepName, Flags] : DepEDUSymbols) {
3650 auto DepSymItr = DepJD.Symbols.find(SymbolStringPtr(DepName));
3651 assert(DepSymItr != DepJD.Symbols.end() &&
3652 "Symbol not present in table");
3653 auto &DepSym = DepSymItr->second;
3654
3655 assert(DepSym.getState() >= SymbolState::Emitted &&
3656 "Symbol has EDU, should have been emitted");
3657 assert(!DepSym.getFlags().hasError() &&
3658 "Symbol is already in the error state?");
3659 DepSym.setFlags(DepSym.getFlags() | JITSymbolFlags::HasError);
3660 (*FailedSymbolsMap)[&DepJD].insert(SymbolStringPtr(DepName));
3661
3662 // This symbol has a defining EDU so its MaterializingInfo object must
3663 // exist.
3664 auto DepMIItr =
3665 DepJD.MaterializingInfos.find(SymbolStringPtr(DepName));
3666 assert(DepMIItr != DepJD.MaterializingInfos.end() &&
3667 "Symbol has defining EDU but not MaterializingInfo");
3668 auto &DepMI = DepMIItr->second;
3669 assert(DepMI.DefiningEDU.get() == DependantEDU &&
3670 "Bad EDU dependence edge");
3671 assert(DepMI.DependantEDUs.empty() &&
3672 "Symbol was emitted, should not have any DependantEDUs");
3673 ExtractFailedQueries(DepMI);
3674 DepJD.MaterializingInfos.erase(SymbolStringPtr(DepName));
3675 }
3676
3677 DepJD.shrinkMaterializationInfoMemory();
3678 }
3679
3680 MI.DependantEDUs.clear();
3681 }
3682
3683 assert(!MI.DefiningEDU && "DefiningEDU should have been reset");
3684 assert(MI.DependantEDUs.empty() &&
3685 "DependantEDUs should have been removed above");
3686 assert(!MI.hasQueriesPending() &&
3687 "Can not delete MaterializingInfo with queries pending");
3688 JD.MaterializingInfos.erase(Name);
3689 }
3690
3691 JD.shrinkMaterializationInfoMemory();
3692
3693#ifdef EXPENSIVE_CHECKS
3694 verifySessionState("exiting ExecutionSession::IL_failSymbols");
3695#endif
3696
3697 return std::make_pair(std::move(FailedQueries), std::move(FailedSymbolsMap));
3698}
3699
3700void ExecutionSession::OL_notifyFailed(MaterializationResponsibility &MR) {
3701
3702 LLVM_DEBUG({
3703 dbgs() << "In " << MR.JD.getName() << " failing materialization for "
3704 << MR.SymbolFlags << "\n";
3705 });
3706
3707 if (MR.SymbolFlags.empty())
3708 return;
3709
3710 SymbolNameVector SymbolsToFail;
3711 for (auto &[Name, Flags] : MR.SymbolFlags)
3712 SymbolsToFail.push_back(Name);
3713 MR.SymbolFlags.clear();
3714
3715 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3716 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
3717
3718 std::tie(FailedQueries, FailedSymbols) = runSessionLocked([&]() {
3719 // If the tracker is defunct then there's nothing to do here.
3720 if (MR.RT->isDefunct())
3721 return std::pair<JITDylib::AsynchronousSymbolQuerySet,
3722 std::shared_ptr<SymbolDependenceMap>>();
3723 return IL_failSymbols(MR.getTargetJITDylib(), SymbolsToFail);
3724 });
3725
3726 for (auto &Q : FailedQueries)
3727 Q->handleFailed(
3728 make_error<FailedToMaterialize>(getSymbolStringPool(), FailedSymbols));
3729}
3730
3731Error ExecutionSession::OL_replace(MaterializationResponsibility &MR,
3732 std::unique_ptr<MaterializationUnit> MU) {
3733 for (auto &KV : MU->getSymbols()) {
3734 assert(MR.SymbolFlags.count(KV.first) &&
3735 "Replacing definition outside this responsibility set");
3736 MR.SymbolFlags.erase(KV.first);
3737 }
3738
3739 if (MU->getInitializerSymbol() == MR.InitSymbol)
3740 MR.InitSymbol = nullptr;
3741
3742 LLVM_DEBUG(MR.JD.getExecutionSession().runSessionLocked([&]() {
3743 dbgs() << "In " << MR.JD.getName() << " replacing symbols with " << *MU
3744 << "\n";
3745 }););
3746
3747 return MR.JD.replace(MR, std::move(MU));
3748}
3749
3750Expected<std::unique_ptr<MaterializationResponsibility>>
3751ExecutionSession::OL_delegate(MaterializationResponsibility &MR,
3752 const SymbolNameSet &Symbols) {
3753
3754 SymbolStringPtr DelegatedInitSymbol;
3755 SymbolFlagsMap DelegatedFlags;
3756
3757 for (auto &Name : Symbols) {
3758 auto I = MR.SymbolFlags.find(Name);
3759 assert(I != MR.SymbolFlags.end() &&
3760 "Symbol is not tracked by this MaterializationResponsibility "
3761 "instance");
3762
3763 DelegatedFlags[Name] = std::move(I->second);
3764 if (Name == MR.InitSymbol)
3765 std::swap(MR.InitSymbol, DelegatedInitSymbol);
3766
3767 MR.SymbolFlags.erase(I);
3768 }
3769
3770 return MR.JD.delegate(MR, std::move(DelegatedFlags),
3771 std::move(DelegatedInitSymbol));
3772}
3773
3774#ifndef NDEBUG
3775void ExecutionSession::dumpDispatchInfo(Task &T) {
3776 runSessionLocked([&]() {
3777 dbgs() << "Dispatching: ";
3778 T.printDescription(dbgs());
3779 dbgs() << "\n";
3780 });
3781}
3782#endif // NDEBUG
3783
3784} // End namespace orc.
3785} // End namespace llvm.
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
#define LLVM_DEBUG(...)
Definition: Debug.h:106
uint64_t Addr
std::string Name
Symbol * Sym
Definition: ELF_riscv.cpp:479
#define _
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
#define H(x, y, z)
Definition: MD5.cpp:57
while(!ToSimplify.empty())
if(PassOpts->AAPipeline)
static StringRef getName(Value *V)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
static uint32_t getFlags(const Symbol *Sym)
Definition: TapiFile.cpp:26
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
const T & front() const
front - Get the first element.
Definition: ArrayRef.h:171
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:168
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:163
const T * data() const
Definition: ArrayRef.h:165
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:156
bool erase(const KeyT &Val)
Definition: DenseMap.h:321
unsigned size() const
Definition: DenseMap.h:99
bool empty() const
Definition: DenseMap.h:98
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:152
iterator end()
Definition: DenseMap.h:84
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:211
Helper for Errors used as out-parameters.
Definition: Error.h:1130
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
Symbol info for RuntimeDyld.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:213
iterator find(const_arg_type_t< ValueT > V)
Definition: DenseSet.h:187
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:95
AsynchronousSymbolQuery(const SymbolLookupSet &Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete)
Create a query for the given symbols.
Definition: Core.cpp:202
void notifySymbolMetRequiredState(const SymbolStringPtr &Name, ExecutorSymbolDef Sym)
Notify the query that a requested symbol has reached the required state.
Definition: Core.cpp:216
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
Definition: Core.h:854
An ExecutionSession represents a running JIT program.
Definition: Core.h:1345
Error endSession()
End the session.
Definition: Core.cpp:1619
void reportError(Error Err)
Report a error for this execution session.
Definition: Core.h:1480
friend class JITDylib
Definition: Core.h:1348
void lookupFlags(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet Symbols, unique_function< void(Expected< SymbolFlagsMap >)> OnComplete)
Search the given JITDylibs to find the flags associated with each of the given symbols.
Definition: Core.cpp:1779
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition: Core.h:1399
JITDylib * getJITDylibByName(StringRef Name)
Return a pointer to the "name" JITDylib.
Definition: Core.cpp:1658
friend class LookupState
Definition: Core.h:1349
JITDylib & createBareJITDylib(std::string Name)
Add a new bare JITDylib to this ExecutionSession.
Definition: Core.cpp:1667
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
Definition: Core.h:1394
void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylibs for the given symbols.
Definition: Core.cpp:1805
Error registerJITDispatchHandlers(JITDylib &JD, JITDispatchHandlerAssociationMap WFs)
For each tag symbol name, associate the corresponding AsyncHandlerWrapperFunction with the address of...
Definition: Core.cpp:1900
void registerResourceManager(ResourceManager &RM)
Register the given ResourceManager with this ExecutionSession.
Definition: Core.cpp:1641
~ExecutionSession()
Destroy an ExecutionSession.
Definition: Core.cpp:1613
void runJITDispatchHandler(SendResultFunction SendResult, ExecutorAddr HandlerFnTagAddr, ArrayRef< char > ArgBuffer)
Run a registered jit-side wrapper function.
Definition: Core.cpp:1939
void deregisterResourceManager(ResourceManager &RM)
Deregister the given ResourceManager with this ExecutionSession.
Definition: Core.cpp:1645
ExecutionSession(std::unique_ptr< ExecutorProcessControl > EPC)
Construct an ExecutionSession with the given ExecutorProcessControl object.
Definition: Core.cpp:1607
decltype(auto) runSessionLocked(Func &&F)
Run the given lambda with the session mutex locked.
Definition: Core.h:1409
void dump(raw_ostream &OS)
Dump the state of all the JITDylibs in this session.
Definition: Core.cpp:1960
Error removeJITDylibs(std::vector< JITDylibSP > JDsToRemove)
Removes the given JITDylibs from the ExecutionSession.
Definition: Core.cpp:1684
Expected< JITDylib & > createJITDylib(std::string Name)
Add a new JITDylib to this ExecutionSession.
Definition: Core.cpp:1676
void dispatchTask(std::unique_ptr< Task > T)
Materialize the given unit.
Definition: Core.h:1553
Represents an address in the executor process.
Represents a defining location for a JIT symbol.
FailedToMaterialize(std::shared_ptr< SymbolStringPool > SSP, std::shared_ptr< SymbolDependenceMap > Symbols)
Definition: Core.cpp:82
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:100
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:104
InProgressFullLookupState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, SymbolState RequiredState, std::shared_ptr< AsynchronousSymbolQuery > Q, RegisterDependenciesFunction RegisterDependencies)
Definition: Core.cpp:566
void complete(std::unique_ptr< InProgressLookupState > IPLS) override
Definition: Core.cpp:576
void fail(Error Err) override
Definition: Core.cpp:582
void complete(std::unique_ptr< InProgressLookupState > IPLS) override
Definition: Core.cpp:553
void fail(Error Err) override
Definition: Core.cpp:558
InProgressLookupFlagsState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, unique_function< void(Expected< SymbolFlagsMap >)> OnComplete)
Definition: Core.cpp:546
virtual ~InProgressLookupState()=default
SymbolLookupSet DefGeneratorCandidates
Definition: Core.cpp:533
JITDylibSearchOrder SearchOrder
Definition: Core.cpp:527
std::vector< std::weak_ptr< DefinitionGenerator > > CurDefGeneratorStack
Definition: Core.cpp:541
SymbolLookupSet LookupSet
Definition: Core.cpp:528
virtual void complete(std::unique_ptr< InProgressLookupState > IPLS)=0
enum llvm::orc::InProgressLookupState::@502 GenState
InProgressLookupState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, SymbolState RequiredState)
Definition: Core.cpp:516
SymbolLookupSet DefGeneratorNonCandidates
Definition: Core.cpp:534
virtual void fail(Error Err)=0
Represents a JIT'd dynamic library.
Definition: Core.h:897
Error clear()
Calls remove on all trackers currently associated with this JITDylib.
Definition: Core.cpp:657
Error define(std::unique_ptr< MaterializationUnitType > &&MU, ResourceTrackerSP RT=nullptr)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Definition: Core.h:1852
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
Definition: Core.h:916
ResourceTrackerSP createResourceTracker()
Create a resource tracker for this JITDylib.
Definition: Core.cpp:681
Expected< std::vector< JITDylibSP > > getReverseDFSLinkOrder()
Rteurn this JITDylib and its transitive dependencies in reverse DFS order based on linkage relationsh...
Definition: Core.cpp:1775
ResourceTrackerSP getDefaultResourceTracker()
Get the default resource tracker for this JITDylib.
Definition: Core.cpp:672
void removeGenerator(DefinitionGenerator &G)
Remove a definition generator from this JITDylib.
Definition: Core.cpp:689
Expected< std::vector< JITDylibSP > > getDFSLinkOrder()
Return this JITDylib and its transitive dependencies in DFS order based on linkage relationships.
Definition: Core.cpp:1771
Wraps state for a lookup-in-progress.
Definition: Core.h:829
void continueLookup(Error Err)
Continue the lookup.
Definition: Core.cpp:633
LookupState & operator=(LookupState &&)
void run() override
Definition: Core.cpp:1605
static char ID
Definition: Core.h:1334
void printDescription(raw_ostream &OS) override
Definition: Core.cpp:1603
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition: Core.h:571
void printDescription(raw_ostream &OS) override
Definition: Core.cpp:1592
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:163
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:167
Non-owning SymbolStringPool entry pointer.
static void lookupInitSymbolsAsync(unique_function< void(Error)> OnComplete, ExecutionSession &ES, const DenseMap< JITDylib *, SymbolLookupSet > &InitSyms)
Performs an async lookup for the given symbols in each of the given JITDylibs, calling the given hand...
Definition: Core.cpp:1543
static Expected< DenseMap< JITDylib *, SymbolMap > > lookupInitSymbols(ExecutionSession &ES, const DenseMap< JITDylib *, SymbolLookupSet > &InitSyms)
A utility function for looking up initializer symbols.
Definition: Core.cpp:1494
StringRef getName() const override
Return the name of this materialization unit.
Definition: Core.cpp:307
ReExportsMaterializationUnit(JITDylib *SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolAliasMap Aliases)
SourceJD is allowed to be nullptr, in which case the source JITDylib is taken to be whatever JITDylib...
Definition: Core.cpp:301
std::function< bool(SymbolStringPtr)> SymbolPredicate
Definition: Core.h:1941
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &LookupSet) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
Definition: Core.cpp:598
ReexportsGenerator(JITDylib &SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolPredicate Allow=SymbolPredicate())
Create a reexports generator.
Definition: Core.cpp:592
Listens for ResourceTracker operations.
Definition: Core.h:125
ResourceTrackerDefunct(ResourceTrackerSP RT)
Definition: Core.cpp:71
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:78
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:74
API to remove / transfer ownership of JIT resources.
Definition: Core.h:77
JITDylib & getJITDylib() const
Return the JITDylib targeted by this tracker.
Definition: Core.h:92
void transferTo(ResourceTracker &DstRT)
Transfer all resources associated with this key to the given tracker, which must target the same JITD...
Definition: Core.cpp:59
ResourceTracker(const ResourceTracker &)=delete
Error remove()
Remove all resources associated with this key.
Definition: Core.cpp:55
void lookupAsync(LookupAsyncOnCompleteFn OnComplete) const
Definition: Core.cpp:181
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition: Core.h:194
static SymbolLookupSet fromMapKeys(const DenseMap< SymbolStringPtr, ValT > &M, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Construct a SymbolLookupSet from DenseMap keys.
Definition: Core.h:248
Pointer to a pooled string representing a symbol name.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:155
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:159
SymbolsCouldNotBeRemoved(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
Definition: Core.cpp:149
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:145
SymbolsNotFound(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
Definition: Core.cpp:127
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:141
Represents an abstract task for ORC to run.
Definition: TaskDispatch.h:35
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:172
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:176
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:120
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:116
UnsatisfiedSymbolDependencies(std::shared_ptr< SymbolStringPool > SSP, JITDylibSP JD, SymbolNameSet FailedSymbols, SymbolDependenceMap BadDeps, std::string Explanation)
Definition: Core.cpp:108
static WrapperFunctionResult createOutOfBandError(const char *Msg)
Create an out-of-band error by copying the given string.
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:460
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
unique_function is a type-erasing functor similar to std::function.
@ Entry
Definition: COFF.h:844
IntrusiveRefCntPtr< JITDylib > JITDylibSP
Definition: Core.h:52
JITDylibSearchOrder makeJITDylibSearchOrder(ArrayRef< JITDylib * > JDs, JITDylibLookupFlags Flags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Convenience function for creating a search order from an ArrayRef of JITDylib*, all with the same fla...
Definition: Core.h:177
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
Definition: Core.h:173
std::function< void(const SymbolDependenceMap &)> RegisterDependenciesFunction
Callback to register the dependencies for a given query.
Definition: Core.h:419
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
Definition: Core.h:745
SymbolLookupFlags
Lookup flags that apply to each symbol in a lookup.
Definition: Core.h:156
std::unique_ptr< ReExportsMaterializationUnit > reexports(JITDylib &SourceJD, SymbolAliasMap Aliases, JITDylibLookupFlags SourceJDLookupFlags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Create a materialization unit for re-exporting symbols from another JITDylib with alternative names/f...
Definition: Core.h:754
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
Definition: Core.h:412
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
Definition: Core.h:146
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
DenseMap< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
unique_function< void(Expected< SymbolMap >)> SymbolsResolvedCallback
Callback to notify client that symbols have been resolved.
Definition: Core.h:415
DenseSet< SymbolStringPtr > SymbolNameSet
A set of symbol names (represented by SymbolStringPtrs for.
LookupKind
Describes the kind of lookup being performed.
Definition: Core.h:168
RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
Definition: Core.cpp:38
std::vector< SymbolStringPtr > SymbolNameVector
A vector of symbol names.
SymbolState
Represents the state that a symbol has reached during materialization.
Definition: Core.h:767
@ Materializing
Added to the symbol table, never queried.
@ NeverSearched
No symbol should be in this state.
@ Ready
Emitted to memory, but waiting on transitive dependencies.
@ Emitted
Assigned address, still materializing.
@ Resolved
Queried, materialization begun.
std::error_code orcError(OrcErrorCode ErrCode)
Definition: OrcError.cpp:84
DenseMap< JITDylib *, SymbolNameSet > SymbolDependenceMap
A map from JITDylibs to sets of symbols.
Expected< SymbolAliasMap > buildSimpleReexportsAliasMap(JITDylib &SourceJD, const SymbolNameSet &Symbols)
Build a SymbolAliasMap for the common case where you want to re-export symbols from another JITDylib ...
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1759
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2115
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:420
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition: Error.h:438
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:125
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1978
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1873
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1766
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1903
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
#define NDEBUG
Definition: regutils.h:48