12#include "llvm/Config/llvm-config.h"
20#include <condition_variable>
24#define DEBUG_TYPE "orc"
43void MaterializationUnit::anchor() {}
46 assert((
reinterpret_cast<uintptr_t
>(JD.get()) & 0x1) == 0 &&
47 "JITDylib must be two byte aligned");
49 JDAndFlag.store(
reinterpret_cast<uintptr_t
>(JD.get()));
65void ResourceTracker::makeDefunct() {
66 uintptr_t Val = JDAndFlag.load();
81 OS <<
"Resource tracker " << (
void *)RT.get() <<
" became defunct";
89 OS <<
"JITDylib " << JD->getName() <<
" (" << (
void *)JD.get()
94 std::shared_ptr<SymbolStringPool> SSP,
95 std::shared_ptr<SymbolDependenceMap> Symbols)
97 assert(this->SSP &&
"String pool cannot be null");
98 assert(!this->Symbols->empty() &&
"Can not fail to resolve an empty set");
102 for (
auto &[JD, Syms] : *this->Symbols)
107 for (
auto &[JD, Syms] : *Symbols)
116 OS <<
"Failed to materialize symbols: " << *Symbols;
120 std::shared_ptr<SymbolStringPool> SSP,
JITDylibSP JD,
122 std::string Explanation)
124 FailedSymbols(
std::
move(FailedSymbols)), BadDeps(
std::
move(BadDeps)),
125 Explanation(
std::
move(Explanation)) {}
132 OS <<
"In " << JD->getName() <<
", failed to materialize " << FailedSymbols
133 <<
", due to unsatisfied dependencies " << BadDeps;
134 if (!Explanation.empty())
135 OS <<
" (" << Explanation <<
")";
142 assert(!this->Symbols.
empty() &&
"Can not fail to resolve an empty set");
148 assert(!this->Symbols.empty() &&
"Can not fail to resolve an empty set");
156 OS <<
"Symbols not found: " << Symbols;
160 std::shared_ptr<SymbolStringPool> SSP,
SymbolNameSet Symbols)
162 assert(!this->Symbols.
empty() &&
"Can not fail to resolve an empty set");
170 OS <<
"Symbols could not be removed: " << Symbols;
178 OS <<
"Missing definitions in module " << ModuleName
187 OS <<
"Unexpected definitions in module " << ModuleName
192 JD->getExecutionSession().lookup(
195 [OnComplete = std::move(OnComplete)
202 assert(
Result->size() == 1 &&
"Unexpected number of results");
204 "Result does not contain expected symbol");
205 OnComplete(
Result->begin()->second);
207 OnComplete(
Result.takeError());
215 : NotifyComplete(
std::
move(NotifyComplete)), RequiredState(RequiredState) {
217 "Cannot query for a symbols that have not reached the resolve state "
220 OutstandingSymbolsCount = Symbols.size();
222 for (
auto &[Name, Flags] : Symbols)
228 auto I = ResolvedSymbols.find(Name);
229 assert(
I != ResolvedSymbols.end() &&
230 "Resolving symbol outside the requested set");
232 "Redundantly resolving symbol Name");
237 ResolvedSymbols.erase(
I);
239 I->second = std::move(Sym);
240 --OutstandingSymbolsCount;
244 assert(OutstandingSymbolsCount == 0 &&
245 "Symbols remain, handleComplete called prematurely");
247 class RunQueryCompleteTask :
public Task {
249 RunQueryCompleteTask(
SymbolMap ResolvedSymbols,
251 : ResolvedSymbols(
std::
move(ResolvedSymbols)),
252 NotifyComplete(
std::
move(NotifyComplete)) {}
254 OS <<
"Execute query complete callback for " << ResolvedSymbols;
256 void run()
override { NotifyComplete(std::move(ResolvedSymbols)); }
263 auto T = std::make_unique<RunQueryCompleteTask>(std::move(ResolvedSymbols),
264 std::move(NotifyComplete));
269void AsynchronousSymbolQuery::handleFailed(
Error Err) {
270 assert(QueryRegistrations.empty() && ResolvedSymbols.empty() &&
271 OutstandingSymbolsCount == 0 &&
272 "Query should already have been abandoned");
273 NotifyComplete(std::move(Err));
277void AsynchronousSymbolQuery::addQueryDependence(
JITDylib &JD,
279 bool Added = QueryRegistrations[&JD].insert(std::move(Name)).second;
281 assert(Added &&
"Duplicate dependence notification?");
284void AsynchronousSymbolQuery::removeQueryDependence(
286 auto QRI = QueryRegistrations.find(&JD);
287 assert(QRI != QueryRegistrations.end() &&
288 "No dependencies registered for JD");
289 assert(QRI->second.count(Name) &&
"No dependency on Name in JD");
290 QRI->second.erase(Name);
291 if (QRI->second.empty())
292 QueryRegistrations.erase(QRI);
296 auto I = ResolvedSymbols.find(Name);
297 assert(
I != ResolvedSymbols.end() &&
298 "Redundant removal of weakly-referenced symbol");
299 ResolvedSymbols.erase(
I);
300 --OutstandingSymbolsCount;
303void AsynchronousSymbolQuery::detach() {
304 ResolvedSymbols.clear();
305 OutstandingSymbolsCount = 0;
306 for (
auto &[JD, Syms] : QueryRegistrations)
307 JD->detachQueryHelper(*
this, Syms);
308 QueryRegistrations.clear();
315 SourceJDLookupFlags(SourceJDLookupFlags), Aliases(
std::
move(Aliases)) {}
318 return "<Reexports>";
321void ReExportsMaterializationUnit::materialize(
322 std::unique_ptr<MaterializationResponsibility> R) {
324 auto &ES = R->getTargetJITDylib().getExecutionSession();
325 JITDylib &TgtJD = R->getTargetJITDylib();
326 JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD;
331 auto RequestedSymbols = R->getRequestedSymbols();
334 for (
auto &Name : RequestedSymbols) {
335 auto I = Aliases.
find(Name);
336 assert(
I != Aliases.
end() &&
"Symbol not found in aliases map?");
337 RequestedAliases[Name] = std::move(
I->second);
343 dbgs() <<
"materializing reexports: target = " << TgtJD.
getName()
344 <<
", source = " << SrcJD.
getName() <<
" " << RequestedAliases
349 if (!Aliases.empty()) {
350 auto Err = SourceJD ?
R->replace(
reexports(*SourceJD, std::move(Aliases),
351 SourceJDLookupFlags))
358 R->failMaterialization();
365 struct OnResolveInfo {
366 OnResolveInfo(std::unique_ptr<MaterializationResponsibility> R,
367 SymbolAliasMap Aliases)
368 :
R(std::
move(
R)), Aliases(std::
move(Aliases)) {}
370 std::unique_ptr<MaterializationResponsibility>
R;
372 std::vector<SymbolDependenceGroup> SDGs;
383 std::vector<std::pair<SymbolLookupSet, std::shared_ptr<OnResolveInfo>>>
385 while (!RequestedAliases.
empty()) {
386 SymbolNameSet ResponsibilitySymbols;
387 SymbolLookupSet QuerySymbols;
388 SymbolAliasMap QueryAliases;
391 for (auto &[Alias, AliasInfo] : RequestedAliases) {
393 if (&SrcJD == &TgtJD && (QueryAliases.count(AliasInfo.Aliasee) ||
394 RequestedAliases.count(AliasInfo.Aliasee)))
397 ResponsibilitySymbols.insert(Alias);
398 QuerySymbols.add(AliasInfo.Aliasee,
399 AliasInfo.AliasFlags.hasMaterializationSideEffectsOnly()
400 ? SymbolLookupFlags::WeaklyReferencedSymbol
401 : SymbolLookupFlags::RequiredSymbol);
402 QueryAliases[Alias] = std::move(AliasInfo);
406 for (
auto &KV : QueryAliases)
407 RequestedAliases.
erase(KV.first);
409 assert(!QuerySymbols.empty() &&
"Alias cycle detected!");
411 auto NewR =
R->delegate(ResponsibilitySymbols);
414 R->failMaterialization();
418 auto QueryInfo = std::make_shared<OnResolveInfo>(std::move(*NewR),
419 std::move(QueryAliases));
420 QueryInfos.push_back(
421 make_pair(std::move(QuerySymbols), std::move(QueryInfo)));
425 while (!QueryInfos.empty()) {
426 auto QuerySymbols = std::move(QueryInfos.back().first);
427 auto QueryInfo = std::move(QueryInfos.back().second);
429 QueryInfos.pop_back();
431 auto RegisterDependencies = [QueryInfo,
438 assert(Deps.size() == 1 && Deps.count(&SrcJD) &&
439 "Unexpected dependencies for reexports");
441 auto &SrcJDDeps = Deps.find(&SrcJD)->second;
443 for (
auto &[Alias, AliasInfo] : QueryInfo->Aliases)
444 if (SrcJDDeps.count(AliasInfo.Aliasee))
445 QueryInfo->SDGs.push_back({{Alias}, {{&SrcJD, {AliasInfo.Aliasee}}}});
448 auto OnComplete = [QueryInfo](Expected<SymbolMap>
Result) {
449 auto &ES = QueryInfo->R->getTargetJITDylib().getExecutionSession();
452 for (
auto &KV : QueryInfo->Aliases) {
453 assert((KV.second.AliasFlags.hasMaterializationSideEffectsOnly() ||
454 Result->count(KV.second.Aliasee)) &&
455 "Result map missing entry?");
457 if (KV.second.AliasFlags.hasMaterializationSideEffectsOnly())
460 ResolutionMap[KV.first] = {(*Result)[KV.second.Aliasee].getAddress(),
461 KV.second.AliasFlags};
463 if (
auto Err = QueryInfo->R->notifyResolved(ResolutionMap)) {
465 QueryInfo->R->failMaterialization();
468 if (
auto Err = QueryInfo->R->notifyEmitted(QueryInfo->SDGs)) {
470 QueryInfo->R->failMaterialization();
475 QueryInfo->R->failMaterialization();
482 std::move(RegisterDependencies));
486void ReExportsMaterializationUnit::discard(
const JITDylib &JD,
487 const SymbolStringPtr &Name) {
488 assert(Aliases.count(Name) &&
489 "Symbol not covered by this MaterializationUnit");
493MaterializationUnit::Interface
494ReExportsMaterializationUnit::extractFlags(
const SymbolAliasMap &Aliases) {
496 for (
auto &KV : Aliases)
499 return MaterializationUnit::Interface(std::move(SymbolFlags),
nullptr);
510 return Flags.takeError();
513 for (
auto &Name : Symbols) {
514 assert(Flags->count(Name) &&
"Missing entry in flags map");
533 virtual void complete(std::unique_ptr<InProgressLookupState> IPLS) = 0;
550 } GenState = NotInGenerator;
561 OnComplete(
std::
move(OnComplete)) {}
563 void complete(std::unique_ptr<InProgressLookupState> IPLS)
override {
564 auto &ES =
SearchOrder.front().first->getExecutionSession();
565 ES.OL_completeLookupFlags(std::move(IPLS), std::move(OnComplete));
568 void fail(
Error Err)
override { OnComplete(std::move(Err)); }
579 std::shared_ptr<AsynchronousSymbolQuery> Q,
583 Q(
std::
move(Q)), RegisterDependencies(
std::
move(RegisterDependencies)) {
586 void complete(std::unique_ptr<InProgressLookupState> IPLS)
override {
587 auto &ES =
SearchOrder.front().first->getExecutionSession();
588 ES.OL_completeLookup(std::move(IPLS), std::move(Q),
589 std::move(RegisterDependencies));
594 Q->handleFailed(std::move(Err));
598 std::shared_ptr<AsynchronousSymbolQuery> Q;
605 : SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
612 assert(&JD != &SourceJD &&
"Cannot re-export from the same dylib");
616 K, {{&SourceJD, JDLookupFlags}}, LookupSet);
618 return Flags.takeError();
622 for (
auto &KV : *Flags)
623 if (!Allow || Allow(KV.first))
626 if (AliasMap.empty())
636void LookupState::reset(InProgressLookupState *IPLS) { this->IPLS.reset(IPLS); }
644 assert(IPLS &&
"Cannot call continueLookup on empty LookupState");
645 auto &ES = IPLS->SearchOrder.begin()->first->getExecutionSession();
646 ES.OL_applyQueryPhase1(std::move(IPLS), std::move(Err));
650 std::deque<LookupState> LookupsToFail;
652 std::lock_guard<std::mutex> Lock(M);
653 std::swap(PendingLookups, LookupsToFail);
657 for (
auto &LS : LookupsToFail)
659 "Query waiting on DefinitionGenerator that was destroyed",
668 std::vector<ResourceTrackerSP> TrackersToRemove;
669 ES.runSessionLocked([&]() {
670 assert(State != Closed &&
"JD is defunct");
671 for (
auto &KV : TrackerSymbols)
672 TrackersToRemove.push_back(KV.first);
677 for (
auto &RT : TrackersToRemove)
678 Err =
joinErrors(std::move(Err), RT->remove());
683 return ES.runSessionLocked([
this] {
684 assert(State != Closed &&
"JD is defunct");
687 return DefaultTracker;
692 return ES.runSessionLocked([
this] {
693 assert(State == Open &&
"JD is defunct");
702 std::shared_ptr<DefinitionGenerator> TmpDG;
704 ES.runSessionLocked([&] {
705 assert(State == Open &&
"JD is defunct");
707 [&](
const std::shared_ptr<DefinitionGenerator> &
H) {
708 return H.get() == &
G;
710 assert(
I != DefGenerators.end() &&
"Generator not found");
711 TmpDG = std::move(*
I);
712 DefGenerators.erase(
I);
721 if (FromMR.RT->isDefunct())
724 std::vector<NonOwningSymbolStringPtr> AddedSyms;
725 std::vector<NonOwningSymbolStringPtr> RejectedWeakDefs;
727 for (
auto &[Name, Flags] : SymbolFlags) {
728 auto EntryItr = Symbols.
find(Name);
731 if (EntryItr != Symbols.
end()) {
734 if (!Flags.isWeak()) {
736 for (
auto &S : AddedSyms)
741 std::string(*Name),
"defineMaterializing operation");
745 RejectedWeakDefs.push_back(NonOwningSymbolStringPtr(Name));
749 Symbols.
insert(std::make_pair(Name, SymbolTableEntry(Flags))).first;
751 AddedSyms.push_back(NonOwningSymbolStringPtr(Name));
756 while (!RejectedWeakDefs.empty()) {
758 RejectedWeakDefs.pop_back();
766 std::unique_ptr<MaterializationUnit> MU) {
767 assert(MU !=
nullptr &&
"Can not replace with a null MaterializationUnit");
768 std::unique_ptr<MaterializationUnit> MustRunMU;
769 std::unique_ptr<MaterializationResponsibility> MustRunMR;
772 ES.runSessionLocked([&,
this]() ->
Error {
773 if (FromMR.RT->isDefunct())
777 for (
auto &KV : MU->getSymbols()) {
778 auto SymI = Symbols.find(KV.first);
779 assert(SymI != Symbols.end() &&
"Replacing unknown symbol");
781 "Can not replace a symbol that ha is not materializing");
782 assert(!SymI->second.hasMaterializerAttached() &&
783 "Symbol should not have materializer attached already");
784 assert(UnmaterializedInfos.count(KV.first) == 0 &&
785 "Symbol being replaced should have no UnmaterializedInfo");
793 for (
auto &KV : MU->getSymbols()) {
794 auto MII = MaterializingInfos.find(KV.first);
795 if (MII != MaterializingInfos.end()) {
796 if (MII->second.hasQueriesPending()) {
797 MustRunMR = ES.createMaterializationResponsibility(
798 *FromMR.RT, std::move(MU->SymbolFlags),
799 std::move(MU->InitSymbol));
800 MustRunMU = std::move(MU);
807 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU),
809 for (
auto &KV : UMI->MU->getSymbols()) {
810 auto SymI = Symbols.find(KV.first);
812 "Can not replace a symbol that is not materializing");
813 assert(!SymI->second.hasMaterializerAttached() &&
814 "Can not replace a symbol that has a materializer attached");
815 assert(UnmaterializedInfos.count(KV.first) == 0 &&
816 "Unexpected materializer entry in map");
817 SymI->second.setAddress(SymI->second.getAddress());
818 SymI->second.setMaterializerAttached(
true);
820 auto &UMIEntry = UnmaterializedInfos[KV.first];
821 assert((!UMIEntry || !UMIEntry->MU) &&
822 "Replacing symbol with materializer still attached");
833 assert(MustRunMR &&
"MustRunMU set implies MustRunMR set");
834 ES.dispatchTask(std::make_unique<MaterializationTask>(
835 std::move(MustRunMU), std::move(MustRunMR)));
837 assert(!MustRunMR &&
"MustRunMU unset implies MustRunMR unset");
843Expected<std::unique_ptr<MaterializationResponsibility>>
847 return ES.runSessionLocked(
848 [&]() -> Expected<std::unique_ptr<MaterializationResponsibility>> {
849 if (FromMR.RT->isDefunct())
852 return ES.createMaterializationResponsibility(
853 *FromMR.RT, std::move(SymbolFlags), std::move(InitSymbol));
858JITDylib::getRequestedSymbols(
const SymbolFlagsMap &SymbolFlags)
const {
859 return ES.runSessionLocked([&]() {
862 for (
auto &KV : SymbolFlags) {
863 assert(Symbols.count(KV.first) &&
"JITDylib does not cover this symbol?");
864 assert(Symbols.find(KV.first)->second.getState() !=
867 "getRequestedSymbols can only be called for symbols that have "
868 "started materializing");
869 auto I = MaterializingInfos.find(KV.first);
870 if (
I == MaterializingInfos.end())
873 if (
I->second.hasQueriesPending())
874 RequestedSymbols.insert(KV.first);
877 return RequestedSymbols;
883 AsynchronousSymbolQuerySet CompletedQueries;
885 if (
auto Err = ES.runSessionLocked([&,
this]() ->
Error {
886 if (MR.RT->isDefunct())
887 return make_error<ResourceTrackerDefunct>(MR.RT);
890 return make_error<StringError>(
"JITDylib " + getName() +
892 inconvertibleErrorCode());
894 struct WorklistEntry {
895 SymbolTable::iterator SymI;
896 ExecutorSymbolDef ResolvedSym;
900 std::vector<WorklistEntry> Worklist;
906 assert(!KV.second.getFlags().hasError() &&
907 "Resolution result can not have error flag set");
909 auto SymI = Symbols.find(KV.first);
911 assert(SymI != Symbols.end() &&
"Symbol not found");
912 assert(!SymI->second.hasMaterializerAttached() &&
913 "Resolving symbol with materializer attached?");
915 "Symbol should be materializing");
916 assert(SymI->second.getAddress() == ExecutorAddr() &&
917 "Symbol has already been resolved");
919 if (SymI->second.getFlags().hasError())
920 SymbolsInErrorState.insert(KV.first);
923 [[maybe_unused]]
auto WeakOrCommon =
925 assert((KV.second.getFlags() & WeakOrCommon) &&
926 "Common symbols must be resolved as common or weak");
927 assert((KV.second.getFlags() & ~WeakOrCommon) ==
929 "Resolving symbol with incorrect flags");
932 assert(KV.second.getFlags() == SymI->second.getFlags() &&
933 "Resolved flags should match the declared flags");
936 {SymI, {KV.second.getAddress(), SymI->second.getFlags()}});
941 if (!SymbolsInErrorState.empty()) {
942 auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
943 (*FailedSymbolsDepMap)[this] = std::move(SymbolsInErrorState);
944 return make_error<FailedToMaterialize>(
945 getExecutionSession().getSymbolStringPool(),
946 std::move(FailedSymbolsDepMap));
949 while (!Worklist.empty()) {
950 auto SymI = Worklist.back().SymI;
951 auto ResolvedSym = Worklist.back().ResolvedSym;
954 auto &Name = SymI->first;
957 JITSymbolFlags ResolvedFlags = ResolvedSym.getFlags();
958 SymI->second.setAddress(ResolvedSym.getAddress());
959 SymI->second.setFlags(ResolvedFlags);
960 SymI->second.setState(SymbolState::Resolved);
962 auto MII = MaterializingInfos.find(Name);
963 if (MII == MaterializingInfos.end())
966 auto &MI = MII->second;
967 for (auto &Q : MI.takeQueriesMeeting(SymbolState::Resolved)) {
968 Q->notifySymbolMetRequiredState(Name, ResolvedSym);
970 CompletedQueries.insert(std::move(Q));
979 for (
auto &Q : CompletedQueries) {
980 assert(Q->isComplete() &&
"Q not completed");
981 Q->handleComplete(ES);
987void JITDylib::unlinkMaterializationResponsibility(
988 MaterializationResponsibility &MR) {
990 auto I = TrackerMRs.find(MR.RT.get());
991 assert(
I != TrackerMRs.end() &&
"No MRs in TrackerMRs list for RT");
992 assert(
I->second.count(&MR) &&
"MR not in TrackerMRs list for RT");
993 I->second.erase(&MR);
994 if (
I->second.empty())
995 TrackerMRs.erase(MR.RT.get());
999void JITDylib::shrinkMaterializationInfoMemory() {
1003 if (UnmaterializedInfos.empty())
1004 UnmaterializedInfos.clear();
1006 if (MaterializingInfos.empty())
1007 MaterializingInfos.clear();
1011 bool LinkAgainstThisJITDylibFirst) {
1012 ES.runSessionLocked([&]() {
1013 assert(State == Open &&
"JD is defunct");
1014 if (LinkAgainstThisJITDylibFirst) {
1016 if (NewLinkOrder.empty() || NewLinkOrder.front().first !=
this)
1017 LinkOrder.push_back(
1021 LinkOrder = std::move(NewLinkOrder);
1026 ES.runSessionLocked([&]() {
1027 for (
auto &KV : NewLinks) {
1032 LinkOrder.push_back(std::move(KV));
1038 ES.runSessionLocked([&]() { LinkOrder.push_back({&JD, JDLookupFlags}); });
1043 ES.runSessionLocked([&]() {
1044 assert(State == Open &&
"JD is defunct");
1045 for (
auto &KV : LinkOrder)
1046 if (KV.first == &OldJD) {
1047 KV = {&NewJD, JDLookupFlags};
1054 ES.runSessionLocked([&]() {
1055 assert(State == Open &&
"JD is defunct");
1057 [&](
const JITDylibSearchOrder::value_type &KV) {
1058 return KV.first == &JD;
1060 if (
I != LinkOrder.end())
1066 return ES.runSessionLocked([&]() ->
Error {
1067 assert(State == Open &&
"JD is defunct");
1068 using SymbolMaterializerItrPair =
1069 std::pair<SymbolTable::iterator, UnmaterializedInfosMap::iterator>;
1070 std::vector<SymbolMaterializerItrPair> SymbolsToRemove;
1074 for (
auto &Name : Names) {
1075 auto I = Symbols.find(Name);
1078 if (
I == Symbols.end()) {
1079 Missing.insert(Name);
1090 auto UMII =
I->second.hasMaterializerAttached()
1091 ? UnmaterializedInfos.find(Name)
1092 : UnmaterializedInfos.end();
1093 SymbolsToRemove.push_back(std::make_pair(
I, UMII));
1097 if (!Missing.empty())
1099 std::move(Missing));
1107 for (
auto &SymbolMaterializerItrPair : SymbolsToRemove) {
1108 auto UMII = SymbolMaterializerItrPair.second;
1111 if (UMII != UnmaterializedInfos.end()) {
1112 UMII->second->MU->doDiscard(*
this, UMII->first);
1113 UnmaterializedInfos.erase(UMII);
1116 auto SymI = SymbolMaterializerItrPair.first;
1117 Symbols.erase(SymI);
1120 shrinkMaterializationInfoMemory();
1127 ES.runSessionLocked([&,
this]() {
1128 OS <<
"JITDylib \"" <<
getName() <<
"\" (ES: "
1129 <<
format(
"0x%016" PRIx64,
reinterpret_cast<uintptr_t
>(&ES))
1143 if (State == Closed)
1145 OS <<
"Link order: " << LinkOrder <<
"\n"
1146 <<
"Symbol table:\n";
1149 std::vector<std::pair<SymbolStringPtr, SymbolTableEntry *>> SymbolsSorted;
1150 for (
auto &KV : Symbols)
1151 SymbolsSorted.emplace_back(KV.first, &KV.second);
1152 std::sort(SymbolsSorted.begin(), SymbolsSorted.end(),
1153 [](
const auto &L,
const auto &R) { return *L.first < *R.first; });
1155 for (
auto &KV : SymbolsSorted) {
1156 OS <<
" \"" << *KV.first <<
"\": ";
1157 if (
auto Addr = KV.second->getAddress())
1160 OS <<
"<not resolved> ";
1162 OS <<
" " << KV.second->getFlags() <<
" " << KV.second->getState();
1164 if (KV.second->hasMaterializerAttached()) {
1165 OS <<
" (Materializer ";
1166 auto I = UnmaterializedInfos.find(KV.first);
1167 assert(
I != UnmaterializedInfos.end() &&
1168 "Lazy symbol should have UnmaterializedInfo");
1169 OS <<
I->second->MU.get() <<
", " <<
I->second->MU->getName() <<
")\n";
1174 if (!MaterializingInfos.empty())
1175 OS <<
" MaterializingInfos entries:\n";
1176 for (
auto &KV : MaterializingInfos) {
1177 OS <<
" \"" << *KV.first <<
"\":\n"
1178 <<
" " << KV.second.pendingQueries().size()
1179 <<
" pending queries: { ";
1180 for (
const auto &Q : KV.second.pendingQueries())
1181 OS << Q.get() <<
" (" << Q->getRequiredState() <<
") ";
1187void JITDylib::MaterializingInfo::addQuery(
1188 std::shared_ptr<AsynchronousSymbolQuery> Q) {
1192 [](
const std::shared_ptr<AsynchronousSymbolQuery> &V,
SymbolState S) {
1193 return V->getRequiredState() <= S;
1195 PendingQueries.insert(
I.base(), std::move(Q));
1198void JITDylib::MaterializingInfo::removeQuery(
1199 const AsynchronousSymbolQuery &Q) {
1202 PendingQueries, [&Q](
const std::shared_ptr<AsynchronousSymbolQuery> &V) {
1203 return V.get() == &Q;
1205 if (
I != PendingQueries.end())
1206 PendingQueries.erase(
I);
1209JITDylib::AsynchronousSymbolQueryList
1210JITDylib::MaterializingInfo::takeQueriesMeeting(SymbolState RequiredState) {
1211 AsynchronousSymbolQueryList
Result;
1212 while (!PendingQueries.empty()) {
1213 if (PendingQueries.back()->getRequiredState() > RequiredState)
1216 Result.push_back(std::move(PendingQueries.back()));
1217 PendingQueries.pop_back();
1223JITDylib::JITDylib(ExecutionSession &ES, std::string Name)
1224 : JITLinkDylib(std::
move(
Name)), ES(ES) {
1228JITDylib::RemoveTrackerResult JITDylib::IL_removeTracker(
ResourceTracker &RT) {
1230 assert(State != Closed &&
"JD is defunct");
1235 if (&RT == DefaultTracker.get()) {
1237 for (
auto &KV : TrackerSymbols)
1240 for (
auto &KV : Symbols) {
1241 auto &Sym = KV.first;
1242 if (!TrackedSymbols.count(Sym))
1243 SymbolsToRemove.push_back(Sym);
1246 DefaultTracker.reset();
1249 auto I = TrackerSymbols.find(&RT);
1250 if (
I != TrackerSymbols.end()) {
1251 SymbolsToRemove = std::move(
I->second);
1252 TrackerSymbols.erase(
I);
1257 for (
auto &Sym : SymbolsToRemove) {
1258 assert(Symbols.count(Sym) &&
"Symbol not in symbol table");
1261 auto MII = MaterializingInfos.find(Sym);
1262 if (MII != MaterializingInfos.end())
1263 SymbolsToFail.push_back(Sym);
1266 auto [QueriesToFail, FailedSymbols] =
1267 ES.IL_failSymbols(*
this, std::move(SymbolsToFail));
1269 std::vector<std::unique_ptr<MaterializationUnit>> DefunctMUs;
1272 for (
auto &Sym : SymbolsToRemove) {
1273 auto I = Symbols.find(Sym);
1274 assert(
I != Symbols.end() &&
"Symbol not present in table");
1277 if (
I->second.hasMaterializerAttached()) {
1279 auto J = UnmaterializedInfos.find(Sym);
1280 assert(J != UnmaterializedInfos.end() &&
1281 "Symbol table indicates MU present, but no UMI record");
1283 DefunctMUs.push_back(std::move(J->second->MU));
1284 UnmaterializedInfos.erase(J);
1286 assert(!UnmaterializedInfos.count(Sym) &&
1287 "Symbol has materializer attached");
1293 shrinkMaterializationInfoMemory();
1295 return {std::move(QueriesToFail), std::move(FailedSymbols),
1296 std::move(DefunctMUs)};
1300 assert(State != Closed &&
"JD is defunct");
1301 assert(&DstRT != &SrcRT &&
"No-op transfers shouldn't call transferTracker");
1302 assert(&DstRT.getJITDylib() ==
this &&
"DstRT is not for this JITDylib");
1303 assert(&SrcRT.getJITDylib() ==
this &&
"SrcRT is not for this JITDylib");
1306 for (
auto &KV : UnmaterializedInfos) {
1307 if (KV.second->RT == &SrcRT)
1308 KV.second->RT = &DstRT;
1313 auto I = TrackerMRs.find(&SrcRT);
1314 if (
I != TrackerMRs.end()) {
1315 auto &SrcMRs =
I->second;
1316 auto &DstMRs = TrackerMRs[&DstRT];
1317 for (
auto *MR : SrcMRs)
1320 DstMRs = std::move(SrcMRs);
1322 DstMRs.insert_range(SrcMRs);
1325 TrackerMRs.erase(&SrcRT);
1331 if (&DstRT == DefaultTracker.get()) {
1332 TrackerSymbols.erase(&SrcRT);
1338 if (&SrcRT == DefaultTracker.get()) {
1339 assert(!TrackerSymbols.count(&SrcRT) &&
1340 "Default tracker should not appear in TrackerSymbols");
1345 for (
auto &KV : TrackerSymbols)
1348 for (
auto &KV : Symbols) {
1349 auto &Sym = KV.first;
1350 if (!CurrentlyTrackedSymbols.count(Sym))
1351 SymbolsToTrack.push_back(Sym);
1354 TrackerSymbols[&DstRT] = std::move(SymbolsToTrack);
1358 auto &DstTrackedSymbols = TrackerSymbols[&DstRT];
1362 auto SI = TrackerSymbols.find(&SrcRT);
1363 if (SI == TrackerSymbols.end())
1366 DstTrackedSymbols.reserve(DstTrackedSymbols.size() +
SI->second.size());
1367 for (
auto &Sym :
SI->second)
1368 DstTrackedSymbols.push_back(std::move(Sym));
1369 TrackerSymbols.erase(SI);
1376 std::vector<SymbolStringPtr> ExistingDefsOverridden;
1377 std::vector<SymbolStringPtr> MUDefsOverridden;
1379 for (
const auto &KV : MU.getSymbols()) {
1380 auto I = Symbols.find(KV.first);
1382 if (
I != Symbols.end()) {
1383 if (KV.second.isStrong()) {
1384 if (
I->second.getFlags().isStrong() ||
1386 Duplicates.insert(KV.first);
1389 "Overridden existing def should be in the never-searched "
1391 ExistingDefsOverridden.push_back(KV.first);
1394 MUDefsOverridden.push_back(KV.first);
1399 if (!Duplicates.empty()) {
1401 {
dbgs() <<
" Error: Duplicate symbols " << Duplicates <<
"\n"; });
1403 MU.getName().str());
1408 if (!MUDefsOverridden.empty())
1409 dbgs() <<
" Defs in this MU overridden: " << MUDefsOverridden <<
"\n";
1411 for (
auto &S : MUDefsOverridden)
1412 MU.doDiscard(*
this, S);
1416 if (!ExistingDefsOverridden.empty())
1417 dbgs() <<
" Existing defs overridden by this MU: " << MUDefsOverridden
1420 for (
auto &S : ExistingDefsOverridden) {
1422 auto UMII = UnmaterializedInfos.find(S);
1423 assert(UMII != UnmaterializedInfos.end() &&
1424 "Overridden existing def should have an UnmaterializedInfo");
1425 UMII->second->MU->doDiscard(*
this, S);
1429 for (
auto &KV : MU.getSymbols()) {
1430 auto &SymEntry = Symbols[KV.first];
1431 SymEntry.setFlags(KV.second);
1433 SymEntry.setMaterializerAttached(
true);
1439void JITDylib::installMaterializationUnit(
1443 if (&RT != DefaultTracker.get()) {
1444 auto &TS = TrackerSymbols[&RT];
1445 TS.reserve(TS.size() + MU->getSymbols().size());
1446 for (
auto &KV : MU->getSymbols())
1447 TS.push_back(KV.first);
1450 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU), &RT);
1451 for (
auto &KV : UMI->MU->getSymbols())
1452 UnmaterializedInfos[KV.first] = UMI;
1457 for (
auto &QuerySymbol : QuerySymbols) {
1458 auto MII = MaterializingInfos.find(QuerySymbol);
1459 if (MII != MaterializingInfos.end())
1460 MII->second.removeQuery(Q);
1472 std::mutex LookupMutex;
1473 std::condition_variable CV;
1477 dbgs() <<
"Issuing init-symbol lookup:\n";
1478 for (
auto &KV : InitSyms)
1479 dbgs() <<
" " << KV.first->getName() <<
": " << KV.second <<
"\n";
1482 for (
auto &KV : InitSyms) {
1483 auto *JD = KV.first;
1484 auto Names = std::move(KV.second);
1491 std::lock_guard<std::mutex> Lock(LookupMutex);
1495 "Duplicate JITDylib in lookup?");
1496 CompoundResult[JD] = std::move(*
Result);
1506 std::unique_lock<std::mutex> Lock(LookupMutex);
1507 CV.wait(Lock, [&] {
return Count == 0; });
1510 return std::move(CompoundErr);
1512 return std::move(CompoundResult);
1519 class TriggerOnComplete {
1522 TriggerOnComplete(OnCompleteFn OnComplete)
1523 : OnComplete(std::move(OnComplete)) {}
1524 ~TriggerOnComplete() { OnComplete(std::move(LookupResult)); }
1525 void reportResult(
Error Err) {
1526 std::lock_guard<std::mutex> Lock(ResultMutex);
1527 LookupResult =
joinErrors(std::move(LookupResult), std::move(Err));
1531 std::mutex ResultMutex;
1533 OnCompleteFn OnComplete;
1537 dbgs() <<
"Issuing init-symbol lookup:\n";
1538 for (
auto &KV : InitSyms)
1539 dbgs() <<
" " << KV.first->getName() <<
": " << KV.second <<
"\n";
1542 auto TOC = std::make_shared<TriggerOnComplete>(std::move(OnComplete));
1544 for (
auto &KV : InitSyms) {
1545 auto *JD = KV.first;
1546 auto Names = std::move(KV.second);
1552 TOC->reportResult(
Result.takeError());
1561 MR->failMaterialization();
1565 OS <<
"Materialization task: " << MU->getName() <<
" in "
1566 << MR->getTargetJITDylib().getName();
1570 assert(MU &&
"MU should not be null");
1571 assert(MR &&
"MR should not be null");
1572 MU->materialize(std::move(MR));
1582 this->EPC->ES =
this;
1584 for (
auto &[Name, Ptr] : this->EPC->getBootstrapSymbolsMap())
1585 BootstrapSymbols[
intern(Name)] =
1595 "Session still open. Did you forget to call endSession?");
1599 LLVM_DEBUG(
dbgs() <<
"Ending ExecutionSession " <<
this <<
"\n");
1601 WaitingOnGraph::OpRecorder *GOpRecorderToEnd =
nullptr;
1604#ifdef EXPENSIVE_CHECKS
1605 verifySessionState(
"Entering ExecutionSession::endSession");
1609 GOpRecorderToEnd = GOpRecorder;
1610 SessionOpen =
false;
1614 std::reverse(JDsToRemove.begin(), JDsToRemove.end());
1618 Err =
joinErrors(std::move(Err), EPC->disconnect());
1620 if (GOpRecorderToEnd)
1621 GOpRecorderToEnd->recordEnd();
1632 assert(!ResourceManagers.empty() &&
"No managers registered");
1633 if (ResourceManagers.back() == &RM)
1634 ResourceManagers.pop_back();
1637 assert(
I != ResourceManagers.end() &&
"RM not registered");
1638 ResourceManagers.erase(
I);
1645 for (
auto &JD : JDs)
1646 if (JD->getName() == Name)
1655 assert(SessionOpen &&
"Cannot create JITDylib after session is closed");
1656 JDs.push_back(
new JITDylib(*
this, std::move(Name)));
1664 if (
auto Err = P->setupJITDylib(JD))
1665 return std::move(Err);
1672 for (
auto &JD : JDsToRemove) {
1673 assert(JD->State == JITDylib::Open &&
"JD already closed");
1674 JD->State = JITDylib::Closing;
1676 assert(
I != JDs.end() &&
"JD does not appear in session JDs");
1683 for (
auto JD : JDsToRemove) {
1684 Err =
joinErrors(std::move(Err), JD->clear());
1686 Err =
joinErrors(std::move(Err), P->teardownJITDylib(*JD));
1691 for (
auto &JD : JDsToRemove) {
1692 assert(JD->State == JITDylib::Closing &&
"JD should be closing");
1693 JD->State = JITDylib::Closed;
1694 assert(JD->Symbols.empty() &&
"JD.Symbols is not empty after clear");
1695 assert(JD->UnmaterializedInfos.empty() &&
1696 "JD.UnmaterializedInfos is not empty after clear");
1697 assert(JD->MaterializingInfos.empty() &&
1698 "JD.MaterializingInfos is not empty after clear");
1699 assert(JD->TrackerSymbols.empty() &&
1700 "TrackerSymbols is not empty after clear");
1701 JD->DefGenerators.clear();
1702 JD->LinkOrder.clear();
1712 return std::vector<JITDylibSP>();
1714 auto &ES = JDs.
front()->getExecutionSession();
1715 return ES.runSessionLocked([&]() ->
Expected<std::vector<JITDylibSP>> {
1717 std::vector<JITDylibSP>
Result;
1719 for (
auto &JD : JDs) {
1721 if (JD->State != Open)
1723 "Error building link order: " + JD->getName() +
" is defunct",
1725 if (Visited.
count(JD.get()))
1730 Visited.
insert(JD.get());
1732 while (!WorkStack.
empty()) {
1733 Result.push_back(std::move(WorkStack.
back()));
1737 auto &JD = *KV.first;
1738 if (!Visited.
insert(&JD).second)
1768 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1769 K, std::move(SearchOrder), std::move(LookupSet),
1770 std::move(OnComplete)),
1778 std::promise<MSVCPExpected<SymbolFlagsMap>> ResultP;
1779 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1780 K, std::move(SearchOrder), std::move(LookupSet),
1782 ResultP.set_value(std::move(
Result));
1786 auto ResultF = ResultP.get_future();
1787 return ResultF.
get();
1798 dbgs() <<
"Looking up " << Symbols <<
" in " << SearchOrder
1799 <<
" (required state: " << RequiredState <<
")\n";
1806 dispatchOutstandingMUs();
1808 auto Unresolved = std::move(Symbols);
1809 auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
1810 std::move(NotifyComplete));
1812 auto IPLS = std::make_unique<InProgressFullLookupState>(
1813 K, SearchOrder, std::move(Unresolved), RequiredState, std::move(Q),
1814 std::move(RegisterDependencies));
1824#if LLVM_ENABLE_THREADS
1826 std::promise<MSVCPExpected<SymbolMap>> PromisedResult;
1829 PromisedResult.set_value(std::move(R));
1841 ResolutionError = R.takeError();
1846 lookup(K, SearchOrder, std::move(Symbols), RequiredState,
1847 std::move(NotifyComplete), RegisterDependencies);
1849#if LLVM_ENABLE_THREADS
1850 return PromisedResult.get_future().get();
1852 if (ResolutionError)
1853 return std::move(ResolutionError);
1866 assert(ResultMap->size() == 1 &&
"Unexpected number of results");
1867 assert(ResultMap->count(Name) &&
"Missing result for symbol");
1868 return std::move(ResultMap->begin()->second);
1870 return ResultMap.takeError();
1882 return lookup(SearchOrder,
intern(Name), RequiredState);
1892 return TagSyms.takeError();
1895 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1898 for (
auto &[TagName, TagSym] : *TagSyms) {
1899 auto TagAddr = TagSym.getAddress();
1900 if (JITDispatchHandlers.count(TagAddr))
1902 " (for " + *TagName +
1903 ") already registered",
1908 for (
auto &[TagName, TagSym] : *TagSyms) {
1909 auto TagAddr = TagSym.getAddress();
1910 auto I = WFs.
find(TagName);
1912 "JITDispatchHandler implementation missing");
1913 JITDispatchHandlers[TagAddr] =
1914 std::make_shared<JITDispatchHandlerFunction>(std::move(
I->second));
1916 dbgs() <<
"Associated function tag \"" << *TagName <<
"\" ("
1917 <<
formatv(
"{0:x}", TagAddr) <<
") with handler\n";
1928 std::shared_ptr<JITDispatchHandlerFunction>
F;
1930 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1931 auto I = JITDispatchHandlers.find(HandlerFnTagAddr);
1932 if (
I != JITDispatchHandlers.end())
1937 (*F)(std::move(SendResult), ArgBytes.
data(), ArgBytes.
size());
1940 (
"No function registered for tag " +
1941 formatv(
"{0:x16}", HandlerFnTagAddr))
1947 for (
auto &JD : JDs)
1952#ifdef EXPENSIVE_CHECKS
1953bool ExecutionSession::verifySessionState(
Twine Phase) {
1957 for (
auto &JD : JDs) {
1960 auto &Stream =
errs();
1962 Stream <<
"ERROR: Bad ExecutionSession state detected " <<
Phase
1964 Stream <<
" In JITDylib " << JD->getName() <<
", ";
1969 if (JD->State != JITDylib::Open) {
1971 <<
"state is not Open, but JD is in ExecutionSession list.";
1979 for (
auto &[Sym, Entry] : JD->Symbols) {
1982 if (Entry.getAddress()) {
1983 LogFailure() <<
"symbol " << Sym <<
" has state "
1985 <<
" (not-yet-resolved) but non-null address "
1986 << Entry.getAddress() <<
".\n";
1991 auto UMIItr = JD->UnmaterializedInfos.find(Sym);
1992 if (
Entry.hasMaterializerAttached()) {
1993 if (UMIItr == JD->UnmaterializedInfos.end()) {
1994 LogFailure() <<
"symbol " << Sym
1995 <<
" entry claims materializer attached, but "
1996 "UnmaterializedInfos has no corresponding entry.\n";
1998 }
else if (UMIItr != JD->UnmaterializedInfos.end()) {
2001 <<
" entry claims no materializer attached, but "
2002 "UnmaterializedInfos has an unexpected entry for it.\n";
2008 for (
auto &[Sym, UMI] : JD->UnmaterializedInfos) {
2009 auto SymItr = JD->Symbols.find(Sym);
2010 if (SymItr == JD->Symbols.end()) {
2013 <<
" has UnmaterializedInfos entry, but no Symbols entry.\n";
2018 for (
auto &[Sym, MII] : JD->MaterializingInfos) {
2020 auto SymItr = JD->Symbols.find(Sym);
2021 if (SymItr == JD->Symbols.end()) {
2026 <<
" has MaterializingInfos entry, but no Symbols entry.\n";
2034 <<
" is in Ready state, should not have MaterializingInfo.\n";
2039 static_cast<std::underlying_type_t<SymbolState>
>(
2040 SymItr->second.getState()) + 1);
2041 for (
auto &Q : MII.PendingQueries) {
2042 if (Q->getRequiredState() != CurState) {
2043 if (Q->getRequiredState() > CurState)
2044 CurState = Q->getRequiredState();
2046 LogFailure() <<
"symbol " << Sym
2047 <<
" has stale or misordered queries.\n";
2059void ExecutionSession::dispatchOutstandingMUs() {
2062 std::optional<std::pair<std::unique_ptr<MaterializationUnit>,
2063 std::unique_ptr<MaterializationResponsibility>>>
2067 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2068 if (!OutstandingMUs.empty()) {
2069 JMU.emplace(std::move(OutstandingMUs.back()));
2070 OutstandingMUs.pop_back();
2077 assert(JMU->first &&
"No MU?");
2078 LLVM_DEBUG(
dbgs() <<
" Dispatching \"" << JMU->first->getName() <<
"\"\n");
2079 dispatchTask(std::make_unique<MaterializationTask>(std::move(JMU->first),
2080 std::move(JMU->second)));
2082 LLVM_DEBUG(
dbgs() <<
"Done dispatching MaterializationUnits.\n");
2087 dbgs() <<
"In " << RT.getJITDylib().getName() <<
" removing tracker "
2088 <<
formatv(
"{0:x}", RT.getKeyUnsafe()) <<
"\n";
2090 std::vector<ResourceManager *> CurrentResourceManagers;
2092 JITDylib::RemoveTrackerResult
R;
2095 CurrentResourceManagers = ResourceManagers;
2097 R = RT.getJITDylib().IL_removeTracker(RT);
2101 R.DefunctMUs.clear();
2105 auto &JD = RT.getJITDylib();
2106 for (
auto *L :
reverse(CurrentResourceManagers))
2108 L->handleRemoveResources(JD, RT.getKeyUnsafe()));
2110 for (
auto &Q :
R.QueriesToFail)
2120 dbgs() <<
"In " << SrcRT.getJITDylib().getName()
2121 <<
" transfering resources from tracker "
2122 <<
formatv(
"{0:x}", SrcRT.getKeyUnsafe()) <<
" to tracker "
2123 <<
formatv(
"{0:x}", DstRT.getKeyUnsafe()) <<
"\n";
2127 if (&DstRT == &SrcRT)
2130 assert(&DstRT.getJITDylib() == &SrcRT.getJITDylib() &&
2131 "Can't transfer resources between JITDylibs");
2133 SrcRT.makeDefunct();
2134 auto &JD = DstRT.getJITDylib();
2135 JD.transferTracker(DstRT, SrcRT);
2136 for (
auto *L :
reverse(ResourceManagers))
2137 L->handleTransferResources(JD, DstRT.getKeyUnsafe(),
2138 SrcRT.getKeyUnsafe());
2145 dbgs() <<
"In " << RT.getJITDylib().getName() <<
" destroying tracker "
2146 <<
formatv(
"{0:x}", RT.getKeyUnsafe()) <<
"\n";
2148 if (!RT.isDefunct())
2149 transferResourceTracker(*RT.getJITDylib().getDefaultResourceTracker(),
2154Error ExecutionSession::IL_updateCandidatesFor(
2157 return Candidates.forEachWithRemoval(
2158 [&](
const SymbolStringPtr &Name,
2162 auto SymI = JD.Symbols.find(Name);
2163 if (SymI == JD.Symbols.end())
2171 if (!SymI->second.getFlags().isExported() &&
2174 NonCandidates->add(Name, SymLookupFlags);
2183 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2190 if (SymI->second.getFlags().hasError()) {
2191 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2192 (*FailedSymbolsMap)[&JD] = {
Name};
2194 std::move(FailedSymbolsMap));
2202void ExecutionSession::OL_resumeLookupAfterGeneration(
2206 "Should not be called for not-in-generator lookups");
2211 if (
auto DG = IPLS.CurDefGeneratorStack.back().lock()) {
2212 IPLS.CurDefGeneratorStack.pop_back();
2213 std::lock_guard<std::mutex> Lock(DG->M);
2217 if (DG->PendingLookups.empty()) {
2223 LS = std::move(DG->PendingLookups.front());
2224 DG->PendingLookups.pop_front();
2229 dispatchTask(std::make_unique<LookupTask>(std::move(LS)));
2233void ExecutionSession::OL_applyQueryPhase1(
2234 std::unique_ptr<InProgressLookupState> IPLS,
Error Err) {
2237 dbgs() <<
"Entering OL_applyQueryPhase1:\n"
2238 <<
" Lookup kind: " << IPLS->K <<
"\n"
2239 <<
" Search order: " << IPLS->SearchOrder
2240 <<
", Current index = " << IPLS->CurSearchOrderIndex
2241 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2242 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2243 <<
" Definition generator candidates: "
2244 << IPLS->DefGeneratorCandidates <<
"\n"
2245 <<
" Definition generator non-candidates: "
2246 << IPLS->DefGeneratorNonCandidates <<
"\n";
2250 OL_resumeLookupAfterGeneration(*IPLS);
2253 "Lookup should not be in InGenerator state here");
2260 while (IPLS->CurSearchOrderIndex != IPLS->SearchOrder.size()) {
2266 return IPLS->fail(std::move(Err));
2269 auto &KV = IPLS->SearchOrder[IPLS->CurSearchOrderIndex];
2270 auto &JD = *KV.first;
2271 auto JDLookupFlags = KV.second;
2274 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2275 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2279 if (IPLS->NewJITDylib) {
2283 SymbolLookupSet Tmp;
2284 std::swap(IPLS->DefGeneratorNonCandidates, Tmp);
2285 IPLS->DefGeneratorCandidates.append(std::move(Tmp));
2288 dbgs() <<
" First time visiting " << JD.getName()
2289 <<
", resetting candidate sets and building generator stack\n";
2294 IPLS->CurDefGeneratorStack.reserve(JD.DefGenerators.size());
2300 IPLS->NewJITDylib =
false;
2309 Err = IL_updateCandidatesFor(
2310 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2311 JD.DefGenerators.empty() ?
nullptr
2312 : &IPLS->DefGeneratorNonCandidates);
2314 dbgs() <<
" Remaining candidates = " << IPLS->DefGeneratorCandidates
2322 IPLS->DefGeneratorCandidates.empty())
2323 OL_resumeLookupAfterGeneration(*IPLS);
2329 return IPLS->fail(std::move(Err));
2333 if (IPLS->CurDefGeneratorStack.empty())
2334 LLVM_DEBUG(
dbgs() <<
" No generators to run for this JITDylib.\n");
2335 else if (IPLS->DefGeneratorCandidates.empty())
2338 dbgs() <<
" Running " << IPLS->CurDefGeneratorStack.size()
2339 <<
" remaining generators for "
2340 << IPLS->DefGeneratorCandidates.size() <<
" candidates\n";
2342 while (!IPLS->CurDefGeneratorStack.empty() &&
2343 !IPLS->DefGeneratorCandidates.empty()) {
2344 auto DG = IPLS->CurDefGeneratorStack.back().lock();
2348 "DefinitionGenerator removed while lookup in progress",
2361 std::lock_guard<std::mutex> Lock(DG->M);
2363 DG->PendingLookups.push_back(std::move(IPLS));
2372 auto &LookupSet = IPLS->DefGeneratorCandidates;
2377 LLVM_DEBUG(
dbgs() <<
" Attempting to generate " << LookupSet <<
"\n");
2379 Err = DG->tryToGenerate(LS, K, JD, JDLookupFlags, LookupSet);
2380 IPLS = std::move(
LS.IPLS);
2386 OL_resumeLookupAfterGeneration(*IPLS);
2391 dbgs() <<
" Error attempting to generate " << LookupSet <<
"\n";
2393 assert(IPLS &&
"LS cannot be retained if error is returned");
2394 return IPLS->fail(std::move(Err));
2400 {
dbgs() <<
" LookupState captured. Exiting phase1 for now.\n"; });
2407 LLVM_DEBUG(
dbgs() <<
" Updating candidate set post-generation\n");
2408 Err = IL_updateCandidatesFor(
2409 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2410 JD.DefGenerators.empty() ?
nullptr
2411 : &IPLS->DefGeneratorNonCandidates);
2416 LLVM_DEBUG(
dbgs() <<
" Error encountered while updating candidates\n");
2417 return IPLS->fail(std::move(Err));
2421 if (IPLS->DefGeneratorCandidates.empty() &&
2422 IPLS->DefGeneratorNonCandidates.empty()) {
2425 IPLS->CurSearchOrderIndex = IPLS->SearchOrder.size();
2431 ++IPLS->CurSearchOrderIndex;
2432 IPLS->NewJITDylib =
true;
2437 IPLS->DefGeneratorCandidates.remove_if(
2445 if (IPLS->DefGeneratorCandidates.empty()) {
2447 IPLS->complete(std::move(IPLS));
2449 LLVM_DEBUG(
dbgs() <<
"Phase 1 failed with unresolved symbols.\n");
2455void ExecutionSession::OL_completeLookup(
2456 std::unique_ptr<InProgressLookupState> IPLS,
2457 std::shared_ptr<AsynchronousSymbolQuery> Q,
2461 dbgs() <<
"Entering OL_completeLookup:\n"
2462 <<
" Lookup kind: " << IPLS->K <<
"\n"
2463 <<
" Search order: " << IPLS->SearchOrder
2464 <<
", Current index = " << IPLS->CurSearchOrderIndex
2465 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2466 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2467 <<
" Definition generator candidates: "
2468 << IPLS->DefGeneratorCandidates <<
"\n"
2469 <<
" Definition generator non-candidates: "
2470 << IPLS->DefGeneratorNonCandidates <<
"\n";
2473 bool QueryComplete =
false;
2474 DenseMap<JITDylib *, JITDylib::UnmaterializedInfosList> CollectedUMIs;
2477 for (
auto &KV : IPLS->SearchOrder) {
2478 auto &JD = *KV.first;
2479 auto JDLookupFlags = KV.second;
2481 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2482 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2485 auto Err = IPLS->LookupSet.forEachWithRemoval(
2486 [&](
const SymbolStringPtr &Name,
2489 dbgs() <<
" Attempting to match \"" <<
Name <<
"\" ("
2490 << SymLookupFlags <<
")... ";
2495 auto SymI = JD.Symbols.find(Name);
2496 if (SymI == JD.Symbols.end()) {
2503 if (!SymI->second.getFlags().isExported() &&
2515 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2519 "required, but symbol is has-side-effects-only\n";
2527 if (SymI->second.getFlags().hasError()) {
2529 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2530 (*FailedSymbolsMap)[&JD] = {
Name};
2539 if (SymI->second.getState() >= Q->getRequiredState()) {
2541 <<
"matched, symbol already in required state\n");
2542 Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
2547 Q->addQueryDependence(JD, Name);
2555 if (SymI->second.hasMaterializerAttached()) {
2556 assert(SymI->second.getAddress() == ExecutorAddr() &&
2557 "Symbol not resolved but already has address?");
2558 auto UMII = JD.UnmaterializedInfos.find(Name);
2559 assert(UMII != JD.UnmaterializedInfos.end() &&
2560 "Lazy symbol should have UnmaterializedInfo");
2562 auto UMI = UMII->second;
2563 assert(UMI->MU &&
"Materializer should not be null");
2564 assert(UMI->RT &&
"Tracker should not be null");
2566 dbgs() <<
"matched, preparing to dispatch MU@" << UMI->MU.get()
2567 <<
" (" << UMI->MU->getName() <<
")\n";
2572 for (
auto &KV : UMI->MU->getSymbols()) {
2573 auto SymK = JD.Symbols.find(KV.first);
2574 assert(SymK != JD.Symbols.end() &&
2575 "No entry for symbol covered by MaterializationUnit");
2576 SymK->second.setMaterializerAttached(
false);
2578 JD.UnmaterializedInfos.erase(KV.first);
2582 CollectedUMIs[&JD].push_back(std::move(UMI));
2590 "By this line the symbol should be materializing");
2591 auto &
MI = JD.MaterializingInfos[
Name];
2593 Q->addQueryDependence(JD, Name);
2598 JD.shrinkMaterializationInfoMemory();
2604 dbgs() <<
"Lookup failed. Detaching query and replacing MUs.\n";
2611 for (
auto &KV : CollectedUMIs) {
2612 auto &JD = *KV.first;
2613 for (
auto &UMI : KV.second)
2614 for (
auto &KV2 : UMI->MU->getSymbols()) {
2615 assert(!JD.UnmaterializedInfos.count(KV2.first) &&
2616 "Unexpected materializer in map");
2617 auto SymI = JD.Symbols.find(KV2.first);
2618 assert(SymI != JD.Symbols.end() &&
"Missing symbol entry");
2620 "Can not replace symbol that is not materializing");
2621 assert(!SymI->second.hasMaterializerAttached() &&
2622 "MaterializerAttached flag should not be set");
2623 SymI->second.setMaterializerAttached(
true);
2624 JD.UnmaterializedInfos[KV2.first] = UMI;
2632 LLVM_DEBUG(
dbgs() <<
"Stripping unmatched weakly-referenced symbols\n");
2633 IPLS->LookupSet.forEachWithRemoval(
2636 Q->dropSymbol(Name);
2642 if (!IPLS->LookupSet.empty()) {
2645 IPLS->LookupSet.getSymbolNames());
2649 QueryComplete = Q->isComplete();
2652 dbgs() <<
"Query successfully "
2653 << (QueryComplete ?
"completed" :
"lodged") <<
"\n";
2657 if (!CollectedUMIs.empty()) {
2658 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2661 for (
auto &KV : CollectedUMIs) {
2663 auto &JD = *KV.first;
2664 dbgs() <<
" For " << JD.getName() <<
": Adding " << KV.second.size()
2667 for (
auto &UMI : KV.second) {
2668 auto MR = createMaterializationResponsibility(
2669 *UMI->RT, std::move(UMI->MU->SymbolFlags),
2670 std::move(UMI->MU->InitSymbol));
2671 OutstandingMUs.push_back(
2672 std::make_pair(std::move(UMI->MU), std::move(MR)));
2678 if (RegisterDependencies && !Q->QueryRegistrations.empty()) {
2680 RegisterDependencies(Q->QueryRegistrations);
2690 Q->handleFailed(std::move(LodgingErr));
2694 if (QueryComplete) {
2696 Q->handleComplete(*
this);
2699 dispatchOutstandingMUs();
2702void ExecutionSession::OL_completeLookupFlags(
2703 std::unique_ptr<InProgressLookupState> IPLS,
2704 unique_function<
void(Expected<SymbolFlagsMap>)> OnComplete) {
2708 dbgs() <<
"Entering OL_completeLookupFlags:\n"
2709 <<
" Lookup kind: " << IPLS->K <<
"\n"
2710 <<
" Search order: " << IPLS->SearchOrder
2711 <<
", Current index = " << IPLS->CurSearchOrderIndex
2712 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2713 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2714 <<
" Definition generator candidates: "
2715 << IPLS->DefGeneratorCandidates <<
"\n"
2716 <<
" Definition generator non-candidates: "
2717 << IPLS->DefGeneratorNonCandidates <<
"\n";
2723 for (
auto &KV : IPLS->SearchOrder) {
2724 auto &JD = *KV.first;
2725 auto JDLookupFlags = KV.second;
2727 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2728 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2731 IPLS->LookupSet.forEachWithRemoval([&](
const SymbolStringPtr &Name,
2734 dbgs() <<
" Attempting to match \"" <<
Name <<
"\" ("
2735 << SymLookupFlags <<
")... ";
2740 auto SymI = JD.Symbols.find(Name);
2741 if (SymI == JD.Symbols.end()) {
2747 if (!SymI->second.getFlags().isExported() &&
2754 dbgs() <<
"matched, \"" <<
Name <<
"\" -> " << SymI->second.getFlags()
2763 IPLS->LookupSet.remove_if(
2768 if (!IPLS->LookupSet.empty()) {
2771 IPLS->LookupSet.getSymbolNames());
2780 OnComplete(std::move(
Result));
2783void ExecutionSession::OL_destroyMaterializationResponsibility(
2786 assert(MR.SymbolFlags.empty() &&
2787 "All symbols should have been explicitly materialized or failed");
2788 MR.JD.unlinkMaterializationResponsibility(MR);
2793 return MR.JD.getRequestedSymbols(MR.SymbolFlags);
2799 dbgs() <<
"In " << MR.JD.getName() <<
" resolving " <<
Symbols <<
"\n";
2802 for (
auto &KV : Symbols) {
2803 auto I = MR.SymbolFlags.find(KV.first);
2804 assert(
I != MR.SymbolFlags.end() &&
2805 "Resolving symbol outside this responsibility set");
2806 assert(!
I->second.hasMaterializationSideEffectsOnly() &&
2807 "Can't resolve materialization-side-effects-only symbol");
2810 assert((KV.second.getFlags() & WeakOrCommon) &&
2811 "Common symbols must be resolved as common or weak");
2812 assert((KV.second.getFlags() & ~WeakOrCommon) ==
2814 "Resolving symbol with incorrect flags");
2816 assert(KV.second.getFlags() ==
I->second &&
2817 "Resolving symbol with incorrect flags");
2821 return MR.JD.resolve(MR, Symbols);
2825ExecutionSession::IL_getSymbolState(
JITDylib *JD,
2827 if (JD->State != JITDylib::Open)
2828 return WaitingOnGraph::ExternalState::Failed;
2830 auto I = JD->Symbols.find_as(Name);
2833 if (
I == JD->Symbols.end())
2834 return WaitingOnGraph::ExternalState::Failed;
2836 if (
I->second.getFlags().hasError())
2837 return WaitingOnGraph::ExternalState::Failed;
2840 return WaitingOnGraph::ExternalState::Ready;
2842 return WaitingOnGraph::ExternalState::None;
2845template <
typename UpdateSymbolFn,
typename UpdateQueryFn>
2846void ExecutionSession::IL_collectQueries(
2847 JITDylib::AsynchronousSymbolQuerySet &Qs,
2848 WaitingOnGraph::ContainerElementsMap &QualifiedSymbols,
2849 UpdateSymbolFn &&UpdateSymbol, UpdateQueryFn &&UpdateQuery) {
2851 for (
auto &[JD, Symbols] : QualifiedSymbols) {
2856 assert(JD->State == JITDylib::Open &&
2857 "WaitingOnGraph includes definition in defunct JITDylib");
2858 for (
auto &Symbol : Symbols) {
2860 auto I = JD->Symbols.find_as(Symbol);
2861 assert(
I != JD->Symbols.end() &&
2862 "Failed Symbol missing from JD symbol table");
2864 UpdateSymbol(Entry);
2867 auto J = JD->MaterializingInfos.find_as(Symbol);
2868 if (J != JD->MaterializingInfos.end()) {
2869 for (
auto &Q : J->second.takeAllPendingQueries()) {
2870 UpdateQuery(*Q, *JD, Symbol, Entry);
2871 Qs.insert(std::move(Q));
2873 JD->MaterializingInfos.erase(J);
2879Expected<ExecutionSession::EmitQueries>
2881 WaitingOnGraph::SimplifyResult SR) {
2883 if (MR.RT->isDefunct())
2886 auto &TargetJD = MR.getTargetJITDylib();
2887 if (TargetJD.State != JITDylib::Open)
2892#ifdef EXPENSIVE_CHECKS
2893 verifySessionState(
"entering ExecutionSession::IL_emit");
2896 auto ER = G.emit(std::move(SR),
2897 [
this](
JITDylib *JD, NonOwningSymbolStringPtr Name) {
2898 return IL_getSymbolState(JD, Name);
2904 for (
auto &SN : ER.Failed)
2906 EQ.Failed, SN->defs(),
2907 [](JITDylib::SymbolTableEntry &
E) {
2908 E.setFlags(E.getFlags() = JITSymbolFlags::HasError);
2910 [&](AsynchronousSymbolQuery &Q,
JITDylib &JD,
2911 NonOwningSymbolStringPtr Name, JITDylib::SymbolTableEntry &
E) {
2912 auto &FS = EQ.FailedSymsForQuery[&Q];
2914 FS = std::make_shared<SymbolDependenceMap>();
2915 (*FS)[&JD].insert(SymbolStringPtr(Name));
2918 for (
auto &FQ :
EQ.Failed)
2921 for (
auto &SN : ER.Ready)
2923 EQ.Completed, SN->defs(),
2924 [](JITDylib::SymbolTableEntry &
E) { E.setState(SymbolState::Ready); },
2925 [](AsynchronousSymbolQuery &Q,
JITDylib &JD,
2926 NonOwningSymbolStringPtr Name, JITDylib::SymbolTableEntry &
E) {
2927 Q.notifySymbolMetRequiredState(SymbolStringPtr(Name), E.getSymbol());
2932 for (
auto it =
EQ.Completed.begin(), end =
EQ.Completed.end(); it != end;) {
2933 if ((*it)->isComplete()) {
2936 it =
EQ.Completed.erase(it);
2940#ifdef EXPENSIVE_CHECKS
2941 verifySessionState(
"exiting ExecutionSession::IL_emit");
2944 return std::move(
EQ);
2947Error ExecutionSession::OL_notifyEmitted(
2951 dbgs() <<
"In " << MR.JD.getName() <<
" emitting " << MR.SymbolFlags
2953 if (!DepGroups.empty()) {
2954 dbgs() <<
" Initial dependencies:\n";
2955 for (
auto &SDG : DepGroups) {
2956 dbgs() <<
" Symbols: " << SDG.Symbols
2957 <<
", Dependencies: " << SDG.Dependencies <<
"\n";
2964 for (
auto &DG : DepGroups) {
2965 for (
auto &Sym : DG.Symbols) {
2966 assert(MR.SymbolFlags.count(Sym) &&
2967 "DG contains dependence for symbol outside this MR");
2968 assert(Visited.insert(Sym).second &&
2969 "DG contains duplicate entries for Name");
2974 std::vector<std::unique_ptr<WaitingOnGraph::SuperNode>> SNs;
2975 WaitingOnGraph::ContainerElementsMap Residual;
2977 auto &JDResidual = Residual[&MR.getTargetJITDylib()];
2978 for (
auto &[Name, Flags] : MR.getSymbols())
2979 JDResidual.insert(NonOwningSymbolStringPtr(Name));
2981 for (
auto &SDG : DepGroups) {
2982 WaitingOnGraph::ContainerElementsMap Defs;
2983 assert(!SDG.Symbols.empty());
2984 auto &JDDefs = Defs[&MR.getTargetJITDylib()];
2985 for (
auto &Def : SDG.Symbols) {
2986 JDDefs.insert(NonOwningSymbolStringPtr(Def));
2987 JDResidual.erase(NonOwningSymbolStringPtr(Def));
2989 WaitingOnGraph::ContainerElementsMap Deps;
2990 if (!SDG.Dependencies.empty()) {
2991 for (
auto &[JD, Syms] : SDG.Dependencies) {
2992 auto &JDDeps = Deps[JD];
2993 for (
auto &Dep : Syms)
2994 JDDeps.insert(NonOwningSymbolStringPtr(Dep));
2997 SNs.push_back(std::make_unique<WaitingOnGraph::SuperNode>(
2998 std::move(Defs), std::move(Deps)));
3000 if (!JDResidual.empty())
3001 SNs.push_back(std::make_unique<WaitingOnGraph::SuperNode>(
3002 std::move(Residual), WaitingOnGraph::ContainerElementsMap()));
3008 dbgs() <<
" Simplified dependencies:\n";
3009 for (
auto &SN : SR.superNodes()) {
3011 auto SortedLibs = [](WaitingOnGraph::ContainerElementsMap &
C) {
3012 std::vector<JITDylib *> JDs;
3013 for (
auto &[JD,
_] :
C)
3016 return LHS->getName() <
RHS->getName();
3021 auto SortedNames = [](WaitingOnGraph::ElementSet &Elems) {
3022 std::vector<NonOwningSymbolStringPtr> Names(Elems.begin(), Elems.end());
3024 const NonOwningSymbolStringPtr &
RHS) {
3030 dbgs() <<
" Defs: {";
3031 for (
auto *JD : SortedLibs(SN->defs())) {
3032 dbgs() <<
" (" << JD->getName() <<
", [";
3033 for (
auto &Sym : SortedNames(SN->defs()[JD]))
3034 dbgs() <<
" " << Sym;
3037 dbgs() <<
" }, Deps: {";
3038 for (
auto *JD : SortedLibs(SN->deps())) {
3039 dbgs() <<
" (" << JD->getName() <<
", [";
3040 for (
auto &Sym : SortedNames(SN->deps()[JD]))
3041 dbgs() <<
" " << Sym;
3052 return EmitQueries.takeError();
3060 for (
auto &FQ : EmitQueries->Failed) {
3062 assert(EmitQueries->FailedSymsForQuery.count(FQ.get()) &&
3063 "Missing failed symbols for query");
3064 auto FailedSyms = std::move(EmitQueries->FailedSymsForQuery[FQ.get()]);
3065 for (
auto &[JD, Syms] : *FailedSyms) {
3066 auto &BadDepsForJD = BadDeps[JD];
3067 for (
auto &Sym : Syms)
3068 BadDepsForJD.insert(Sym);
3071 std::move(FailedSyms)));
3075 for (
auto &UQ : EmitQueries->Completed)
3076 UQ->handleComplete(*
this);
3079 if (!BadDeps.empty()) {
3085 for (
auto &[Name, Flags] : MR.getSymbols())
3087 MR.SymbolFlags.clear();
3090 std::move(BadDeps),
"dependencies removed or in error state");
3093 MR.SymbolFlags.
clear();
3097Error ExecutionSession::OL_defineMaterializing(
3101 dbgs() <<
"In " << MR.JD.getName() <<
" defining materializing symbols "
3102 << NewSymbolFlags <<
"\n";
3104 if (
auto AcceptedDefs =
3105 MR.JD.defineMaterializing(MR, std::move(NewSymbolFlags))) {
3107 for (
auto &KV : *AcceptedDefs)
3108 MR.SymbolFlags.insert(KV);
3111 return AcceptedDefs.takeError();
3114std::pair<JITDylib::AsynchronousSymbolQuerySet,
3115 std::shared_ptr<SymbolDependenceMap>>
3116ExecutionSession::IL_failSymbols(
JITDylib &JD,
3119#ifdef EXPENSIVE_CHECKS
3120 verifySessionState(
"entering ExecutionSession::IL_failSymbols");
3124 if (SymbolsToFail.empty())
3127 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3128 auto Fail = [&](
JITDylib *FailJD, NonOwningSymbolStringPtr FailSym) {
3129 auto I = FailJD->Symbols.find_as(FailSym);
3130 assert(
I != FailJD->Symbols.end());
3132 auto J = FailJD->MaterializingInfos.find_as(FailSym);
3133 if (J != FailJD->MaterializingInfos.end()) {
3134 for (
auto &Q : J->second.takeAllPendingQueries())
3135 FailedQueries.insert(std::move(Q));
3136 FailJD->MaterializingInfos.erase(J);
3140 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
3143 auto &FailedSymsForJD = (*FailedSymbolsMap)[&JD];
3144 for (
auto &Sym : SymbolsToFail) {
3145 FailedSymsForJD.insert(Sym);
3146 Fail(&JD, NonOwningSymbolStringPtr(Sym));
3150 WaitingOnGraph::ContainerElementsMap ToFail;
3151 auto &JDToFail = ToFail[&JD];
3152 for (
auto &Sym : SymbolsToFail)
3153 JDToFail.insert(NonOwningSymbolStringPtr(Sym));
3155 auto FailedSNs = G.fail(ToFail, GOpRecorder);
3157 for (
auto &SN : FailedSNs) {
3158 for (
auto &[FailJD, Defs] : SN->defs()) {
3159 auto &FailedSymsForFailJD = (*FailedSymbolsMap)[FailJD];
3160 for (
auto &Def : Defs) {
3161 FailedSymsForFailJD.insert(SymbolStringPtr(Def));
3168 for (
auto &Q : FailedQueries)
3171#ifdef EXPENSIVE_CHECKS
3172 verifySessionState(
"exiting ExecutionSession::IL_failSymbols");
3175 return std::make_pair(std::move(FailedQueries), std::move(FailedSymbolsMap));
3181 dbgs() <<
"In " << MR.JD.getName() <<
" failing materialization for "
3182 << MR.SymbolFlags <<
"\n";
3185 if (MR.SymbolFlags.empty())
3189 for (
auto &[Name, Flags] : MR.SymbolFlags)
3190 SymbolsToFail.push_back(Name);
3191 MR.SymbolFlags.clear();
3193 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3194 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
3198 if (MR.RT->isDefunct())
3199 return std::pair<JITDylib::AsynchronousSymbolQuerySet,
3200 std::shared_ptr<SymbolDependenceMap>>();
3201 return IL_failSymbols(MR.getTargetJITDylib(), SymbolsToFail);
3204 for (
auto &Q : FailedQueries) {
3212 std::unique_ptr<MaterializationUnit> MU) {
3213 for (
auto &KV : MU->getSymbols()) {
3214 assert(MR.SymbolFlags.count(KV.first) &&
3215 "Replacing definition outside this responsibility set");
3216 MR.SymbolFlags.erase(KV.first);
3219 if (MU->getInitializerSymbol() == MR.InitSymbol)
3220 MR.InitSymbol =
nullptr;
3222 LLVM_DEBUG(MR.JD.getExecutionSession().runSessionLocked([&]() {
3223 dbgs() <<
"In " << MR.JD.getName() <<
" replacing symbols with " << *MU
3227 return MR.JD.replace(MR, std::move(MU));
3230Expected<std::unique_ptr<MaterializationResponsibility>>
3234 SymbolStringPtr DelegatedInitSymbol;
3237 for (
auto &Name : Symbols) {
3238 auto I = MR.SymbolFlags.find(Name);
3239 assert(
I != MR.SymbolFlags.end() &&
3240 "Symbol is not tracked by this MaterializationResponsibility "
3243 DelegatedFlags[
Name] = std::move(
I->second);
3244 if (Name == MR.InitSymbol)
3245 std::swap(MR.InitSymbol, DelegatedInitSymbol);
3247 MR.SymbolFlags.erase(
I);
3250 return MR.JD.delegate(MR, std::move(DelegatedFlags),
3251 std::move(DelegatedInitSymbol));
3255void ExecutionSession::dumpDispatchInfo(
Task &
T) {
3257 dbgs() <<
"Dispatching: ";
3258 T.printDescription(
dbgs());
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static StringRef getName(Value *V)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & front() const
front - Get the first element.
bool empty() const
empty - Check if the array is empty.
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
Helper for Errors used as out-parameters.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
reference get()
Returns a reference to the stored T value.
bool hasMaterializationSideEffectsOnly() const
Returns true if this symbol is a materialization-side-effects-only symbol.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
std::pair< iterator, bool > insert(const ValueT &V)
void reserve(size_t Size)
Grow the DenseSet so that it can contain at least NumEntries items before resizing again.
void insert_range(Range &&R)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
const std::string & getName() const
Get the name for this JITLinkDylib.
A symbol query that returns results via a callback when results are ready.
LLVM_ABI AsynchronousSymbolQuery(const SymbolLookupSet &Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete)
Create a query for the given symbols.
LLVM_ABI void notifySymbolMetRequiredState(const SymbolStringPtr &Name, ExecutorSymbolDef Sym)
Notify the query that a requested symbol has reached the required state.
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
virtual ~DefinitionGenerator()
An ExecutionSession represents a running JIT program.
LLVM_ABI void runJITDispatchHandler(SendResultFunction SendResult, ExecutorAddr HandlerFnTagAddr, shared::WrapperFunctionBuffer ArgBytes)
Run a registered jit-side wrapper function.
LLVM_ABI Error endSession()
End the session.
void reportError(Error Err)
Report a error for this execution session.
LLVM_ABI 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.
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
LLVM_ABI JITDylib * getJITDylibByName(StringRef Name)
Return a pointer to the "name" JITDylib.
LLVM_ABI JITDylib & createBareJITDylib(std::string Name)
Add a new bare JITDylib to this ExecutionSession.
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
LLVM_ABI void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylibs for the given symbols.
LLVM_ABI Error registerJITDispatchHandlers(JITDylib &JD, JITDispatchHandlerAssociationMap WFs)
For each tag symbol name, associate the corresponding AsyncHandlerWrapperFunction with the address of...
LLVM_ABI void registerResourceManager(ResourceManager &RM)
Register the given ResourceManager with this ExecutionSession.
LLVM_ABI ~ExecutionSession()
Destroy an ExecutionSession.
LLVM_ABI void deregisterResourceManager(ResourceManager &RM)
Deregister the given ResourceManager with this ExecutionSession.
LLVM_ABI ExecutionSession(std::unique_ptr< ExecutorProcessControl > EPC)
Construct an ExecutionSession with the given ExecutorProcessControl object.
decltype(auto) runSessionLocked(Func &&F)
Run the given lambda with the session mutex locked.
LLVM_ABI void dump(raw_ostream &OS)
Dump the state of all the JITDylibs in this session.
unique_function< void(shared::WrapperFunctionBuffer)> SendResultFunction
Send a result to the remote.
LLVM_ABI Error removeJITDylibs(std::vector< JITDylibSP > JDsToRemove)
Removes the given JITDylibs from the ExecutionSession.
LLVM_ABI Expected< JITDylib & > createJITDylib(std::string Name)
Add a new JITDylib to this ExecutionSession.
void dispatchTask(std::unique_ptr< Task > T)
Materialize the given unit.
DenseMap< SymbolStringPtr, JITDispatchHandlerFunction > JITDispatchHandlerAssociationMap
A map associating tag names with asynchronous wrapper function implementations in the JIT.
Represents an address in the executor process.
Represents a defining location for a JIT symbol.
const JITSymbolFlags & getFlags() const
FailedToMaterialize(std::shared_ptr< SymbolStringPool > SSP, std::shared_ptr< SymbolDependenceMap > Symbols)
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
~FailedToMaterialize() override
void log(raw_ostream &OS) const override
Print an error message to an output stream.
InProgressFullLookupState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, SymbolState RequiredState, std::shared_ptr< AsynchronousSymbolQuery > Q, RegisterDependenciesFunction RegisterDependencies)
void complete(std::unique_ptr< InProgressLookupState > IPLS) override
void fail(Error Err) override
void complete(std::unique_ptr< InProgressLookupState > IPLS) override
void fail(Error Err) override
InProgressLookupFlagsState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, unique_function< void(Expected< SymbolFlagsMap >)> OnComplete)
virtual ~InProgressLookupState()=default
SymbolLookupSet DefGeneratorCandidates
JITDylibSearchOrder SearchOrder
std::vector< std::weak_ptr< DefinitionGenerator > > CurDefGeneratorStack
size_t CurSearchOrderIndex
SymbolLookupSet LookupSet
virtual void complete(std::unique_ptr< InProgressLookupState > IPLS)=0
InProgressLookupState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, SymbolState RequiredState)
SymbolState RequiredState
SymbolLookupSet DefGeneratorNonCandidates
virtual void fail(Error Err)=0
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Represents a JIT'd dynamic library.
LLVM_ABI Error remove(const SymbolNameSet &Names)
Tries to remove the given symbols.
LLVM_ABI Error clear()
Calls remove on all trackers currently associated with this JITDylib.
LLVM_ABI void dump(raw_ostream &OS)
Dump current JITDylib state to OS.
LLVM_ABI void replaceInLinkOrder(JITDylib &OldJD, JITDylib &NewJD, JITDylibLookupFlags JDLookupFlags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Replace OldJD with NewJD in the link order if OldJD is present.
Error define(std::unique_ptr< MaterializationUnitType > &&MU, ResourceTrackerSP RT=nullptr)
Define all symbols provided by the materialization unit to be part of this JITDylib.
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
LLVM_ABI void addToLinkOrder(const JITDylibSearchOrder &NewLinks)
Append the given JITDylibSearchOrder to the link order for this JITDylib (discarding any elements alr...
LLVM_ABI ResourceTrackerSP createResourceTracker()
Create a resource tracker for this JITDylib.
LLVM_ABI void removeFromLinkOrder(JITDylib &JD)
Remove the given JITDylib from the link order for this JITDylib if it is present.
LLVM_ABI void setLinkOrder(JITDylibSearchOrder NewSearchOrder, bool LinkAgainstThisJITDylibFirst=true)
Set the link order to be used when fixing up definitions in JITDylib.
LLVM_ABI Expected< std::vector< JITDylibSP > > getReverseDFSLinkOrder()
Rteurn this JITDylib and its transitive dependencies in reverse DFS order based on linkage relationsh...
LLVM_ABI ResourceTrackerSP getDefaultResourceTracker()
Get the default resource tracker for this JITDylib.
JITDylib(const JITDylib &)=delete
LLVM_ABI void removeGenerator(DefinitionGenerator &G)
Remove a definition generator from this JITDylib.
LLVM_ABI Expected< std::vector< JITDylibSP > > getDFSLinkOrder()
Return this JITDylib and its transitive dependencies in DFS order based on linkage relationships.
Wraps state for a lookup-in-progress.
LLVM_ABI void continueLookup(Error Err)
Continue the lookup.
LLVM_ABI LookupState & operator=(LookupState &&)
void printDescription(raw_ostream &OS) override
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
void printDescription(raw_ostream &OS) override
~MaterializationTask() override
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
MaterializationUnit(Interface I)
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Non-owning SymbolStringPool entry pointer.
StringRef getName() const override
Return the name of this materialization unit.
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...
std::function< bool(SymbolStringPtr)> SymbolPredicate
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.
ReexportsGenerator(JITDylib &SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolPredicate Allow=SymbolPredicate())
Create a reexports generator.
Listens for ResourceTracker operations.
virtual ~ResourceManager()
ResourceTrackerDefunct(ResourceTrackerSP RT)
void log(raw_ostream &OS) const override
Print an error message to an output stream.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
API to remove / transfer ownership of JIT resources.
JITDylib & getJITDylib() const
Return the JITDylib targeted by this tracker.
LLVM_ABI void transferTo(ResourceTracker &DstRT)
Transfer all resources associated with this key to the given tracker, which must target the same JITD...
LLVM_ABI ~ResourceTracker()
ResourceTracker(const ResourceTracker &)=delete
LLVM_ABI Error remove()
Remove all resources associated with this key.
LLVM_ABI void lookupAsync(LookupAsyncOnCompleteFn OnComplete) const
unique_function< void(Expected< ExecutorSymbolDef >)> LookupAsyncOnCompleteFn
A set of symbols to look up, each associated with a SymbolLookupFlags value.
static SymbolLookupSet fromMapKeys(const DenseMap< SymbolStringPtr, ValT > &M, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Construct a SymbolLookupSet from DenseMap keys.
Pointer to a pooled string representing a symbol name.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
SymbolsCouldNotBeRemoved(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
void log(raw_ostream &OS) const override
Print an error message to an output stream.
SymbolsNotFound(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Represents an abstract task for ORC to run.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
UnsatisfiedSymbolDependencies(std::shared_ptr< SymbolStringPool > SSP, JITDylibSP JD, SymbolNameSet FailedSymbols, SymbolDependenceMap BadDeps, std::string Explanation)
static SimplifyResult simplify(std::vector< std::unique_ptr< SuperNode > > SNs, OpRecorder *Rec=nullptr)
C++ wrapper function buffer: Same as CWrapperFunctionBuffer but auto-releases memory.
size_t size() const
Returns the size of the data contained in this instance.
static WrapperFunctionBuffer createOutOfBandError(const char *Msg)
Create an out-of-band error by copying the given string.
char * data()
Get a pointer to the data contained in this instance.
A raw_ostream that writes to a file descriptor.
This class implements an extremely fast bulk output stream that can only output to a stream.
unique_function is a type-erasing functor similar to std::function.
@ C
The default llvm calling convention, compatible with C.
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...
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
IntrusiveRefCntPtr< JITDylib > JITDylibSP
IntrusiveRefCntPtr< ResourceTracker > ResourceTrackerSP
@ MissingSymbolDefinitions
@ UnexpectedSymbolDefinitions
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
std::unique_ptr< AbsoluteSymbolsMaterializationUnit > absoluteSymbols(SymbolMap Symbols)
Create an AbsoluteSymbolsMaterializationUnit with the given symbols.
std::function< void(const SymbolDependenceMap &)> RegisterDependenciesFunction
Callback to register the dependencies for a given query.
SymbolLookupFlags
Lookup flags that apply to each symbol in a lookup.
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...
LLVM_ABI 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 ...
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
@ MatchExportedSymbolsOnly
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
LookupKind
Describes the kind of lookup being performed.
LLVM_ABI RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
std::vector< SymbolStringPtr > SymbolNameVector
A vector of symbol names.
DenseMap< JITDylib *, SymbolNameSet > SymbolDependenceMap
A map from JITDylibs to sets of symbols.
DenseSet< SymbolStringPtr > SymbolNameSet
A set of symbol names (represented by SymbolStringPtrs for.
SymbolState
Represents the state that a symbol has reached during materialization.
@ 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.
@ Resolved
Queried, materialization begun.
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
LLVM_ABI std::error_code orcError(OrcErrorCode ErrCode)
unique_function< void(Expected< SymbolMap >)> SymbolsResolvedCallback
Callback to notify client that symbols have been resolved.
DenseMap< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
This is an optimization pass for GlobalISel generic memory operations.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
auto reverse(ContainerTy &&C)
Error joinErrors(Error E1, Error E2)
Concatenate errors.
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
FunctionAddr VTableAddr Count
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Implement std::hash so that hash_code can be used in STL containers.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.