LLVM 24.0.0git
Core.cpp
Go to the documentation of this file.
1//===--- Core.cpp - Core ORC APIs (MaterializationUnit, JITDylib, etc.) ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/Config/llvm-config.h"
19
20#include <condition_variable>
21#include <future>
22#include <optional>
23
24#define DEBUG_TYPE "orc"
25
26namespace llvm {
27namespace orc {
28
30char JITDylibDefunct::ID = 0;
32char SymbolsNotFound::ID = 0;
38char LookupTask::ID = 0;
39
42
43void MaterializationUnit::anchor() {}
44
46 assert((reinterpret_cast<uintptr_t>(JD.get()) & 0x1) == 0 &&
47 "JITDylib must be two byte aligned");
48 JD->Retain();
49 JDAndFlag.store(reinterpret_cast<uintptr_t>(JD.get()));
50}
51
53 getJITDylib().getExecutionSession().destroyResourceTracker(*this);
55}
56
58 return getJITDylib().getExecutionSession().removeResourceTracker(*this);
59}
60
62 getJITDylib().getExecutionSession().transferResourceTracker(DstRT, *this);
63}
64
65void ResourceTracker::makeDefunct() {
66 uintptr_t Val = JDAndFlag.load();
67 Val |= 0x1U;
68 JDAndFlag.store(Val);
69}
70
72
75
79
81 OS << "Resource tracker " << (void *)RT.get() << " became defunct";
82}
83
87
89 OS << "JITDylib " << JD->getName() << " (" << (void *)JD.get()
90 << ") is defunct";
91}
92
94 std::shared_ptr<SymbolStringPool> SSP,
95 std::shared_ptr<SymbolDependenceMap> Symbols)
96 : SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
97 assert(this->SSP && "String pool cannot be null");
98 assert(!this->Symbols->empty() && "Can not fail to resolve an empty set");
99
100 // FIXME: Use a new dep-map type for FailedToMaterialize errors so that we
101 // don't have to manually retain/release.
102 for (auto &[JD, Syms] : *this->Symbols)
103 JD->Retain();
104}
105
107 for (auto &[JD, Syms] : *Symbols)
108 JD->Release();
109}
110
114
116 OS << "Failed to materialize symbols: " << *Symbols;
117}
118
120 std::shared_ptr<SymbolStringPool> SSP, JITDylibSP JD,
121 SymbolNameSet FailedSymbols, SymbolDependenceMap BadDeps,
122 std::string Explanation)
123 : SSP(std::move(SSP)), JD(std::move(JD)),
124 FailedSymbols(std::move(FailedSymbols)), BadDeps(std::move(BadDeps)),
125 Explanation(std::move(Explanation)) {}
126
130
132 OS << "In " << JD->getName() << ", failed to materialize " << FailedSymbols
133 << ", due to unsatisfied dependencies " << BadDeps;
134 if (!Explanation.empty())
135 OS << " (" << Explanation << ")";
136}
137
138SymbolsNotFound::SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
139 SymbolNameSet Symbols)
140 : SSP(std::move(SSP)) {
141 llvm::append_range(this->Symbols, Symbols);
142 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
143}
144
145SymbolsNotFound::SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
146 SymbolNameVector Symbols)
147 : SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
148 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
149}
150
154
156 OS << "Symbols not found: " << Symbols;
157}
158
160 std::shared_ptr<SymbolStringPool> SSP, SymbolNameSet Symbols)
161 : SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
162 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
163}
164
168
170 OS << "Symbols could not be removed: " << Symbols;
171}
172
176
178 OS << "Missing definitions in module " << ModuleName
179 << ": " << Symbols;
180}
181
185
187 OS << "Unexpected definitions in module " << ModuleName
188 << ": " << Symbols;
189}
190
192 const SymbolLookupSet &Symbols, SymbolState RequiredState,
193 SymbolsResolvedCallback NotifyComplete)
194 : NotifyComplete(std::move(NotifyComplete)), RequiredState(RequiredState) {
195 assert(RequiredState >= SymbolState::Resolved &&
196 "Cannot query for a symbols that have not reached the resolve state "
197 "yet");
198
199 OutstandingSymbolsCount = Symbols.size();
200
201 for (auto &[Name, Flags] : Symbols)
202 ResolvedSymbols[Name] = ExecutorSymbolDef();
203}
204
206 const SymbolStringPtr &Name, ExecutorSymbolDef Sym) {
207 auto I = ResolvedSymbols.find(Name);
208 assert(I != ResolvedSymbols.end() &&
209 "Resolving symbol outside the requested set");
210 assert(I->second == ExecutorSymbolDef() &&
211 "Redundantly resolving symbol Name");
212
213 // If this is a materialization-side-effects-only symbol then drop it,
214 // otherwise update its map entry with its resolved address.
216 ResolvedSymbols.erase(I);
217 else
218 I->second = std::move(Sym);
219 --OutstandingSymbolsCount;
220}
221
222void AsynchronousSymbolQuery::handleComplete(ExecutionSession &ES) {
223 assert(OutstandingSymbolsCount == 0 &&
224 "Symbols remain, handleComplete called prematurely");
225
226 class RunQueryCompleteTask : public Task {
227 public:
228 RunQueryCompleteTask(SymbolMap ResolvedSymbols,
229 SymbolsResolvedCallback NotifyComplete)
230 : ResolvedSymbols(std::move(ResolvedSymbols)),
231 NotifyComplete(std::move(NotifyComplete)) {}
232 void printDescription(raw_ostream &OS) override {
233 OS << "Execute query complete callback for " << ResolvedSymbols;
234 }
235 void run() override { NotifyComplete(std::move(ResolvedSymbols)); }
236
237 private:
238 SymbolMap ResolvedSymbols;
239 SymbolsResolvedCallback NotifyComplete;
240 };
241
242 auto T = std::make_unique<RunQueryCompleteTask>(std::move(ResolvedSymbols),
243 std::move(NotifyComplete));
244 NotifyComplete = SymbolsResolvedCallback();
245 ES.dispatchTask(std::move(T));
246}
247
248void AsynchronousSymbolQuery::handleFailed(Error Err) {
249 assert(QueryRegistrations.empty() && ResolvedSymbols.empty() &&
250 OutstandingSymbolsCount == 0 &&
251 "Query should already have been abandoned");
252 NotifyComplete(std::move(Err));
253 NotifyComplete = SymbolsResolvedCallback();
254}
255
256void AsynchronousSymbolQuery::addQueryDependence(JITDylib &JD,
257 SymbolStringPtr Name) {
258 bool Added = QueryRegistrations[&JD].insert(std::move(Name)).second;
259 (void)Added;
260 assert(Added && "Duplicate dependence notification?");
261}
262
263void AsynchronousSymbolQuery::removeQueryDependence(
264 JITDylib &JD, const SymbolStringPtr &Name) {
265 auto QRI = QueryRegistrations.find(&JD);
266 assert(QRI != QueryRegistrations.end() &&
267 "No dependencies registered for JD");
268 assert(QRI->second.count(Name) && "No dependency on Name in JD");
269 QRI->second.erase(Name);
270 if (QRI->second.empty())
271 QueryRegistrations.erase(QRI);
272}
273
274void AsynchronousSymbolQuery::dropSymbol(const SymbolStringPtr &Name) {
275 auto I = ResolvedSymbols.find(Name);
276 assert(I != ResolvedSymbols.end() &&
277 "Redundant removal of weakly-referenced symbol");
278 ResolvedSymbols.erase(I);
279 --OutstandingSymbolsCount;
280}
281
282void AsynchronousSymbolQuery::detach() {
283 ResolvedSymbols.clear();
284 OutstandingSymbolsCount = 0;
285 for (auto &[JD, Syms] : QueryRegistrations)
286 JD->detachQueryHelper(*this, Syms);
287 QueryRegistrations.clear();
288}
289
291 JITDylib *SourceJD, JITDylibLookupFlags SourceJDLookupFlags,
292 SymbolAliasMap Aliases)
293 : MaterializationUnit(extractFlags(Aliases)), SourceJD(SourceJD),
294 SourceJDLookupFlags(SourceJDLookupFlags), Aliases(std::move(Aliases)) {}
295
297 return "<Reexports>";
298}
299
300void ReExportsMaterializationUnit::materialize(
301 std::unique_ptr<MaterializationResponsibility> R) {
302
303 auto &ES = R->getTargetJITDylib().getExecutionSession();
304 JITDylib &TgtJD = R->getTargetJITDylib();
305 JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD;
306
307 // Find the set of requested aliases and aliasees. Return any unrequested
308 // aliases back to the JITDylib so as to not prematurely materialize any
309 // aliasees.
310 auto RequestedSymbols = R->getRequestedSymbols();
311 SymbolAliasMap RequestedAliases;
312
313 for (auto &Name : RequestedSymbols) {
314 auto I = Aliases.find(Name);
315 assert(I != Aliases.end() && "Symbol not found in aliases map?");
316 RequestedAliases[Name] = std::move(I->second);
317 Aliases.erase(I);
318 }
319
320 LLVM_DEBUG({
321 ES.runSessionLocked([&]() {
322 dbgs() << "materializing reexports: target = " << TgtJD.getName()
323 << ", source = " << SrcJD.getName() << " " << RequestedAliases
324 << "\n";
325 });
326 });
327
328 if (!Aliases.empty()) {
329 auto Err = SourceJD ? R->replace(reexports(*SourceJD, std::move(Aliases),
330 SourceJDLookupFlags))
331 : R->replace(symbolAliases(std::move(Aliases)));
332
333 if (Err) {
334 // FIXME: Should this be reported / treated as failure to materialize?
335 // Or should this be treated as a sanctioned bailing-out?
336 ES.reportError(std::move(Err));
337 R->failMaterialization();
338 return;
339 }
340 }
341
342 // The OnResolveInfo struct will hold the aliases and responsibility for each
343 // query in the list.
344 struct OnResolveInfo {
345 OnResolveInfo(std::unique_ptr<MaterializationResponsibility> R,
346 SymbolAliasMap Aliases)
347 : R(std::move(R)), Aliases(std::move(Aliases)) {}
348
349 std::unique_ptr<MaterializationResponsibility> R;
350 SymbolAliasMap Aliases;
351 std::vector<SymbolDependenceGroup> SDGs;
352 };
353
354 // Build a list of queries to issue. In each round we build a query for the
355 // largest set of aliases that we can resolve without encountering a chain of
356 // aliases (e.g. Foo -> Bar, Bar -> Baz). Such a chain would deadlock as the
357 // query would be waiting on a symbol that it itself had to resolve. Creating
358 // a new query for each link in such a chain eliminates the possibility of
359 // deadlock. In practice chains are likely to be rare, and this algorithm will
360 // usually result in a single query to issue.
361
362 std::vector<std::pair<SymbolLookupSet, std::shared_ptr<OnResolveInfo>>>
363 QueryInfos;
364 while (!RequestedAliases.empty()) {
365 SymbolNameSet ResponsibilitySymbols;
366 SymbolLookupSet QuerySymbols;
367 SymbolAliasMap QueryAliases;
368
369 // Collect as many aliases as we can without including a chain.
370 for (auto &[Alias, AliasInfo] : RequestedAliases) {
371 // Chain detected. Skip this symbol for this round.
372 if (&SrcJD == &TgtJD && (QueryAliases.count(AliasInfo.Aliasee) ||
373 RequestedAliases.count(AliasInfo.Aliasee)))
374 continue;
375
376 ResponsibilitySymbols.insert(Alias);
377 QuerySymbols.add(AliasInfo.Aliasee,
378 AliasInfo.AliasFlags.hasMaterializationSideEffectsOnly()
379 ? SymbolLookupFlags::WeaklyReferencedSymbol
380 : SymbolLookupFlags::RequiredSymbol);
381 QueryAliases[Alias] = std::move(AliasInfo);
382 }
383
384 // Remove the aliases collected this round from the RequestedAliases map.
385 for (auto &KV : QueryAliases)
386 RequestedAliases.erase(KV.first);
387
388 assert(!QuerySymbols.empty() && "Alias cycle detected!");
389
390 auto NewR = R->delegate(ResponsibilitySymbols);
391 if (!NewR) {
392 ES.reportError(NewR.takeError());
393 R->failMaterialization();
394 return;
395 }
396
397 auto QueryInfo = std::make_shared<OnResolveInfo>(std::move(*NewR),
398 std::move(QueryAliases));
399 QueryInfos.push_back(
400 make_pair(std::move(QuerySymbols), std::move(QueryInfo)));
401 }
402
403 // Issue the queries.
404 while (!QueryInfos.empty()) {
405 auto QuerySymbols = std::move(QueryInfos.back().first);
406 auto QueryInfo = std::move(QueryInfos.back().second);
407
408 QueryInfos.pop_back();
409
410 auto RegisterDependencies = [QueryInfo,
411 &SrcJD](const SymbolDependenceMap &Deps) {
412 // If there were no materializing symbols, just bail out.
413 if (Deps.empty())
414 return;
415
416 // Otherwise the only deps should be on SrcJD.
417 assert(Deps.size() == 1 && Deps.count(&SrcJD) &&
418 "Unexpected dependencies for reexports");
419
420 auto &SrcJDDeps = Deps.find(&SrcJD)->second;
421
422 for (auto &[Alias, AliasInfo] : QueryInfo->Aliases)
423 if (SrcJDDeps.count(AliasInfo.Aliasee))
424 QueryInfo->SDGs.push_back({{Alias}, {{&SrcJD, {AliasInfo.Aliasee}}}});
425 };
426
427 auto OnComplete = [QueryInfo](Expected<SymbolMap> Result) {
428 auto &ES = QueryInfo->R->getTargetJITDylib().getExecutionSession();
429 if (Result) {
430 SymbolMap ResolutionMap;
431 for (auto &KV : QueryInfo->Aliases) {
432 assert((KV.second.AliasFlags.hasMaterializationSideEffectsOnly() ||
433 Result->count(KV.second.Aliasee)) &&
434 "Result map missing entry?");
435 // Don't try to resolve materialization-side-effects-only symbols.
436 if (KV.second.AliasFlags.hasMaterializationSideEffectsOnly())
437 continue;
438
439 ResolutionMap[KV.first] = {(*Result)[KV.second.Aliasee].getAddress(),
440 KV.second.AliasFlags};
441 }
442 if (auto Err = QueryInfo->R->notifyResolved(ResolutionMap)) {
443 ES.reportError(std::move(Err));
444 QueryInfo->R->failMaterialization();
445 return;
446 }
447 if (auto Err = QueryInfo->R->notifyEmitted(QueryInfo->SDGs)) {
448 ES.reportError(std::move(Err));
449 QueryInfo->R->failMaterialization();
450 return;
451 }
452 } else {
453 ES.reportError(Result.takeError());
454 QueryInfo->R->failMaterialization();
455 }
456 };
457
459 JITDylibSearchOrder({{&SrcJD, SourceJDLookupFlags}}),
460 QuerySymbols, SymbolState::Resolved, std::move(OnComplete),
461 std::move(RegisterDependencies));
462 }
463}
464
465void ReExportsMaterializationUnit::discard(const JITDylib &JD,
466 const SymbolStringPtr &Name) {
467 assert(Aliases.count(Name) &&
468 "Symbol not covered by this MaterializationUnit");
469 Aliases.erase(Name);
470}
471
472MaterializationUnit::Interface
473ReExportsMaterializationUnit::extractFlags(const SymbolAliasMap &Aliases) {
475 for (auto &KV : Aliases)
476 SymbolFlags[KV.first] = KV.second.AliasFlags;
477
478 return MaterializationUnit::Interface(std::move(SymbolFlags), nullptr);
479}
480
483 SymbolLookupSet LookupSet(Symbols);
484 auto Flags = SourceJD.getExecutionSession().lookupFlags(
486 SymbolLookupSet(std::move(Symbols)));
487
488 if (!Flags)
489 return Flags.takeError();
490
492 for (auto &Name : Symbols) {
493 assert(Flags->count(Name) && "Missing entry in flags map");
494 Result[Name] = SymbolAliasMapEntry(Name, (*Flags)[Name]);
495 }
496
497 return Result;
498}
499
501public:
502 // FIXME: Reduce the number of SymbolStringPtrs here. See
503 // https://github.com/llvm/llvm-project/issues/55576.
504
511 virtual ~InProgressLookupState() = default;
512 virtual void complete(std::unique_ptr<InProgressLookupState> IPLS) = 0;
513 virtual void fail(Error Err) = 0;
514
519
521 bool NewJITDylib = true;
524
525 enum {
526 NotInGenerator, // Not currently using a generator.
527 ResumedForGenerator, // Resumed after being auto-suspended before generator.
528 InGenerator // Currently using generator.
529 } GenState = NotInGenerator;
530 std::vector<std::weak_ptr<DefinitionGenerator>> CurDefGeneratorStack;
531};
532
534public:
541
542 void complete(std::unique_ptr<InProgressLookupState> IPLS) override {
543 auto &ES = SearchOrder.front().first->getExecutionSession();
544 ES.OL_completeLookupFlags(std::move(IPLS), std::move(OnComplete));
545 }
546
547 void fail(Error Err) override { OnComplete(std::move(Err)); }
548
549private:
551};
552
554public:
558 std::shared_ptr<AsynchronousSymbolQuery> Q,
559 RegisterDependenciesFunction RegisterDependencies)
562 Q(std::move(Q)), RegisterDependencies(std::move(RegisterDependencies)) {
563 }
564
565 void complete(std::unique_ptr<InProgressLookupState> IPLS) override {
566 auto &ES = SearchOrder.front().first->getExecutionSession();
567 ES.OL_completeLookup(std::move(IPLS), std::move(Q),
568 std::move(RegisterDependencies));
569 }
570
571 void fail(Error Err) override {
572 Q->detach();
573 Q->handleFailed(std::move(Err));
574 }
575
576private:
577 std::shared_ptr<AsynchronousSymbolQuery> Q;
578 RegisterDependenciesFunction RegisterDependencies;
579};
580
582 JITDylibLookupFlags SourceJDLookupFlags,
583 SymbolPredicate Allow)
584 : SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
585 Allow(std::move(Allow)) {}
586
588 JITDylib &JD,
589 JITDylibLookupFlags JDLookupFlags,
590 const SymbolLookupSet &LookupSet) {
591 assert(&JD != &SourceJD && "Cannot re-export from the same dylib");
592
593 // Use lookupFlags to find the subset of symbols that match our lookup.
594 auto Flags = JD.getExecutionSession().lookupFlags(
595 K, {{&SourceJD, JDLookupFlags}}, LookupSet);
596 if (!Flags)
597 return Flags.takeError();
598
599 // Create an alias map.
600 orc::SymbolAliasMap AliasMap;
601 for (auto &KV : *Flags)
602 if (!Allow || Allow(KV.first))
603 AliasMap[KV.first] = SymbolAliasMapEntry(KV.first, KV.second);
604
605 if (AliasMap.empty())
606 return Error::success();
607
608 // Define the re-exports.
609 return JD.define(reexports(SourceJD, AliasMap, SourceJDLookupFlags));
610}
611
612LookupState::LookupState(std::unique_ptr<InProgressLookupState> IPLS)
613 : IPLS(std::move(IPLS)) {}
614
615void LookupState::reset(InProgressLookupState *IPLS) { this->IPLS.reset(IPLS); }
616
617LookupState::LookupState() = default;
618LookupState::LookupState(LookupState &&) = default;
619LookupState &LookupState::operator=(LookupState &&) = default;
620LookupState::~LookupState() = default;
621
623 assert(IPLS && "Cannot call continueLookup on empty LookupState");
624 auto &ES = IPLS->SearchOrder.begin()->first->getExecutionSession();
625 ES.OL_applyQueryPhase1(std::move(IPLS), std::move(Err));
626}
627
629 std::deque<LookupState> LookupsToFail;
630 {
631 std::lock_guard<std::mutex> Lock(M);
632 std::swap(PendingLookups, LookupsToFail);
633 InUse = false;
634 }
635
636 for (auto &LS : LookupsToFail)
637 LS.continueLookup(make_error<StringError>(
638 "Query waiting on DefinitionGenerator that was destroyed",
640}
641
643 LLVM_DEBUG(dbgs() << "Destroying JITDylib " << getName() << "\n");
644}
645
647 std::vector<ResourceTrackerSP> TrackersToRemove;
648 ES.runSessionLocked([&]() {
649 assert(State != Closed && "JD is defunct");
650 for (auto &KV : TrackerSymbols)
651 TrackersToRemove.push_back(KV.first);
652 TrackersToRemove.push_back(getDefaultResourceTracker());
653 });
654
655 Error Err = Error::success();
656 for (auto &RT : TrackersToRemove)
657 Err = joinErrors(std::move(Err), RT->remove());
658 return Err;
659}
660
662 return ES.runSessionLocked([this] {
663 assert(State != Closed && "JD is defunct");
664 if (!DefaultTracker)
665 DefaultTracker = new ResourceTracker(this);
666 return DefaultTracker;
667 });
668}
669
671 return ES.runSessionLocked([this] {
672 assert(State == Open && "JD is defunct");
673 ResourceTrackerSP RT = new ResourceTracker(this);
674 return RT;
675 });
676}
677
679 // DefGenerator moved into TmpDG to ensure that it's destroyed outside the
680 // session lock (since it may have to send errors to pending queries).
681 std::shared_ptr<DefinitionGenerator> TmpDG;
682
683 ES.runSessionLocked([&] {
684 assert(State == Open && "JD is defunct");
685 auto I = llvm::find_if(DefGenerators,
686 [&](const std::shared_ptr<DefinitionGenerator> &H) {
687 return H.get() == &G;
688 });
689 assert(I != DefGenerators.end() && "Generator not found");
690 TmpDG = std::move(*I);
691 DefGenerators.erase(I);
692 });
693}
694
696JITDylib::defineMaterializing(MaterializationResponsibility &FromMR,
697 SymbolFlagsMap SymbolFlags) {
698
699 return ES.runSessionLocked([&]() -> Expected<SymbolFlagsMap> {
700 if (FromMR.RT->isDefunct())
701 return make_error<ResourceTrackerDefunct>(FromMR.RT);
702
703 std::vector<NonOwningSymbolStringPtr> AddedSyms;
704 std::vector<NonOwningSymbolStringPtr> RejectedWeakDefs;
705
706 for (auto &[Name, Flags] : SymbolFlags) {
707 auto EntryItr = Symbols.find(Name);
708
709 // If the entry already exists...
710 if (EntryItr != Symbols.end()) {
711
712 // If this is a strong definition then error out.
713 if (!Flags.isWeak()) {
714 // Remove any symbols already added.
715 for (auto &S : AddedSyms)
716 Symbols.erase(Symbols.find_as(S));
717
718 // FIXME: Return all duplicates.
720 std::string(*Name), "defineMaterializing operation");
721 }
722
723 // Otherwise just make a note to discard this symbol after the loop.
724 RejectedWeakDefs.push_back(NonOwningSymbolStringPtr(Name));
725 continue;
726 } else
727 EntryItr =
728 Symbols.insert(std::make_pair(Name, SymbolTableEntry(Flags))).first;
729
730 AddedSyms.push_back(NonOwningSymbolStringPtr(Name));
731 EntryItr->second.setState(SymbolState::Materializing);
732 }
733
734 // Remove any rejected weak definitions from the SymbolFlags map.
735 while (!RejectedWeakDefs.empty()) {
736 SymbolFlags.erase(SymbolFlags.find_as(RejectedWeakDefs.back()));
737 RejectedWeakDefs.pop_back();
738 }
739
740 return SymbolFlags;
741 });
742}
743
744Error JITDylib::replace(MaterializationResponsibility &FromMR,
745 std::unique_ptr<MaterializationUnit> MU) {
746 assert(MU != nullptr && "Can not replace with a null MaterializationUnit");
747 std::unique_ptr<MaterializationUnit> MustRunMU;
748 std::unique_ptr<MaterializationResponsibility> MustRunMR;
749
750 auto Err =
751 ES.runSessionLocked([&, this]() -> Error {
752 if (FromMR.RT->isDefunct())
753 return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
754
755#ifndef NDEBUG
756 for (auto &KV : MU->getSymbols()) {
757 auto SymI = Symbols.find(KV.first);
758 assert(SymI != Symbols.end() && "Replacing unknown symbol");
759 assert(SymI->second.getState() == SymbolState::Materializing &&
760 "Can not replace a symbol that ha is not materializing");
761 assert(!SymI->second.hasMaterializerAttached() &&
762 "Symbol should not have materializer attached already");
763 assert(UnmaterializedInfos.count(KV.first) == 0 &&
764 "Symbol being replaced should have no UnmaterializedInfo");
765 }
766#endif // NDEBUG
767
768 // If the tracker is defunct we need to bail out immediately.
769
770 // If any symbol has pending queries against it then we need to
771 // materialize MU immediately.
772 for (auto &KV : MU->getSymbols()) {
773 auto MII = MaterializingInfos.find(KV.first);
774 if (MII != MaterializingInfos.end()) {
775 if (MII->second.hasQueriesPending()) {
776 MustRunMR = ES.createMaterializationResponsibility(
777 *FromMR.RT, std::move(MU->SymbolFlags),
778 std::move(MU->InitSymbol));
779 MustRunMU = std::move(MU);
780 return Error::success();
781 }
782 }
783 }
784
785 // Otherwise, make MU responsible for all the symbols.
786 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU),
787 FromMR.RT.get());
788 for (auto &KV : UMI->MU->getSymbols()) {
789 auto SymI = Symbols.find(KV.first);
790 assert(SymI->second.getState() == SymbolState::Materializing &&
791 "Can not replace a symbol that is not materializing");
792 assert(!SymI->second.hasMaterializerAttached() &&
793 "Can not replace a symbol that has a materializer attached");
794 assert(UnmaterializedInfos.count(KV.first) == 0 &&
795 "Unexpected materializer entry in map");
796 SymI->second.setAddress(SymI->second.getAddress());
797 SymI->second.setMaterializerAttached(true);
798
799 auto &UMIEntry = UnmaterializedInfos[KV.first];
800 assert((!UMIEntry || !UMIEntry->MU) &&
801 "Replacing symbol with materializer still attached");
802 UMIEntry = UMI;
803 }
804
805 return Error::success();
806 });
807
808 if (Err)
809 return Err;
810
811 if (MustRunMU) {
812 assert(MustRunMR && "MustRunMU set implies MustRunMR set");
813 ES.dispatchTask(std::make_unique<MaterializationTask>(
814 std::move(MustRunMU), std::move(MustRunMR)));
815 } else {
816 assert(!MustRunMR && "MustRunMU unset implies MustRunMR unset");
817 }
818
819 return Error::success();
820}
821
822Expected<std::unique_ptr<MaterializationResponsibility>>
823JITDylib::delegate(MaterializationResponsibility &FromMR,
824 SymbolFlagsMap SymbolFlags, SymbolStringPtr InitSymbol) {
825
826 return ES.runSessionLocked(
827 [&]() -> Expected<std::unique_ptr<MaterializationResponsibility>> {
828 if (FromMR.RT->isDefunct())
829 return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
830
831 return ES.createMaterializationResponsibility(
832 *FromMR.RT, std::move(SymbolFlags), std::move(InitSymbol));
833 });
834}
835
837JITDylib::getRequestedSymbols(const SymbolFlagsMap &SymbolFlags) const {
838 return ES.runSessionLocked([&]() {
839 SymbolNameSet RequestedSymbols;
840
841 for (auto &KV : SymbolFlags) {
842 assert(Symbols.count(KV.first) && "JITDylib does not cover this symbol?");
843 assert(Symbols.find(KV.first)->second.getState() !=
845 Symbols.find(KV.first)->second.getState() != SymbolState::Ready &&
846 "getRequestedSymbols can only be called for symbols that have "
847 "started materializing");
848 auto I = MaterializingInfos.find(KV.first);
849 if (I == MaterializingInfos.end())
850 continue;
851
852 if (I->second.hasQueriesPending())
853 RequestedSymbols.insert(KV.first);
854 }
855
856 return RequestedSymbols;
857 });
858}
859
860Error JITDylib::resolve(MaterializationResponsibility &MR,
861 const SymbolMap &Resolved) {
862 AsynchronousSymbolQuerySet CompletedQueries;
863
864 if (auto Err = ES.runSessionLocked([&, this]() -> Error {
865 if (MR.RT->isDefunct())
866 return make_error<ResourceTrackerDefunct>(MR.RT);
867
868 if (State != Open)
869 return make_error<StringError>("JITDylib " + getName() +
870 " is defunct",
871 inconvertibleErrorCode());
872
873 struct WorklistEntry {
874 SymbolTable::iterator SymI;
875 ExecutorSymbolDef ResolvedSym;
876 };
877
878 SymbolNameSet SymbolsInErrorState;
879 std::vector<WorklistEntry> Worklist;
880 Worklist.reserve(Resolved.size());
881
882 // Build worklist and check for any symbols in the error state.
883 for (const auto &KV : Resolved) {
884
885 assert(!KV.second.getFlags().hasError() &&
886 "Resolution result can not have error flag set");
887
888 auto SymI = Symbols.find(KV.first);
889
890 assert(SymI != Symbols.end() && "Symbol not found");
891 assert(!SymI->second.hasMaterializerAttached() &&
892 "Resolving symbol with materializer attached?");
893 assert(SymI->second.getState() == SymbolState::Materializing &&
894 "Symbol should be materializing");
895 assert(SymI->second.getAddress() == ExecutorAddr() &&
896 "Symbol has already been resolved");
897
898 if (SymI->second.getFlags().hasError())
899 SymbolsInErrorState.insert(KV.first);
900 else {
901 if (SymI->second.getFlags() & JITSymbolFlags::Common) {
902 [[maybe_unused]] auto WeakOrCommon =
904 assert((KV.second.getFlags() & WeakOrCommon) &&
905 "Common symbols must be resolved as common or weak");
906 assert((KV.second.getFlags() & ~WeakOrCommon) ==
907 (SymI->second.getFlags() & ~JITSymbolFlags::Common) &&
908 "Resolving symbol with incorrect flags");
909
910 } else
911 assert(KV.second.getFlags() == SymI->second.getFlags() &&
912 "Resolved flags should match the declared flags");
913
914 Worklist.push_back(
915 {SymI, {KV.second.getAddress(), SymI->second.getFlags()}});
916 }
917 }
918
919 // If any symbols were in the error state then bail out.
920 if (!SymbolsInErrorState.empty()) {
921 auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
922 (*FailedSymbolsDepMap)[this] = std::move(SymbolsInErrorState);
923 return make_error<FailedToMaterialize>(
924 getExecutionSession().getSymbolStringPool(),
925 std::move(FailedSymbolsDepMap));
926 }
927
928 while (!Worklist.empty()) {
929 auto SymI = Worklist.back().SymI;
930 auto ResolvedSym = Worklist.back().ResolvedSym;
931 Worklist.pop_back();
932
933 auto &Name = SymI->first;
934
935 // Resolved symbols can not be weak: discard the weak flag.
936 JITSymbolFlags ResolvedFlags = ResolvedSym.getFlags();
937 SymI->second.setAddress(ResolvedSym.getAddress());
938 SymI->second.setFlags(ResolvedFlags);
939 SymI->second.setState(SymbolState::Resolved);
940
941 auto MII = MaterializingInfos.find(Name);
942 if (MII == MaterializingInfos.end())
943 continue;
944
945 auto &MI = MII->second;
946 for (auto &Q : MI.takeQueriesMeeting(SymbolState::Resolved)) {
947 Q->notifySymbolMetRequiredState(Name, ResolvedSym);
948 if (Q->isComplete())
949 CompletedQueries.insert(std::move(Q));
950 }
951 }
952
953 return Error::success();
954 }))
955 return Err;
956
957 // Otherwise notify all the completed queries.
958 for (auto &Q : CompletedQueries) {
959 assert(Q->isComplete() && "Q not completed");
960 Q->handleComplete(ES);
961 }
962
963 return Error::success();
964}
965
966void JITDylib::unlinkMaterializationResponsibility(
967 MaterializationResponsibility &MR) {
968 ES.runSessionLocked([&]() {
969 auto I = TrackerMRs.find(MR.RT.get());
970 assert(I != TrackerMRs.end() && "No MRs in TrackerMRs list for RT");
971 assert(I->second.count(&MR) && "MR not in TrackerMRs list for RT");
972 I->second.erase(&MR);
973 if (I->second.empty())
974 TrackerMRs.erase(MR.RT.get());
975 });
976}
977
978void JITDylib::shrinkMaterializationInfoMemory() {
979 // DenseMap::erase never shrinks its storage; use clear to heuristically free
980 // memory since we may have long-lived JDs after linking is done.
981
982 if (UnmaterializedInfos.empty())
983 UnmaterializedInfos.clear();
984
985 if (MaterializingInfos.empty())
986 MaterializingInfos.clear();
987}
988
990 bool LinkAgainstThisJITDylibFirst) {
991 ES.runSessionLocked([&]() {
992 assert(State == Open && "JD is defunct");
993 if (LinkAgainstThisJITDylibFirst) {
994 LinkOrder.clear();
995 if (NewLinkOrder.empty() || NewLinkOrder.front().first != this)
996 LinkOrder.push_back(
997 std::make_pair(this, JITDylibLookupFlags::MatchAllSymbols));
998 llvm::append_range(LinkOrder, NewLinkOrder);
999 } else
1000 LinkOrder = std::move(NewLinkOrder);
1001 });
1002}
1003
1005 ES.runSessionLocked([&]() {
1006 for (auto &KV : NewLinks) {
1007 // Skip elements of NewLinks that are already in the link order.
1008 if (llvm::is_contained(LinkOrder, KV))
1009 continue;
1010
1011 LinkOrder.push_back(std::move(KV));
1012 }
1013 });
1014}
1015
1017 ES.runSessionLocked([&]() { LinkOrder.push_back({&JD, JDLookupFlags}); });
1018}
1019
1021 JITDylibLookupFlags JDLookupFlags) {
1022 ES.runSessionLocked([&]() {
1023 assert(State == Open && "JD is defunct");
1024 for (auto &KV : LinkOrder)
1025 if (KV.first == &OldJD) {
1026 KV = {&NewJD, JDLookupFlags};
1027 break;
1028 }
1029 });
1030}
1031
1033 ES.runSessionLocked([&]() {
1034 assert(State == Open && "JD is defunct");
1035 auto I = llvm::find_if(LinkOrder,
1036 [&](const JITDylibSearchOrder::value_type &KV) {
1037 return KV.first == &JD;
1038 });
1039 if (I != LinkOrder.end())
1040 LinkOrder.erase(I);
1041 });
1042}
1043
1045 return ES.runSessionLocked([&]() -> Error {
1046 assert(State == Open && "JD is defunct");
1047 SmallVector<SymbolStringPtr, 0> SymbolsToRemove;
1048 SymbolNameSet Missing;
1050
1051 for (auto &Name : Names) {
1052 auto I = Symbols.find(Name);
1053
1054 // Note symbol missing.
1055 if (I == Symbols.end()) {
1056 Missing.insert(Name);
1057 continue;
1058 }
1059
1060 // Note symbol materializing.
1061 if (I->second.getState() != SymbolState::NeverSearched &&
1062 I->second.getState() != SymbolState::Ready) {
1063 Materializing.insert(Name);
1064 continue;
1065 }
1066
1067 SymbolsToRemove.push_back(Name);
1068 }
1069
1070 // If any of the symbols are not defined, return an error.
1071 if (!Missing.empty())
1072 return make_error<SymbolsNotFound>(ES.getSymbolStringPool(),
1073 std::move(Missing));
1074
1075 // If any of the symbols are currently materializing, return an error.
1076 if (!Materializing.empty())
1077 return make_error<SymbolsCouldNotBeRemoved>(ES.getSymbolStringPool(),
1078 std::move(Materializing));
1079
1080 // Remove the symbols. Erase by key rather than holding iterators across the
1081 // loop: a prior erase invalidates other stored iterators under
1082 // backward-shift deletion.
1083 for (const SymbolStringPtr &Name : SymbolsToRemove) {
1084 // If there is a materializer attached, call discard.
1085 auto UMII = UnmaterializedInfos.find(Name);
1086 if (UMII != UnmaterializedInfos.end()) {
1087 UMII->second->MU->doDiscard(*this, UMII->first);
1088 UnmaterializedInfos.erase(UMII);
1089 }
1090
1091 Symbols.erase(Name);
1092 }
1093
1094 shrinkMaterializationInfoMemory();
1095
1096 return Error::success();
1097 });
1098}
1099
1101 ES.runSessionLocked([&, this]() {
1102 OS << "JITDylib \"" << getName() << "\" (ES: "
1103 << format("0x%016" PRIx64, reinterpret_cast<uintptr_t>(&ES))
1104 << ", State = ";
1105 switch (State) {
1106 case Open:
1107 OS << "Open";
1108 break;
1109 case Closing:
1110 OS << "Closing";
1111 break;
1112 case Closed:
1113 OS << "Closed";
1114 break;
1115 }
1116 OS << ")\n";
1117 if (State == Closed)
1118 return;
1119 OS << "Link order: " << LinkOrder << "\n"
1120 << "Symbol table:\n";
1121
1122 // Sort symbols so we get a deterministic order and can check them in tests.
1123 std::vector<std::pair<SymbolStringPtr, SymbolTableEntry *>> SymbolsSorted;
1124 for (auto &KV : Symbols)
1125 SymbolsSorted.emplace_back(KV.first, &KV.second);
1126 std::sort(SymbolsSorted.begin(), SymbolsSorted.end(),
1127 [](const auto &L, const auto &R) { return *L.first < *R.first; });
1128
1129 for (auto &KV : SymbolsSorted) {
1130 OS << " \"" << *KV.first << "\": ";
1131 if (auto Addr = KV.second->getAddress())
1132 OS << Addr;
1133 else
1134 OS << "<not resolved> ";
1135
1136 OS << " " << KV.second->getFlags() << " " << KV.second->getState();
1137
1138 if (KV.second->hasMaterializerAttached()) {
1139 OS << " (Materializer ";
1140 auto I = UnmaterializedInfos.find(KV.first);
1141 assert(I != UnmaterializedInfos.end() &&
1142 "Lazy symbol should have UnmaterializedInfo");
1143 OS << I->second->MU.get() << ", " << I->second->MU->getName() << ")\n";
1144 } else
1145 OS << "\n";
1146 }
1147
1148 if (!MaterializingInfos.empty())
1149 OS << " MaterializingInfos entries:\n";
1150 for (auto &KV : MaterializingInfos) {
1151 OS << " \"" << *KV.first << "\":\n"
1152 << " " << KV.second.pendingQueries().size()
1153 << " pending queries: { ";
1154 for (const auto &Q : KV.second.pendingQueries())
1155 OS << Q.get() << " (" << Q->getRequiredState() << ") ";
1156 OS << "}\n";
1157 }
1158 });
1159}
1160
1161void JITDylib::MaterializingInfo::addQuery(
1162 std::shared_ptr<AsynchronousSymbolQuery> Q) {
1163
1164 auto I = llvm::lower_bound(
1165 llvm::reverse(PendingQueries), Q->getRequiredState(),
1166 [](const std::shared_ptr<AsynchronousSymbolQuery> &V, SymbolState S) {
1167 return V->getRequiredState() <= S;
1168 });
1169 PendingQueries.insert(I.base(), std::move(Q));
1170}
1171
1172void JITDylib::MaterializingInfo::removeQuery(
1173 const AsynchronousSymbolQuery &Q) {
1174 // FIXME: Implement 'find_as' for shared_ptr<T>/T*.
1175 auto I = llvm::find_if(
1176 PendingQueries, [&Q](const std::shared_ptr<AsynchronousSymbolQuery> &V) {
1177 return V.get() == &Q;
1178 });
1179 if (I != PendingQueries.end())
1180 PendingQueries.erase(I);
1181}
1182
1183JITDylib::AsynchronousSymbolQueryList
1184JITDylib::MaterializingInfo::takeQueriesMeeting(SymbolState RequiredState) {
1185 AsynchronousSymbolQueryList Result;
1186 while (!PendingQueries.empty()) {
1187 if (PendingQueries.back()->getRequiredState() > RequiredState)
1188 break;
1189
1190 Result.push_back(std::move(PendingQueries.back()));
1191 PendingQueries.pop_back();
1192 }
1193
1194 return Result;
1195}
1196
1197JITDylib::JITDylib(ExecutionSession &ES, std::string Name)
1198 : JITLinkDylib(std::move(Name)), ES(ES) {
1199 LinkOrder.push_back({this, JITDylibLookupFlags::MatchAllSymbols});
1200}
1201
1202JITDylib::RemoveTrackerResult JITDylib::IL_removeTracker(ResourceTracker &RT) {
1203 // Note: Should be called under the session lock.
1204 assert(State != Closed && "JD is defunct");
1205
1206 SymbolNameVector SymbolsToRemove;
1207 SymbolNameVector SymbolsToFail;
1208
1209 if (&RT == DefaultTracker.get()) {
1210 SymbolNameSet TrackedSymbols;
1211 for (auto &KV : TrackerSymbols)
1212 TrackedSymbols.insert_range(KV.second);
1213
1214 for (auto &KV : Symbols) {
1215 auto &Sym = KV.first;
1216 if (!TrackedSymbols.count(Sym))
1217 SymbolsToRemove.push_back(Sym);
1218 }
1219
1220 DefaultTracker.reset();
1221 } else {
1222 /// Check for a non-default tracker.
1223 auto I = TrackerSymbols.find(&RT);
1224 if (I != TrackerSymbols.end()) {
1225 SymbolsToRemove = std::move(I->second);
1226 TrackerSymbols.erase(I);
1227 }
1228 // ... if not found this tracker was already defunct. Nothing to do.
1229 }
1230
1231 for (auto &Sym : SymbolsToRemove) {
1232 assert(Symbols.count(Sym) && "Symbol not in symbol table");
1233
1234 // If there is a MaterializingInfo then collect any queries to fail.
1235 auto MII = MaterializingInfos.find(Sym);
1236 if (MII != MaterializingInfos.end())
1237 SymbolsToFail.push_back(Sym);
1238 }
1239
1240 auto [QueriesToFail, FailedSymbols] =
1241 ES.IL_failSymbols(*this, std::move(SymbolsToFail));
1242
1243 std::vector<std::unique_ptr<MaterializationUnit>> DefunctMUs;
1244
1245 // Removed symbols should be taken out of the table altogether.
1246 for (auto &Sym : SymbolsToRemove) {
1247 auto I = Symbols.find(Sym);
1248 assert(I != Symbols.end() && "Symbol not present in table");
1249
1250 // Remove Materializer if present.
1251 if (I->second.hasMaterializerAttached()) {
1252 // FIXME: Should this discard the symbols?
1253 auto J = UnmaterializedInfos.find(Sym);
1254 assert(J != UnmaterializedInfos.end() &&
1255 "Symbol table indicates MU present, but no UMI record");
1256 if (J->second->MU)
1257 DefunctMUs.push_back(std::move(J->second->MU));
1258 UnmaterializedInfos.erase(J);
1259 } else {
1260 assert(!UnmaterializedInfos.count(Sym) &&
1261 "Symbol has materializer attached");
1262 }
1263
1264 Symbols.erase(I);
1265 }
1266
1267 shrinkMaterializationInfoMemory();
1268
1269 return {std::move(QueriesToFail), std::move(FailedSymbols),
1270 std::move(DefunctMUs)};
1271}
1272
1273void JITDylib::transferTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT) {
1274 assert(State != Closed && "JD is defunct");
1275 assert(&DstRT != &SrcRT && "No-op transfers shouldn't call transferTracker");
1276 assert(&DstRT.getJITDylib() == this && "DstRT is not for this JITDylib");
1277 assert(&SrcRT.getJITDylib() == this && "SrcRT is not for this JITDylib");
1278
1279 // Update trackers for any not-yet materialized units.
1280 for (auto &KV : UnmaterializedInfos) {
1281 if (KV.second->RT == &SrcRT)
1282 KV.second->RT = &DstRT;
1283 }
1284
1285 // Update trackers for any active materialization responsibilities.
1286 {
1287 auto I = TrackerMRs.find(&SrcRT);
1288 if (I != TrackerMRs.end()) {
1289 auto &SrcMRs = I->second;
1290 auto &DstMRs = TrackerMRs[&DstRT];
1291 for (auto *MR : SrcMRs)
1292 MR->RT = &DstRT;
1293 if (DstMRs.empty())
1294 DstMRs = std::move(SrcMRs);
1295 else
1296 DstMRs.insert_range(SrcMRs);
1297 // Erase SrcRT entry in TrackerMRs. Use &SrcRT key rather than iterator I
1298 // for this, since I may have been invalidated by 'TrackerMRs[&DstRT]'.
1299 TrackerMRs.erase(&SrcRT);
1300 }
1301 }
1302
1303 // If we're transfering to the default tracker we just need to delete the
1304 // tracked symbols for the source tracker.
1305 if (&DstRT == DefaultTracker.get()) {
1306 TrackerSymbols.erase(&SrcRT);
1307 return;
1308 }
1309
1310 // If we're transferring from the default tracker we need to find all
1311 // currently untracked symbols.
1312 if (&SrcRT == DefaultTracker.get()) {
1313 assert(!TrackerSymbols.count(&SrcRT) &&
1314 "Default tracker should not appear in TrackerSymbols");
1315
1316 SymbolNameVector SymbolsToTrack;
1317
1318 SymbolNameSet CurrentlyTrackedSymbols;
1319 for (auto &KV : TrackerSymbols)
1320 CurrentlyTrackedSymbols.insert_range(KV.second);
1321
1322 for (auto &KV : Symbols) {
1323 auto &Sym = KV.first;
1324 if (!CurrentlyTrackedSymbols.count(Sym))
1325 SymbolsToTrack.push_back(Sym);
1326 }
1327
1328 TrackerSymbols[&DstRT] = std::move(SymbolsToTrack);
1329 return;
1330 }
1331
1332 auto &DstTrackedSymbols = TrackerSymbols[&DstRT];
1333
1334 // Finally if neither SrtRT or DstRT are the default tracker then
1335 // just append DstRT's tracked symbols to SrtRT's.
1336 auto SI = TrackerSymbols.find(&SrcRT);
1337 if (SI == TrackerSymbols.end())
1338 return;
1339
1340 DstTrackedSymbols.reserve(DstTrackedSymbols.size() + SI->second.size());
1341 for (auto &Sym : SI->second)
1342 DstTrackedSymbols.push_back(std::move(Sym));
1343 TrackerSymbols.erase(SI);
1344}
1345
1346Error JITDylib::defineImpl(MaterializationUnit &MU) {
1347 LLVM_DEBUG({ dbgs() << " " << MU.getSymbols() << "\n"; });
1348
1349 SymbolNameSet Duplicates;
1350 std::vector<SymbolStringPtr> ExistingDefsOverridden;
1351 std::vector<SymbolStringPtr> MUDefsOverridden;
1352
1353 for (const auto &KV : MU.getSymbols()) {
1354 auto I = Symbols.find(KV.first);
1355
1356 if (I != Symbols.end()) {
1357 if (KV.second.isStrong()) {
1358 if (I->second.getFlags().isStrong() ||
1359 I->second.getState() > SymbolState::NeverSearched)
1360 Duplicates.insert(KV.first);
1361 else {
1362 assert(I->second.getState() == SymbolState::NeverSearched &&
1363 "Overridden existing def should be in the never-searched "
1364 "state");
1365 ExistingDefsOverridden.push_back(KV.first);
1366 }
1367 } else
1368 MUDefsOverridden.push_back(KV.first);
1369 }
1370 }
1371
1372 // If there were any duplicate definitions then bail out.
1373 if (!Duplicates.empty()) {
1374 LLVM_DEBUG(
1375 { dbgs() << " Error: Duplicate symbols " << Duplicates << "\n"; });
1376 return make_error<DuplicateDefinition>(std::string(**Duplicates.begin()),
1377 MU.getName().str());
1378 }
1379
1380 // Discard any overridden defs in this MU.
1381 LLVM_DEBUG({
1382 if (!MUDefsOverridden.empty())
1383 dbgs() << " Defs in this MU overridden: " << MUDefsOverridden << "\n";
1384 });
1385 for (auto &S : MUDefsOverridden)
1386 MU.doDiscard(*this, S);
1387
1388 // Discard existing overridden defs.
1389 LLVM_DEBUG({
1390 if (!ExistingDefsOverridden.empty())
1391 dbgs() << " Existing defs overridden by this MU: " << MUDefsOverridden
1392 << "\n";
1393 });
1394 for (auto &S : ExistingDefsOverridden) {
1395
1396 auto UMII = UnmaterializedInfos.find(S);
1397 assert(UMII != UnmaterializedInfos.end() &&
1398 "Overridden existing def should have an UnmaterializedInfo");
1399 UMII->second->MU->doDiscard(*this, S);
1400 }
1401
1402 // Finally, add the defs from this MU.
1403 for (auto &KV : MU.getSymbols()) {
1404 auto &SymEntry = Symbols[KV.first];
1405 SymEntry.setFlags(KV.second);
1406 SymEntry.setState(SymbolState::NeverSearched);
1407 SymEntry.setMaterializerAttached(true);
1408 }
1409
1410 return Error::success();
1411}
1412
1413void JITDylib::installMaterializationUnit(
1414 std::unique_ptr<MaterializationUnit> MU, ResourceTracker &RT) {
1415
1416 /// defineImpl succeeded.
1417 if (&RT != DefaultTracker.get()) {
1418 auto &TS = TrackerSymbols[&RT];
1419 TS.reserve(TS.size() + MU->getSymbols().size());
1420 for (auto &KV : MU->getSymbols())
1421 TS.push_back(KV.first);
1422 }
1423
1424 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU), &RT);
1425 for (auto &KV : UMI->MU->getSymbols())
1426 UnmaterializedInfos[KV.first] = UMI;
1427}
1428
1429void JITDylib::detachQueryHelper(AsynchronousSymbolQuery &Q,
1430 const SymbolNameSet &QuerySymbols) {
1431 for (auto &QuerySymbol : QuerySymbols) {
1432 auto MII = MaterializingInfos.find(QuerySymbol);
1433 if (MII != MaterializingInfos.end())
1434 MII->second.removeQuery(Q);
1435 }
1436}
1437
1438Platform::~Platform() = default;
1439
1441 ExecutionSession &ES,
1442 const DenseMap<JITDylib *, SymbolLookupSet> &InitSyms) {
1443
1444 DenseMap<JITDylib *, SymbolMap> CompoundResult;
1445 Error CompoundErr = Error::success();
1446 std::mutex LookupMutex;
1447 std::condition_variable CV;
1448 uint64_t Count = InitSyms.size();
1449
1450 LLVM_DEBUG({
1451 dbgs() << "Issuing init-symbol lookup:\n";
1452 for (auto &KV : InitSyms)
1453 dbgs() << " " << KV.first->getName() << ": " << KV.second << "\n";
1454 });
1455
1456 for (auto &KV : InitSyms) {
1457 auto *JD = KV.first;
1458 auto Names = std::move(KV.second);
1459 ES.lookup(
1462 std::move(Names), SymbolState::Ready,
1463 [&, JD](Expected<SymbolMap> Result) {
1464 {
1465 std::lock_guard<std::mutex> Lock(LookupMutex);
1466 --Count;
1467 if (Result) {
1468 assert(!CompoundResult.count(JD) &&
1469 "Duplicate JITDylib in lookup?");
1470 CompoundResult[JD] = std::move(*Result);
1471 } else
1472 CompoundErr =
1473 joinErrors(std::move(CompoundErr), Result.takeError());
1474 }
1475 CV.notify_one();
1476 },
1478 }
1479
1480 std::unique_lock<std::mutex> Lock(LookupMutex);
1481 CV.wait(Lock, [&] { return Count == 0; });
1482
1483 if (CompoundErr)
1484 return std::move(CompoundErr);
1485
1486 return std::move(CompoundResult);
1487}
1488
1490 unique_function<void(Error)> OnComplete, ExecutionSession &ES,
1491 const DenseMap<JITDylib *, SymbolLookupSet> &InitSyms) {
1492
1493 class TriggerOnComplete {
1494 public:
1495 using OnCompleteFn = unique_function<void(Error)>;
1496 TriggerOnComplete(OnCompleteFn OnComplete)
1497 : OnComplete(std::move(OnComplete)) {}
1498 ~TriggerOnComplete() { OnComplete(std::move(LookupResult)); }
1499 void reportResult(Error Err) {
1500 std::lock_guard<std::mutex> Lock(ResultMutex);
1501 LookupResult = joinErrors(std::move(LookupResult), std::move(Err));
1502 }
1503
1504 private:
1505 std::mutex ResultMutex;
1506 Error LookupResult{Error::success()};
1507 OnCompleteFn OnComplete;
1508 };
1509
1510 LLVM_DEBUG({
1511 dbgs() << "Issuing init-symbol lookup:\n";
1512 for (auto &KV : InitSyms)
1513 dbgs() << " " << KV.first->getName() << ": " << KV.second << "\n";
1514 });
1515
1516 auto TOC = std::make_shared<TriggerOnComplete>(std::move(OnComplete));
1517
1518 for (auto &KV : InitSyms) {
1519 auto *JD = KV.first;
1520 auto Names = std::move(KV.second);
1521 ES.lookup(
1524 std::move(Names), SymbolState::Ready,
1526 TOC->reportResult(Result.takeError());
1527 },
1529 }
1530}
1531
1533 // If this task wasn't run then fail materialization.
1534 if (MR)
1535 MR->failMaterialization();
1536}
1537
1539 OS << "Materialization task: " << MU->getName() << " in "
1540 << MR->getTargetJITDylib().getName();
1541}
1542
1544 assert(MU && "MU should not be null");
1545 assert(MR && "MR should not be null");
1546 MU->materialize(std::move(MR));
1547}
1548
1549void LookupTask::printDescription(raw_ostream &OS) { OS << "Lookup task"; }
1550
1551void LookupTask::run() { LS.continueLookup(Error::success()); }
1552
1553ExecutionSession::ExecutionSession(std::unique_ptr<ExecutorProcessControl> EPC)
1554 : EPC(std::move(EPC)), BootstrapJD(createBareJITDylib("<bootstrap>")) {
1555 // Associated EPC and this.
1556 this->EPC->ES = this;
1557 SymbolMap BootstrapSymbols;
1558 for (auto &[Name, Ptr] : this->EPC->getBootstrapSymbolsMap())
1559 BootstrapSymbols[intern(Name)] =
1561 // Can't fail: BootstrapJD is a new, empty JD and the BootstrapSymbols
1562 // variable is a map, so can't contain duplicates.
1563 cantFail(BootstrapJD.define(absoluteSymbols(std::move(BootstrapSymbols))));
1564}
1565
1567 // You must call endSession prior to destroying the session.
1568 assert(!SessionOpen &&
1569 "Session still open. Did you forget to call endSession?");
1570}
1571
1573 LLVM_DEBUG(dbgs() << "Ending ExecutionSession " << this << "\n");
1574
1575 WaitingOnGraph::OpRecorder *GOpRecorderToEnd = nullptr;
1576 auto JDsToRemove = runSessionLocked([&] {
1577
1578#ifdef EXPENSIVE_CHECKS
1579 verifySessionState("Entering ExecutionSession::endSession");
1580#endif
1581
1582 if (SessionOpen)
1583 GOpRecorderToEnd = GOpRecorder;
1584 SessionOpen = false;
1585 return JDs;
1586 });
1587
1588 std::reverse(JDsToRemove.begin(), JDsToRemove.end());
1589
1590 auto Err = removeJITDylibs(std::move(JDsToRemove));
1591
1592 Err = joinErrors(std::move(Err), EPC->disconnect());
1593
1594 if (GOpRecorderToEnd)
1595 GOpRecorderToEnd->recordEnd();
1596
1597 return Err;
1598}
1599
1601 runSessionLocked([&] { ResourceManagers.push_back(&RM); });
1602}
1603
1605 runSessionLocked([&] {
1606 assert(!ResourceManagers.empty() && "No managers registered");
1607 if (ResourceManagers.back() == &RM)
1608 ResourceManagers.pop_back();
1609 else {
1610 auto I = llvm::find(ResourceManagers, &RM);
1611 assert(I != ResourceManagers.end() && "RM not registered");
1612 ResourceManagers.erase(I);
1613 }
1614 });
1615}
1616
1618 return runSessionLocked([&, this]() -> JITDylib * {
1619 for (auto &JD : JDs)
1620 if (JD->getName() == Name)
1621 return JD.get();
1622 return nullptr;
1623 });
1624}
1625
1627 assert(!getJITDylibByName(Name) && "JITDylib with that name already exists");
1628 return runSessionLocked([&, this]() -> JITDylib & {
1629 assert(SessionOpen && "Cannot create JITDylib after session is closed");
1630 JDs.push_back(new JITDylib(*this, std::move(Name)));
1631 return *JDs.back();
1632 });
1633}
1634
1636 auto &JD = createBareJITDylib(Name);
1637 if (P)
1638 if (auto Err = P->setupJITDylib(JD))
1639 return std::move(Err);
1640 return JD;
1641}
1642
1643Error ExecutionSession::removeJITDylibs(std::vector<JITDylibSP> JDsToRemove) {
1644 // Set JD to 'Closing' state and remove JD from the ExecutionSession.
1645 runSessionLocked([&] {
1646 for (auto &JD : JDsToRemove) {
1647 assert(JD->State == JITDylib::Open && "JD already closed");
1648 JD->State = JITDylib::Closing;
1649 auto I = llvm::find(JDs, JD);
1650 assert(I != JDs.end() && "JD does not appear in session JDs");
1651 JDs.erase(I);
1652 }
1653 });
1654
1655 // Clear JITDylibs and notify the platform.
1656 Error Err = Error::success();
1657 for (auto JD : JDsToRemove) {
1658 Err = joinErrors(std::move(Err), JD->clear());
1659 if (P)
1660 Err = joinErrors(std::move(Err), P->teardownJITDylib(*JD));
1661 }
1662
1663 // Set JD to closed state. Clear remaining data structures.
1664 runSessionLocked([&] {
1665 for (auto &JD : JDsToRemove) {
1666 assert(JD->State == JITDylib::Closing && "JD should be closing");
1667 JD->State = JITDylib::Closed;
1668 assert(JD->Symbols.empty() && "JD.Symbols is not empty after clear");
1669 assert(JD->UnmaterializedInfos.empty() &&
1670 "JD.UnmaterializedInfos is not empty after clear");
1671 assert(JD->MaterializingInfos.empty() &&
1672 "JD.MaterializingInfos is not empty after clear");
1673 assert(JD->TrackerSymbols.empty() &&
1674 "TrackerSymbols is not empty after clear");
1675 JD->DefGenerators.clear();
1676 JD->LinkOrder.clear();
1677 }
1678 });
1679
1680 return Err;
1681}
1682
1685 if (JDs.empty())
1686 return std::vector<JITDylibSP>();
1687
1688 auto &ES = JDs.front()->getExecutionSession();
1689 return ES.runSessionLocked([&]() -> Expected<std::vector<JITDylibSP>> {
1690 DenseSet<JITDylib *> Visited;
1691 std::vector<JITDylibSP> Result;
1692
1693 for (auto &JD : JDs) {
1694
1695 if (JD->State != Open)
1697 "Error building link order: " + JD->getName() + " is defunct",
1699 if (Visited.count(JD.get()))
1700 continue;
1701
1703 WorkStack.push_back(JD);
1704 Visited.insert(JD.get());
1705
1706 while (!WorkStack.empty()) {
1707 Result.push_back(std::move(WorkStack.back()));
1708 WorkStack.pop_back();
1709
1710 for (auto &KV : llvm::reverse(Result.back()->LinkOrder)) {
1711 auto &JD = *KV.first;
1712 if (!Visited.insert(&JD).second)
1713 continue;
1714 WorkStack.push_back(&JD);
1715 }
1716 }
1717 }
1718 return Result;
1719 });
1720}
1721
1724 auto Result = getDFSLinkOrder(JDs);
1725 if (Result)
1726 std::reverse(Result->begin(), Result->end());
1727 return Result;
1728}
1729
1733
1737
1739 LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet,
1740 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete) {
1741
1742 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1743 K, std::move(SearchOrder), std::move(LookupSet),
1744 std::move(OnComplete)),
1745 Error::success());
1746}
1747
1750 SymbolLookupSet LookupSet) {
1751
1752 std::promise<MSVCPExpected<SymbolFlagsMap>> ResultP;
1753 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1754 K, std::move(SearchOrder), std::move(LookupSet),
1755 [&ResultP](Expected<SymbolFlagsMap> Result) {
1756 ResultP.set_value(std::move(Result));
1757 }),
1758 Error::success());
1759
1760 auto ResultF = ResultP.get_future();
1761 return ResultF.get();
1762}
1763
1765 LookupKind K, const JITDylibSearchOrder &SearchOrder,
1766 SymbolLookupSet Symbols, SymbolState RequiredState,
1767 SymbolsResolvedCallback NotifyComplete,
1768 RegisterDependenciesFunction RegisterDependencies) {
1769
1770 LLVM_DEBUG({
1771 runSessionLocked([&]() {
1772 dbgs() << "Looking up " << Symbols << " in " << SearchOrder
1773 << " (required state: " << RequiredState << ")\n";
1774 });
1775 });
1776
1777 // lookup can be re-entered recursively if running on a single thread. Run any
1778 // outstanding MUs in case this query depends on them, otherwise this lookup
1779 // will starve waiting for a result from an MU that is stuck in the queue.
1780 dispatchOutstandingMUs();
1781
1782 auto Unresolved = std::move(Symbols);
1783 auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
1784 std::move(NotifyComplete));
1785
1786 auto IPLS = std::make_unique<InProgressFullLookupState>(
1787 K, SearchOrder, std::move(Unresolved), RequiredState, std::move(Q),
1788 std::move(RegisterDependencies));
1789
1790 OL_applyQueryPhase1(std::move(IPLS), Error::success());
1791}
1792
1795 SymbolLookupSet Symbols, LookupKind K,
1796 SymbolState RequiredState,
1797 RegisterDependenciesFunction RegisterDependencies) {
1798#if LLVM_ENABLE_THREADS
1799 // In the threaded case we use promises to return the results.
1800 std::promise<MSVCPExpected<SymbolMap>> PromisedResult;
1801
1802 auto NotifyComplete = [&](Expected<SymbolMap> R) {
1803 PromisedResult.set_value(std::move(R));
1804 };
1805
1806#else
1808 Error ResolutionError = Error::success();
1809
1810 auto NotifyComplete = [&](Expected<SymbolMap> R) {
1811 ErrorAsOutParameter _(ResolutionError);
1812 if (R)
1813 Result = std::move(*R);
1814 else
1815 ResolutionError = R.takeError();
1816 };
1817#endif
1818
1819 // Perform the asynchronous lookup.
1820 lookup(K, SearchOrder, std::move(Symbols), RequiredState,
1821 std::move(NotifyComplete), RegisterDependencies);
1822
1823#if LLVM_ENABLE_THREADS
1824 return PromisedResult.get_future().get();
1825#else
1826 if (ResolutionError)
1827 return std::move(ResolutionError);
1828
1829 return Result;
1830#endif
1831}
1832
1835 SymbolStringPtr Name, SymbolState RequiredState) {
1836 SymbolLookupSet Names({Name});
1837
1838 if (auto ResultMap = lookup(SearchOrder, std::move(Names), LookupKind::Static,
1839 RequiredState, NoDependenciesToRegister)) {
1840 assert(ResultMap->size() == 1 && "Unexpected number of results");
1841 assert(ResultMap->count(Name) && "Missing result for symbol");
1842 return std::move(ResultMap->begin()->second);
1843 } else
1844 return ResultMap.takeError();
1845}
1846
1849 SymbolState RequiredState) {
1850 return lookup(makeJITDylibSearchOrder(SearchOrder), Name, RequiredState);
1851}
1852
1855 SymbolState RequiredState) {
1856 return lookup(SearchOrder, intern(Name), RequiredState);
1857}
1858
1861
1862 auto TagSyms = lookup({{&JD, JITDylibLookupFlags::MatchAllSymbols}},
1865 if (!TagSyms)
1866 return TagSyms.takeError();
1867
1868 // Associate tag addresses with implementations.
1869 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1870
1871 // Check that no tags are being overwritten.
1872 for (auto &[TagName, TagSym] : *TagSyms) {
1873 auto TagAddr = TagSym.getAddress();
1874 if (JITDispatchHandlers.count(TagAddr))
1875 return make_error<StringError>("Tag " + formatv("{0:x}", TagAddr) +
1876 " (for " + *TagName +
1877 ") already registered",
1879 }
1880
1881 // At this point we're guaranteed to succeed. Install the handlers.
1882 for (auto &[TagName, TagSym] : *TagSyms) {
1883 auto TagAddr = TagSym.getAddress();
1884 auto I = WFs.find(TagName);
1885 assert(I != WFs.end() && I->second &&
1886 "JITDispatchHandler implementation missing");
1887 JITDispatchHandlers[TagAddr] =
1888 std::make_shared<JITDispatchHandlerFunction>(std::move(I->second));
1889 LLVM_DEBUG({
1890 dbgs() << "Associated function tag \"" << *TagName << "\" ("
1891 << formatv("{0:x}", TagAddr) << ") with handler\n";
1892 });
1893 }
1894
1895 return Error::success();
1896}
1897
1899 SendResultFunction SendResult, ExecutorAddr HandlerFnTagAddr,
1901
1902 std::shared_ptr<JITDispatchHandlerFunction> F;
1903 {
1904 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1905 auto I = JITDispatchHandlers.find(HandlerFnTagAddr);
1906 if (I != JITDispatchHandlers.end())
1907 F = I->second;
1908 }
1909
1910 if (F)
1911 (*F)(std::move(SendResult), ArgBytes.data(), ArgBytes.size());
1912 else
1914 ("No function registered for tag " +
1915 formatv("{0:x16}", HandlerFnTagAddr))
1916 .str()));
1917}
1918
1920 runSessionLocked([this, &OS]() {
1921 for (auto &JD : JDs)
1922 JD->dump(OS);
1923 });
1924}
1925
1926#ifdef EXPENSIVE_CHECKS
1927bool ExecutionSession::verifySessionState(Twine Phase) {
1928 return runSessionLocked([&]() {
1929 bool AllOk = true;
1930
1931 for (auto &JD : JDs) {
1932
1933 auto LogFailure = [&]() -> raw_fd_ostream & {
1934 auto &Stream = errs();
1935 if (AllOk)
1936 Stream << "ERROR: Bad ExecutionSession state detected " << Phase
1937 << "\n";
1938 Stream << " In JITDylib " << JD->getName() << ", ";
1939 AllOk = false;
1940 return Stream;
1941 };
1942
1943 if (JD->State != JITDylib::Open) {
1944 LogFailure()
1945 << "state is not Open, but JD is in ExecutionSession list.";
1946 }
1947
1948 // Check symbol table.
1949 // 1. If the entry state isn't resolved then check that no address has
1950 // been set.
1951 // 2. Check that if the hasMaterializerAttached flag is set then there is
1952 // an UnmaterializedInfo entry, and vice-versa.
1953 for (auto &[Sym, Entry] : JD->Symbols) {
1954 // Check that unresolved symbols have null addresses.
1955 if (Entry.getState() < SymbolState::Resolved) {
1956 if (Entry.getAddress()) {
1957 LogFailure() << "symbol " << Sym << " has state "
1958 << Entry.getState()
1959 << " (not-yet-resolved) but non-null address "
1960 << Entry.getAddress() << ".\n";
1961 }
1962 }
1963
1964 // Check that the hasMaterializerAttached flag is correct.
1965 auto UMIItr = JD->UnmaterializedInfos.find(Sym);
1966 if (Entry.hasMaterializerAttached()) {
1967 if (UMIItr == JD->UnmaterializedInfos.end()) {
1968 LogFailure() << "symbol " << Sym
1969 << " entry claims materializer attached, but "
1970 "UnmaterializedInfos has no corresponding entry.\n";
1971 }
1972 } else if (UMIItr != JD->UnmaterializedInfos.end()) {
1973 LogFailure()
1974 << "symbol " << Sym
1975 << " entry claims no materializer attached, but "
1976 "UnmaterializedInfos has an unexpected entry for it.\n";
1977 }
1978 }
1979
1980 // Check that every UnmaterializedInfo entry has a corresponding entry
1981 // in the Symbols table.
1982 for (auto &[Sym, UMI] : JD->UnmaterializedInfos) {
1983 auto SymItr = JD->Symbols.find(Sym);
1984 if (SymItr == JD->Symbols.end()) {
1985 LogFailure()
1986 << "symbol " << Sym
1987 << " has UnmaterializedInfos entry, but no Symbols entry.\n";
1988 }
1989 }
1990
1991 // Check consistency of the MaterializingInfos table.
1992 for (auto &[Sym, MII] : JD->MaterializingInfos) {
1993
1994 auto SymItr = JD->Symbols.find(Sym);
1995 if (SymItr == JD->Symbols.end()) {
1996 // If there's no Symbols entry for this MaterializingInfos entry then
1997 // report that.
1998 LogFailure()
1999 << "symbol " << Sym
2000 << " has MaterializingInfos entry, but no Symbols entry.\n";
2001 } else {
2002 // Otherwise check consistency between Symbols and MaterializingInfos.
2003
2004 // Ready symbols should not have MaterializingInfos.
2005 if (SymItr->second.getState() == SymbolState::Ready) {
2006 LogFailure()
2007 << "symbol " << Sym
2008 << " is in Ready state, should not have MaterializingInfo.\n";
2009 }
2010
2011 // Pending queries should be for subsequent states.
2012 auto CurState = static_cast<SymbolState>(
2013 static_cast<std::underlying_type_t<SymbolState>>(
2014 SymItr->second.getState()) + 1);
2015 for (auto &Q : MII.PendingQueries) {
2016 if (Q->getRequiredState() != CurState) {
2017 if (Q->getRequiredState() > CurState)
2018 CurState = Q->getRequiredState();
2019 else
2020 LogFailure() << "symbol " << Sym
2021 << " has stale or misordered queries.\n";
2022 }
2023 }
2024 }
2025 }
2026 }
2027
2028 return AllOk;
2029 });
2030}
2031#endif // EXPENSIVE_CHECKS
2032
2033void ExecutionSession::dispatchOutstandingMUs() {
2034 LLVM_DEBUG(dbgs() << "Dispatching MaterializationUnits...\n");
2035 while (true) {
2036 std::optional<std::pair<std::unique_ptr<MaterializationUnit>,
2037 std::unique_ptr<MaterializationResponsibility>>>
2038 JMU;
2039
2040 {
2041 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2042 if (!OutstandingMUs.empty()) {
2043 JMU.emplace(std::move(OutstandingMUs.back()));
2044 OutstandingMUs.pop_back();
2045 }
2046 }
2047
2048 if (!JMU)
2049 break;
2050
2051 assert(JMU->first && "No MU?");
2052 LLVM_DEBUG(dbgs() << " Dispatching \"" << JMU->first->getName() << "\"\n");
2053 dispatchTask(std::make_unique<MaterializationTask>(std::move(JMU->first),
2054 std::move(JMU->second)));
2055 }
2056 LLVM_DEBUG(dbgs() << "Done dispatching MaterializationUnits.\n");
2057}
2058
2059Error ExecutionSession::removeResourceTracker(ResourceTracker &RT) {
2060 LLVM_DEBUG({
2061 dbgs() << "In " << RT.getJITDylib().getName() << " removing tracker "
2062 << formatv("{0:x}", RT.getKeyUnsafe()) << "\n";
2063 });
2064 std::vector<ResourceManager *> CurrentResourceManagers;
2065
2066 JITDylib::RemoveTrackerResult R;
2067
2068 runSessionLocked([&] {
2069 CurrentResourceManagers = ResourceManagers;
2070 RT.makeDefunct();
2071 R = RT.getJITDylib().IL_removeTracker(RT);
2072 });
2073
2074 // Release any defunct MaterializationUnits.
2075 R.DefunctMUs.clear();
2076
2077 Error Err = Error::success();
2078
2079 auto &JD = RT.getJITDylib();
2080 for (auto *L : reverse(CurrentResourceManagers))
2081 Err = joinErrors(std::move(Err),
2082 L->handleRemoveResources(JD, RT.getKeyUnsafe()));
2083
2084 for (auto &Q : R.QueriesToFail)
2086 R.FailedSymbols));
2087
2088 return Err;
2089}
2090
2091void ExecutionSession::transferResourceTracker(ResourceTracker &DstRT,
2092 ResourceTracker &SrcRT) {
2093 LLVM_DEBUG({
2094 dbgs() << "In " << SrcRT.getJITDylib().getName()
2095 << " transfering resources from tracker "
2096 << formatv("{0:x}", SrcRT.getKeyUnsafe()) << " to tracker "
2097 << formatv("{0:x}", DstRT.getKeyUnsafe()) << "\n";
2098 });
2099
2100 // No-op transfers are allowed and do not invalidate the source.
2101 if (&DstRT == &SrcRT)
2102 return;
2103
2104 assert(&DstRT.getJITDylib() == &SrcRT.getJITDylib() &&
2105 "Can't transfer resources between JITDylibs");
2106 runSessionLocked([&]() {
2107 SrcRT.makeDefunct();
2108 auto &JD = DstRT.getJITDylib();
2109 JD.transferTracker(DstRT, SrcRT);
2110 for (auto *L : reverse(ResourceManagers))
2111 L->handleTransferResources(JD, DstRT.getKeyUnsafe(),
2112 SrcRT.getKeyUnsafe());
2113 });
2114}
2115
2116void ExecutionSession::destroyResourceTracker(ResourceTracker &RT) {
2117 runSessionLocked([&]() {
2118 LLVM_DEBUG({
2119 dbgs() << "In " << RT.getJITDylib().getName() << " destroying tracker "
2120 << formatv("{0:x}", RT.getKeyUnsafe()) << "\n";
2121 });
2122 if (!RT.isDefunct())
2123 transferResourceTracker(*RT.getJITDylib().getDefaultResourceTracker(),
2124 RT);
2125 });
2126}
2127
2128Error ExecutionSession::IL_updateCandidatesFor(
2129 JITDylib &JD, JITDylibLookupFlags JDLookupFlags,
2130 SymbolLookupSet &Candidates, SymbolLookupSet *NonCandidates) {
2131 return Candidates.forEachWithRemoval(
2132 [&](const SymbolStringPtr &Name,
2133 SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
2134 /// Search for the symbol. If not found then continue without
2135 /// removal.
2136 auto SymI = JD.Symbols.find(Name);
2137 if (SymI == JD.Symbols.end())
2138 return false;
2139
2140 // If this is a non-exported symbol and we're matching exported
2141 // symbols only then remove this symbol from the candidates list.
2142 //
2143 // If we're tracking non-candidates then add this to the non-candidate
2144 // list.
2145 if (!SymI->second.getFlags().isExported() &&
2147 if (NonCandidates)
2148 NonCandidates->add(Name, SymLookupFlags);
2149 return true;
2150 }
2151
2152 // If we match against a materialization-side-effects only symbol
2153 // then make sure it is weakly-referenced. Otherwise bail out with
2154 // an error.
2155 // FIXME: Use a "materialization-side-effects-only symbols must be
2156 // weakly referenced" specific error here to reduce confusion.
2157 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2161
2162 // If we matched against this symbol but it is in the error state
2163 // then bail out and treat it as a failure to materialize.
2164 if (SymI->second.getFlags().hasError()) {
2165 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2166 (*FailedSymbolsMap)[&JD] = {Name};
2168 std::move(FailedSymbolsMap));
2169 }
2170
2171 // Otherwise this is a match. Remove it from the candidate set.
2172 return true;
2173 });
2174}
2175
2176void ExecutionSession::OL_resumeLookupAfterGeneration(
2177 InProgressLookupState &IPLS) {
2178
2180 "Should not be called for not-in-generator lookups");
2182
2184
2185 if (auto DG = IPLS.CurDefGeneratorStack.back().lock()) {
2186 IPLS.CurDefGeneratorStack.pop_back();
2187 std::lock_guard<std::mutex> Lock(DG->M);
2188
2189 // If there are no pending lookups then mark the generator as free and
2190 // return.
2191 if (DG->PendingLookups.empty()) {
2192 DG->InUse = false;
2193 return;
2194 }
2195
2196 // Otherwise resume the next lookup.
2197 LS = std::move(DG->PendingLookups.front());
2198 DG->PendingLookups.pop_front();
2199 }
2200
2201 if (LS.IPLS) {
2203 dispatchTask(std::make_unique<LookupTask>(std::move(LS)));
2204 }
2205}
2206
2207void ExecutionSession::OL_applyQueryPhase1(
2208 std::unique_ptr<InProgressLookupState> IPLS, Error Err) {
2209
2210 LLVM_DEBUG({
2211 dbgs() << "Entering OL_applyQueryPhase1:\n"
2212 << " Lookup kind: " << IPLS->K << "\n"
2213 << " Search order: " << IPLS->SearchOrder
2214 << ", Current index = " << IPLS->CurSearchOrderIndex
2215 << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2216 << " Lookup set: " << IPLS->LookupSet << "\n"
2217 << " Definition generator candidates: "
2218 << IPLS->DefGeneratorCandidates << "\n"
2219 << " Definition generator non-candidates: "
2220 << IPLS->DefGeneratorNonCandidates << "\n";
2221 });
2222
2223 if (IPLS->GenState == InProgressLookupState::InGenerator)
2224 OL_resumeLookupAfterGeneration(*IPLS);
2225
2226 assert(IPLS->GenState != InProgressLookupState::InGenerator &&
2227 "Lookup should not be in InGenerator state here");
2228
2229 // FIXME: We should attach the query as we go: This provides a result in a
2230 // single pass in the common case where all symbols have already reached the
2231 // required state. The query could be detached again in the 'fail' method on
2232 // IPLS. Phase 2 would be reduced to collecting and dispatching the MUs.
2233
2234 while (IPLS->CurSearchOrderIndex != IPLS->SearchOrder.size()) {
2235
2236 // If we've been handed an error or received one back from a generator then
2237 // fail the query. We don't need to unlink: At this stage the query hasn't
2238 // actually been lodged.
2239 if (Err)
2240 return IPLS->fail(std::move(Err));
2241
2242 // Get the next JITDylib and lookup flags.
2243 auto &KV = IPLS->SearchOrder[IPLS->CurSearchOrderIndex];
2244 auto &JD = *KV.first;
2245 auto JDLookupFlags = KV.second;
2246
2247 LLVM_DEBUG({
2248 dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2249 << ") with lookup set " << IPLS->LookupSet << ":\n";
2250 });
2251
2252 // If we've just reached a new JITDylib then perform some setup.
2253 if (IPLS->NewJITDylib) {
2254 // Add any non-candidates from the last JITDylib (if any) back on to the
2255 // list of definition candidates for this JITDylib, reset definition
2256 // non-candidates to the empty set.
2257 SymbolLookupSet Tmp;
2258 std::swap(IPLS->DefGeneratorNonCandidates, Tmp);
2259 IPLS->DefGeneratorCandidates.append(std::move(Tmp));
2260
2261 LLVM_DEBUG({
2262 dbgs() << " First time visiting " << JD.getName()
2263 << ", resetting candidate sets and building generator stack\n";
2264 });
2265
2266 // Build the definition generator stack for this JITDylib.
2267 runSessionLocked([&] {
2268 IPLS->CurDefGeneratorStack.reserve(JD.DefGenerators.size());
2269 llvm::append_range(IPLS->CurDefGeneratorStack,
2270 reverse(JD.DefGenerators));
2271 });
2272
2273 // Flag that we've done our initialization.
2274 IPLS->NewJITDylib = false;
2275 }
2276
2277 // Remove any generation candidates that are already defined (and match) in
2278 // this JITDylib.
2279 runSessionLocked([&] {
2280 // Update the list of candidates (and non-candidates) for definition
2281 // generation.
2282 LLVM_DEBUG(dbgs() << " Updating candidate set...\n");
2283 Err = IL_updateCandidatesFor(
2284 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2285 JD.DefGenerators.empty() ? nullptr
2286 : &IPLS->DefGeneratorNonCandidates);
2287 LLVM_DEBUG({
2288 dbgs() << " Remaining candidates = " << IPLS->DefGeneratorCandidates
2289 << "\n";
2290 });
2291
2292 // If this lookup was resumed after auto-suspension but all candidates
2293 // have already been generated (by some previous call to the generator)
2294 // treat the lookup as if it had completed generation.
2295 if (IPLS->GenState == InProgressLookupState::ResumedForGenerator &&
2296 IPLS->DefGeneratorCandidates.empty())
2297 OL_resumeLookupAfterGeneration(*IPLS);
2298 });
2299
2300 // If we encountered an error while filtering generation candidates then
2301 // bail out.
2302 if (Err)
2303 return IPLS->fail(std::move(Err));
2304
2305 /// Apply any definition generators on the stack.
2306 LLVM_DEBUG({
2307 if (IPLS->CurDefGeneratorStack.empty())
2308 LLVM_DEBUG(dbgs() << " No generators to run for this JITDylib.\n");
2309 else if (IPLS->DefGeneratorCandidates.empty())
2310 LLVM_DEBUG(dbgs() << " No candidates to generate.\n");
2311 else
2312 dbgs() << " Running " << IPLS->CurDefGeneratorStack.size()
2313 << " remaining generators for "
2314 << IPLS->DefGeneratorCandidates.size() << " candidates\n";
2315 });
2316 while (!IPLS->CurDefGeneratorStack.empty() &&
2317 !IPLS->DefGeneratorCandidates.empty()) {
2318 auto DG = IPLS->CurDefGeneratorStack.back().lock();
2319
2320 if (!DG)
2321 return IPLS->fail(make_error<StringError>(
2322 "DefinitionGenerator removed while lookup in progress",
2324
2325 // At this point the lookup is in either the NotInGenerator state, or in
2326 // the ResumedForGenerator state.
2327 // If this lookup is in the NotInGenerator state then check whether the
2328 // generator is in use. If the generator is not in use then move the
2329 // lookup to the InGenerator state and continue. If the generator is
2330 // already in use then just add this lookup to the pending lookups list
2331 // and bail out.
2332 // If this lookup is in the ResumedForGenerator state then just move it
2333 // to InGenerator and continue.
2334 if (IPLS->GenState == InProgressLookupState::NotInGenerator) {
2335 std::lock_guard<std::mutex> Lock(DG->M);
2336 if (DG->InUse) {
2337 DG->PendingLookups.push_back(std::move(IPLS));
2338 return;
2339 }
2340 DG->InUse = true;
2341 }
2342
2343 IPLS->GenState = InProgressLookupState::InGenerator;
2344
2345 auto K = IPLS->K;
2346 auto &LookupSet = IPLS->DefGeneratorCandidates;
2347
2348 // Run the generator. If the generator takes ownership of QA then this
2349 // will break the loop.
2350 {
2351 LLVM_DEBUG(dbgs() << " Attempting to generate " << LookupSet << "\n");
2352 LookupState LS(std::move(IPLS));
2353 Err = DG->tryToGenerate(LS, K, JD, JDLookupFlags, LookupSet);
2354 IPLS = std::move(LS.IPLS);
2355 }
2356
2357 // If the lookup returned then pop the generator stack and unblock the
2358 // next lookup on this generator (if any).
2359 if (IPLS)
2360 OL_resumeLookupAfterGeneration(*IPLS);
2361
2362 // If there was an error then fail the query.
2363 if (Err) {
2364 LLVM_DEBUG({
2365 dbgs() << " Error attempting to generate " << LookupSet << "\n";
2366 });
2367 assert(IPLS && "LS cannot be retained if error is returned");
2368 return IPLS->fail(std::move(Err));
2369 }
2370
2371 // Otherwise if QA was captured then break the loop.
2372 if (!IPLS) {
2373 LLVM_DEBUG(
2374 { dbgs() << " LookupState captured. Exiting phase1 for now.\n"; });
2375 return;
2376 }
2377
2378 // Otherwise if we're continuing around the loop then update candidates
2379 // for the next round.
2380 runSessionLocked([&] {
2381 LLVM_DEBUG(dbgs() << " Updating candidate set post-generation\n");
2382 Err = IL_updateCandidatesFor(
2383 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2384 JD.DefGenerators.empty() ? nullptr
2385 : &IPLS->DefGeneratorNonCandidates);
2386 });
2387
2388 // If updating candidates failed then fail the query.
2389 if (Err) {
2390 LLVM_DEBUG(dbgs() << " Error encountered while updating candidates\n");
2391 return IPLS->fail(std::move(Err));
2392 }
2393 }
2394
2395 if (IPLS->DefGeneratorCandidates.empty() &&
2396 IPLS->DefGeneratorNonCandidates.empty()) {
2397 // Early out if there are no remaining symbols.
2398 LLVM_DEBUG(dbgs() << "All symbols matched.\n");
2399 IPLS->CurSearchOrderIndex = IPLS->SearchOrder.size();
2400 break;
2401 } else {
2402 // If we get here then we've moved on to the next JITDylib with candidates
2403 // remaining.
2404 LLVM_DEBUG(dbgs() << "Phase 1 moving to next JITDylib.\n");
2405 ++IPLS->CurSearchOrderIndex;
2406 IPLS->NewJITDylib = true;
2407 }
2408 }
2409
2410 // Remove any weakly referenced candidates that could not be found/generated.
2411 IPLS->DefGeneratorCandidates.remove_if(
2412 [](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2413 return SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol;
2414 });
2415
2416 // If we get here then we've finished searching all JITDylibs.
2417 // If we matched all symbols then move to phase 2, otherwise fail the query
2418 // with a SymbolsNotFound error.
2419 if (IPLS->DefGeneratorCandidates.empty()) {
2420 LLVM_DEBUG(dbgs() << "Phase 1 succeeded.\n");
2421 IPLS->complete(std::move(IPLS));
2422 } else {
2423 LLVM_DEBUG(dbgs() << "Phase 1 failed with unresolved symbols.\n");
2424 IPLS->fail(make_error<SymbolsNotFound>(
2425 getSymbolStringPool(), IPLS->DefGeneratorCandidates.getSymbolNames()));
2426 }
2427}
2428
2429void ExecutionSession::OL_completeLookup(
2430 std::unique_ptr<InProgressLookupState> IPLS,
2431 std::shared_ptr<AsynchronousSymbolQuery> Q,
2432 RegisterDependenciesFunction RegisterDependencies) {
2433
2434 LLVM_DEBUG({
2435 dbgs() << "Entering OL_completeLookup:\n"
2436 << " Lookup kind: " << IPLS->K << "\n"
2437 << " Search order: " << IPLS->SearchOrder
2438 << ", Current index = " << IPLS->CurSearchOrderIndex
2439 << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2440 << " Lookup set: " << IPLS->LookupSet << "\n"
2441 << " Definition generator candidates: "
2442 << IPLS->DefGeneratorCandidates << "\n"
2443 << " Definition generator non-candidates: "
2444 << IPLS->DefGeneratorNonCandidates << "\n";
2445 });
2446
2447 bool QueryComplete = false;
2448 DenseMap<JITDylib *, JITDylib::UnmaterializedInfosList> CollectedUMIs;
2449
2450 auto LodgingErr = runSessionLocked([&]() -> Error {
2451 for (auto &KV : IPLS->SearchOrder) {
2452 auto &JD = *KV.first;
2453 auto JDLookupFlags = KV.second;
2454 LLVM_DEBUG({
2455 dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2456 << ") with lookup set " << IPLS->LookupSet << ":\n";
2457 });
2458
2459 auto Err = IPLS->LookupSet.forEachWithRemoval(
2460 [&](const SymbolStringPtr &Name,
2461 SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
2462 LLVM_DEBUG({
2463 dbgs() << " Attempting to match \"" << Name << "\" ("
2464 << SymLookupFlags << ")... ";
2465 });
2466
2467 /// Search for the symbol. If not found then continue without
2468 /// removal.
2469 auto SymI = JD.Symbols.find(Name);
2470 if (SymI == JD.Symbols.end()) {
2471 LLVM_DEBUG(dbgs() << "skipping: not present\n");
2472 return false;
2473 }
2474
2475 // If this is a non-exported symbol and we're matching exported
2476 // symbols only then skip this symbol without removal.
2477 if (!SymI->second.getFlags().isExported() &&
2478 JDLookupFlags ==
2480 LLVM_DEBUG(dbgs() << "skipping: not exported\n");
2481 return false;
2482 }
2483
2484 // If we match against a materialization-side-effects only symbol
2485 // then make sure it is weakly-referenced. Otherwise bail out with
2486 // an error.
2487 // FIXME: Use a "materialization-side-effects-only symbols must be
2488 // weakly referenced" specific error here to reduce confusion.
2489 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2491 LLVM_DEBUG({
2492 dbgs() << "error: "
2493 "required, but symbol is has-side-effects-only\n";
2494 });
2497 }
2498
2499 // If we matched against this symbol but it is in the error state
2500 // then bail out and treat it as a failure to materialize.
2501 if (SymI->second.getFlags().hasError()) {
2502 LLVM_DEBUG(dbgs() << "error: symbol is in error state\n");
2503 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2504 (*FailedSymbolsMap)[&JD] = {Name};
2506 getSymbolStringPool(), std::move(FailedSymbolsMap));
2507 }
2508
2509 // Otherwise this is a match.
2510
2511 // If this symbol is already in the required state then notify the
2512 // query, remove the symbol and continue.
2513 if (SymI->second.getState() >= Q->getRequiredState()) {
2515 << "matched, symbol already in required state\n");
2516 Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
2517
2518 // If this symbol is in anything other than the Ready state then
2519 // we need to track the dependence.
2520 if (SymI->second.getState() != SymbolState::Ready)
2521 Q->addQueryDependence(JD, Name);
2522
2523 return true;
2524 }
2525
2526 // Otherwise this symbol does not yet meet the required state. Check
2527 // whether it has a materializer attached, and if so prepare to run
2528 // it.
2529 if (SymI->second.hasMaterializerAttached()) {
2530 assert(SymI->second.getAddress() == ExecutorAddr() &&
2531 "Symbol not resolved but already has address?");
2532 auto UMII = JD.UnmaterializedInfos.find(Name);
2533 assert(UMII != JD.UnmaterializedInfos.end() &&
2534 "Lazy symbol should have UnmaterializedInfo");
2535
2536 auto UMI = UMII->second;
2537 assert(UMI->MU && "Materializer should not be null");
2538 assert(UMI->RT && "Tracker should not be null");
2539 LLVM_DEBUG({
2540 dbgs() << "matched, preparing to dispatch MU@" << UMI->MU.get()
2541 << " (" << UMI->MU->getName() << ")\n";
2542 });
2543
2544 // Move all symbols associated with this MaterializationUnit into
2545 // materializing state.
2546 for (auto &KV : UMI->MU->getSymbols()) {
2547 auto SymK = JD.Symbols.find(KV.first);
2548 assert(SymK != JD.Symbols.end() &&
2549 "No entry for symbol covered by MaterializationUnit");
2550 SymK->second.setMaterializerAttached(false);
2551 SymK->second.setState(SymbolState::Materializing);
2552 JD.UnmaterializedInfos.erase(KV.first);
2553 }
2554
2555 // Add MU to the list of MaterializationUnits to be materialized.
2556 CollectedUMIs[&JD].push_back(std::move(UMI));
2557 } else
2558 LLVM_DEBUG(dbgs() << "matched, registering query");
2559
2560 // Add the query to the PendingQueries list and continue, deleting
2561 // the element from the lookup set.
2562 assert(SymI->second.getState() != SymbolState::NeverSearched &&
2563 SymI->second.getState() != SymbolState::Ready &&
2564 "By this line the symbol should be materializing");
2565 auto &MI = JD.MaterializingInfos[Name];
2566 MI.addQuery(Q);
2567 Q->addQueryDependence(JD, Name);
2568
2569 return true;
2570 });
2571
2572 JD.shrinkMaterializationInfoMemory();
2573
2574 // Handle failure.
2575 if (Err) {
2576
2577 LLVM_DEBUG({
2578 dbgs() << "Lookup failed. Detaching query and replacing MUs.\n";
2579 });
2580
2581 // Detach the query.
2582 Q->detach();
2583
2584 // Replace the MUs.
2585 for (auto &KV : CollectedUMIs) {
2586 auto &JD = *KV.first;
2587 for (auto &UMI : KV.second)
2588 for (auto &KV2 : UMI->MU->getSymbols()) {
2589 assert(!JD.UnmaterializedInfos.count(KV2.first) &&
2590 "Unexpected materializer in map");
2591 auto SymI = JD.Symbols.find(KV2.first);
2592 assert(SymI != JD.Symbols.end() && "Missing symbol entry");
2593 assert(SymI->second.getState() == SymbolState::Materializing &&
2594 "Can not replace symbol that is not materializing");
2595 assert(!SymI->second.hasMaterializerAttached() &&
2596 "MaterializerAttached flag should not be set");
2597 SymI->second.setMaterializerAttached(true);
2598 JD.UnmaterializedInfos[KV2.first] = UMI;
2599 }
2600 }
2601
2602 return Err;
2603 }
2604 }
2605
2606 LLVM_DEBUG(dbgs() << "Stripping unmatched weakly-referenced symbols\n");
2607 IPLS->LookupSet.forEachWithRemoval(
2608 [&](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2609 if (SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol) {
2610 Q->dropSymbol(Name);
2611 return true;
2612 } else
2613 return false;
2614 });
2615
2616 if (!IPLS->LookupSet.empty()) {
2617 LLVM_DEBUG(dbgs() << "Failing due to unresolved symbols\n");
2619 IPLS->LookupSet.getSymbolNames());
2620 }
2621
2622 // Record whether the query completed.
2623 QueryComplete = Q->isComplete();
2624
2625 LLVM_DEBUG({
2626 dbgs() << "Query successfully "
2627 << (QueryComplete ? "completed" : "lodged") << "\n";
2628 });
2629
2630 // Move the collected MUs to the OutstandingMUs list.
2631 if (!CollectedUMIs.empty()) {
2632 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2633
2634 LLVM_DEBUG(dbgs() << "Adding MUs to dispatch:\n");
2635 for (auto &KV : CollectedUMIs) {
2636 LLVM_DEBUG({
2637 auto &JD = *KV.first;
2638 dbgs() << " For " << JD.getName() << ": Adding " << KV.second.size()
2639 << " MUs.\n";
2640 });
2641 for (auto &UMI : KV.second) {
2642 auto MR = createMaterializationResponsibility(
2643 *UMI->RT, std::move(UMI->MU->SymbolFlags),
2644 std::move(UMI->MU->InitSymbol));
2645 OutstandingMUs.push_back(
2646 std::make_pair(std::move(UMI->MU), std::move(MR)));
2647 }
2648 }
2649 } else
2650 LLVM_DEBUG(dbgs() << "No MUs to dispatch.\n");
2651
2652 if (RegisterDependencies && !Q->QueryRegistrations.empty()) {
2653 LLVM_DEBUG(dbgs() << "Registering dependencies\n");
2654 RegisterDependencies(Q->QueryRegistrations);
2655 } else
2656 LLVM_DEBUG(dbgs() << "No dependencies to register\n");
2657
2658 return Error::success();
2659 });
2660
2661 if (LodgingErr) {
2662 LLVM_DEBUG(dbgs() << "Failing query\n");
2663 Q->detach();
2664 Q->handleFailed(std::move(LodgingErr));
2665 return;
2666 }
2667
2668 if (QueryComplete) {
2669 LLVM_DEBUG(dbgs() << "Completing query\n");
2670 Q->handleComplete(*this);
2671 }
2672
2673 dispatchOutstandingMUs();
2674}
2675
2676void ExecutionSession::OL_completeLookupFlags(
2677 std::unique_ptr<InProgressLookupState> IPLS,
2678 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete) {
2679
2680 auto Result = runSessionLocked([&]() -> Expected<SymbolFlagsMap> {
2681 LLVM_DEBUG({
2682 dbgs() << "Entering OL_completeLookupFlags:\n"
2683 << " Lookup kind: " << IPLS->K << "\n"
2684 << " Search order: " << IPLS->SearchOrder
2685 << ", Current index = " << IPLS->CurSearchOrderIndex
2686 << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2687 << " Lookup set: " << IPLS->LookupSet << "\n"
2688 << " Definition generator candidates: "
2689 << IPLS->DefGeneratorCandidates << "\n"
2690 << " Definition generator non-candidates: "
2691 << IPLS->DefGeneratorNonCandidates << "\n";
2692 });
2693
2695
2696 // Attempt to find flags for each symbol.
2697 for (auto &KV : IPLS->SearchOrder) {
2698 auto &JD = *KV.first;
2699 auto JDLookupFlags = KV.second;
2700 LLVM_DEBUG({
2701 dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2702 << ") with lookup set " << IPLS->LookupSet << ":\n";
2703 });
2704
2705 IPLS->LookupSet.forEachWithRemoval([&](const SymbolStringPtr &Name,
2706 SymbolLookupFlags SymLookupFlags) {
2707 LLVM_DEBUG({
2708 dbgs() << " Attempting to match \"" << Name << "\" ("
2709 << SymLookupFlags << ")... ";
2710 });
2711
2712 // Search for the symbol. If not found then continue without removing
2713 // from the lookup set.
2714 auto SymI = JD.Symbols.find(Name);
2715 if (SymI == JD.Symbols.end()) {
2716 LLVM_DEBUG(dbgs() << "skipping: not present\n");
2717 return false;
2718 }
2719
2720 // If this is a non-exported symbol then it doesn't match. Skip it.
2721 if (!SymI->second.getFlags().isExported() &&
2723 LLVM_DEBUG(dbgs() << "skipping: not exported\n");
2724 return false;
2725 }
2726
2727 LLVM_DEBUG({
2728 dbgs() << "matched, \"" << Name << "\" -> " << SymI->second.getFlags()
2729 << "\n";
2730 });
2731 Result[Name] = SymI->second.getFlags();
2732 return true;
2733 });
2734 }
2735
2736 // Remove any weakly referenced symbols that haven't been resolved.
2737 IPLS->LookupSet.remove_if(
2738 [](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2739 return SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol;
2740 });
2741
2742 if (!IPLS->LookupSet.empty()) {
2743 LLVM_DEBUG(dbgs() << "Failing due to unresolved symbols\n");
2745 IPLS->LookupSet.getSymbolNames());
2746 }
2747
2748 LLVM_DEBUG(dbgs() << "Succeded, result = " << Result << "\n");
2749 return Result;
2750 });
2751
2752 // Run the callback on the result.
2753 LLVM_DEBUG(dbgs() << "Sending result to handler.\n");
2754 OnComplete(std::move(Result));
2755}
2756
2757void ExecutionSession::OL_destroyMaterializationResponsibility(
2759
2760 assert(MR.SymbolFlags.empty() &&
2761 "All symbols should have been explicitly materialized or failed");
2762 MR.JD.unlinkMaterializationResponsibility(MR);
2763}
2764
2765SymbolNameSet ExecutionSession::OL_getRequestedSymbols(
2767 return MR.JD.getRequestedSymbols(MR.SymbolFlags);
2768}
2769
2770Error ExecutionSession::OL_notifyResolved(MaterializationResponsibility &MR,
2771 const SymbolMap &Symbols) {
2772 LLVM_DEBUG({
2773 dbgs() << "In " << MR.JD.getName() << " resolving " << Symbols << "\n";
2774 });
2775#ifndef NDEBUG
2776 for (auto &KV : Symbols) {
2777 auto I = MR.SymbolFlags.find(KV.first);
2778 assert(I != MR.SymbolFlags.end() &&
2779 "Resolving symbol outside this responsibility set");
2780 assert(!I->second.hasMaterializationSideEffectsOnly() &&
2781 "Can't resolve materialization-side-effects-only symbol");
2782 if (I->second & JITSymbolFlags::Common) {
2783 auto WeakOrCommon = JITSymbolFlags::Weak | JITSymbolFlags::Common;
2784 assert((KV.second.getFlags() & WeakOrCommon) &&
2785 "Common symbols must be resolved as common or weak");
2786 assert((KV.second.getFlags() & ~WeakOrCommon) ==
2787 (I->second & ~JITSymbolFlags::Common) &&
2788 "Resolving symbol with incorrect flags");
2789 } else
2790 assert(KV.second.getFlags() == I->second &&
2791 "Resolving symbol with incorrect flags");
2792 }
2793#endif
2794
2795 return MR.JD.resolve(MR, Symbols);
2796}
2797
2799ExecutionSession::IL_getSymbolState(JITDylib *JD,
2801 if (JD->State != JITDylib::Open)
2802 return WaitingOnGraph::ExternalState::Failed;
2803
2804 auto I = JD->Symbols.find_as(Name);
2805
2806 // FIXME: Can we eliminate this possibility if we support query binding?
2807 if (I == JD->Symbols.end())
2808 return WaitingOnGraph::ExternalState::Failed;
2809
2810 if (I->second.getFlags().hasError())
2811 return WaitingOnGraph::ExternalState::Failed;
2812
2813 if (I->second.getState() == SymbolState::Ready)
2814 return WaitingOnGraph::ExternalState::Ready;
2815
2816 return WaitingOnGraph::ExternalState::None;
2817}
2818
2819template <typename UpdateSymbolFn, typename UpdateQueryFn>
2820void ExecutionSession::IL_collectQueries(
2821 JITDylib::AsynchronousSymbolQuerySet &Qs,
2822 WaitingOnGraph::ContainerElementsMap &QualifiedSymbols,
2823 UpdateSymbolFn &&UpdateSymbol, UpdateQueryFn &&UpdateQuery) {
2824
2825 for (auto &[JD, Symbols] : QualifiedSymbols) {
2826 // IL_emit and JITDylib removal are synchronized by the session lock.
2827 // Since JITDylib removal removes any contained nodes from the
2828 // WaitingOnGraph, we should be able to assert that all nodes in the
2829 // WaitingOnGraph have not been removed.
2830 assert(JD->State == JITDylib::Open &&
2831 "WaitingOnGraph includes definition in defunct JITDylib");
2832 for (auto &Symbol : Symbols) {
2833 // Update symbol table.
2834 auto I = JD->Symbols.find_as(Symbol);
2835 assert(I != JD->Symbols.end() &&
2836 "Failed Symbol missing from JD symbol table");
2837 auto &Entry = I->second;
2838 UpdateSymbol(Entry);
2839
2840 // Collect queries.
2841 auto J = JD->MaterializingInfos.find_as(Symbol);
2842 if (J != JD->MaterializingInfos.end()) {
2843 for (auto &Q : J->second.takeAllPendingQueries()) {
2844 UpdateQuery(*Q, *JD, Symbol, Entry);
2845 Qs.insert(std::move(Q));
2846 }
2847 JD->MaterializingInfos.erase(J);
2848 }
2849 }
2850 }
2851}
2852
2853Expected<ExecutionSession::EmitQueries>
2854ExecutionSession::IL_emit(MaterializationResponsibility &MR,
2855 WaitingOnGraph::SimplifyResult SR) {
2856
2857 if (MR.RT->isDefunct())
2859
2860 auto &TargetJD = MR.getTargetJITDylib();
2861 if (TargetJD.State != JITDylib::Open)
2862 return make_error<StringError>("JITDylib " + TargetJD.getName() +
2863 " is defunct",
2865
2866#ifdef EXPENSIVE_CHECKS
2867 verifySessionState("entering ExecutionSession::IL_emit");
2868#endif
2869
2870 auto ER = G.emit(std::move(SR),
2871 [this](JITDylib *JD, NonOwningSymbolStringPtr Name) {
2872 return IL_getSymbolState(JD, Name);
2873 });
2874
2875 EmitQueries EQ;
2876
2877 // Handle failed queries.
2878 for (auto &SN : ER.Failed)
2879 IL_collectQueries(
2880 EQ.Failed, SN->defs(),
2881 [](JITDylib::SymbolTableEntry &E) {
2882 E.setFlags(E.getFlags() = JITSymbolFlags::HasError);
2883 },
2884 [&](AsynchronousSymbolQuery &Q, JITDylib &JD,
2885 NonOwningSymbolStringPtr Name, JITDylib::SymbolTableEntry &E) {
2886 auto &FS = EQ.FailedSymsForQuery[&Q];
2887 if (!FS)
2888 FS = std::make_shared<SymbolDependenceMap>();
2889 (*FS)[&JD].insert(SymbolStringPtr(Name));
2890 });
2891
2892 for (auto &FQ : EQ.Failed)
2893 FQ->detach();
2894
2895 for (auto &SN : ER.Ready)
2896 IL_collectQueries(
2897 EQ.Completed, SN->defs(),
2898 [](JITDylib::SymbolTableEntry &E) { E.setState(SymbolState::Ready); },
2899 [](AsynchronousSymbolQuery &Q, JITDylib &JD,
2900 NonOwningSymbolStringPtr Name, JITDylib::SymbolTableEntry &E) {
2901 Q.notifySymbolMetRequiredState(SymbolStringPtr(Name), E.getSymbol());
2902 });
2903
2904 // std::erase_if is not available in C++17, and llvm::erase_if does not work
2905 // here.
2906 for (auto it = EQ.Completed.begin(), end = EQ.Completed.end(); it != end;) {
2907 if ((*it)->isComplete()) {
2908 ++it;
2909 } else {
2910 it = EQ.Completed.erase(it);
2911 }
2912 }
2913
2914#ifdef EXPENSIVE_CHECKS
2915 verifySessionState("exiting ExecutionSession::IL_emit");
2916#endif
2917
2918 return std::move(EQ);
2919}
2920
2921Error ExecutionSession::OL_notifyEmitted(
2924 LLVM_DEBUG({
2925 dbgs() << "In " << MR.JD.getName() << " emitting " << MR.SymbolFlags
2926 << "\n";
2927 if (!DepGroups.empty()) {
2928 dbgs() << " Initial dependencies:\n";
2929 for (auto &SDG : DepGroups) {
2930 dbgs() << " Symbols: " << SDG.Symbols
2931 << ", Dependencies: " << SDG.Dependencies << "\n";
2932 }
2933 }
2934 });
2935
2936#ifndef NDEBUG
2937 SymbolNameSet Visited;
2938 for (auto &DG : DepGroups) {
2939 for (auto &Sym : DG.Symbols) {
2940 assert(MR.SymbolFlags.count(Sym) &&
2941 "DG contains dependence for symbol outside this MR");
2942 assert(Visited.insert(Sym).second &&
2943 "DG contains duplicate entries for Name");
2944 }
2945 }
2946#endif // NDEBUG
2947
2948 std::vector<std::unique_ptr<WaitingOnGraph::SuperNode>> SNs;
2949 WaitingOnGraph::ContainerElementsMap Residual;
2950 {
2951 auto &JDResidual = Residual[&MR.getTargetJITDylib()];
2952 for (auto &[Name, Flags] : MR.getSymbols())
2953 JDResidual.insert(NonOwningSymbolStringPtr(Name));
2954
2955 for (auto &SDG : DepGroups) {
2956 WaitingOnGraph::ContainerElementsMap Defs;
2957 assert(!SDG.Symbols.empty());
2958 auto &JDDefs = Defs[&MR.getTargetJITDylib()];
2959 for (auto &Def : SDG.Symbols) {
2960 JDDefs.insert(NonOwningSymbolStringPtr(Def));
2961 JDResidual.erase(NonOwningSymbolStringPtr(Def));
2962 }
2963 WaitingOnGraph::ContainerElementsMap Deps;
2964 if (!SDG.Dependencies.empty()) {
2965 for (auto &[JD, Syms] : SDG.Dependencies) {
2966 auto &JDDeps = Deps[JD];
2967 for (auto &Dep : Syms)
2968 JDDeps.insert(NonOwningSymbolStringPtr(Dep));
2969 }
2970 }
2971 SNs.push_back(std::make_unique<WaitingOnGraph::SuperNode>(
2972 std::move(Defs), std::move(Deps)));
2973 }
2974 if (!JDResidual.empty())
2975 SNs.push_back(std::make_unique<WaitingOnGraph::SuperNode>(
2976 std::move(Residual), WaitingOnGraph::ContainerElementsMap()));
2977 }
2978
2979 auto SR = WaitingOnGraph::simplify(std::move(SNs), GOpRecorder);
2980
2981 LLVM_DEBUG({
2982 dbgs() << " Simplified dependencies:\n";
2983 for (auto &SN : SR.superNodes()) {
2984
2985 auto SortedLibs = [](WaitingOnGraph::ContainerElementsMap &C) {
2986 std::vector<JITDylib *> JDs;
2987 for (auto &[JD, _] : C)
2988 JDs.push_back(JD);
2989 llvm::sort(JDs, [](const JITDylib *LHS, const JITDylib *RHS) {
2990 return LHS->getName() < RHS->getName();
2991 });
2992 return JDs;
2993 };
2994
2995 auto SortedNames = [](WaitingOnGraph::ElementSet &Elems) {
2996 std::vector<NonOwningSymbolStringPtr> Names(Elems.begin(), Elems.end());
2997 llvm::sort(Names, [](const NonOwningSymbolStringPtr &LHS,
2998 const NonOwningSymbolStringPtr &RHS) {
2999 return *LHS < *RHS;
3000 });
3001 return Names;
3002 };
3003
3004 dbgs() << " Defs: {";
3005 for (auto *JD : SortedLibs(SN->defs())) {
3006 dbgs() << " (" << JD->getName() << ", [";
3007 for (auto &Sym : SortedNames(SN->defs()[JD]))
3008 dbgs() << " " << Sym;
3009 dbgs() << " ])";
3010 }
3011 dbgs() << " }, Deps: {";
3012 for (auto *JD : SortedLibs(SN->deps())) {
3013 dbgs() << " (" << JD->getName() << ", [";
3014 for (auto &Sym : SortedNames(SN->deps()[JD]))
3015 dbgs() << " " << Sym;
3016 dbgs() << " ])";
3017 }
3018 dbgs() << " }\n";
3019 }
3020 });
3021 auto EmitQueries =
3022 runSessionLocked([&]() { return IL_emit(MR, std::move(SR)); });
3023
3024 // On error bail out.
3025 if (!EmitQueries)
3026 return EmitQueries.takeError();
3027
3028 // Otherwise notify failed queries, and any updated queries that have been
3029 // completed.
3030
3031 // FIXME: Get rid of error return from notifyEmitted.
3032 SymbolDependenceMap BadDeps;
3033 {
3034 for (auto &FQ : EmitQueries->Failed) {
3035 FQ->detach();
3036 assert(EmitQueries->FailedSymsForQuery.count(FQ.get()) &&
3037 "Missing failed symbols for query");
3038 auto FailedSyms = std::move(EmitQueries->FailedSymsForQuery[FQ.get()]);
3039 for (auto &[JD, Syms] : *FailedSyms) {
3040 auto &BadDepsForJD = BadDeps[JD];
3041 for (auto &Sym : Syms)
3042 BadDepsForJD.insert(Sym);
3043 }
3045 std::move(FailedSyms)));
3046 }
3047 }
3048
3049 for (auto &UQ : EmitQueries->Completed)
3050 UQ->handleComplete(*this);
3051
3052 // If there are any bad dependencies then return an error.
3053 if (!BadDeps.empty()) {
3054 SymbolNameSet BadNames;
3055 // Note: The name set calculated here is bogus: it includes all symbols in
3056 // the MR, not just the ones that failed. We want to remove the error
3057 // return path from notifyEmitted anyway, so this is just a brief
3058 // placeholder to maintain (roughly) the current error behavior.
3059 for (auto &[Name, Flags] : MR.getSymbols())
3060 BadNames.insert(Name);
3061 MR.SymbolFlags.clear();
3063 getSymbolStringPool(), &MR.getTargetJITDylib(), std::move(BadNames),
3064 std::move(BadDeps), "dependencies removed or in error state");
3065 }
3066
3067 MR.SymbolFlags.clear();
3068 return Error::success();
3069}
3070
3071Error ExecutionSession::OL_defineMaterializing(
3072 MaterializationResponsibility &MR, SymbolFlagsMap NewSymbolFlags) {
3073
3074 LLVM_DEBUG({
3075 dbgs() << "In " << MR.JD.getName() << " defining materializing symbols "
3076 << NewSymbolFlags << "\n";
3077 });
3078 if (auto AcceptedDefs =
3079 MR.JD.defineMaterializing(MR, std::move(NewSymbolFlags))) {
3080 // Add all newly accepted symbols to this responsibility object.
3081 for (auto &KV : *AcceptedDefs)
3082 MR.SymbolFlags.insert(KV);
3083 return Error::success();
3084 } else
3085 return AcceptedDefs.takeError();
3086}
3087
3088std::pair<JITDylib::AsynchronousSymbolQuerySet,
3089 std::shared_ptr<SymbolDependenceMap>>
3090ExecutionSession::IL_failSymbols(JITDylib &JD,
3091 const SymbolNameVector &SymbolsToFail) {
3092
3093#ifdef EXPENSIVE_CHECKS
3094 verifySessionState("entering ExecutionSession::IL_failSymbols");
3095#endif
3096
3097 // Early out in the easy case.
3098 if (SymbolsToFail.empty())
3099 return {};
3100
3101 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3102 auto Fail = [&](JITDylib *FailJD, NonOwningSymbolStringPtr FailSym) {
3103 auto I = FailJD->Symbols.find_as(FailSym);
3104 assert(I != FailJD->Symbols.end());
3105 I->second.setFlags(I->second.getFlags() | JITSymbolFlags::HasError);
3106 auto J = FailJD->MaterializingInfos.find_as(FailSym);
3107 if (J != FailJD->MaterializingInfos.end()) {
3108 for (auto &Q : J->second.takeAllPendingQueries())
3109 FailedQueries.insert(std::move(Q));
3110 FailJD->MaterializingInfos.erase(J);
3111 }
3112 };
3113
3114 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
3115
3116 {
3117 auto &FailedSymsForJD = (*FailedSymbolsMap)[&JD];
3118 for (auto &Sym : SymbolsToFail) {
3119 FailedSymsForJD.insert(Sym);
3120 Fail(&JD, NonOwningSymbolStringPtr(Sym));
3121 }
3122 }
3123
3124 WaitingOnGraph::ContainerElementsMap ToFail;
3125 auto &JDToFail = ToFail[&JD];
3126 for (auto &Sym : SymbolsToFail)
3127 JDToFail.insert(NonOwningSymbolStringPtr(Sym));
3128
3129 auto FailedSNs = G.fail(ToFail, GOpRecorder);
3130
3131 for (auto &SN : FailedSNs) {
3132 for (auto &[FailJD, Defs] : SN->defs()) {
3133 auto &FailedSymsForFailJD = (*FailedSymbolsMap)[FailJD];
3134 for (auto &Def : Defs) {
3135 FailedSymsForFailJD.insert(SymbolStringPtr(Def));
3136 Fail(FailJD, Def);
3137 }
3138 }
3139 }
3140
3141 // Detach all failed queries.
3142 for (auto &Q : FailedQueries)
3143 Q->detach();
3144
3145#ifdef EXPENSIVE_CHECKS
3146 verifySessionState("exiting ExecutionSession::IL_failSymbols");
3147#endif
3148
3149 return std::make_pair(std::move(FailedQueries), std::move(FailedSymbolsMap));
3150}
3151
3152void ExecutionSession::OL_notifyFailed(MaterializationResponsibility &MR) {
3153
3154 LLVM_DEBUG({
3155 dbgs() << "In " << MR.JD.getName() << " failing materialization for "
3156 << MR.SymbolFlags << "\n";
3157 });
3158
3159 if (MR.SymbolFlags.empty())
3160 return;
3161
3162 SymbolNameVector SymbolsToFail;
3163 for (auto &[Name, Flags] : MR.SymbolFlags)
3164 SymbolsToFail.push_back(Name);
3165 MR.SymbolFlags.clear();
3166
3167 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3168 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
3169
3170 std::tie(FailedQueries, FailedSymbols) = runSessionLocked([&]() {
3171 // If the tracker is defunct then there's nothing to do here.
3172 if (MR.RT->isDefunct())
3173 return std::pair<JITDylib::AsynchronousSymbolQuerySet,
3174 std::shared_ptr<SymbolDependenceMap>>();
3175 return IL_failSymbols(MR.getTargetJITDylib(), SymbolsToFail);
3176 });
3177
3178 for (auto &Q : FailedQueries) {
3179 Q->detach();
3180 Q->handleFailed(
3182 }
3183}
3184
3185Error ExecutionSession::OL_replace(MaterializationResponsibility &MR,
3186 std::unique_ptr<MaterializationUnit> MU) {
3187 for (auto &KV : MU->getSymbols()) {
3188 assert(MR.SymbolFlags.count(KV.first) &&
3189 "Replacing definition outside this responsibility set");
3190 MR.SymbolFlags.erase(KV.first);
3191 }
3192
3193 if (MU->getInitializerSymbol() == MR.InitSymbol)
3194 MR.InitSymbol = nullptr;
3195
3196 LLVM_DEBUG(MR.JD.getExecutionSession().runSessionLocked([&]() {
3197 dbgs() << "In " << MR.JD.getName() << " replacing symbols with " << *MU
3198 << "\n";
3199 }););
3200
3201 return MR.JD.replace(MR, std::move(MU));
3202}
3203
3204Expected<std::unique_ptr<MaterializationResponsibility>>
3205ExecutionSession::OL_delegate(MaterializationResponsibility &MR,
3206 const SymbolNameSet &Symbols) {
3207
3208 SymbolStringPtr DelegatedInitSymbol;
3209 SymbolFlagsMap DelegatedFlags;
3210
3211 for (auto &Name : Symbols) {
3212 auto I = MR.SymbolFlags.find(Name);
3213 assert(I != MR.SymbolFlags.end() &&
3214 "Symbol is not tracked by this MaterializationResponsibility "
3215 "instance");
3216
3217 DelegatedFlags[Name] = std::move(I->second);
3218 if (Name == MR.InitSymbol)
3219 std::swap(MR.InitSymbol, DelegatedInitSymbol);
3220
3221 MR.SymbolFlags.erase(I);
3222 }
3223
3224 return MR.JD.delegate(MR, std::move(DelegatedFlags),
3225 std::move(DelegatedInitSymbol));
3226}
3227
3228#ifndef NDEBUG
3229void ExecutionSession::dumpDispatchInfo(Task &T) {
3230 runSessionLocked([&]() {
3231 dbgs() << "Dispatching: ";
3232 T.printDescription(dbgs());
3233 dbgs() << "\n";
3234 });
3235}
3236#endif // NDEBUG
3237
3238} // End namespace orc.
3239} // End namespace llvm.
#define Fail
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< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define _
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define H(x, y, z)
Definition MD5.cpp:56
#define T
if(PassOpts->AAPipeline)
static StringRef getName(Value *V)
This file contains some templates that are useful if you are working with the STL at all.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
bool erase(const KeyT &Val)
Definition DenseMap.h:377
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition DenseMap.h:236
unsigned size() const
Definition DenseMap.h:172
bool empty() const
Definition DenseMap.h:171
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:219
bool remove_if(Predicate Pred)
Remove entries that match the given predicate.
Definition DenseMap.h:393
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Helper for Errors used as out-parameters.
Definition Error.h:1160
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
bool hasMaterializationSideEffectsOnly() const
Returns true if this symbol is a materialization-side-effects-only symbol.
Definition JITSymbol.h:162
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
void insert_range(Range &&R)
Definition DenseSet.h:235
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
void reserve(size_t Size)
Grow the DenseSet so that it can contain at least NumEntries items before resizing again.
Definition DenseSet.h:93
A symbol query that returns results via a callback when results are ready.
Definition Core.h:558
LLVM_ABI AsynchronousSymbolQuery(const SymbolLookupSet &Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete)
Create a query for the given symbols.
Definition Core.cpp:191
LLVM_ABI void notifySymbolMetRequiredState(const SymbolStringPtr &Name, ExecutorSymbolDef Sym)
Notify the query that a requested symbol has reached the required state.
Definition Core.cpp:205
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
Definition Core.h:632
An ExecutionSession represents a running JIT program.
Definition Core.h:1111
LLVM_ABI void runJITDispatchHandler(SendResultFunction SendResult, ExecutorAddr HandlerFnTagAddr, shared::WrapperFunctionBuffer ArgBytes)
Run a registered jit-side wrapper function.
Definition Core.cpp:1898
LLVM_ABI Error endSession()
End the session.
Definition Core.cpp:1572
void reportError(Error Err)
Report a error for this execution session.
Definition Core.h:1262
friend class JITDylib
Definition Core.h:1114
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.
Definition Core.cpp:1738
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition Core.h:1165
LLVM_ABI JITDylib * getJITDylibByName(StringRef Name)
Return a pointer to the "name" JITDylib.
Definition Core.cpp:1617
friend class LookupState
Definition Core.h:1115
LLVM_ABI JITDylib & createBareJITDylib(std::string Name)
Add a new bare JITDylib to this ExecutionSession.
Definition Core.cpp:1626
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
Definition Core.h:1160
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.
Definition Core.cpp:1764
LLVM_ABI Error registerJITDispatchHandlers(JITDylib &JD, JITDispatchHandlerAssociationMap WFs)
For each tag symbol name, associate the corresponding AsyncHandlerWrapperFunction with the address of...
Definition Core.cpp:1859
LLVM_ABI void registerResourceManager(ResourceManager &RM)
Register the given ResourceManager with this ExecutionSession.
Definition Core.cpp:1600
LLVM_ABI ~ExecutionSession()
Destroy an ExecutionSession.
Definition Core.cpp:1566
LLVM_ABI void deregisterResourceManager(ResourceManager &RM)
Deregister the given ResourceManager with this ExecutionSession.
Definition Core.cpp:1604
LLVM_ABI ExecutionSession(std::unique_ptr< ExecutorProcessControl > EPC)
Construct an ExecutionSession with the given ExecutorProcessControl object.
Definition Core.cpp:1553
decltype(auto) runSessionLocked(Func &&F)
Run the given lambda with the session mutex locked.
Definition Core.h:1191
LLVM_ABI void dump(raw_ostream &OS)
Dump the state of all the JITDylibs in this session.
Definition Core.cpp:1919
unique_function< void(shared::WrapperFunctionBuffer)> SendResultFunction
Send a result to the remote.
Definition Core.h:1124
LLVM_ABI Error removeJITDylibs(std::vector< JITDylibSP > JDsToRemove)
Removes the given JITDylibs from the ExecutionSession.
Definition Core.cpp:1643
LLVM_ABI Expected< JITDylib & > createJITDylib(std::string Name)
Add a new JITDylib to this ExecutionSession.
Definition Core.cpp:1635
void dispatchTask(std::unique_ptr< Task > T)
Materialize the given unit.
Definition Core.h:1336
DenseMap< SymbolStringPtr, JITDispatchHandlerFunction > JITDispatchHandlerAssociationMap
A map associating tag names with asynchronous wrapper function implementations in the JIT.
Definition Core.h:1134
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)
Definition Core.cpp:93
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:111
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:115
InProgressFullLookupState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, SymbolState RequiredState, std::shared_ptr< AsynchronousSymbolQuery > Q, RegisterDependenciesFunction RegisterDependencies)
Definition Core.cpp:555
void complete(std::unique_ptr< InProgressLookupState > IPLS) override
Definition Core.cpp:565
void fail(Error Err) override
Definition Core.cpp:571
void complete(std::unique_ptr< InProgressLookupState > IPLS) override
Definition Core.cpp:542
void fail(Error Err) override
Definition Core.cpp:547
InProgressLookupFlagsState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, unique_function< void(Expected< SymbolFlagsMap >)> OnComplete)
Definition Core.cpp:535
virtual ~InProgressLookupState()=default
SymbolLookupSet DefGeneratorCandidates
Definition Core.cpp:522
JITDylibSearchOrder SearchOrder
Definition Core.cpp:516
std::vector< std::weak_ptr< DefinitionGenerator > > CurDefGeneratorStack
Definition Core.cpp:530
virtual void complete(std::unique_ptr< InProgressLookupState > IPLS)=0
InProgressLookupState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, SymbolState RequiredState)
Definition Core.cpp:505
SymbolLookupSet DefGeneratorNonCandidates
Definition Core.cpp:523
virtual void fail(Error Err)=0
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:84
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:88
Represents a JIT'd dynamic library.
Definition Core.h:675
LLVM_ABI ~JITDylib()
Definition Core.cpp:642
LLVM_ABI Error remove(const SymbolNameSet &Names)
Tries to remove the given symbols.
Definition Core.cpp:1044
LLVM_ABI Error clear()
Calls remove on all trackers currently associated with this JITDylib.
Definition Core.cpp:646
LLVM_ABI void dump(raw_ostream &OS)
Dump current JITDylib state to OS.
Definition Core.cpp:1100
LLVM_ABI void replaceInLinkOrder(JITDylib &OldJD, JITDylib &NewJD, JITDylibLookupFlags JDLookupFlags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Replace OldJD with NewJD in the link order if OldJD is present.
Definition Core.cpp:1020
Error define(std::unique_ptr< MaterializationUnitType > &&MU, ResourceTrackerSP RT=nullptr)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Definition Core.h:1649
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
Definition Core.h:694
LLVM_ABI void addToLinkOrder(const JITDylibSearchOrder &NewLinks)
Append the given JITDylibSearchOrder to the link order for this JITDylib (discarding any elements alr...
Definition Core.cpp:1004
LLVM_ABI ResourceTrackerSP createResourceTracker()
Create a resource tracker for this JITDylib.
Definition Core.cpp:670
LLVM_ABI void removeFromLinkOrder(JITDylib &JD)
Remove the given JITDylib from the link order for this JITDylib if it is present.
Definition Core.cpp:1032
LLVM_ABI void setLinkOrder(JITDylibSearchOrder NewSearchOrder, bool LinkAgainstThisJITDylibFirst=true)
Set the link order to be used when fixing up definitions in JITDylib.
Definition Core.cpp:989
LLVM_ABI Expected< std::vector< JITDylibSP > > getReverseDFSLinkOrder()
Rteurn this JITDylib and its transitive dependencies in reverse DFS order based on linkage relationsh...
Definition Core.cpp:1734
LLVM_ABI ResourceTrackerSP getDefaultResourceTracker()
Get the default resource tracker for this JITDylib.
Definition Core.cpp:661
JITDylib(const JITDylib &)=delete
LLVM_ABI void removeGenerator(DefinitionGenerator &G)
Remove a definition generator from this JITDylib.
Definition Core.cpp:678
LLVM_ABI Expected< std::vector< JITDylibSP > > getDFSLinkOrder()
Return this JITDylib and its transitive dependencies in DFS order based on linkage relationships.
Definition Core.cpp:1730
Wraps state for a lookup-in-progress.
Definition Core.h:607
LLVM_ABI void continueLookup(Error Err)
Continue the lookup.
Definition Core.cpp:622
LLVM_ABI LookupState & operator=(LookupState &&)
void run() override
Definition Core.cpp:1551
static char ID
Definition Core.h:1100
void printDescription(raw_ostream &OS) override
Definition Core.cpp:1549
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition Core.h:349
void printDescription(raw_ostream &OS) override
Definition Core.cpp:1538
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:173
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:177
Non-owning SymbolStringPool entry pointer.
static void lookupInitSymbolsAsync(unique_function< void(Error)> OnComplete, ExecutionSession &ES, const DenseMap< JITDylib *, SymbolLookupSet > &InitSyms)
Performs an async lookup for the given symbols in each of the given JITDylibs, calling the given hand...
Definition Core.cpp:1489
static Expected< DenseMap< JITDylib *, SymbolMap > > lookupInitSymbols(ExecutionSession &ES, const DenseMap< JITDylib *, SymbolLookupSet > &InitSyms)
A utility function for looking up initializer symbols.
Definition Core.cpp:1440
StringRef getName() const override
Return the name of this materialization unit.
Definition Core.cpp:296
ReExportsMaterializationUnit(JITDylib *SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolAliasMap Aliases)
SourceJD is allowed to be nullptr, in which case the source JITDylib is taken to be whatever JITDylib...
Definition Core.cpp:290
std::function< bool(SymbolStringPtr)> SymbolPredicate
Definition Core.h:1739
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &LookupSet) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
Definition Core.cpp:587
ReexportsGenerator(JITDylib &SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolPredicate Allow=SymbolPredicate())
Create a reexports generator.
Definition Core.cpp:581
Listens for ResourceTracker operations.
Definition Core.h:111
ResourceTrackerDefunct(ResourceTrackerSP RT)
Definition Core.cpp:73
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:80
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:76
API to remove / transfer ownership of JIT resources.
Definition Core.h:63
JITDylib & getJITDylib() const
Return the JITDylib targeted by this tracker.
Definition Core.h:78
LLVM_ABI void transferTo(ResourceTracker &DstRT)
Transfer all resources associated with this key to the given tracker, which must target the same JITD...
Definition Core.cpp:61
LLVM_ABI ~ResourceTracker()
Definition Core.cpp:52
ResourceTracker(const ResourceTracker &)=delete
LLVM_ABI Error remove()
Remove all resources associated with this key.
Definition Core.cpp:57
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.
Definition Core.cpp:165
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:169
SymbolsCouldNotBeRemoved(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
Definition Core.cpp:159
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:155
SymbolsNotFound(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
Definition Core.cpp:138
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:151
Represents an abstract task for ORC to run.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:182
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:186
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:131
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:127
UnsatisfiedSymbolDependencies(std::shared_ptr< SymbolStringPool > SSP, JITDylibSP JD, SymbolNameSet FailedSymbols, SymbolDependenceMap BadDeps, std::string Explanation)
Definition Core.cpp:119
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.
Definition raw_ostream.h:53
unique_function is a type-erasing functor similar to std::function.
@ Entry
Definition COFF.h:862
SymbolFlags
Symbol flags.
Definition Symbol.h:25
JITDylibSearchOrder makeJITDylibSearchOrder(ArrayRef< JITDylib * > JDs, JITDylibLookupFlags Flags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Convenience function for creating a search order from an ArrayRef of JITDylib*, all with the same fla...
Definition Core.h:153
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
Definition Core.h:148
IntrusiveRefCntPtr< JITDylib > JITDylibSP
Definition Core.h:58
IntrusiveRefCntPtr< ResourceTracker > ResourceTrackerSP
Definition Core.h:57
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
Definition Core.h:523
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.
Definition Core.h:179
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...
Definition Core.h:532
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
Definition Core.h:132
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
LookupKind
Describes the kind of lookup being performed.
Definition Core.h:144
LLVM_ABI RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
Definition Core.cpp:40
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.
Definition Core.h:545
@ Materializing
Added to the symbol table, never queried.
Definition Core.h:548
@ NeverSearched
No symbol should be in this state.
Definition Core.h:547
@ Ready
Emitted to memory, but waiting on transitive dependencies.
Definition Core.h:551
@ Resolved
Queried, materialization begun.
Definition Core.h:549
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
Definition Core.h:173
LLVM_ABI std::error_code orcError(OrcErrorCode ErrCode)
Definition OrcError.cpp:84
unique_function< void(Expected< SymbolMap >)> SymbolsResolvedCallback
Callback to notify client that symbols have been resolved.
Definition Core.h:176
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 ...
Definition Core.cpp:482
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.
Definition STLExtras.h:1765
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition Error.h:442
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:94
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
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.
Definition Error.h:769
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2052
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
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.
Definition STLExtras.h:1917
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1772
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define EQ(a, b)
Definition regexec.c:65