12 #include "llvm/Config/llvm-config.h" 19 #if LLVM_ENABLE_THREADS 23 #define DEBUG_TYPE "orc" 32 cl::desc(
"debug print hidden symbols defined by " 33 "materialization units"),
37 cl::desc(
"debug print callable symbols defined by " 38 "materialization units"),
42 cl::desc(
"debug print data symbols defined by " 43 "materialization units"),
49 template <
typename T>
struct PrintAll {
50 bool operator()(
const T &
E) {
return true; }
53 bool anyPrintSymbolOptionSet() {
55 return PrintHidden || PrintCallable || PrintData;
84 typename Pred = PrintAll<typename Sequence::value_type>>
85 class SequencePrinter {
87 SequencePrinter(
const Sequence &S,
char OpenSeq,
char CloseSeq,
88 Pred ShouldPrint = Pred())
89 : S(S), OpenSeq(OpenSeq), CloseSeq(CloseSeq),
90 ShouldPrint(std::move(ShouldPrint)) {}
93 bool PrintComma =
false;
103 OS <<
' ' << CloseSeq;
110 mutable Pred ShouldPrint;
113 template <
typename Sequence,
typename Pred>
114 SequencePrinter<Sequence, Pred> printSequence(
const Sequence &S,
char OpenSeq,
115 char CloseSeq, Pred
P = Pred()) {
116 return SequencePrinter<Sequence, Pred>(S, OpenSeq, CloseSeq, std::move(
P));
120 template <
typename Sequence,
typename Pred>
122 const SequencePrinter<Sequence, Pred> &
Printer) {
127 struct PrintSymbolFlagsMapElemsMatchingCLOpts {
129 return flagsMatchCLOpts(KV.second);
133 struct PrintSymbolMapElemsMatchingCLOpts {
135 return flagsMatchCLOpts(KV.second.getFlags());
151 void MaterializationUnit::anchor() {}
158 return OS << printSequence(Symbols,
'{',
'}', PrintAll<SymbolStringPtr>());
162 return OS << printSequence(Symbols, '[', ']', PrintAll<SymbolStringPtr>());
189 return OS <<
"(\"" << KV.first <<
"\", " << KV.second <<
")";
193 return OS <<
"(\"" << KV.first <<
"\": " << KV.second <<
")";
197 return OS << printSequence(SymbolFlags,
'{',
'}',
198 PrintSymbolFlagsMapElemsMatchingCLOpts());
202 return OS << printSequence(Symbols,
'{',
'}',
203 PrintSymbolMapElemsMatchingCLOpts());
207 const SymbolDependenceMap::value_type &KV) {
208 return OS <<
"(" << KV.first <<
", " << KV.second <<
")";
212 return OS << printSequence(Deps,
'{',
'}',
213 PrintAll<SymbolDependenceMap::value_type>());
217 OS <<
"MU@" << &MU <<
" (\"" << MU.
getName() <<
"\"";
218 if (anyPrintSymbolOptionSet())
226 return OS <<
"Static";
227 case LookupKind::DLSym:
228 return OS <<
"DLSym";
235 switch (JDLookupFlags) {
236 case JITDylibLookupFlags::MatchExportedSymbolsOnly:
237 return OS <<
"MatchExportedSymbolsOnly";
238 case JITDylibLookupFlags::MatchAllSymbols:
239 return OS <<
"MatchAllSymbols";
245 switch (LookupFlags) {
246 case SymbolLookupFlags::RequiredSymbol:
247 return OS <<
"RequiredSymbol";
248 case SymbolLookupFlags::WeaklyReferencedSymbol:
249 return OS <<
"WeaklyReferencedSymbol";
256 return OS <<
"(" << KV.first <<
", " << KV.second <<
")";
260 return OS << printSequence(LookupSet,
'{',
'}',
261 PrintAll<SymbolLookupSet::value_type>());
267 if (!SearchOrder.empty()) {
268 assert(SearchOrder.front().first &&
269 "JITDylibList entries must not be null");
270 OS <<
" (\"" << SearchOrder.front().first->getName() <<
"\", " 271 << SearchOrder.begin()->second <<
")";
273 make_range(std::next(SearchOrder.begin(), 1), SearchOrder.end())) {
274 assert(KV.first &&
"JITDylibList entries must not be null");
275 OS <<
", (\"" << KV.first->getName() <<
"\", " << KV.second <<
")";
284 for (
auto &KV : Aliases)
285 OS <<
" " << *KV.first <<
": " << KV.second.Aliasee <<
" " 286 << KV.second.AliasFlags;
294 return OS <<
"Invalid";
295 case SymbolState::NeverSearched:
296 return OS <<
"Never-Searched";
297 case SymbolState::Materializing:
298 return OS <<
"Materializing";
299 case SymbolState::Resolved:
300 return OS <<
"Resolved";
301 case SymbolState::Emitted:
302 return OS <<
"Emitted";
303 case SymbolState::Ready:
304 return OS <<
"Ready";
309 FailedToMaterialize::FailedToMaterialize(
310 std::shared_ptr<SymbolDependenceMap> Symbols)
311 : Symbols(
std::move(Symbols)) {
312 assert(!this->Symbols->empty() &&
"Can not fail to resolve an empty set");
320 OS <<
"Failed to materialize symbols: " << *Symbols;
324 for (
auto &Sym : Symbols)
325 this->Symbols.push_back(Sym);
326 assert(!this->Symbols.empty() &&
"Can not fail to resolve an empty set");
330 : Symbols(
std::move(Symbols)) {
331 assert(!this->Symbols.empty() &&
"Can not fail to resolve an empty set");
339 OS <<
"Symbols not found: " << Symbols;
343 : Symbols(
std::move(Symbols)) {
344 assert(!this->Symbols.
empty() &&
"Can not fail to resolve an empty set");
352 OS <<
"Symbols could not be removed: " << Symbols;
358 : NotifyComplete(
std::move(NotifyComplete)), RequiredState(RequiredState) {
360 "Cannot query for a symbols that have not reached the resolve state " 363 OutstandingSymbolsCount = Symbols.
size();
365 for (
auto &KV : Symbols)
366 ResolvedSymbols[KV.first] =
nullptr;
371 auto I = ResolvedSymbols.
find(Name);
373 "Resolving symbol outside the requested set");
374 assert(
I->second.getAddress() == 0 &&
"Redundantly resolving symbol Name");
375 I->second = std::move(Sym);
376 --OutstandingSymbolsCount;
380 assert(OutstandingSymbolsCount == 0 &&
381 "Symbols remain, handleComplete called prematurely");
383 auto TmpNotifyComplete = std::move(NotifyComplete);
385 TmpNotifyComplete(std::move(ResolvedSymbols));
388 bool AsynchronousSymbolQuery::canStillFail() {
return !!NotifyComplete; }
390 void AsynchronousSymbolQuery::handleFailed(
Error Err) {
392 OutstandingSymbolsCount == 0 &&
393 "Query should already have been abandoned");
394 NotifyComplete(std::move(Err));
398 void AsynchronousSymbolQuery::addQueryDependence(
JITDylib &JD,
400 bool Added = QueryRegistrations[&JD].
insert(std::move(Name)).second;
402 assert(Added &&
"Duplicate dependence notification?");
405 void AsynchronousSymbolQuery::removeQueryDependence(
407 auto QRI = QueryRegistrations.
find(&JD);
408 assert(QRI != QueryRegistrations.
end() &&
409 "No dependencies registered for JD");
410 assert(QRI->second.count(Name) &&
"No dependency on Name in JD");
411 QRI->second.erase(Name);
412 if (QRI->second.empty())
413 QueryRegistrations.
erase(QRI);
416 void AsynchronousSymbolQuery::detach() {
417 ResolvedSymbols.
clear();
418 OutstandingSymbolsCount = 0;
419 for (
auto &KV : QueryRegistrations)
420 KV.first->detachQueryHelper(*
this, KV.second);
421 QueryRegistrations.clear();
426 : JD(JD),
SymbolFlags(std::move(SymbolFlags)), K(std::move(K)) {
427 assert(!this->SymbolFlags.
empty() &&
"Materializing nothing?");
432 "All symbols should have been explicitly materialized or failed");
436 return JD.getRequestedSymbols(SymbolFlags);
441 dbgs() <<
"In " << JD.
getName() <<
" resolving " << Symbols <<
"\n";
444 for (
auto &KV : Symbols) {
446 auto I = SymbolFlags.
find(KV.first);
448 "Resolving symbol outside this responsibility set");
449 assert((KV.second.getFlags() & ~WeakFlags) == (
I->second & ~WeakFlags) &&
450 "Resolving symbol with incorrect flags");
454 return JD.resolve(Symbols);
460 dbgs() <<
"In " << JD.
getName() <<
" emitting " << SymbolFlags <<
"\n";
463 if (
auto Err = JD.emit(SymbolFlags))
474 dbgs() <<
"In " << JD.
getName() <<
" defining materializing symbols " 475 << NewSymbolFlags <<
"\n";
477 if (
auto AcceptedDefs = JD.defineMaterializing(std::move(NewSymbolFlags))) {
479 for (
auto &KV : *AcceptedDefs)
483 return AcceptedDefs.takeError();
489 dbgs() <<
"In " << JD.
getName() <<
" failing materialization for " 490 << SymbolFlags <<
"\n";
493 JITDylib::FailedSymbolsWorklist Worklist;
495 for (
auto &KV : SymbolFlags)
496 Worklist.push_back(std::make_pair(&JD, KV.first));
499 JD.notifyFailed(std::move(Worklist));
503 std::unique_ptr<MaterializationUnit> MU) {
504 for (
auto &KV : MU->getSymbols())
505 SymbolFlags.
erase(KV.first);
508 dbgs() <<
"In " << JD.
getName() <<
" replacing symbols with " << *MU
512 JD.replace(std::move(MU));
524 for (
auto &Name : Symbols) {
525 auto I = SymbolFlags.
find(Name);
527 "Symbol is not tracked by this MaterializationResponsibility " 530 DelegatedFlags[
Name] = std::move(
I->second);
541 "Symbol not covered by this MaterializationResponsibility instance");
542 JD.addDependencies(Name, Dependencies);
547 for (
auto &KV : SymbolFlags)
548 JD.addDependencies(KV.first, Dependencies);
554 Symbols(
std::move(Symbols)) {}
557 return "<Absolute Symbols>";
560 void AbsoluteSymbolsMaterializationUnit::materialize(
567 void AbsoluteSymbolsMaterializationUnit::discard(
const JITDylib &JD,
569 assert(Symbols.
count(Name) &&
"Symbol is not part of this MU");
574 AbsoluteSymbolsMaterializationUnit::extractFlags(
const SymbolMap &Symbols) {
576 for (
const auto &KV : Symbols)
577 Flags[KV.first] = KV.second.getFlags();
585 SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
586 Aliases(
std::move(Aliases)) {}
589 return "<Reexports>";
592 void ReExportsMaterializationUnit::materialize(
597 JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD;
605 for (
auto &Name : RequestedSymbols) {
606 auto I = Aliases.
find(Name);
607 assert(
I != Aliases.
end() &&
"Symbol not found in aliases map?");
608 RequestedAliases[
Name] = std::move(
I->second);
613 ES.runSessionLocked([&]() {
614 dbgs() <<
"materializing reexports: target = " << TgtJD.
getName()
615 <<
", source = " << SrcJD.
getName() <<
" " << RequestedAliases
620 if (!Aliases.
empty()) {
629 struct OnResolveInfo {
631 : R(std::move(R)), Aliases(std::move(Aliases)) {}
643 std::vector<std::pair<SymbolLookupSet, std::shared_ptr<OnResolveInfo>>>
645 while (!RequestedAliases.
empty()) {
651 for (
auto &KV : RequestedAliases) {
653 if (&SrcJD == &TgtJD && (QueryAliases.
count(KV.second.Aliasee) ||
654 RequestedAliases.count(KV.second.Aliasee)))
657 ResponsibilitySymbols.
insert(KV.first);
658 QuerySymbols.
add(KV.second.Aliasee);
659 QueryAliases[KV.first] = std::move(KV.second);
663 for (
auto &KV : QueryAliases)
664 RequestedAliases.erase(KV.first);
666 assert(!QuerySymbols.
empty() &&
"Alias cycle detected!");
668 auto QueryInfo = std::make_shared<OnResolveInfo>(
669 R.
delegate(ResponsibilitySymbols), std::move(QueryAliases));
670 QueryInfos.push_back(
671 make_pair(std::move(QuerySymbols), std::move(QueryInfo)));
675 while (!QueryInfos.empty()) {
676 auto QuerySymbols = std::move(QueryInfos.back().first);
677 auto QueryInfo = std::move(QueryInfos.back().second);
679 QueryInfos.pop_back();
681 auto RegisterDependencies = [QueryInfo,
689 "Unexpected dependencies for reexports");
691 auto &SrcJDDeps = Deps.
find(&SrcJD)->second;
693 auto &PerAliasDeps = PerAliasDepsMap[&SrcJD];
695 for (
auto &KV : QueryInfo->Aliases)
696 if (SrcJDDeps.count(KV.second.Aliasee)) {
697 PerAliasDeps = {KV.second.Aliasee};
698 QueryInfo->R.addDependencies(KV.first, PerAliasDepsMap);
703 auto &ES = QueryInfo->R.getTargetJITDylib().getExecutionSession();
706 for (
auto &KV : QueryInfo->Aliases) {
707 assert(Result->count(KV.second.Aliasee) &&
708 "Result map missing entry?");
710 (*Result)[KV.second.Aliasee].getAddress(), KV.second.AliasFlags);
712 if (
auto Err = QueryInfo->R.notifyResolved(ResolutionMap)) {
713 ES.reportError(std::move(Err));
714 QueryInfo->R.failMaterialization();
717 if (
auto Err = QueryInfo->R.notifyEmitted()) {
718 ES.reportError(std::move(Err));
719 QueryInfo->R.failMaterialization();
723 ES.reportError(Result.takeError());
724 QueryInfo->R.failMaterialization();
731 std::move(RegisterDependencies));
735 void ReExportsMaterializationUnit::discard(
const JITDylib &JD,
737 assert(Aliases.count(Name) &&
738 "Symbol not covered by this MaterializationUnit");
743 ReExportsMaterializationUnit::extractFlags(
const SymbolAliasMap &Aliases) {
745 for (
auto &KV : Aliases)
746 SymbolFlags[KV.first] = KV.second.AliasFlags;
758 return Flags.takeError();
760 if (!LookupSet.
empty()) {
766 for (
auto &Name : Symbols) {
767 assert(Flags->count(Name) &&
"Missing entry in flags map");
777 : SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
778 Allow(
std::move(Allow)) {}
783 assert(&JD != &SourceJD &&
"Cannot re-export from the same dylib");
786 auto Flags = SourceJD.
lookupFlags(K, JDLookupFlags, LookupSet);
788 return Flags.takeError();
792 for (
auto &KV : *Flags)
793 if (!Allow || Allow(KV.first))
796 if (AliasMap.
empty())
806 ES.runSessionLocked([&]() {
807 auto I =
std::find_if(DefGenerators.begin(), DefGenerators.end(),
808 [&](
const std::unique_ptr<DefinitionGenerator> &
H) {
809 return H.get() == &
G;
811 assert(
I != DefGenerators.end() &&
"Generator not found");
812 DefGenerators.erase(
I);
820 std::vector<SymbolTable::iterator> AddedSyms;
821 std::vector<SymbolFlagsMap::iterator> RejectedWeakDefs;
823 for (
auto SFItr = SymbolFlags.
begin(), SFEnd = SymbolFlags.
end();
824 SFItr != SFEnd; ++SFItr) {
826 auto &Name = SFItr->first;
827 auto &Flags = SFItr->second;
829 auto EntryItr = Symbols.
find(Name);
832 if (EntryItr != Symbols.
end()) {
835 if (!Flags.isWeak()) {
837 for (
auto &
SI : AddedSyms)
841 return make_error<DuplicateDefinition>(*Name);
845 RejectedWeakDefs.push_back(SFItr);
849 Symbols.
insert(std::make_pair(Name, SymbolTableEntry(Flags))).first;
851 AddedSyms.push_back(EntryItr);
856 while (!RejectedWeakDefs.empty()) {
857 SymbolFlags.
erase(RejectedWeakDefs.back());
858 RejectedWeakDefs.pop_back();
865 void JITDylib::replace(std::unique_ptr<MaterializationUnit> MU) {
866 assert(MU !=
nullptr &&
"Can not replace with a null MaterializationUnit");
869 ES.runSessionLocked([&,
this]() -> std::unique_ptr<MaterializationUnit> {
872 for (
auto &KV : MU->getSymbols()) {
873 auto SymI = Symbols.
find(KV.first);
874 assert(SymI != Symbols.
end() &&
"Replacing unknown symbol");
875 assert(SymI->second.isInMaterializationPhase() &&
876 "Can not call replace on a symbol that is not materializing");
877 assert(!SymI->second.hasMaterializerAttached() &&
878 "Symbol should not have materializer attached already");
879 assert(UnmaterializedInfos.count(KV.first) == 0 &&
880 "Symbol being replaced should have no UnmaterializedInfo");
886 for (
auto &KV : MU->getSymbols()) {
887 auto MII = MaterializingInfos.find(KV.first);
888 if (MII != MaterializingInfos.end()) {
889 if (MII->second.hasQueriesPending())
890 return std::move(MU);
895 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU));
896 for (
auto &KV : UMI->MU->getSymbols()) {
897 auto SymI = Symbols.
find(KV.first);
899 "Can not replace a symbol that is not materializing");
900 assert(!SymI->second.hasMaterializerAttached() &&
901 "Can not replace a symbol that has a materializer attached");
902 assert(UnmaterializedInfos.count(KV.first) == 0 &&
903 "Unexpected materializer entry in map");
904 SymI->second.setAddress(SymI->second.getAddress());
905 SymI->second.setMaterializerAttached(
true);
906 UnmaterializedInfos[KV.first] = UMI;
913 ES.dispatchMaterialization(*
this, std::move(MustRunMU));
917 JITDylib::getRequestedSymbols(
const SymbolFlagsMap &SymbolFlags)
const {
918 return ES.runSessionLocked([&]() {
921 for (
auto &KV : SymbolFlags) {
922 assert(Symbols.
count(KV.first) &&
"JITDylib does not cover this symbol?");
923 assert(Symbols.
find(KV.first)->second.isInMaterializationPhase() &&
924 "getRequestedSymbols can only be called for symbols that have " 925 "started materializing");
926 auto I = MaterializingInfos.find(KV.first);
927 if (I == MaterializingInfos.end())
930 if (I->second.hasQueriesPending())
931 RequestedSymbols.
insert(KV.first);
934 return RequestedSymbols;
940 assert(Symbols.
count(Name) &&
"Name not in symbol table");
941 assert(Symbols[Name].isInMaterializationPhase() &&
942 "Can not add dependencies for a symbol that is not materializing");
945 if (Symbols[Name].
getFlags().hasError())
948 auto &
MI = MaterializingInfos[
Name];
950 "Can not add dependencies to an emitted symbol");
952 bool DependsOnSymbolInErrorState =
false;
956 for (
auto &KV : Dependencies) {
957 assert(KV.first &&
"Null JITDylib in dependency?");
958 auto &OtherJITDylib = *KV.first;
959 auto &DepsOnOtherJITDylib =
MI.UnemittedDependencies[&OtherJITDylib];
961 for (
auto &OtherSymbol : KV.second) {
964 auto OtherSymI = OtherJITDylib.Symbols.find(OtherSymbol);
969 assert(OtherSymI != OtherJITDylib.Symbols.end() &&
971 "Dependency on emitted/ready symbol"));
974 auto &OtherSymEntry = OtherSymI->second;
978 if (OtherSymEntry.getFlags().hasError()) {
979 DependsOnSymbolInErrorState =
true;
985 assert(OtherJITDylib.MaterializingInfos.count(OtherSymbol) &&
986 "No MaterializingInfo for dependency");
987 auto &OtherMI = OtherJITDylib.MaterializingInfos[OtherSymbol];
990 transferEmittedNodeDependencies(
MI, Name, OtherMI);
991 else if (&OtherJITDylib !=
this || OtherSymbol != Name) {
992 OtherMI.Dependants[
this].insert(Name);
993 DepsOnOtherJITDylib.insert(OtherSymbol);
997 if (DepsOnOtherJITDylib.empty())
998 MI.UnemittedDependencies.erase(&OtherJITDylib);
1003 if (DependsOnSymbolInErrorState)
1011 ES.runSessionLocked([&,
this]() {
1012 struct WorklistEntry {
1017 std::vector<WorklistEntry> Worklist;
1018 Worklist.reserve(Resolved.
size());
1021 for (
const auto &KV : Resolved) {
1023 assert(!KV.second.getFlags().hasError() &&
1024 "Resolution result can not have error flag set");
1026 auto SymI = Symbols.
find(KV.first);
1028 assert(SymI != Symbols.
end() &&
"Symbol not found");
1029 assert(!SymI->second.hasMaterializerAttached() &&
1030 "Resolving symbol with materializer attached?");
1032 "Symbol should be materializing");
1033 assert(SymI->second.getAddress() == 0 &&
1034 "Symbol has already been resolved");
1036 if (SymI->second.getFlags().hasError())
1037 SymbolsInErrorState.
insert(KV.first);
1039 auto Flags = KV.second.getFlags();
1041 assert(Flags == (SymI->second.getFlags() &
1043 "Resolved flags should match the declared flags");
1051 if (!SymbolsInErrorState.
empty())
1054 while (!Worklist.empty()) {
1055 auto SymI = Worklist.back().SymI;
1056 auto ResolvedSym = Worklist.back().ResolvedSym;
1057 Worklist.pop_back();
1059 auto &Name = SymI->first;
1063 SymI->second.setAddress(ResolvedSym.getAddress());
1064 SymI->second.setFlags(ResolvedFlags);
1067 auto &
MI = MaterializingInfos[
Name];
1069 Q->notifySymbolMetRequiredState(Name, ResolvedSym);
1070 Q->removeQueryDependence(*
this, Name);
1071 if (Q->isComplete())
1072 CompletedQueries.insert(std::move(Q));
1077 assert((SymbolsInErrorState.
empty() || CompletedQueries.empty()) &&
1078 "Can't fail symbols and completed queries at the same time");
1081 if (!SymbolsInErrorState.
empty()) {
1082 auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
1083 (*FailedSymbolsDepMap)[
this] = std::move(SymbolsInErrorState);
1084 return make_error<FailedToMaterialize>(std::move(FailedSymbolsDepMap));
1088 for (
auto &Q : CompletedQueries) {
1089 assert(Q->isComplete() &&
"Q not completed");
1090 Q->handleComplete();
1100 ES.runSessionLocked([&,
this]() {
1101 std::vector<SymbolTable::iterator> Worklist;
1104 for (
const auto &KV : Emitted) {
1105 auto &Name = KV.first;
1107 auto SymI = Symbols.
find(Name);
1108 assert(SymI != Symbols.
end() &&
"No symbol table entry for Name");
1110 if (SymI->second.getFlags().hasError())
1111 SymbolsInErrorState.
insert(Name);
1113 Worklist.push_back(SymI);
1117 if (!SymbolsInErrorState.
empty())
1121 while (!Worklist.empty()) {
1122 auto SymI = Worklist.back();
1123 Worklist.pop_back();
1125 auto &Name = SymI->first;
1126 auto &SymEntry = SymI->second;
1130 "Emitting from state other than Resolved");
1133 auto MII = MaterializingInfos.find(Name);
1134 assert(MII != MaterializingInfos.end() &&
1135 "Missing MaterializingInfo entry");
1136 auto &
MI = MII->second;
1141 for (
auto &KV : MI.Dependants) {
1142 auto &DependantJD = *KV.first;
1143 for (
auto &DependantName : KV.second) {
1145 DependantJD.MaterializingInfos.find(DependantName);
1146 assert(DependantMII != DependantJD.MaterializingInfos.end() &&
1147 "Dependant should have MaterializingInfo");
1149 auto &DependantMI = DependantMII->second;
1152 assert(DependantMI.UnemittedDependencies.count(
this) &&
1153 "Dependant does not have an unemitted dependencies record for " 1155 assert(DependantMI.UnemittedDependencies[
this].count(Name) &&
1156 "Dependant does not count this symbol as a dependency?");
1158 DependantMI.UnemittedDependencies[
this].erase(Name);
1159 if (DependantMI.UnemittedDependencies[
this].empty())
1160 DependantMI.UnemittedDependencies.erase(
this);
1163 DependantJD.transferEmittedNodeDependencies(DependantMI,
1166 auto DependantSymI = DependantJD.Symbols.find(DependantName);
1167 assert(DependantSymI != DependantJD.Symbols.end() &&
1168 "Dependant has no entry in the Symbols table");
1169 auto &DependantSymEntry = DependantSymI->second;
1175 DependantMI.UnemittedDependencies.empty()) {
1176 assert(DependantMI.Dependants.empty() &&
1177 "Dependants should be empty by now");
1184 Q->notifySymbolMetRequiredState(
1185 DependantName, DependantSymI->second.getSymbol());
1186 if (Q->isComplete())
1187 CompletedQueries.insert(Q);
1188 Q->removeQueryDependence(DependantJD, DependantName);
1191 DependantJD.MaterializingInfos.erase(DependantMII);
1196 MI.Dependants.clear();
1197 if (MI.UnemittedDependencies.empty()) {
1200 Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
1201 if (Q->isComplete())
1202 CompletedQueries.insert(Q);
1203 Q->removeQueryDependence(*
this, Name);
1205 MaterializingInfos.erase(MII);
1210 assert((SymbolsInErrorState.
empty() || CompletedQueries.empty()) &&
1211 "Can't fail symbols and completed queries at the same time");
1214 if (!SymbolsInErrorState.
empty()) {
1215 auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
1216 (*FailedSymbolsDepMap)[
this] = std::move(SymbolsInErrorState);
1217 return make_error<FailedToMaterialize>(std::move(FailedSymbolsDepMap));
1221 for (
auto &Q : CompletedQueries) {
1222 assert(Q->isComplete() &&
"Q is not complete");
1223 Q->handleComplete();
1229 void JITDylib::notifyFailed(FailedSymbolsWorklist Worklist) {
1231 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
1234 if (Worklist.empty())
1237 auto &ES = Worklist.front().first->getExecutionSession();
1239 ES.runSessionLocked([&]() {
1240 while (!Worklist.empty()) {
1241 assert(Worklist.back().first &&
"Failed JITDylib can not be null");
1242 auto &JD = *Worklist.back().first;
1243 auto Name = std::move(Worklist.back().second);
1244 Worklist.pop_back();
1246 (*FailedSymbolsMap)[&JD].insert(Name);
1248 assert(JD.Symbols.count(Name) &&
"No symbol table entry for Name");
1249 auto &Sym = JD.Symbols[
Name];
1259 auto MII = JD.MaterializingInfos.find(Name);
1261 if (MII == JD.MaterializingInfos.end())
1264 auto &
MI = MII->second;
1267 for (
auto &KV :
MI.Dependants) {
1268 auto &DependantJD = *KV.first;
1269 for (
auto &DependantName : KV.second) {
1270 assert(DependantJD.Symbols.count(DependantName) &&
1271 "No symbol table entry for DependantName");
1272 auto &DependantSym = DependantJD.Symbols[DependantName];
1273 DependantSym.setFlags(DependantSym.getFlags() |
1276 assert(DependantJD.MaterializingInfos.count(DependantName) &&
1277 "No MaterializingInfo for dependant");
1278 auto &DependantMI = DependantJD.MaterializingInfos[DependantName];
1280 auto UnemittedDepI = DependantMI.UnemittedDependencies.find(&JD);
1281 assert(UnemittedDepI != DependantMI.UnemittedDependencies.end() &&
1282 "No UnemittedDependencies entry for this JITDylib");
1283 assert(UnemittedDepI->second.count(Name) &&
1284 "No UnemittedDependencies entry for this symbol");
1285 UnemittedDepI->second.erase(Name);
1286 if (UnemittedDepI->second.empty())
1287 DependantMI.UnemittedDependencies.erase(UnemittedDepI);
1293 assert(DependantMI.Dependants.empty() &&
1294 "Emitted symbol should not have dependants");
1295 Worklist.push_back(std::make_pair(&DependantJD, DependantName));
1299 MI.Dependants.clear();
1302 for (
auto &KV :
MI.UnemittedDependencies) {
1303 auto &UnemittedDepJD = *KV.first;
1304 for (
auto &UnemittedDepName : KV.second) {
1305 auto UnemittedDepMII =
1306 UnemittedDepJD.MaterializingInfos.find(UnemittedDepName);
1307 assert(UnemittedDepMII != UnemittedDepJD.MaterializingInfos.end() &&
1308 "Missing MII for unemitted dependency");
1309 assert(UnemittedDepMII->second.Dependants.count(&JD) &&
1310 "JD not listed as a dependant of unemitted dependency");
1311 assert(UnemittedDepMII->second.Dependants[&JD].count(Name) &&
1312 "Name is not listed as a dependant of unemitted dependency");
1313 UnemittedDepMII->second.Dependants[&JD].erase(Name);
1314 if (UnemittedDepMII->second.Dependants[&JD].empty())
1315 UnemittedDepMII->second.Dependants.erase(&JD);
1318 MI.UnemittedDependencies.clear();
1321 AsynchronousSymbolQueryList ToDetach;
1322 for (
auto &Q : MII->second.pendingQueries()) {
1324 FailedQueries.insert(Q);
1325 ToDetach.push_back(Q);
1327 for (
auto &Q : ToDetach)
1331 "Can not delete MaterializingInfo with dependants still attached");
1332 assert(
MI.UnemittedDependencies.empty() &&
1333 "Can not delete MaterializingInfo with unemitted dependencies " 1336 "Can not delete MaterializingInfo with queries pending");
1337 JD.MaterializingInfos.erase(MII);
1341 for (
auto &Q : FailedQueries)
1342 Q->handleFailed(make_error<FailedToMaterialize>(FailedSymbolsMap));
1346 bool SearchThisJITDylibFirst) {
1347 ES.runSessionLocked([&]() {
1348 if (SearchThisJITDylibFirst) {
1349 SearchOrder.clear();
1350 if (NewSearchOrder.empty() || NewSearchOrder.front().first !=
this)
1351 SearchOrder.push_back(
1353 SearchOrder.insert(SearchOrder.end(), NewSearchOrder.begin(),
1354 NewSearchOrder.end());
1356 SearchOrder = std::move(NewSearchOrder);
1362 ES.runSessionLocked([&]() { SearchOrder.push_back({&JD, JDLookupFlags}); });
1367 ES.runSessionLocked([&]() {
1368 for (
auto &KV : SearchOrder)
1369 if (KV.first == &OldJD) {
1370 KV = {&NewJD, JDLookupFlags};
1377 ES.runSessionLocked([&]() {
1378 auto I =
std::find_if(SearchOrder.begin(), SearchOrder.end(),
1379 [&](
const JITDylibSearchOrder::value_type &KV) {
1380 return KV.first == &JD;
1382 if (
I != SearchOrder.end())
1383 SearchOrder.erase(
I);
1388 return ES.runSessionLocked([&]() ->
Error {
1389 using SymbolMaterializerItrPair =
1390 std::pair<SymbolTable::iterator, UnmaterializedInfosMap::iterator>;
1391 std::vector<SymbolMaterializerItrPair> SymbolsToRemove;
1395 for (
auto &
Name : Names) {
1396 auto I = Symbols.find(
Name);
1399 if (
I == Symbols.end()) {
1405 if (
I->second.isInMaterializationPhase()) {
1410 auto UMII =
I->second.hasMaterializerAttached()
1411 ? UnmaterializedInfos.find(
Name)
1412 : UnmaterializedInfos.end();
1413 SymbolsToRemove.push_back(std::make_pair(
I, UMII));
1417 if (!Missing.
empty())
1418 return make_error<SymbolsNotFound>(std::move(Missing));
1421 if (!Materializing.
empty())
1422 return make_error<SymbolsCouldNotBeRemoved>(std::move(Materializing));
1425 for (
auto &SymbolMaterializerItrPair : SymbolsToRemove) {
1426 auto UMII = SymbolMaterializerItrPair.second;
1429 if (UMII != UnmaterializedInfos.end()) {
1430 UMII->second->MU->doDiscard(*
this, UMII->first);
1431 UnmaterializedInfos.erase(UMII);
1434 auto SymI = SymbolMaterializerItrPair.first;
1435 Symbols.erase(SymI);
1447 lookupFlagsImpl(Result, K, JDLookupFlags, LookupSet);
1450 for (
auto &DG : DefGenerators) {
1453 if (LookupSet.
empty())
1457 if (
auto Err = DG->tryToGenerate(K, *
this, JDLookupFlags, LookupSet))
1458 return std::move(Err);
1461 lookupFlagsImpl(Result, K, JDLookupFlags, LookupSet);
1474 auto I = Symbols.find(Name);
1475 if (
I == Symbols.end())
1477 assert(!Result.
count(Name) &&
"Symbol already present in Flags map");
1478 Result[
Name] =
I->second.getFlags();
1484 std::shared_ptr<AsynchronousSymbolQuery> &Q,
1487 assert(Q &&
"Query can not be null");
1489 if (
auto Err = lodgeQueryImpl(MUs, Q, K, JDLookupFlags, Unresolved))
1493 for (
auto &DG : DefGenerators) {
1496 if (Unresolved.
empty())
1500 if (
auto Err = DG->tryToGenerate(K, *
this, JDLookupFlags, Unresolved))
1506 cantFail(lodgeQueryImpl(MUs, Q, K, JDLookupFlags, Unresolved));
1513 std::shared_ptr<AsynchronousSymbolQuery> &Q,
1522 auto SymI = Symbols.find(Name);
1523 if (SymI == Symbols.end())
1528 if (!SymI->second.getFlags().isExported() &&
1534 if (SymI->second.getFlags().hasError()) {
1535 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
1536 (*FailedSymbolsMap)[
this] = {Name};
1537 return make_error<FailedToMaterialize>(std::move(FailedSymbolsMap));
1542 if (SymI->second.getState() >= Q->getRequiredState()) {
1543 Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
1549 if (SymI->second.hasMaterializerAttached()) {
1550 assert(SymI->second.getAddress() == 0 &&
1551 "Symbol not resolved but already has address?");
1552 auto UMII = UnmaterializedInfos.find(Name);
1553 assert(UMII != UnmaterializedInfos.end() &&
1554 "Lazy symbol should have UnmaterializedInfo");
1555 auto MU = std::move(UMII->second->MU);
1556 assert(MU !=
nullptr &&
"Materializer should not be null");
1560 for (
auto &KV : MU->getSymbols()) {
1561 auto SymK = Symbols.find(KV.first);
1562 SymK->second.setMaterializerAttached(
false);
1564 UnmaterializedInfos.erase(KV.first);
1568 MUs.push_back(std::move(MU));
1573 assert(SymI->second.isInMaterializationPhase() &&
1574 "By this line the symbol should be materializing");
1575 auto &
MI = MaterializingInfos[
Name];
1577 Q->addQueryDependence(*
this, Name);
1585 assert(Q &&
"Query can not be null");
1587 ES.runOutstandingMUs();
1589 bool QueryComplete =
false;
1590 std::vector<std::unique_ptr<MaterializationUnit>> MUs;
1593 auto Err = ES.runSessionLocked([&,
this]() ->
Error {
1594 QueryComplete = lookupImpl(Q, MUs, Unresolved);
1597 for (
auto &DG : DefGenerators) {
1600 if (Unresolved.
empty())
1603 assert(!QueryComplete &&
"query complete but unresolved symbols remain?");
1609 if (!Unresolved.
empty())
1610 QueryComplete = lookupImpl(Q, MUs, Unresolved);
1616 return std::move(Err);
1618 assert((MUs.empty() || !QueryComplete) &&
1619 "If action flags are set, there should be no work to do (so no MUs)");
1622 Q->handleComplete();
1628 std::lock_guard<std::recursive_mutex>
Lock(ES.OutstandingMUsMutex);
1629 for (
auto &MU : MUs)
1630 ES.OutstandingMUs.push_back(make_pair(
this, std::move(MU)));
1632 ES.runOutstandingMUs();
1639 for (
auto &KV : Unresolved)
1640 RemainingSymbols.
insert(KV.first);
1642 return RemainingSymbols;
1645 bool JITDylib::lookupImpl(
1646 std::shared_ptr<AsynchronousSymbolQuery> &Q,
1647 std::vector<std::unique_ptr<MaterializationUnit>> &MUs,
1649 bool QueryComplete =
false;
1651 std::vector<SymbolStringPtr> ToRemove;
1655 auto SymI = Symbols.find(Name);
1656 if (SymI == Symbols.end())
1661 if (SymI->second.getState() >= Q->getRequiredState()) {
1662 Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
1663 if (Q->isComplete())
1664 QueryComplete =
true;
1669 if (SymI->second.hasMaterializerAttached()) {
1670 assert(SymI->second.getAddress() == 0 &&
1671 "Lazy symbol should not have a resolved address");
1672 auto UMII = UnmaterializedInfos.find(Name);
1673 assert(UMII != UnmaterializedInfos.end() &&
1674 "Lazy symbol should have UnmaterializedInfo");
1675 auto MU = std::move(UMII->second->MU);
1676 assert(MU !=
nullptr &&
"Materializer should not be null");
1680 for (
auto &KV : MU->getSymbols()) {
1681 auto SymK = Symbols.find(KV.first);
1682 assert(SymK != Symbols.end() &&
"Missing symbol table entry");
1684 SymK->second.setMaterializerAttached(
false);
1685 UnmaterializedInfos.erase(KV.first);
1689 MUs.push_back(std::move(MU));
1693 assert(SymI->second.isInMaterializationPhase() &&
1694 "By this line the symbol should be materializing");
1695 auto &
MI = MaterializingInfos[
Name];
1697 Q->addQueryDependence(*
this, Name);
1701 return QueryComplete;
1705 ES.runSessionLocked([&,
this]() {
1706 OS <<
"JITDylib \"" << JITDylibName <<
"\" (ES: " 1707 <<
format(
"0x%016" PRIx64, reinterpret_cast<uintptr_t>(&ES)) <<
"):\n" 1708 <<
"Search order: " << SearchOrder <<
"\n" 1709 <<
"Symbol table:\n";
1711 for (
auto &KV : Symbols) {
1712 OS <<
" \"" << *KV.first <<
"\": ";
1713 if (
auto Addr = KV.second.getAddress())
1714 OS <<
format(
"0x%016" PRIx64, Addr) <<
", " << KV.second.getFlags()
1717 OS <<
"<not resolved> ";
1719 OS << KV.second.getState();
1721 if (KV.second.hasMaterializerAttached()) {
1722 OS <<
" (Materializer ";
1723 auto I = UnmaterializedInfos.find(KV.first);
1724 assert(
I != UnmaterializedInfos.end() &&
1725 "Lazy symbol should have UnmaterializedInfo");
1726 OS <<
I->second->MU.get() <<
")\n";
1731 if (!MaterializingInfos.empty())
1732 OS <<
" MaterializingInfos entries:\n";
1733 for (
auto &KV : MaterializingInfos) {
1734 OS <<
" \"" << *KV.first <<
"\":\n" 1735 <<
" " << KV.second.pendingQueries().size()
1736 <<
" pending queries: { ";
1737 for (
const auto &Q : KV.second.pendingQueries())
1738 OS << Q.get() <<
" (" << Q->getRequiredState() <<
") ";
1739 OS <<
"}\n Dependants:\n";
1740 for (
auto &KV2 : KV.second.Dependants)
1741 OS <<
" " << KV2.first->getName() <<
": " << KV2.second <<
"\n";
1742 OS <<
" Unemitted Dependencies:\n";
1743 for (
auto &KV2 : KV.second.UnemittedDependencies)
1744 OS <<
" " << KV2.first->getName() <<
": " << KV2.second <<
"\n";
1749 void JITDylib::MaterializingInfo::addQuery(
1750 std::shared_ptr<AsynchronousSymbolQuery> Q) {
1753 PendingQueries.rbegin(), PendingQueries.rend(), Q->getRequiredState(),
1754 [](
const std::shared_ptr<AsynchronousSymbolQuery> &V,
SymbolState S) {
1755 return V->getRequiredState() <= S;
1757 PendingQueries.insert(
I.base(), std::move(Q));
1760 void JITDylib::MaterializingInfo::removeQuery(
1764 std::find_if(PendingQueries.begin(), PendingQueries.end(),
1765 [&Q](
const std::shared_ptr<AsynchronousSymbolQuery> &V) {
1766 return V.get() == &Q;
1768 assert(
I != PendingQueries.end() &&
1769 "Query is not attached to this MaterializingInfo");
1770 PendingQueries.erase(
I);
1773 JITDylib::AsynchronousSymbolQueryList
1774 JITDylib::MaterializingInfo::takeQueriesMeeting(
SymbolState RequiredState) {
1775 AsynchronousSymbolQueryList Result;
1776 while (!PendingQueries.empty()) {
1777 if (PendingQueries.back()->getRequiredState() > RequiredState)
1780 Result.push_back(std::move(PendingQueries.back()));
1781 PendingQueries.pop_back();
1788 : ES(ES), JITDylibName(std::move(Name)) {
1794 std::vector<SymbolStringPtr> ExistingDefsOverridden;
1795 std::vector<SymbolStringPtr> MUDefsOverridden;
1798 auto I = Symbols.find(KV.first);
1800 if (
I != Symbols.end()) {
1801 if (KV.second.isStrong()) {
1802 if (
I->second.getFlags().isStrong() ||
1804 Duplicates.
insert(KV.first);
1807 "Overridden existing def should be in the never-searched " 1809 ExistingDefsOverridden.push_back(KV.first);
1812 MUDefsOverridden.push_back(KV.first);
1817 if (!Duplicates.
empty())
1818 return make_error<DuplicateDefinition>(**Duplicates.
begin());
1821 for (
auto &S : MUDefsOverridden)
1825 for (
auto &S : ExistingDefsOverridden) {
1827 auto UMII = UnmaterializedInfos.find(S);
1828 assert(UMII != UnmaterializedInfos.end() &&
1829 "Overridden existing def should have an UnmaterializedInfo");
1830 UMII->second->MU->doDiscard(*
this, S);
1835 auto &SymEntry = Symbols[KV.first];
1836 SymEntry.setFlags(KV.second);
1838 SymEntry.setMaterializerAttached(
true);
1846 for (
auto &QuerySymbol : QuerySymbols) {
1847 assert(MaterializingInfos.count(QuerySymbol) &&
1848 "QuerySymbol does not have MaterializingInfo");
1849 auto &
MI = MaterializingInfos[QuerySymbol];
1854 void JITDylib::transferEmittedNodeDependencies(
1856 MaterializingInfo &EmittedMI) {
1857 for (
auto &KV : EmittedMI.UnemittedDependencies) {
1858 auto &DependencyJD = *KV.first;
1859 SymbolNameSet *UnemittedDependenciesOnDependencyJD =
nullptr;
1861 for (
auto &DependencyName : KV.second) {
1862 auto &DependencyMI = DependencyJD.MaterializingInfos[DependencyName];
1865 if (&DependencyMI == &DependantMI)
1870 if (!UnemittedDependenciesOnDependencyJD)
1871 UnemittedDependenciesOnDependencyJD =
1872 &DependantMI.UnemittedDependencies[&DependencyJD];
1874 DependencyMI.Dependants[
this].
insert(DependantName);
1875 UnemittedDependenciesOnDependencyJD->
insert(DependencyName);
1886 for (
auto &JD : JDs)
1887 if (JD->getName() ==
Name)
1897 std::unique_ptr<JITDylib>(
new JITDylib(*
this, std::move(Name))));
1903 assert(!!Err &&
"Error should be in failure state");
1905 bool SendErrorToQuery;
1908 SendErrorToQuery = Q.canStillFail();
1911 if (SendErrorToQuery)
1912 Q.handleFailed(std::move(Err));
1921 #if LLVM_ENABLE_THREADS 1923 std::promise<SymbolMap> PromisedResult;
1927 PromisedResult.set_value(std::move(*R));
1930 ResolutionError = R.takeError();
1941 Result = std::move(*R);
1943 ResolutionError = R.takeError();
1947 auto Query = std::make_shared<AsynchronousSymbolQuery>(
1951 SymbolNameSet UnresolvedSymbols = AsyncLookup(Query, std::move(Names));
1955 if (UnresolvedSymbols.empty())
1956 RegisterDependencies(Query->QueryRegistrations);
1960 return Query->canStillFail();
1962 auto Err = make_error<SymbolsNotFound>(std::move(UnresolvedSymbols));
1964 Query->handleFailed(std::move(Err));
1969 #if LLVM_ENABLE_THREADS 1970 auto ResultFuture = PromisedResult.get_future();
1971 auto Result = ResultFuture.get();
1972 if (ResolutionError)
1973 return std::move(ResolutionError);
1974 return std::move(Result);
1977 if (ResolutionError)
1978 return std::move(ResolutionError);
1992 dbgs() <<
"Looking up " << Symbols <<
" in " << SearchOrder
1993 <<
" (required state: " << RequiredState <<
")\n";
2000 runOutstandingMUs();
2002 auto Unresolved = std::move(Symbols);
2003 std::map<JITDylib *, MaterializationUnitList> CollectedMUsMap;
2004 auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
2005 std::move(NotifyComplete));
2006 bool QueryComplete =
false;
2009 auto LodgeQuery = [&]() ->
Error {
2010 for (
auto &KV : SearchOrder) {
2011 assert(KV.first &&
"JITDylibList entries must not be null");
2012 assert(!CollectedMUsMap.count(KV.first) &&
2013 "JITDylibList should not contain duplicate entries");
2015 auto &JD = *KV.first;
2016 auto JDLookupFlags = KV.second;
2017 if (
auto Err = JD.lodgeQuery(CollectedMUsMap[&JD], Q, K, JDLookupFlags,
2023 Unresolved.forEachWithRemoval(
2032 if (!Unresolved.empty())
2033 return make_error<SymbolsNotFound>(Unresolved.getSymbolNames());
2038 if (
auto Err = LodgeQuery()) {
2045 for (
auto &KV : CollectedMUsMap)
2046 for (
auto &MU : KV.second)
2047 KV.first->replace(std::move(MU));
2060 if (RegisterDependencies && !Q->QueryRegistrations.
empty())
2061 RegisterDependencies(Q->QueryRegistrations);
2067 Q->handleFailed(std::move(LodgingErr));
2076 std::lock_guard<std::recursive_mutex>
Lock(OutstandingMUsMutex);
2078 for (
auto &KV : CollectedMUsMap)
2079 for (
auto &MU : KV.second)
2080 OutstandingMUs.push_back(std::make_pair(KV.first, std::move(MU)));
2083 runOutstandingMUs();
2091 #if LLVM_ENABLE_THREADS 2093 std::promise<SymbolMap> PromisedResult;
2098 PromisedResult.set_value(std::move(*R));
2101 ResolutionError = R.takeError();
2113 Result = std::move(*R);
2115 ResolutionError = R.takeError();
2120 lookup(K, SearchOrder, Symbols, RequiredState, NotifyComplete,
2121 RegisterDependencies);
2123 #if LLVM_ENABLE_THREADS 2124 auto ResultFuture = PromisedResult.get_future();
2125 auto Result = ResultFuture.get();
2127 if (ResolutionError)
2128 return std::move(ResolutionError);
2130 return std::move(Result);
2133 if (ResolutionError)
2134 return std::move(ResolutionError);
2147 assert(ResultMap->size() == 1 &&
"Unexpected number of results");
2148 assert(ResultMap->count(Name) &&
"Missing result for symbol");
2149 return std::move(ResultMap->begin()->second);
2151 return ResultMap.takeError();
2167 for (
auto &JD : JDs)
2172 void ExecutionSession::runOutstandingMUs() {
2174 std::pair<JITDylib *, std::unique_ptr<MaterializationUnit>> JITDylibAndMU;
2177 std::lock_guard<std::recursive_mutex>
Lock(OutstandingMUsMutex);
2178 if (!OutstandingMUs.empty()) {
2179 JITDylibAndMU = std::move(OutstandingMUs.back());
2180 OutstandingMUs.pop_back();
2184 if (JITDylibAndMU.first) {
2185 assert(JITDylibAndMU.second &&
"JITDylib, but no MU?");
2187 std::move(JITDylibAndMU.second));
2197 std::string MangledName;
2202 return ES.
intern(MangledName);
void log(raw_ostream &OS) const override
Print an error message to an output stream.
auto lower_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Queried, materialization begun.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
JITDylib & createJITDylib(std::string Name)
Add a new JITDylib to this ExecutionSession.
A parsed version of the target data layout string in and methods for querying it. ...
Error notifyEmitted()
Notifies the target JITDylib (and any pending queries on that JITDylib) that all symbols covered by t...
Added to the symbol table, never queried.
LookupKind
Describes the kind of lookup being performed.
bool isCommon() const
Returns true if the Common flag is set.
This class represents lattice values for constants.
String pool for symbol names used by the JIT.
void dispatchMaterialization(JITDylib &JD, std::unique_ptr< MaterializationUnit > MU)
Materialize the given unit.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
Expected< SymbolAliasMap > buildSimpleReexportsAliasMap(JITDylib &SourceJD, const SymbolNameSet &Symbols)
void replace(std::unique_ptr< MaterializationUnit > MU)
Transfers responsibility to the given MaterializationUnit for all symbols defined by that Materializa...
~MaterializationResponsibility()
Destruct a MaterializationResponsibility instance.
std::function< void(const SymbolDependenceMap &)> RegisterDependenciesFunction
Callback to register the dependencies for a given query.
void doDiscard(const JITDylib &JD, const SymbolStringPtr &Name)
Called by JITDylibs to notify MaterializationUnits that the given symbol has been overridden...
bool isComplete() const
Returns true if all symbols covered by this query have been resolved.
ReExportsMaterializationUnit(JITDylib *SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolAliasMap Aliases, VModuleKey K)
SourceJD is allowed to be nullptr, in which case the source JITDylib is taken to be whatever JITDylib...
SymbolState
Represents the state that a symbol has reached during materialization.
Error remove(const SymbolNameSet &Names)
Tries to remove the given symbols.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
JITSymbolFlags getFlags() const
Return the flags for this symbol.
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup...
auto forEachWithRemoval(BodyFn &&Body) -> typename std::enable_if< std::is_same< decltype(Body(std::declval< const SymbolStringPtr &>(), std::declval< SymbolLookupFlags >())), bool >::value >::type
Loop over the elements of this SymbolLookupSet, applying the Body function to each one...
void addDependencies(const SymbolStringPtr &Name, const SymbolDependenceMap &Dependencies)
void notifySymbolMetRequiredState(const SymbolStringPtr &Name, JITEvaluatedSymbol Sym)
Notify the query that a requested symbol has reached the required state.
print alias Alias Set Printer
JITDylib(const JITDylib &)=delete
std::function< bool(SymbolStringPtr)> SymbolPredicate
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
bool isWeak() const
Returns true if the Weak flag is set.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
MaterializationResponsibility(MaterializationResponsibility &&)=default
SymbolsCouldNotBeRemoved(SymbolNameSet Symbols)
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
std::error_code orcError(OrcErrorCode ErrCode)
SymbolFlagsMap SymbolFlags
Error define(std::unique_ptr< MaterializationUnitType > &&MU)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Tagged union holding either a T or a Error.
std::function< SymbolNameSet(std::shared_ptr< AsynchronousSymbolQuery > Q, SymbolNameSet Names)> LegacyAsyncLookupFunction
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
void replaceInSearchOrder(JITDylib &OldJD, JITDylib &NewJD, JITDylibLookupFlags JDLookupFlags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Replace OldJD with NewJD in the search order if OldJD is present.
void dump(raw_ostream &OS)
Dump the state of all the JITDylibs in this session.
SymbolLookupFlags
Lookup flags that apply to each symbol in a lookup.
std::set< std::shared_ptr< AsynchronousSymbolQuery > > AsynchronousSymbolQuerySet
llvm::detail::DenseMapPair< SymbolStringPtr, JITSymbolFlags > value_type
SymbolStringPtr operator()(StringRef Name)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
void dropSymbol(const SymbolStringPtr &Name)
Remove a symbol from the query.
void legacyFailQuery(AsynchronousSymbolQuery &Q, Error Err)
JITDylib & getTargetJITDylib() const
Returns the target JITDylib that these symbols are being materialized into.
void removeGenerator(DefinitionGenerator &G)
Remove a definition generator from this JITDylib.
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
void removeFromSearchOrder(JITDylib &JD)
Remove the given JITDylib from the search order for this JITDylib if it is present.
bool isCallable() const
Returns true if the given symbol is known to be callable.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
void handleComplete()
Call the NotifyComplete callback.
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases, VModuleKey K=VModuleKey())
Create a ReExportsMaterializationUnit with the given aliases.
Pointer to a pooled string representing a symbol name.
iterator find(const_arg_type_t< KeyT > Val)
initializer< Ty > init(const Ty &Val)
bool erase(const KeyT &Val)
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Expected< SymbolNameSet > legacyLookup(std::shared_ptr< AsynchronousSymbolQuery > Q, SymbolNameSet Names)
FIXME: Remove this when we remove the old ORC layers.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::pair< iterator, bool > insert(const ValueT &V)
Flags for symbols in the JIT.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
SymbolNameVector getSymbolNames() const
Construct a SymbolNameVector from this instance by dropping the Flags values.
void add(SymbolStringPtr Name, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Add an element to the set.
DenseMap< SymbolStringPtr, JITEvaluatedSymbol > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
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 generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
Expected< SymbolFlagsMap > lookupFlags(LookupKind K, JITDylibLookupFlags JDLookupFlags, SymbolLookupSet LookupSet)
Search the given JITDylib for the symbols in Symbols.
Error notifyResolved(const SymbolMap &Symbols)
Notifies the target JITDylib that the given symbols have been resolved.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Expected< SymbolMap > legacyLookup(LegacyAsyncLookupFunction AsyncLookup, SymbolNameSet Names, SymbolState RequiredState, RegisterDependenciesFunction RegisterDependencies)
A legacy lookup function for JITSymbolResolverAdapter.
AsynchronousSymbolQuery(const SymbolLookupSet &Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete)
Create a query for the given symbols.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
No symbol should be in this state.
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group...
MangleAndInterner(ExecutionSession &ES, const DataLayout &DL)
static ErrorSuccess success()
Create a success value.
MaterializationResponsibility delegate(const SymbolNameSet &Symbols, VModuleKey NewKey=VModuleKey())
Delegates responsibility for the given symbols to the returned materialization responsibility.
void addDependenciesForAll(const SymbolDependenceMap &Dependencies)
Add dependencies that apply to all symbols covered by this instance.
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Emitted to memory, but waiting on transitive dependencies.
SymbolsNotFound(SymbolNameSet Symbols)
static uint32_t getFlags(const Symbol *Sym)
SymbolNameSet getRequestedSymbols() const
Returns the names of any symbols covered by this MaterializationResponsibility object that have queri...
An ExecutionSession represents a running JIT program.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool hasError() const
Return true if there was an error retrieving this symbol.
ReexportsGenerator(JITDylib &SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolPredicate Allow=SymbolPredicate())
Create a reexports generator.
void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylib list for the given symbols.
Represents a symbol that has been evaluated to an address already.
Helper for Errors used as out-parameters.
void setSearchOrder(JITDylibSearchOrder NewSearchOrder, bool SearchThisJITDylibFirst=true)
Set the search order to be used when fixing up definitions in JITDylib.
A symbol query that returns results via a callback when results are ready.
std::vector< std::unique_ptr< MaterializationUnit > > MaterializationUnitList
uint8_t uint64_t VModuleKey
VModuleKey provides a unique identifier (allocated and managed by ExecutionSessions) for a module add...
const SymbolFlagsMap & getSymbols() const
Return the set of symbols that this source provides.
AbsoluteSymbolsMaterializationUnit(SymbolMap Symbols, VModuleKey K)
void reportError(Error Err)
Report a error for this execution session.
std::unique_ptr< ReExportsMaterializationUnit > reexports(JITDylib &SourceJD, SymbolAliasMap Aliases, JITDylibLookupFlags SourceJDLookupFlags=JITDylibLookupFlags::MatchExportedSymbolsOnly, VModuleKey K=VModuleKey())
Create a materialization unit for re-exporting symbols from another JITDylib with alternative names/f...
auto runSessionLocked(Func &&F) -> decltype(F())
Run the given lambda with the session mutex locked.
bool isExported() const
Returns true if the Exported flag is set.
Error defineMaterializing(SymbolFlagsMap SymbolFlags)
Attempt to claim responsibility for new definitions.
Sequence
A sequence of states that a pointer may go through in which an objc_retain and objc_release are actua...
const std::string & getName() const
Get the name for this JITDylib.
UnderlyingVector::size_type size() const
Error tryToGenerate(LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &LookupSet) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib...
StringRef getName() const override
Return the name of this materialization unit.
JITDylib * getJITDylibByName(StringRef Name)
Return a pointer to the "name" JITDylib.
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
LLVM_NODISCARD bool empty() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void failMaterialization()
Notify all not-yet-emitted covered by this MaterializationResponsibility instance that an error has o...
void addToSearchOrder(JITDylib &JD, JITDylibLookupFlags JDLookupFlags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Add the given JITDylib to the search order for definitions in this JITDylib.
A raw_ostream that writes to an std::string.
Assigned address, still materializing.
std::pair< SymbolStringPtr, SymbolLookupFlags > value_type
Lightweight error class with error context and mandatory checking.
This class implements an extremely fast bulk output stream that can only output to a stream...
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
StringRef - Represent a constant reference to a string, i.e.
JITTargetAddress getAddress() const
Return the address of this symbol.
void sortByName()
Sort the lookup set lexicographically.
RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
static cl::opt< bool > PrintAll("print-all-alias-modref-info", cl::ReallyHidden)
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
StringRef getName() const override
Return the name of this materialization unit.
ExecutionSession(std::shared_ptr< SymbolStringPool > SSP=nullptr)
Construct an ExecutionSession.
unique_function< void(Expected< SymbolMap >)> SymbolsResolvedCallback
Callback to notify client that symbols have been resolved.
virtual ~DefinitionGenerator()
std::vector< SymbolStringPtr > SymbolNameVector
A vector of symbol names.
A symbol table that supports asynchoronous symbol queries.
void dump(raw_ostream &OS)
Dump current JITDylib state to OS.
virtual StringRef getName() const =0
Return the name of this materialization unit.