LLVM 23.0.0git
Core.h
Go to the documentation of this file.
1//===------ Core.h -- Core ORC APIs (Layer, JITDylib, etc.) -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Contains core ORC APIs.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_EXECUTIONENGINE_ORC_CORE_H
14#define LLVM_EXECUTIONENGINE_ORC_CORE_H
15
17#include "llvm/ADT/DenseSet.h"
31#include "llvm/Support/Debug.h"
33
34#include <atomic>
35#include <deque>
36#include <future>
37#include <memory>
38#include <vector>
39
40namespace llvm {
41namespace orc {
42
43// Forward declare some classes.
47class JITDylib;
48class ResourceTracker;
50
51enum class SymbolState : uint8_t;
52
55
58
59/// A definition of a Symbol within a JITDylib.
61public:
64
66 : JD(std::move(JD)), Name(std::move(Name)) {}
67
68 const JITDylib &getJITDylib() const { return *JD; }
69 const SymbolStringPtr &getName() const { return Name; }
70
72 LLVM_ABI void lookupAsync(LookupAsyncOnCompleteFn OnComplete) const;
73
74private:
75 JITDylibSP JD;
76 SymbolStringPtr Name;
77};
78
79using ResourceKey = uintptr_t;
80
81/// API to remove / transfer ownership of JIT resources.
82class ResourceTracker : public ThreadSafeRefCountedBase<ResourceTracker> {
83private:
84 friend class ExecutionSession;
85 friend class JITDylib;
87
88public:
93
95
96 /// Return the JITDylib targeted by this tracker.
98 return *reinterpret_cast<JITDylib *>(JDAndFlag.load() &
99 ~static_cast<uintptr_t>(1));
100 }
101
102 /// Runs the given callback under the session lock, passing in the associated
103 /// ResourceKey. This is the safe way to associate resources with trackers.
104 template <typename Func> Error withResourceKeyDo(Func &&F);
105
106 /// Remove all resources associated with this key.
108
109 /// Transfer all resources associated with this key to the given
110 /// tracker, which must target the same JITDylib as this one.
112
113 /// Return true if this tracker has become defunct.
114 bool isDefunct() const { return JDAndFlag.load() & 0x1; }
115
116 /// Returns the key associated with this tracker.
117 /// This method should not be used except for debug logging: there is no
118 /// guarantee that the returned value will remain valid.
119 ResourceKey getKeyUnsafe() const { return reinterpret_cast<uintptr_t>(this); }
120
121private:
123
124 void makeDefunct();
125
126 std::atomic_uintptr_t JDAndFlag;
127};
128
129/// Listens for ResourceTracker operations.
131public:
133
134 /// This function will be called *outside* the session lock. ResourceManagers
135 /// should perform book-keeping under the session lock, and any expensive
136 /// cleanup outside the session lock.
138
139 /// This function will be called *inside* the session lock. ResourceManagers
140 /// DO NOT need to re-lock the session.
142 ResourceKey SrcK) = 0;
143};
144
145/// Lookup flags that apply to each dylib in the search order for a lookup.
146///
147/// If MatchHiddenSymbolsOnly is used (the default) for a given dylib, then
148/// only symbols in that Dylib's interface will be searched. If
149/// MatchHiddenSymbols is used then symbols with hidden visibility will match
150/// as well.
152
153/// Lookup flags that apply to each symbol in a lookup.
154///
155/// If RequiredSymbol is used (the default) for a given symbol then that symbol
156/// must be found during the lookup or the lookup will fail returning a
157/// SymbolNotFound error. If WeaklyReferencedSymbol is used and the given
158/// symbol is not found then the query will continue, and no result for the
159/// missing symbol will be present in the result (assuming the rest of the
160/// lookup succeeds).
162
163/// Describes the kind of lookup being performed. The lookup kind is passed to
164/// symbol generators (if they're invoked) to help them determine what
165/// definitions to generate.
166///
167/// Static -- Lookup is being performed as-if at static link time (e.g.
168/// generators representing static archives should pull in new
169/// definitions).
170///
171/// DLSym -- Lookup is being performed as-if at runtime (e.g. generators
172/// representing static archives should not pull in new definitions).
173enum class LookupKind { Static, DLSym };
174
175/// A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search
176/// order during symbol lookup.
178 std::vector<std::pair<JITDylib *, JITDylibLookupFlags>>;
179
180/// Convenience function for creating a search order from an ArrayRef of
181/// JITDylib*, all with the same flags.
186 O.reserve(JDs.size());
187 for (auto *JD : JDs)
188 O.push_back(std::make_pair(JD, Flags));
189 return O;
190}
191
192/// A set of symbols to look up, each associated with a SymbolLookupFlags
193/// value.
194///
195/// This class is backed by a vector and optimized for fast insertion,
196/// deletion and iteration. It does not guarantee a stable order between
197/// operations, and will not automatically detect duplicate elements (they
198/// can be manually checked by calling the validate method).
200public:
201 using value_type = std::pair<SymbolStringPtr, SymbolLookupFlags>;
202 using UnderlyingVector = std::vector<value_type>;
203 using iterator = UnderlyingVector::iterator;
204 using const_iterator = UnderlyingVector::const_iterator;
205
206 SymbolLookupSet() = default;
207
208 SymbolLookupSet(std::initializer_list<value_type> Elems) {
209 for (auto &E : Elems)
210 Symbols.push_back(std::move(E));
211 }
212
214 SymbolStringPtr Name,
216 add(std::move(Name), Flags);
217 }
218
219 /// Construct a SymbolLookupSet from an initializer list of SymbolStringPtrs.
221 std::initializer_list<SymbolStringPtr> Names,
223 Symbols.reserve(Names.size());
224 for (const auto &Name : Names)
225 add(std::move(Name), Flags);
226 }
227
228 /// Construct a SymbolLookupSet from a SymbolNameSet with the given
229 /// Flags used for each value.
231 const SymbolNameSet &Names,
233 Symbols.reserve(Names.size());
234 for (const auto &Name : Names)
235 add(Name, Flags);
236 }
237
238 /// Construct a SymbolLookupSet from a vector of symbols with the given Flags
239 /// used for each value.
240 /// If the ArrayRef contains duplicates it is up to the client to remove these
241 /// before using this instance for lookup.
245 Symbols.reserve(Names.size());
246 for (const auto &Name : Names)
247 add(Name, Flags);
248 }
249
250 /// Construct a SymbolLookupSet from DenseMap keys.
251 template <typename ValT>
252 static SymbolLookupSet
256 Result.Symbols.reserve(M.size());
257 for (const auto &[Name, Val] : M)
258 Result.add(Name, Flags);
259 return Result;
260 }
261
262 /// Add an element to the set. The client is responsible for checking that
263 /// duplicates are not added.
267 Symbols.push_back(std::make_pair(std::move(Name), Flags));
268 return *this;
269 }
270
271 /// Quickly append one lookup set to another.
273 Symbols.reserve(Symbols.size() + Other.size());
274 for (auto &KV : Other)
275 Symbols.push_back(std::move(KV));
276 return *this;
277 }
278
279 bool empty() const { return Symbols.empty(); }
280 UnderlyingVector::size_type size() const { return Symbols.size(); }
281 iterator begin() { return Symbols.begin(); }
282 iterator end() { return Symbols.end(); }
283 const_iterator begin() const { return Symbols.begin(); }
284 const_iterator end() const { return Symbols.end(); }
285
286 /// Removes the Ith element of the vector, replacing it with the last element.
287 void remove(UnderlyingVector::size_type I) {
288 std::swap(Symbols[I], Symbols.back());
289 Symbols.pop_back();
290 }
291
292 /// Removes the element pointed to by the given iterator. This iterator and
293 /// all subsequent ones (including end()) are invalidated.
294 void remove(iterator I) { remove(I - begin()); }
295
296 /// Removes all elements matching the given predicate, which must be callable
297 /// as bool(const SymbolStringPtr &, SymbolLookupFlags Flags).
298 template <typename PredFn> void remove_if(PredFn &&Pred) {
299 UnderlyingVector::size_type I = 0;
300 while (I != Symbols.size()) {
301 const auto &Name = Symbols[I].first;
302 auto Flags = Symbols[I].second;
303 if (Pred(Name, Flags))
304 remove(I);
305 else
306 ++I;
307 }
308 }
309
310 /// Loop over the elements of this SymbolLookupSet, applying the Body function
311 /// to each one. Body must be callable as
312 /// bool(const SymbolStringPtr &, SymbolLookupFlags).
313 /// If Body returns true then the element just passed in is removed from the
314 /// set. If Body returns false then the element is retained.
315 template <typename BodyFn>
316 auto forEachWithRemoval(BodyFn &&Body) -> std::enable_if_t<
317 std::is_same<decltype(Body(std::declval<const SymbolStringPtr &>(),
318 std::declval<SymbolLookupFlags>())),
319 bool>::value> {
320 UnderlyingVector::size_type I = 0;
321 while (I != Symbols.size()) {
322 const auto &Name = Symbols[I].first;
323 auto Flags = Symbols[I].second;
324 if (Body(Name, Flags))
325 remove(I);
326 else
327 ++I;
328 }
329 }
330
331 /// Loop over the elements of this SymbolLookupSet, applying the Body function
332 /// to each one. Body must be callable as
333 /// Expected<bool>(const SymbolStringPtr &, SymbolLookupFlags).
334 /// If Body returns a failure value, the loop exits immediately. If Body
335 /// returns true then the element just passed in is removed from the set. If
336 /// Body returns false then the element is retained.
337 template <typename BodyFn>
338 auto forEachWithRemoval(BodyFn &&Body) -> std::enable_if_t<
339 std::is_same<decltype(Body(std::declval<const SymbolStringPtr &>(),
340 std::declval<SymbolLookupFlags>())),
341 Expected<bool>>::value,
342 Error> {
343 UnderlyingVector::size_type I = 0;
344 while (I != Symbols.size()) {
345 const auto &Name = Symbols[I].first;
346 auto Flags = Symbols[I].second;
347 auto Remove = Body(Name, Flags);
348 if (!Remove)
349 return Remove.takeError();
350 if (*Remove)
351 remove(I);
352 else
353 ++I;
354 }
355 return Error::success();
356 }
357
358 /// Construct a SymbolNameVector from this instance by dropping the Flags
359 /// values.
361 SymbolNameVector Names;
362 Names.reserve(Symbols.size());
363 for (const auto &KV : Symbols)
364 Names.push_back(KV.first);
365 return Names;
366 }
367
368 /// Sort the lookup set by pointer value. This sort is fast but sensitive to
369 /// allocation order and so should not be used where a consistent order is
370 /// required.
372
373 /// Sort the lookup set lexicographically. This sort is slow but the order
374 /// is unaffected by allocation order.
375 void sortByName() {
376 llvm::sort(Symbols, [](const value_type &LHS, const value_type &RHS) {
377 return *LHS.first < *RHS.first;
378 });
379 }
380
381 /// Remove any duplicate elements. If a SymbolLookupSet is not duplicate-free
382 /// by construction, this method can be used to turn it into a proper set.
385 auto LastI = llvm::unique(Symbols);
386 Symbols.erase(LastI, Symbols.end());
387 }
388
389#ifndef NDEBUG
390 /// Returns true if this set contains any duplicates. This should only be used
391 /// in assertions.
393 if (Symbols.size() < 2)
394 return false;
396 for (UnderlyingVector::size_type I = 1; I != Symbols.size(); ++I)
397 if (Symbols[I].first == Symbols[I - 1].first)
398 return true;
399 return false;
400 }
401#endif
402
403private:
404 UnderlyingVector Symbols;
405};
406
415
416/// A map of Symbols to (Symbol, Flags) pairs.
418
419/// Callback to notify client that symbols have been resolved.
421
422/// Callback to register the dependencies for a given query.
424 std::function<void(const SymbolDependenceMap &)>;
425
426/// This can be used as the value for a RegisterDependenciesFunction if there
427/// are no dependants to register with.
429
431 : public ErrorInfo<ResourceTrackerDefunct> {
432public:
433 static char ID;
434
436 std::error_code convertToErrorCode() const override;
437 void log(raw_ostream &OS) const override;
438
439private:
441};
442
443/// Returned by operations that fail because a JITDylib has been closed.
444class LLVM_ABI JITDylibDefunct : public ErrorInfo<JITDylibDefunct> {
445public:
446 static char ID;
447
449 std::error_code convertToErrorCode() const override;
450 void log(raw_ostream &OS) const override;
451
452private:
453 JITDylibSP JD;
454};
455
456/// Used to notify a JITDylib that the given set of symbols failed to
457/// materialize.
458class LLVM_ABI FailedToMaterialize : public ErrorInfo<FailedToMaterialize> {
459public:
460 static char ID;
461
462 FailedToMaterialize(std::shared_ptr<SymbolStringPool> SSP,
463 std::shared_ptr<SymbolDependenceMap> Symbols);
464 ~FailedToMaterialize() override;
465 std::error_code convertToErrorCode() const override;
466 void log(raw_ostream &OS) const override;
467 const SymbolDependenceMap &getSymbols() const { return *Symbols; }
468
469private:
470 std::shared_ptr<SymbolStringPool> SSP;
471 std::shared_ptr<SymbolDependenceMap> Symbols;
472};
473
474/// Used to report failure due to unsatisfiable symbol dependencies.
476 : public ErrorInfo<UnsatisfiedSymbolDependencies> {
477public:
478 static char ID;
479
480 UnsatisfiedSymbolDependencies(std::shared_ptr<SymbolStringPool> SSP,
481 JITDylibSP JD, SymbolNameSet FailedSymbols,
482 SymbolDependenceMap BadDeps,
483 std::string Explanation);
484 std::error_code convertToErrorCode() const override;
485 void log(raw_ostream &OS) const override;
486
487private:
488 std::shared_ptr<SymbolStringPool> SSP;
489 JITDylibSP JD;
490 SymbolNameSet FailedSymbols;
491 SymbolDependenceMap BadDeps;
492 std::string Explanation;
493};
494
495/// Used to notify clients when symbols can not be found during a lookup.
496class LLVM_ABI SymbolsNotFound : public ErrorInfo<SymbolsNotFound> {
497public:
498 static char ID;
499
500 SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP, SymbolNameSet Symbols);
501 SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
502 SymbolNameVector Symbols);
503 std::error_code convertToErrorCode() const override;
504 void log(raw_ostream &OS) const override;
505 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
506 const SymbolNameVector &getSymbols() const { return Symbols; }
507
508private:
509 std::shared_ptr<SymbolStringPool> SSP;
510 SymbolNameVector Symbols;
511};
512
513/// Used to notify clients that a set of symbols could not be removed.
515 : public ErrorInfo<SymbolsCouldNotBeRemoved> {
516public:
517 static char ID;
518
519 SymbolsCouldNotBeRemoved(std::shared_ptr<SymbolStringPool> SSP,
520 SymbolNameSet Symbols);
521 std::error_code convertToErrorCode() const override;
522 void log(raw_ostream &OS) const override;
523 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
524 const SymbolNameSet &getSymbols() const { return Symbols; }
525
526private:
527 std::shared_ptr<SymbolStringPool> SSP;
528 SymbolNameSet Symbols;
529};
530
531/// Errors of this type should be returned if a module fails to include
532/// definitions that are claimed by the module's associated
533/// MaterializationResponsibility. If this error is returned it is indicative of
534/// a broken transformation / compiler / object cache.
536 : public ErrorInfo<MissingSymbolDefinitions> {
537public:
538 static char ID;
539
540 MissingSymbolDefinitions(std::shared_ptr<SymbolStringPool> SSP,
541 std::string ModuleName, SymbolNameVector Symbols)
542 : SSP(std::move(SSP)), ModuleName(std::move(ModuleName)),
543 Symbols(std::move(Symbols)) {}
544 std::error_code convertToErrorCode() const override;
545 void log(raw_ostream &OS) const override;
546 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
547 const std::string &getModuleName() const { return ModuleName; }
548 const SymbolNameVector &getSymbols() const { return Symbols; }
549private:
550 std::shared_ptr<SymbolStringPool> SSP;
551 std::string ModuleName;
552 SymbolNameVector Symbols;
553};
554
555/// Errors of this type should be returned if a module contains definitions for
556/// symbols that are not claimed by the module's associated
557/// MaterializationResponsibility. If this error is returned it is indicative of
558/// a broken transformation / compiler / object cache.
560 : public ErrorInfo<UnexpectedSymbolDefinitions> {
561public:
562 static char ID;
563
564 UnexpectedSymbolDefinitions(std::shared_ptr<SymbolStringPool> SSP,
565 std::string ModuleName, SymbolNameVector Symbols)
566 : SSP(std::move(SSP)), ModuleName(std::move(ModuleName)),
567 Symbols(std::move(Symbols)) {}
568 std::error_code convertToErrorCode() const override;
569 void log(raw_ostream &OS) const override;
570 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
571 const std::string &getModuleName() const { return ModuleName; }
572 const SymbolNameVector &getSymbols() const { return Symbols; }
573private:
574 std::shared_ptr<SymbolStringPool> SSP;
575 std::string ModuleName;
576 SymbolNameVector Symbols;
577};
578
579/// A set of symbols and the their dependencies. Used to describe dependencies
580/// for the MaterializationResponsibility::notifyEmitted operation.
585
586/// Tracks responsibility for materialization, and mediates interactions between
587/// MaterializationUnits and JDs.
588///
589/// An instance of this class is passed to MaterializationUnits when their
590/// materialize method is called. It allows MaterializationUnits to resolve and
591/// emit symbols, or abandon materialization by notifying any unmaterialized
592/// symbols of an error.
594 friend class ExecutionSession;
595 friend class JITDylib;
596
597public:
601
602 /// Destruct a MaterializationResponsibility instance. In debug mode
603 /// this asserts that all symbols being tracked have been either
604 /// emitted or notified of an error.
606
607 /// Return the ResourceTracker associated with this instance.
608 const ResourceTrackerSP &getResourceTracker() const { return RT; }
609
610 /// Runs the given callback under the session lock, passing in the associated
611 /// ResourceKey. This is the safe way to associate resources with trackers.
612 template <typename Func> Error withResourceKeyDo(Func &&F) const {
613 return RT->withResourceKeyDo(std::forward<Func>(F));
614 }
615
616 /// Returns the target JITDylib that these symbols are being materialized
617 /// into.
618 JITDylib &getTargetJITDylib() const { return JD; }
619
620 /// Returns the ExecutionSession for this instance.
622
623 /// Returns the symbol flags map for this responsibility instance.
624 /// Note: The returned flags may have transient flags (Lazy, Materializing)
625 /// set. These should be stripped with JITSymbolFlags::stripTransientFlags
626 /// before using.
627 const SymbolFlagsMap &getSymbols() const { return SymbolFlags; }
628
629 /// Returns the initialization pseudo-symbol, if any. This symbol will also
630 /// be present in the SymbolFlagsMap for this MaterializationResponsibility
631 /// object.
632 const SymbolStringPtr &getInitializerSymbol() const { return InitSymbol; }
633
634 /// Returns the names of any symbols covered by this
635 /// MaterializationResponsibility object that have queries pending. This
636 /// information can be used to return responsibility for unrequested symbols
637 /// back to the JITDylib via the delegate method.
639
640 /// Notifies the target JITDylib that the given symbols have been resolved.
641 /// This will update the given symbols' addresses in the JITDylib, and notify
642 /// any pending queries on the given symbols of their resolution. The given
643 /// symbols must be ones covered by this MaterializationResponsibility
644 /// instance. Individual calls to this method may resolve a subset of the
645 /// symbols, but all symbols must have been resolved prior to calling emit.
646 ///
647 /// This method will return an error if any symbols being resolved have been
648 /// moved to the error state due to the failure of a dependency. If this
649 /// method returns an error then clients should log it and call
650 /// failMaterialize. If no dependencies have been registered for the
651 /// symbols covered by this MaterializationResponsibility then this method
652 /// is guaranteed to return Error::success() and can be wrapped with cantFail.
653 Error notifyResolved(const SymbolMap &Symbols);
654
655 /// Notifies the target JITDylib (and any pending queries on that JITDylib)
656 /// that all symbols covered by this MaterializationResponsibility instance
657 /// have been emitted.
658 ///
659 /// The DepGroups array describes the dependencies of symbols being emitted on
660 /// symbols that are outside this MaterializationResponsibility object. Each
661 /// group consists of a pair of a set of symbols and a SymbolDependenceMap
662 /// that describes the dependencies for the symbols in the first set. The
663 /// elements of DepGroups must be non-overlapping (no symbol should appear in
664 /// more than one of hte symbol sets), but do not have to be exhaustive. Any
665 /// symbol in this MaterializationResponsibility object that is not covered
666 /// by an entry will be treated as having no dependencies.
667 ///
668 /// This method will return an error if any symbols being resolved have been
669 /// moved to the error state due to the failure of a dependency. If this
670 /// method returns an error then clients should log it and call
671 /// failMaterialize. If no dependencies have been registered for the
672 /// symbols covered by this MaterializationResponsibility then this method
673 /// is guaranteed to return Error::success() and can be wrapped with cantFail.
675
676 /// Attempt to claim responsibility for new definitions. This method can be
677 /// used to claim responsibility for symbols that are added to a
678 /// materialization unit during the compilation process (e.g. literal pool
679 /// symbols). Symbol linkage rules are the same as for symbols that are
680 /// defined up front: duplicate strong definitions will result in errors.
681 /// Duplicate weak definitions will be discarded (in which case they will
682 /// not be added to this responsibility instance).
683 ///
684 /// This method can be used by materialization units that want to add
685 /// additional symbols at materialization time (e.g. stubs, compile
686 /// callbacks, metadata).
688
689 /// Notify all not-yet-emitted covered by this MaterializationResponsibility
690 /// instance that an error has occurred.
691 /// This will remove all symbols covered by this MaterializationResponsibility
692 /// from the target JITDylib, and send an error to any queries waiting on
693 /// these symbols.
694 void failMaterialization();
695
696 /// Transfers responsibility to the given MaterializationUnit for all
697 /// symbols defined by that MaterializationUnit. This allows
698 /// materializers to break up work based on run-time information (e.g.
699 /// by introspecting which symbols have actually been looked up and
700 /// materializing only those).
701 Error replace(std::unique_ptr<MaterializationUnit> MU);
702
703 /// Delegates responsibility for the given symbols to the returned
704 /// materialization responsibility. Useful for breaking up work between
705 /// threads, or different kinds of materialization processes.
707 delegate(const SymbolNameSet &Symbols);
708
709private:
710 /// Create a MaterializationResponsibility for the given JITDylib and
711 /// initial symbols.
713 SymbolFlagsMap SymbolFlags,
714 SymbolStringPtr InitSymbol)
715 : JD(RT->getJITDylib()), RT(std::move(RT)),
716 SymbolFlags(std::move(SymbolFlags)), InitSymbol(std::move(InitSymbol)) {
717 assert(!this->SymbolFlags.empty() && "Materializing nothing?");
718 }
719
720 JITDylib &JD;
722 SymbolFlagsMap SymbolFlags;
723 SymbolStringPtr InitSymbol;
724};
725
726/// A materialization unit for symbol aliases. Allows existing symbols to be
727/// aliased with alternate flags.
729public:
730 /// SourceJD is allowed to be nullptr, in which case the source JITDylib is
731 /// taken to be whatever JITDylib these definitions are materialized in (and
732 /// MatchNonExported has no effect). This is useful for defining aliases
733 /// within a JITDylib.
734 ///
735 /// Note: Care must be taken that no sets of aliases form a cycle, as such
736 /// a cycle will result in a deadlock when any symbol in the cycle is
737 /// resolved.
739 JITDylibLookupFlags SourceJDLookupFlags,
740 SymbolAliasMap Aliases);
741
742 StringRef getName() const override;
743
744private:
745 void materialize(std::unique_ptr<MaterializationResponsibility> R) override;
746 void discard(const JITDylib &JD, const SymbolStringPtr &Name) override;
748 extractFlags(const SymbolAliasMap &Aliases);
749
750 JITDylib *SourceJD = nullptr;
751 JITDylibLookupFlags SourceJDLookupFlags;
752 SymbolAliasMap Aliases;
753};
754
755/// Create a ReExportsMaterializationUnit with the given aliases.
756/// Useful for defining symbol aliases.: E.g., given a JITDylib JD containing
757/// symbols "foo" and "bar", we can define aliases "baz" (for "foo") and "qux"
758/// (for "bar") with: \code{.cpp}
759/// SymbolStringPtr Baz = ...;
760/// SymbolStringPtr Qux = ...;
761/// if (auto Err = JD.define(symbolAliases({
762/// {Baz, { Foo, JITSymbolFlags::Exported }},
763/// {Qux, { Bar, JITSymbolFlags::Weak }}}))
764/// return Err;
765/// \endcode
766inline std::unique_ptr<ReExportsMaterializationUnit>
768 return std::make_unique<ReExportsMaterializationUnit>(
769 nullptr, JITDylibLookupFlags::MatchAllSymbols, std::move(Aliases));
770}
771
772/// Create a materialization unit for re-exporting symbols from another JITDylib
773/// with alternative names/flags.
774/// SourceJD will be searched using the given JITDylibLookupFlags.
775inline std::unique_ptr<ReExportsMaterializationUnit>
777 JITDylibLookupFlags SourceJDLookupFlags =
779 return std::make_unique<ReExportsMaterializationUnit>(
780 &SourceJD, SourceJDLookupFlags, std::move(Aliases));
781}
782
783/// Build a SymbolAliasMap for the common case where you want to re-export
784/// symbols from another JITDylib with the same linkage/flags.
787
788/// Represents the state that a symbol has reached during materialization.
789enum class SymbolState : uint8_t {
790 Invalid, /// No symbol should be in this state.
791 NeverSearched, /// Added to the symbol table, never queried.
792 Materializing, /// Queried, materialization begun.
793 Resolved, /// Assigned address, still materializing.
794 Emitted, /// Emitted to memory, but waiting on transitive dependencies.
795 Ready = 0x3f /// Ready and safe for clients to access.
796};
797
798/// A symbol query that returns results via a callback when results are
799/// ready.
800///
801/// makes a callback when all symbols are available.
803 friend class ExecutionSession;
805 friend class JITDylib;
808
809public:
810 /// Create a query for the given symbols. The NotifyComplete
811 /// callback will be called once all queried symbols reach the given
812 /// minimum state.
814 SymbolState RequiredState,
815 SymbolsResolvedCallback NotifyComplete);
816
817 /// Notify the query that a requested symbol has reached the required state.
820
821 /// Returns true if all symbols covered by this query have been
822 /// resolved.
823 bool isComplete() const { return OutstandingSymbolsCount == 0; }
824
825
826private:
827 void handleComplete(ExecutionSession &ES);
828
829 SymbolState getRequiredState() { return RequiredState; }
830
831 void addQueryDependence(JITDylib &JD, SymbolStringPtr Name);
832
833 void removeQueryDependence(JITDylib &JD, const SymbolStringPtr &Name);
834
835 void dropSymbol(const SymbolStringPtr &Name);
836
837 void handleFailed(Error Err);
838
839 void detach();
840
841 SymbolsResolvedCallback NotifyComplete;
842 SymbolDependenceMap QueryRegistrations;
843 SymbolMap ResolvedSymbols;
844 size_t OutstandingSymbolsCount;
845 SymbolState RequiredState;
846};
847
848/// Wraps state for a lookup-in-progress.
849/// DefinitionGenerators can optionally take ownership of a LookupState object
850/// to suspend a lookup-in-progress while they search for definitions.
852 friend class OrcV2CAPIHelper;
853 friend class ExecutionSession;
854
855public:
860
861 /// Continue the lookup. This can be called by DefinitionGenerators
862 /// to re-start a captured query-application operation.
863 LLVM_ABI void continueLookup(Error Err);
864
865private:
866 LookupState(std::unique_ptr<InProgressLookupState> IPLS);
867
868 // For C API.
869 void reset(InProgressLookupState *IPLS);
870
871 std::unique_ptr<InProgressLookupState> IPLS;
872};
873
874/// Definition generators can be attached to JITDylibs to generate new
875/// definitions for otherwise unresolved symbols during lookup.
877 friend class ExecutionSession;
878
879public:
880 virtual ~DefinitionGenerator();
881
882 /// DefinitionGenerators should override this method to insert new
883 /// definitions into the parent JITDylib. K specifies the kind of this
884 /// lookup. JD specifies the target JITDylib being searched, and
885 /// JDLookupFlags specifies whether the search should match against
886 /// hidden symbols. Finally, Symbols describes the set of unresolved
887 /// symbols and their associated lookup flags.
889 JITDylibLookupFlags JDLookupFlags,
890 const SymbolLookupSet &LookupSet) = 0;
891
892private:
893 std::mutex M;
894 bool InUse = false;
895 std::deque<LookupState> PendingLookups;
896};
897
898/// Represents a JIT'd dynamic library.
899///
900/// This class aims to mimic the behavior of a regular dylib or shared object,
901/// but without requiring the contained program representations to be compiled
902/// up-front. The JITDylib's content is defined by adding MaterializationUnits,
903/// and contained MaterializationUnits will typically rely on the JITDylib's
904/// links-against order to resolve external references (similar to a regular
905/// dylib).
906///
907/// The JITDylib object is a thin wrapper that references state held by the
908/// ExecutionSession. JITDylibs can be removed, clearing this underlying state
909/// and leaving the JITDylib object in a defunct state. In this state the
910/// JITDylib's name is guaranteed to remain accessible. If the ExecutionSession
911/// is still alive then other operations are callable but will return an Error
912/// or null result (depending on the API). It is illegal to call any operation
913/// other than getName on a JITDylib after the ExecutionSession has been torn
914/// down.
915///
916/// JITDylibs cannot be moved or copied. Their address is stable, and useful as
917/// a key in some JIT data structures.
918class JITDylib : public ThreadSafeRefCountedBase<JITDylib>,
919 public jitlink::JITLinkDylib {
921 friend class ExecutionSession;
922 friend class Platform;
924public:
925
926 JITDylib(const JITDylib &) = delete;
927 JITDylib &operator=(const JITDylib &) = delete;
928 JITDylib(JITDylib &&) = delete;
931
932 /// Get a reference to the ExecutionSession for this JITDylib.
933 ///
934 /// It is legal to call this method on a defunct JITDylib, however the result
935 /// will only usable if the ExecutionSession is still alive. If this JITDylib
936 /// is held by an error that may have torn down the JIT then the result
937 /// should not be used.
938 ExecutionSession &getExecutionSession() const { return ES; }
939
940 /// Dump current JITDylib state to OS.
941 ///
942 /// It is legal to call this method on a defunct JITDylib.
943 LLVM_ABI void dump(raw_ostream &OS);
944
945 /// Calls remove on all trackers currently associated with this JITDylib.
946 /// Does not run static deinits.
947 ///
948 /// Note that removal happens outside the session lock, so new code may be
949 /// added concurrently while the clear is underway, and the newly added
950 /// code will *not* be cleared. Adding new code concurrently with a clear
951 /// is usually a bug and should be avoided.
952 ///
953 /// It is illegal to call this method on a defunct JITDylib and the client
954 /// is responsible for ensuring that they do not do so.
956
957 /// Get the default resource tracker for this JITDylib.
958 ///
959 /// It is illegal to call this method on a defunct JITDylib and the client
960 /// is responsible for ensuring that they do not do so.
962
963 /// Create a resource tracker for this JITDylib.
964 ///
965 /// It is illegal to call this method on a defunct JITDylib and the client
966 /// is responsible for ensuring that they do not do so.
968
969 /// Adds a definition generator to this JITDylib and returns a referenece to
970 /// it.
971 ///
972 /// When JITDylibs are searched during lookup, if no existing definition of
973 /// a symbol is found, then any generators that have been added are run (in
974 /// the order that they were added) to potentially generate a definition.
975 ///
976 /// It is illegal to call this method on a defunct JITDylib and the client
977 /// is responsible for ensuring that they do not do so.
978 template <typename GeneratorT>
979 GeneratorT &addGenerator(std::unique_ptr<GeneratorT> DefGenerator);
980
981 /// Remove a definition generator from this JITDylib.
982 ///
983 /// The given generator must exist in this JITDylib's generators list (i.e.
984 /// have been added and not yet removed).
985 ///
986 /// It is illegal to call this method on a defunct JITDylib and the client
987 /// is responsible for ensuring that they do not do so.
989
990 /// Set the link order to be used when fixing up definitions in JITDylib.
991 /// This will replace the previous link order, and apply to any symbol
992 /// resolutions made for definitions in this JITDylib after the call to
993 /// setLinkOrder (even if the definition itself was added before the
994 /// call).
995 ///
996 /// If LinkAgainstThisJITDylibFirst is true (the default) then this JITDylib
997 /// will add itself to the beginning of the LinkOrder (Clients should not
998 /// put this JITDylib in the list in this case, to avoid redundant lookups).
999 ///
1000 /// If LinkAgainstThisJITDylibFirst is false then the link order will be used
1001 /// as-is. The primary motivation for this feature is to support deliberate
1002 /// shadowing of symbols in this JITDylib by a facade JITDylib. For example,
1003 /// the facade may resolve function names to stubs, and the stubs may compile
1004 /// lazily by looking up symbols in this dylib. Adding the facade dylib
1005 /// as the first in the link order (instead of this dylib) ensures that
1006 /// definitions within this dylib resolve to the lazy-compiling stubs,
1007 /// rather than immediately materializing the definitions in this dylib.
1008 ///
1009 /// It is illegal to call this method on a defunct JITDylib and the client
1010 /// is responsible for ensuring that they do not do so.
1011 LLVM_ABI void setLinkOrder(JITDylibSearchOrder NewSearchOrder,
1012 bool LinkAgainstThisJITDylibFirst = true);
1013
1014 /// Append the given JITDylibSearchOrder to the link order for this
1015 /// JITDylib (discarding any elements already present in this JITDylib's
1016 /// link order).
1017 LLVM_ABI void addToLinkOrder(const JITDylibSearchOrder &NewLinks);
1018
1019 /// Add the given JITDylib to the link order for definitions in this
1020 /// JITDylib.
1021 ///
1022 /// It is illegal to call this method on a defunct JITDylib and the client
1023 /// is responsible for ensuring that they do not do so.
1024 LLVM_ABI void
1026 JITDylibLookupFlags JDLookupFlags =
1028
1029 /// Replace OldJD with NewJD in the link order if OldJD is present.
1030 /// Otherwise this operation is a no-op.
1031 ///
1032 /// It is illegal to call this method on a defunct JITDylib and the client
1033 /// is responsible for ensuring that they do not do so.
1034 LLVM_ABI void
1035 replaceInLinkOrder(JITDylib &OldJD, JITDylib &NewJD,
1036 JITDylibLookupFlags JDLookupFlags =
1038
1039 /// Remove the given JITDylib from the link order for this JITDylib if it is
1040 /// present. Otherwise this operation is a no-op.
1041 ///
1042 /// It is illegal to call this method on a defunct JITDylib and the client
1043 /// is responsible for ensuring that they do not do so.
1045
1046 /// Do something with the link order (run under the session lock).
1047 ///
1048 /// It is illegal to call this method on a defunct JITDylib and the client
1049 /// is responsible for ensuring that they do not do so.
1050 template <typename Func>
1051 auto withLinkOrderDo(Func &&F)
1052 -> decltype(F(std::declval<const JITDylibSearchOrder &>()));
1053
1054 /// Define all symbols provided by the materialization unit to be part of this
1055 /// JITDylib.
1056 ///
1057 /// If RT is not specified then the default resource tracker will be used.
1058 ///
1059 /// This overload always takes ownership of the MaterializationUnit. If any
1060 /// errors occur, the MaterializationUnit consumed.
1061 ///
1062 /// It is illegal to call this method on a defunct JITDylib and the client
1063 /// is responsible for ensuring that they do not do so.
1064 template <typename MaterializationUnitType>
1065 Error define(std::unique_ptr<MaterializationUnitType> &&MU,
1066 ResourceTrackerSP RT = nullptr);
1067
1068 /// Define all symbols provided by the materialization unit to be part of this
1069 /// JITDylib.
1070 ///
1071 /// This overload only takes ownership of the MaterializationUnit no error is
1072 /// generated. If an error occurs, ownership remains with the caller. This
1073 /// may allow the caller to modify the MaterializationUnit to correct the
1074 /// issue, then re-call define.
1075 ///
1076 /// It is illegal to call this method on a defunct JITDylib and the client
1077 /// is responsible for ensuring that they do not do so.
1078 template <typename MaterializationUnitType>
1079 Error define(std::unique_ptr<MaterializationUnitType> &MU,
1080 ResourceTrackerSP RT = nullptr);
1081
1082 /// Tries to remove the given symbols.
1083 ///
1084 /// If any symbols are not defined in this JITDylib this method will return
1085 /// a SymbolsNotFound error covering the missing symbols.
1086 ///
1087 /// If all symbols are found but some symbols are in the process of being
1088 /// materialized this method will return a SymbolsCouldNotBeRemoved error.
1089 ///
1090 /// On success, all symbols are removed. On failure, the JITDylib state is
1091 /// left unmodified (no symbols are removed).
1092 ///
1093 /// It is illegal to call this method on a defunct JITDylib and the client
1094 /// is responsible for ensuring that they do not do so.
1095 LLVM_ABI Error remove(const SymbolNameSet &Names);
1096
1097 /// Returns the given JITDylibs and all of their transitive dependencies in
1098 /// DFS order (based on linkage relationships). Each JITDylib will appear
1099 /// only once.
1100 ///
1101 /// If any JITDylib in the order is defunct then this method will return an
1102 /// error, otherwise returns the order.
1105
1106 /// Returns the given JITDylibs and all of their transitive dependencies in
1107 /// reverse DFS order (based on linkage relationships). Each JITDylib will
1108 /// appear only once.
1109 ///
1110 /// If any JITDylib in the order is defunct then this method will return an
1111 /// error, otherwise returns the order.
1114
1115 /// Return this JITDylib and its transitive dependencies in DFS order
1116 /// based on linkage relationships.
1117 ///
1118 /// If any JITDylib in the order is defunct then this method will return an
1119 /// error, otherwise returns the order.
1121
1122 /// Rteurn this JITDylib and its transitive dependencies in reverse DFS order
1123 /// based on linkage relationships.
1124 ///
1125 /// If any JITDylib in the order is defunct then this method will return an
1126 /// error, otherwise returns the order.
1128
1129private:
1130 using AsynchronousSymbolQuerySet =
1131 std::set<std::shared_ptr<AsynchronousSymbolQuery>>;
1132
1133 using AsynchronousSymbolQueryList =
1134 std::vector<std::shared_ptr<AsynchronousSymbolQuery>>;
1135
1136 struct UnmaterializedInfo {
1137 UnmaterializedInfo(std::unique_ptr<MaterializationUnit> MU,
1138 ResourceTracker *RT)
1139 : MU(std::move(MU)), RT(RT) {}
1140
1141 std::unique_ptr<MaterializationUnit> MU;
1142 ResourceTracker *RT;
1143 };
1144
1145 using UnmaterializedInfosMap =
1146 DenseMap<SymbolStringPtr, std::shared_ptr<UnmaterializedInfo>>;
1147
1148 using UnmaterializedInfosList =
1149 std::vector<std::shared_ptr<UnmaterializedInfo>>;
1150
1151 // Information about not-yet-ready symbol.
1152 // * DefiningEDU will point to the EmissionDepUnit that defines the symbol.
1153 // * DependantEDUs will hold pointers to any EmissionDepUnits currently
1154 // waiting on this symbol.
1155 // * Pending queries holds any not-yet-completed queries that include this
1156 // symbol.
1157 struct MaterializingInfo {
1158 friend class ExecutionSession;
1159
1160 LLVM_ABI void addQuery(std::shared_ptr<AsynchronousSymbolQuery> Q);
1161 LLVM_ABI void removeQuery(const AsynchronousSymbolQuery &Q);
1162 LLVM_ABI AsynchronousSymbolQueryList
1163 takeQueriesMeeting(SymbolState RequiredState);
1164 AsynchronousSymbolQueryList takeAllPendingQueries() {
1165 return std::move(PendingQueries);
1166 }
1167 bool hasQueriesPending() const { return !PendingQueries.empty(); }
1168 const AsynchronousSymbolQueryList &pendingQueries() const {
1169 return PendingQueries;
1170 }
1171 private:
1172 AsynchronousSymbolQueryList PendingQueries;
1173 };
1174
1175 using MaterializingInfosMap = DenseMap<SymbolStringPtr, MaterializingInfo>;
1176
1177 class SymbolTableEntry {
1178 public:
1179 SymbolTableEntry() = default;
1180 SymbolTableEntry(JITSymbolFlags Flags)
1181 : Flags(Flags), State(static_cast<uint8_t>(SymbolState::NeverSearched)),
1182 MaterializerAttached(false) {}
1183
1184 ExecutorAddr getAddress() const { return Addr; }
1185 JITSymbolFlags getFlags() const { return Flags; }
1186 SymbolState getState() const { return static_cast<SymbolState>(State); }
1187
1188 bool hasMaterializerAttached() const { return MaterializerAttached; }
1189
1190 void setAddress(ExecutorAddr Addr) { this->Addr = Addr; }
1191 void setFlags(JITSymbolFlags Flags) { this->Flags = Flags; }
1192 void setState(SymbolState State) {
1193 assert(static_cast<uint8_t>(State) < (1 << 6) &&
1194 "State does not fit in bitfield");
1195 this->State = static_cast<uint8_t>(State);
1196 }
1197
1198 void setMaterializerAttached(bool MaterializerAttached) {
1199 this->MaterializerAttached = MaterializerAttached;
1200 }
1201
1202 ExecutorSymbolDef getSymbol() const { return {Addr, Flags}; }
1203
1204 private:
1205 ExecutorAddr Addr;
1206 JITSymbolFlags Flags;
1207 uint8_t State : 7;
1208 uint8_t MaterializerAttached : 1;
1209 };
1210
1211 using SymbolTable = DenseMap<SymbolStringPtr, SymbolTableEntry>;
1212
1213 JITDylib(ExecutionSession &ES, std::string Name);
1214
1215 struct RemoveTrackerResult {
1216 AsynchronousSymbolQuerySet QueriesToFail;
1217 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
1218 std::vector<std::unique_ptr<MaterializationUnit>> DefunctMUs;
1219 };
1220
1221 RemoveTrackerResult IL_removeTracker(ResourceTracker &RT);
1222
1223 void transferTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT);
1224
1225 LLVM_ABI Error defineImpl(MaterializationUnit &MU);
1226
1227 LLVM_ABI void
1228 installMaterializationUnit(std::unique_ptr<MaterializationUnit> MU,
1229 ResourceTracker &RT);
1230
1231 void detachQueryHelper(AsynchronousSymbolQuery &Q,
1232 const SymbolNameSet &QuerySymbols);
1233
1234 void transferEmittedNodeDependencies(MaterializingInfo &DependantMI,
1235 const SymbolStringPtr &DependantName,
1236 MaterializingInfo &EmittedMI);
1237
1238 Expected<SymbolFlagsMap>
1239 defineMaterializing(MaterializationResponsibility &FromMR,
1240 SymbolFlagsMap SymbolFlags);
1241
1242 Error replace(MaterializationResponsibility &FromMR,
1243 std::unique_ptr<MaterializationUnit> MU);
1244
1245 Expected<std::unique_ptr<MaterializationResponsibility>>
1246 delegate(MaterializationResponsibility &FromMR, SymbolFlagsMap SymbolFlags,
1247 SymbolStringPtr InitSymbol);
1248
1249 SymbolNameSet getRequestedSymbols(const SymbolFlagsMap &SymbolFlags) const;
1250
1251 void addDependencies(const SymbolStringPtr &Name,
1252 const SymbolDependenceMap &Dependants);
1253
1255
1256 void unlinkMaterializationResponsibility(MaterializationResponsibility &MR);
1257
1258 /// Attempt to reduce memory usage from empty \c UnmaterializedInfos and
1259 /// \c MaterializingInfos tables.
1260 void shrinkMaterializationInfoMemory();
1261
1262 ExecutionSession &ES;
1263 enum { Open, Closing, Closed } State = Open;
1264 std::mutex GeneratorsMutex;
1265 SymbolTable Symbols;
1266 UnmaterializedInfosMap UnmaterializedInfos;
1267 MaterializingInfosMap MaterializingInfos;
1268 std::vector<std::shared_ptr<DefinitionGenerator>> DefGenerators;
1269 JITDylibSearchOrder LinkOrder;
1270 ResourceTrackerSP DefaultTracker;
1271
1272 // Map trackers to sets of symbols tracked.
1273 DenseMap<ResourceTracker *, SymbolNameVector> TrackerSymbols;
1274 DenseMap<ResourceTracker *, DenseSet<MaterializationResponsibility *>>
1275 TrackerMRs;
1276};
1277
1278/// Platforms set up standard symbols and mediate interactions between dynamic
1279/// initializers (e.g. C++ static constructors) and ExecutionSession state.
1280/// Note that Platforms do not automatically run initializers: clients are still
1281/// responsible for doing this.
1283public:
1284 virtual ~Platform();
1285
1286 /// This method will be called outside the session lock each time a JITDylib
1287 /// is created (unless it is created with EmptyJITDylib set) to allow the
1288 /// Platform to install any JITDylib specific standard symbols (e.g
1289 /// __dso_handle).
1290 virtual Error setupJITDylib(JITDylib &JD) = 0;
1291
1292 /// This method will be called outside the session lock each time a JITDylib
1293 /// is removed to allow the Platform to remove any JITDylib-specific data.
1295
1296 /// This method will be called under the ExecutionSession lock each time a
1297 /// MaterializationUnit is added to a JITDylib.
1299 const MaterializationUnit &MU) = 0;
1300
1301 /// This method will be called under the ExecutionSession lock when a
1302 /// ResourceTracker is removed.
1304
1305 /// A utility function for looking up initializer symbols. Performs a blocking
1306 /// lookup for the given symbols in each of the given JITDylibs.
1307 ///
1308 /// Note: This function is deprecated and will be removed in the near future.
1312
1313 /// Performs an async lookup for the given symbols in each of the given
1314 /// JITDylibs, calling the given handler once all lookups have completed.
1315 static void
1317 ExecutionSession &ES,
1319};
1320
1321/// A materialization task.
1323 : public RTTIExtends<MaterializationTask, Task> {
1324public:
1325 static char ID;
1326
1327 MaterializationTask(std::unique_ptr<MaterializationUnit> MU,
1328 std::unique_ptr<MaterializationResponsibility> MR)
1329 : MU(std::move(MU)), MR(std::move(MR)) {}
1330 ~MaterializationTask() override;
1331 void printDescription(raw_ostream &OS) override;
1332 void run() override;
1333
1334private:
1335 std::unique_ptr<MaterializationUnit> MU;
1336 std::unique_ptr<MaterializationResponsibility> MR;
1337};
1338
1339/// Lookups are usually run on the current thread, but in some cases they may
1340/// be run as tasks, e.g. if the lookup has been continued from a suspended
1341/// state.
1342class LLVM_ABI LookupTask : public RTTIExtends<LookupTask, Task> {
1343public:
1344 static char ID;
1345
1346 LookupTask(LookupState LS) : LS(std::move(LS)) {}
1347 void printDescription(raw_ostream &OS) override;
1348 void run() override;
1349
1350private:
1351 LookupState LS;
1352};
1353
1354/// An ExecutionSession represents a running JIT program.
1358 friend class JITDylib;
1359 friend class LookupState;
1361 friend class ResourceTracker;
1362
1363public:
1364 /// For reporting errors.
1366
1367 /// Send a result to the remote.
1369
1370 /// An asynchronous wrapper-function callable from the executor via
1371 /// jit-dispatch.
1373 SendResultFunction SendResult,
1374 const char *ArgData, size_t ArgSize)>;
1375
1376 /// A map associating tag names with asynchronous wrapper function
1377 /// implementations in the JIT.
1380
1381 /// Construct an ExecutionSession with the given ExecutorProcessControl
1382 /// object.
1383 LLVM_ABI ExecutionSession(std::unique_ptr<ExecutorProcessControl> EPC);
1384
1385 /// Destroy an ExecutionSession. Verifies that endSession was called prior to
1386 /// destruction.
1388
1389 /// End the session. Closes all JITDylibs and disconnects from the
1390 /// executor. Clients must call this method before destroying the session.
1392
1393 /// Get the ExecutorProcessControl object associated with this
1394 /// ExecutionSession.
1396
1397 /// Return the triple for the executor.
1398 const Triple &getTargetTriple() const { return EPC->getTargetTriple(); }
1399
1400 // Return the page size for the executor.
1401 size_t getPageSize() const { return EPC->getPageSize(); }
1402
1403 /// Get the SymbolStringPool for this instance.
1404 std::shared_ptr<SymbolStringPool> getSymbolStringPool() {
1405 return EPC->getSymbolStringPool();
1406 }
1407
1408 /// Add a symbol name to the SymbolStringPool and return a pointer to it.
1409 SymbolStringPtr intern(StringRef SymName) { return EPC->intern(SymName); }
1410
1411 /// Returns a reference to the bootstrap JITDylib.
1412 ///
1413 /// This is a bare JITDylib that is created for each ExecutionSession and
1414 /// populated with the bootstrap symbol definitions provided by the
1415 /// ExecutorProcessControl object.
1416 JITDylib &getBootstrapJITDylib() { return BootstrapJD; }
1417
1418 /// Set a WaitingOnGraph::Recorder to capture WaitingOnGraph operations.
1419 ///
1420 /// This method can be called at most once. If called, it should be called
1421 /// before any symbols are materialized.
1422 void setWaitingOnGraphOpRecorder(WaitingOnGraph::OpRecorder &R) {
1423 assert(!GOpRecorder && "WaitingOnGraph recorder already set");
1424 GOpRecorder = &R;
1425 }
1426
1427 /// Set the Platform for this ExecutionSession.
1428 void setPlatform(std::unique_ptr<Platform> P) { this->P = std::move(P); }
1429
1430 /// Get the Platform for this session.
1431 /// Will return null if no Platform has been set for this ExecutionSession.
1432 Platform *getPlatform() { return P.get(); }
1433
1434 /// Run the given lambda with the session mutex locked.
1435 template <typename Func> decltype(auto) runSessionLocked(Func &&F) {
1436 std::lock_guard<std::recursive_mutex> Lock(SessionMutex);
1437 return F();
1438 }
1439
1440 /// Register the given ResourceManager with this ExecutionSession.
1441 /// Managers will be notified of events in reverse order of registration.
1443
1444 /// Deregister the given ResourceManager with this ExecutionSession.
1445 /// Manager must have been previously registered.
1447
1448 /// Return a pointer to the "name" JITDylib.
1449 /// Ownership of JITDylib remains within Execution Session
1451
1452 /// Add a new bare JITDylib to this ExecutionSession.
1453 ///
1454 /// The JITDylib Name is required to be unique. Clients should verify that
1455 /// names are not being re-used (E.g. by calling getJITDylibByName) if names
1456 /// are based on user input.
1457 ///
1458 /// This call does not install any library code or symbols into the newly
1459 /// created JITDylib. The client is responsible for all configuration.
1460 LLVM_ABI JITDylib &createBareJITDylib(std::string Name);
1461
1462 /// Add a new JITDylib to this ExecutionSession.
1463 ///
1464 /// The JITDylib Name is required to be unique. Clients should verify that
1465 /// names are not being re-used (e.g. by calling getJITDylibByName) if names
1466 /// are based on user input.
1467 ///
1468 /// If a Platform is attached then Platform::setupJITDylib will be called to
1469 /// install standard platform symbols (e.g. standard library interposes).
1470 /// If no Platform is attached this call is equivalent to createBareJITDylib.
1472
1473 /// Removes the given JITDylibs from the ExecutionSession.
1474 ///
1475 /// This method clears all resources held for the JITDylibs, puts them in the
1476 /// closed state, and clears all references to them that are held by the
1477 /// ExecutionSession or other JITDylibs. No further code can be added to the
1478 /// removed JITDylibs, and the JITDylib objects will be freed once any
1479 /// remaining JITDylibSPs pointing to them are destroyed.
1480 ///
1481 /// This method does *not* run static destructors for code contained in the
1482 /// JITDylibs, and each JITDylib can only be removed once.
1483 ///
1484 /// JITDylibs will be removed in the order given. Teardown is usually
1485 /// independent for each JITDylib, but not always. In particular, where the
1486 /// ORC runtime is used it is expected that teardown off all JITDylibs will
1487 /// depend on it, so the JITDylib containing the ORC runtime must be removed
1488 /// last. If the client has introduced any other dependencies they should be
1489 /// accounted for in the removal order too.
1490 LLVM_ABI Error removeJITDylibs(std::vector<JITDylibSP> JDsToRemove);
1491
1492 /// Calls removeJTIDylibs on the gives JITDylib.
1494 return removeJITDylibs(std::vector<JITDylibSP>({&JD}));
1495 }
1496
1497 /// Set the error reporter function.
1499 this->ReportError = std::move(ReportError);
1500 return *this;
1501 }
1502
1503 /// Report a error for this execution session.
1504 ///
1505 /// Unhandled errors can be sent here to log them.
1506 void reportError(Error Err) { ReportError(std::move(Err)); }
1507
1508 /// Search the given JITDylibs to find the flags associated with each of the
1509 /// given symbols.
1510 LLVM_ABI void
1512 SymbolLookupSet Symbols,
1513 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete);
1514
1515 /// Blocking version of lookupFlags.
1517 JITDylibSearchOrder SearchOrder,
1518 SymbolLookupSet Symbols);
1519
1520 /// Search the given JITDylibs for the given symbols.
1521 ///
1522 /// SearchOrder lists the JITDylibs to search. For each dylib, the associated
1523 /// boolean indicates whether the search should match against non-exported
1524 /// (hidden visibility) symbols in that dylib (true means match against
1525 /// non-exported symbols, false means do not match).
1526 ///
1527 /// The NotifyComplete callback will be called once all requested symbols
1528 /// reach the required state.
1529 ///
1530 /// If all symbols are found, the RegisterDependencies function will be called
1531 /// while the session lock is held. This gives clients a chance to register
1532 /// dependencies for on the queried symbols for any symbols they are
1533 /// materializing (if a MaterializationResponsibility instance is present,
1534 /// this can be implemented by calling
1535 /// MaterializationResponsibility::addDependencies). If there are no
1536 /// dependenant symbols for this query (e.g. it is being made by a top level
1537 /// client to get an address to call) then the value NoDependenciesToRegister
1538 /// can be used.
1539 LLVM_ABI void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder,
1540 SymbolLookupSet Symbols, SymbolState RequiredState,
1541 SymbolsResolvedCallback NotifyComplete,
1542 RegisterDependenciesFunction RegisterDependencies);
1543
1544 /// Blocking version of lookup above. Returns the resolved symbol map.
1545 /// If WaitUntilReady is true (the default), will not return until all
1546 /// requested symbols are ready (or an error occurs). If WaitUntilReady is
1547 /// false, will return as soon as all requested symbols are resolved,
1548 /// or an error occurs. If WaitUntilReady is false and an error occurs
1549 /// after resolution, the function will return a success value, but the
1550 /// error will be reported via reportErrors.
1552 lookup(const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols,
1554 SymbolState RequiredState = SymbolState::Ready,
1555 RegisterDependenciesFunction RegisterDependencies =
1557
1558 /// Convenience version of blocking lookup.
1559 /// Searches each of the JITDylibs in the search order in turn for the given
1560 /// symbol.
1562 lookup(const JITDylibSearchOrder &SearchOrder, SymbolStringPtr Symbol,
1563 SymbolState RequiredState = SymbolState::Ready);
1564
1565 /// Convenience version of blocking lookup.
1566 /// Searches each of the JITDylibs in the search order in turn for the given
1567 /// symbol. The search will not find non-exported symbols.
1569 lookup(ArrayRef<JITDylib *> SearchOrder, SymbolStringPtr Symbol,
1570 SymbolState RequiredState = SymbolState::Ready);
1571
1572 /// Convenience version of blocking lookup.
1573 /// Searches each of the JITDylibs in the search order in turn for the given
1574 /// symbol. The search will not find non-exported symbols.
1576 lookup(ArrayRef<JITDylib *> SearchOrder, StringRef Symbol,
1577 SymbolState RequiredState = SymbolState::Ready);
1578
1579 /// Materialize the given unit.
1580 void dispatchTask(std::unique_ptr<Task> T) {
1581 assert(T && "T must be non-null");
1582 DEBUG_WITH_TYPE("orc", dumpDispatchInfo(*T));
1583 EPC->getDispatcher().dispatch(std::move(T));
1584 }
1585
1586 /// Returns the bootstrap map.
1588 return EPC->getBootstrapMap();
1589 }
1590
1591 /// Look up and SPS-deserialize a bootstrap map value.
1592 template <typename T, typename SPSTagT>
1593 Error getBootstrapMapValue(StringRef Key, std::optional<T> &Val) const {
1594 return EPC->getBootstrapMapValue<T, SPSTagT>(Key, Val);
1595 }
1596
1597 /// Returns the bootstrap symbol map.
1599 return EPC->getBootstrapSymbolsMap();
1600 }
1601
1602 /// For each (ExecutorAddr&, StringRef) pair, looks up the string in the
1603 /// bootstrap symbols map and writes its address to the ExecutorAddr if
1604 /// found. If any symbol is not found then the function returns an error.
1606 ArrayRef<std::pair<ExecutorAddr &, StringRef>> Pairs) const {
1607 return EPC->getBootstrapSymbols(Pairs);
1608 }
1609
1610 /// Run a wrapper function in the executor. The given WFRHandler will be
1611 /// called on the result when it is returned.
1612 ///
1613 /// The wrapper function should be callable as:
1614 ///
1615 /// \code{.cpp}
1616 /// CWrapperFunctionBuffer fn(uint8_t *Data, uint64_t Size);
1617 /// \endcode{.cpp}
1618 void callWrapperAsync(ExecutorAddr WrapperFnAddr,
1620 ArrayRef<char> ArgBuffer) {
1621 EPC->callWrapperAsync(WrapperFnAddr, std::move(OnComplete), ArgBuffer);
1622 }
1623
1624 /// Run a wrapper function in the executor using the given Runner to dispatch
1625 /// OnComplete when the result is ready.
1626 template <typename RunPolicyT, typename FnT>
1627 void callWrapperAsync(RunPolicyT &&Runner, ExecutorAddr WrapperFnAddr,
1628 FnT &&OnComplete, ArrayRef<char> ArgBuffer) {
1629 EPC->callWrapperAsync(std::forward<RunPolicyT>(Runner), WrapperFnAddr,
1630 std::forward<FnT>(OnComplete), ArgBuffer);
1631 }
1632
1633 /// Run a wrapper function in the executor. OnComplete will be dispatched
1634 /// as a GenericNamedTask using this instance's TaskDispatch object.
1635 template <typename FnT>
1636 void callWrapperAsync(ExecutorAddr WrapperFnAddr, FnT &&OnComplete,
1637 ArrayRef<char> ArgBuffer) {
1638 EPC->callWrapperAsync(WrapperFnAddr, std::forward<FnT>(OnComplete),
1639 ArgBuffer);
1640 }
1641
1642 /// Run a wrapper function in the executor. The wrapper function should be
1643 /// callable as:
1644 ///
1645 /// \code{.cpp}
1646 /// CWrapperFunctionBuffer fn(uint8_t *Data, uint64_t Size);
1647 /// \endcode{.cpp}
1649 ArrayRef<char> ArgBuffer) {
1650 return EPC->callWrapper(WrapperFnAddr, ArgBuffer);
1651 }
1652
1653 /// Run a wrapper function using SPS to serialize the arguments and
1654 /// deserialize the results.
1655 template <typename SPSSignature, typename SendResultT, typename... ArgTs>
1656 void callSPSWrapperAsync(ExecutorAddr WrapperFnAddr, SendResultT &&SendResult,
1657 const ArgTs &...Args) {
1658 EPC->callSPSWrapperAsync<SPSSignature, SendResultT, ArgTs...>(
1659 WrapperFnAddr, std::forward<SendResultT>(SendResult), Args...);
1660 }
1661
1662 /// Run a wrapper function using SPS to serialize the arguments and
1663 /// deserialize the results.
1664 ///
1665 /// If SPSSignature is a non-void function signature then the second argument
1666 /// (the first in the Args list) should be a reference to a return value.
1667 template <typename SPSSignature, typename... WrapperCallArgTs>
1669 WrapperCallArgTs &&...WrapperCallArgs) {
1670 return EPC->callSPSWrapper<SPSSignature, WrapperCallArgTs...>(
1671 WrapperFnAddr, std::forward<WrapperCallArgTs>(WrapperCallArgs)...);
1672 }
1673
1674 /// Wrap a handler that takes concrete argument types (and a sender for a
1675 /// concrete return type) to produce an AsyncHandlerWrapperFunction. Uses SPS
1676 /// to unpack the arguments and pack the result.
1677 ///
1678 /// This function is intended to support easy construction of
1679 /// AsyncHandlerWrapperFunctions that can be associated with a tag
1680 /// (using registerJITDispatchHandler) and called from the executor.
1681 template <typename SPSSignature, typename HandlerT>
1683 return [H = std::forward<HandlerT>(H)](SendResultFunction SendResult,
1684 const char *ArgData,
1685 size_t ArgSize) mutable {
1687 ArgData, ArgSize, std::move(SendResult), H);
1688 };
1689 }
1690
1691 /// Wrap a class method that takes concrete argument types (and a sender for
1692 /// a concrete return type) to produce an AsyncHandlerWrapperFunction. Uses
1693 /// SPS to unpack the arguments and pack the result.
1694 ///
1695 /// This function is intended to support easy construction of
1696 /// AsyncHandlerWrapperFunctions that can be associated with a tag
1697 /// (using registerJITDispatchHandler) and called from the executor.
1698 template <typename SPSSignature, typename ClassT, typename... MethodArgTs>
1700 wrapAsyncWithSPS(ClassT *Instance, void (ClassT::*Method)(MethodArgTs...)) {
1702 [Instance, Method](MethodArgTs &&...MethodArgs) {
1703 (Instance->*Method)(std::forward<MethodArgTs>(MethodArgs)...);
1704 });
1705 }
1706
1707 /// For each tag symbol name, associate the corresponding
1708 /// AsyncHandlerWrapperFunction with the address of that symbol. The
1709 /// handler becomes callable from the executor using the ORC runtime
1710 /// __orc_rt_jit_dispatch function and the given tag.
1711 ///
1712 /// Tag symbols will be looked up in JD using LookupKind::Static,
1713 /// JITDylibLookupFlags::MatchAllSymbols (hidden tags will be found), and
1714 /// LookupFlags::WeaklyReferencedSymbol. Missing tag definitions will not
1715 /// cause an error, the handler will simply be dropped.
1718
1719 /// Run a registered jit-side wrapper function.
1720 /// This should be called by the ExecutorProcessControl instance in response
1721 /// to incoming jit-dispatch requests from the executor.
1723 ExecutorAddr HandlerFnTagAddr,
1725
1726 /// Dump the state of all the JITDylibs in this session.
1727 LLVM_ABI void dump(raw_ostream &OS);
1728
1729 /// Check the internal consistency of ExecutionSession data structures.
1730#ifdef EXPENSIVE_CHECKS
1731 bool verifySessionState(Twine Phase);
1732#endif
1733
1734private:
1735 static void logErrorsToStdErr(Error Err) {
1736 logAllUnhandledErrors(std::move(Err), errs(), "JIT session error: ");
1737 }
1738
1739 void dispatchOutstandingMUs();
1740
1741 static std::unique_ptr<MaterializationResponsibility>
1742 createMaterializationResponsibility(ResourceTracker &RT,
1743 SymbolFlagsMap Symbols,
1744 SymbolStringPtr InitSymbol) {
1745 auto &JD = RT.getJITDylib();
1746 std::unique_ptr<MaterializationResponsibility> MR(
1747 new MaterializationResponsibility(&RT, std::move(Symbols),
1748 std::move(InitSymbol)));
1749 JD.TrackerMRs[&RT].insert(MR.get());
1750 return MR;
1751 }
1752
1753 Error removeResourceTracker(ResourceTracker &RT);
1754 void transferResourceTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT);
1755 void destroyResourceTracker(ResourceTracker &RT);
1756
1757 // State machine functions for query application..
1758
1759 /// IL_updateCandidatesFor is called to remove already-defined symbols that
1760 /// match a given query from the set of candidate symbols to generate
1761 /// definitions for (no need to generate a definition if one already exists).
1762 Error IL_updateCandidatesFor(JITDylib &JD, JITDylibLookupFlags JDLookupFlags,
1763 SymbolLookupSet &Candidates,
1764 SymbolLookupSet *NonCandidates);
1765
1766 /// Handle resumption of a lookup after entering a generator.
1767 void OL_resumeLookupAfterGeneration(InProgressLookupState &IPLS);
1768
1769 /// OL_applyQueryPhase1 is an optionally re-startable loop for triggering
1770 /// definition generation. It is called when a lookup is performed, and again
1771 /// each time that LookupState::continueLookup is called.
1772 void OL_applyQueryPhase1(std::unique_ptr<InProgressLookupState> IPLS,
1773 Error Err);
1774
1775 /// OL_completeLookup is run once phase 1 successfully completes for a lookup
1776 /// call. It attempts to attach the symbol to all symbol table entries and
1777 /// collect all MaterializationUnits to dispatch. If this method fails then
1778 /// all MaterializationUnits will be left un-materialized.
1779 void OL_completeLookup(std::unique_ptr<InProgressLookupState> IPLS,
1780 std::shared_ptr<AsynchronousSymbolQuery> Q,
1781 RegisterDependenciesFunction RegisterDependencies);
1782
1783 /// OL_completeLookupFlags is run once phase 1 successfully completes for a
1784 /// lookupFlags call.
1785 void OL_completeLookupFlags(
1786 std::unique_ptr<InProgressLookupState> IPLS,
1787 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete);
1788
1789 // State machine functions for MaterializationResponsibility.
1790 LLVM_ABI void
1791 OL_destroyMaterializationResponsibility(MaterializationResponsibility &MR);
1793 OL_getRequestedSymbols(const MaterializationResponsibility &MR);
1794 LLVM_ABI Error OL_notifyResolved(MaterializationResponsibility &MR,
1795 const SymbolMap &Symbols);
1796
1797 // FIXME: We should be able to derive FailedSymsForQuery from each query once
1798 // we fix how the detach operation works.
1799 struct EmitQueries {
1800 JITDylib::AsynchronousSymbolQuerySet Completed;
1801 JITDylib::AsynchronousSymbolQuerySet Failed;
1802 DenseMap<AsynchronousSymbolQuery *, std::shared_ptr<SymbolDependenceMap>>
1803 FailedSymsForQuery;
1804 };
1805
1807 IL_getSymbolState(JITDylib *JD, NonOwningSymbolStringPtr Name);
1808
1809 template <typename UpdateSymbolFn, typename UpdateQueryFn>
1810 void IL_collectQueries(JITDylib::AsynchronousSymbolQuerySet &Qs,
1811 WaitingOnGraph::ContainerElementsMap &QualifiedSymbols,
1812 UpdateSymbolFn &&UpdateSymbol,
1813 UpdateQueryFn &&UpdateQuery);
1814
1815 Expected<EmitQueries> IL_emit(MaterializationResponsibility &MR,
1816 WaitingOnGraph::SimplifyResult SR);
1817 LLVM_ABI Error OL_notifyEmitted(MaterializationResponsibility &MR,
1819
1820 LLVM_ABI Error OL_defineMaterializing(MaterializationResponsibility &MR,
1821 SymbolFlagsMap SymbolFlags);
1822
1823 std::pair<JITDylib::AsynchronousSymbolQuerySet,
1824 std::shared_ptr<SymbolDependenceMap>>
1825 IL_failSymbols(JITDylib &JD, const SymbolNameVector &SymbolsToFail);
1826 LLVM_ABI void OL_notifyFailed(MaterializationResponsibility &MR);
1828 std::unique_ptr<MaterializationUnit> MU);
1829 LLVM_ABI Expected<std::unique_ptr<MaterializationResponsibility>>
1830 OL_delegate(MaterializationResponsibility &MR, const SymbolNameSet &Symbols);
1831
1832#ifndef NDEBUG
1833 void dumpDispatchInfo(Task &T);
1834#endif // NDEBUG
1835
1836 mutable std::recursive_mutex SessionMutex;
1837 bool SessionOpen = true;
1838 std::unique_ptr<ExecutorProcessControl> EPC;
1839 std::unique_ptr<Platform> P;
1840 ErrorReporter ReportError = logErrorsToStdErr;
1841
1842 std::vector<ResourceManager *> ResourceManagers;
1843
1844 std::vector<JITDylibSP> JDs;
1845 JITDylib &BootstrapJD;
1847 WaitingOnGraph::OpRecorder *GOpRecorder = nullptr;
1848
1849 // FIXME: Remove this (and runOutstandingMUs) once the linking layer works
1850 // with callbacks from asynchronous queries.
1851 mutable std::recursive_mutex OutstandingMUsMutex;
1852 std::vector<std::pair<std::unique_ptr<MaterializationUnit>,
1853 std::unique_ptr<MaterializationResponsibility>>>
1854 OutstandingMUs;
1855
1856 mutable std::mutex JITDispatchHandlersMutex;
1857 DenseMap<ExecutorAddr, std::shared_ptr<JITDispatchHandlerFunction>>
1858 JITDispatchHandlers;
1859};
1860
1862 return JD->getExecutionSession().lookup({JD.get()}, Name);
1863}
1864
1865template <typename Func> Error ResourceTracker::withResourceKeyDo(Func &&F) {
1867 if (isDefunct())
1869 F(getKeyUnsafe());
1870 return Error::success();
1871 });
1872}
1873
1874inline ExecutionSession &
1876 return JD.getExecutionSession();
1877}
1878
1879template <typename GeneratorT>
1880GeneratorT &JITDylib::addGenerator(std::unique_ptr<GeneratorT> DefGenerator) {
1881 auto &G = *DefGenerator;
1882 ES.runSessionLocked([&] {
1883 assert(State == Open && "Cannot add generator to closed JITDylib");
1884 DefGenerators.push_back(std::move(DefGenerator));
1885 });
1886 return G;
1887}
1888
1889template <typename Func>
1891 -> decltype(F(std::declval<const JITDylibSearchOrder &>())) {
1892 assert(State == Open && "Cannot use link order of closed JITDylib");
1893 return ES.runSessionLocked([&]() { return F(LinkOrder); });
1894}
1895
1896template <typename MaterializationUnitType>
1897Error JITDylib::define(std::unique_ptr<MaterializationUnitType> &&MU,
1898 ResourceTrackerSP RT) {
1899 assert(MU && "Can not define with a null MU");
1900
1901 if (MU->getSymbols().empty()) {
1902 // Empty MUs are allowable but pathological, so issue a warning.
1903 DEBUG_WITH_TYPE("orc", {
1904 dbgs() << "Warning: Discarding empty MU " << MU->getName() << " for "
1905 << getName() << "\n";
1906 });
1907 return Error::success();
1908 } else
1909 DEBUG_WITH_TYPE("orc", {
1910 dbgs() << "Defining MU " << MU->getName() << " for " << getName()
1911 << " (tracker: ";
1912 if (RT == getDefaultResourceTracker())
1913 dbgs() << "default)";
1914 else if (RT)
1915 dbgs() << RT.get() << ")\n";
1916 else
1917 dbgs() << "0x0, default will be used)\n";
1918 });
1919
1920 return ES.runSessionLocked([&, this]() -> Error {
1921 if (State != Open)
1922 return make_error<JITDylibDefunct>(this);
1923
1924 if (auto Err = defineImpl(*MU))
1925 return Err;
1926
1927 if (!RT)
1929
1930 if (auto *P = ES.getPlatform()) {
1931 if (auto Err = P->notifyAdding(*RT, *MU))
1932 return Err;
1933 }
1934
1935 installMaterializationUnit(std::move(MU), *RT);
1936 return Error::success();
1937 });
1938}
1939
1940template <typename MaterializationUnitType>
1941Error JITDylib::define(std::unique_ptr<MaterializationUnitType> &MU,
1942 ResourceTrackerSP RT) {
1943 assert(MU && "Can not define with a null MU");
1944
1945 if (MU->getSymbols().empty()) {
1946 // Empty MUs are allowable but pathological, so issue a warning.
1947 DEBUG_WITH_TYPE("orc", {
1948 dbgs() << "Warning: Discarding empty MU " << MU->getName() << getName()
1949 << "\n";
1950 });
1951 return Error::success();
1952 } else
1953 DEBUG_WITH_TYPE("orc", {
1954 dbgs() << "Defining MU " << MU->getName() << " for " << getName()
1955 << " (tracker: ";
1956 if (RT == getDefaultResourceTracker())
1957 dbgs() << "default)";
1958 else if (RT)
1959 dbgs() << RT.get() << ")\n";
1960 else
1961 dbgs() << "0x0, default will be used)\n";
1962 });
1963
1964 return ES.runSessionLocked([&, this]() -> Error {
1965 assert(State == Open && "JD is defunct");
1966
1967 if (auto Err = defineImpl(*MU))
1968 return Err;
1969
1970 if (!RT)
1972
1973 if (auto *P = ES.getPlatform()) {
1974 if (auto Err = P->notifyAdding(*RT, *MU))
1975 return Err;
1976 }
1977
1978 installMaterializationUnit(std::move(MU), *RT);
1979 return Error::success();
1980 });
1981}
1982
1983/// ReexportsGenerator can be used with JITDylib::addGenerator to automatically
1984/// re-export a subset of the source JITDylib's symbols in the target.
1986public:
1987 using SymbolPredicate = std::function<bool(SymbolStringPtr)>;
1988
1989 /// Create a reexports generator. If an Allow predicate is passed, only
1990 /// symbols for which the predicate returns true will be reexported. If no
1991 /// Allow predicate is passed, all symbols will be exported.
1992 ReexportsGenerator(JITDylib &SourceJD,
1993 JITDylibLookupFlags SourceJDLookupFlags,
1995
1997 JITDylibLookupFlags JDLookupFlags,
1998 const SymbolLookupSet &LookupSet) override;
1999
2000private:
2001 JITDylib &SourceJD;
2002 JITDylibLookupFlags SourceJDLookupFlags;
2003 SymbolPredicate Allow;
2004};
2005
2006// --------------- IMPLEMENTATION --------------
2007// Implementations for inline functions/methods.
2008// ---------------------------------------------
2009
2011 getExecutionSession().OL_destroyMaterializationResponsibility(*this);
2012}
2013
2015 return getExecutionSession().OL_getRequestedSymbols(*this);
2016}
2017
2019 const SymbolMap &Symbols) {
2020 return getExecutionSession().OL_notifyResolved(*this, Symbols);
2021}
2022
2024 ArrayRef<SymbolDependenceGroup> EmittedDeps) {
2025 return getExecutionSession().OL_notifyEmitted(*this, EmittedDeps);
2026}
2027
2029 SymbolFlagsMap SymbolFlags) {
2030 return getExecutionSession().OL_defineMaterializing(*this,
2031 std::move(SymbolFlags));
2032}
2033
2035 getExecutionSession().OL_notifyFailed(*this);
2036}
2037
2039 std::unique_ptr<MaterializationUnit> MU) {
2040 return getExecutionSession().OL_replace(*this, std::move(MU));
2041}
2042
2045 return getExecutionSession().OL_delegate(*this, Symbols);
2046}
2047
2048} // End namespace orc
2049} // End namespace llvm
2050
2051#endif // LLVM_EXECUTIONENGINE_ORC_CORE_H
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Function Alias Analysis false
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:213
This file defines the DenseSet and SmallDenseSet classes.
This file provides a collection of function (or more generally, callable) type erasure utilities supp...
This file defines the RefCountedBase, ThreadSafeRefCountedBase, and IntrusiveRefCntPtr classes.
#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
#define P(N)
static StringRef getName(Value *V)
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition Debug.h:72
Value * RHS
Value * LHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool empty() const
Definition DenseMap.h:109
Base class for user error types.
Definition Error.h:354
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
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
Flags for symbols in the JIT.
Definition JITSymbol.h:75
Inheritance utility for extensible RTTI.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:133
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
size_type size() const
Definition DenseSet.h:87
A symbol query that returns results via a callback when results are ready.
Definition Core.h:802
LLVM_ABI AsynchronousSymbolQuery(const SymbolLookupSet &Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete)
Create a query for the given symbols.
Definition Core.cpp:212
bool isComplete() const
Returns true if all symbols covered by this query have been resolved.
Definition Core.h:823
friend class InProgressFullLookupState
Definition Core.h:804
LLVM_ABI void notifySymbolMetRequiredState(const SymbolStringPtr &Name, ExecutorSymbolDef Sym)
Notify the query that a requested symbol has reached the required state.
Definition Core.cpp:226
friend class JITSymbolResolverAdapter
Definition Core.h:806
friend class MaterializationResponsibility
Definition Core.h:807
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
Definition Core.h:876
virtual Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &LookupSet)=0
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
friend class ExecutionSession
Definition Core.h:877
An ExecutionSession represents a running JIT program.
Definition Core.h:1355
LLVM_ABI void runJITDispatchHandler(SendResultFunction SendResult, ExecutorAddr HandlerFnTagAddr, shared::WrapperFunctionBuffer ArgBytes)
Run a registered jit-side wrapper function.
Definition Core.cpp:1924
LLVM_ABI Error endSession()
End the session.
Definition Core.cpp:1598
ExecutorProcessControl & getExecutorProcessControl()
Get the ExecutorProcessControl object associated with this ExecutionSession.
Definition Core.h:1395
shared::WrapperFunctionBuffer callWrapper(ExecutorAddr WrapperFnAddr, ArrayRef< char > ArgBuffer)
Run a wrapper function in the executor.
Definition Core.h:1648
void reportError(Error Err)
Report a error for this execution session.
Definition Core.h:1506
void callWrapperAsync(ExecutorAddr WrapperFnAddr, ExecutorProcessControl::IncomingWFRHandler OnComplete, ArrayRef< char > ArgBuffer)
Run a wrapper function in the executor.
Definition Core.h:1618
friend class JITDylib
Definition Core.h:1358
friend class InProgressLookupFlagsState
Definition Core.h:1356
const StringMap< ExecutorAddr > & getBootstrapSymbolsMap() const
Returns the bootstrap symbol map.
Definition Core.h:1598
void setPlatform(std::unique_ptr< Platform > P)
Set the Platform for this ExecutionSession.
Definition Core.h:1428
const Triple & getTargetTriple() const
Return the triple for the executor.
Definition Core.h:1398
Platform * getPlatform()
Get the Platform for this session.
Definition Core.h:1432
Error callSPSWrapper(ExecutorAddr WrapperFnAddr, WrapperCallArgTs &&...WrapperCallArgs)
Run a wrapper function using SPS to serialize the arguments and deserialize the results.
Definition Core.h:1668
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:1764
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition Core.h:1409
LLVM_ABI JITDylib * getJITDylibByName(StringRef Name)
Return a pointer to the "name" JITDylib.
Definition Core.cpp:1643
static JITDispatchHandlerFunction wrapAsyncWithSPS(ClassT *Instance, void(ClassT::*Method)(MethodArgTs...))
Wrap a class method that takes concrete argument types (and a sender for a concrete return type) to p...
Definition Core.h:1700
friend class LookupState
Definition Core.h:1359
void callWrapperAsync(RunPolicyT &&Runner, ExecutorAddr WrapperFnAddr, FnT &&OnComplete, ArrayRef< char > ArgBuffer)
Run a wrapper function in the executor using the given Runner to dispatch OnComplete when the result ...
Definition Core.h:1627
LLVM_ABI JITDylib & createBareJITDylib(std::string Name)
Add a new bare JITDylib to this ExecutionSession.
Definition Core.cpp:1652
static JITDispatchHandlerFunction wrapAsyncWithSPS(HandlerT &&H)
Wrap a handler that takes concrete argument types (and a sender for a concrete return type) to produc...
Definition Core.h:1682
void callSPSWrapperAsync(ExecutorAddr WrapperFnAddr, SendResultT &&SendResult, const ArgTs &...Args)
Run a wrapper function using SPS to serialize the arguments and deserialize the results.
Definition Core.h:1656
JITDylib & getBootstrapJITDylib()
Returns a reference to the bootstrap JITDylib.
Definition Core.h:1416
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
Definition Core.h:1404
Error getBootstrapMapValue(StringRef Key, std::optional< T > &Val) const
Look up and SPS-deserialize a bootstrap map value.
Definition Core.h:1593
friend class InProgressFullLookupState
Definition Core.h:1357
Error getBootstrapSymbols(ArrayRef< std::pair< ExecutorAddr &, StringRef > > Pairs) const
For each (ExecutorAddr&, StringRef) pair, looks up the string in the bootstrap symbols map and writes...
Definition Core.h:1605
const StringMap< std::vector< char > > & getBootstrapMap() const
Returns the bootstrap map.
Definition Core.h:1587
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:1790
LLVM_ABI Error registerJITDispatchHandlers(JITDylib &JD, JITDispatchHandlerAssociationMap WFs)
For each tag symbol name, associate the corresponding AsyncHandlerWrapperFunction with the address of...
Definition Core.cpp:1885
friend class MaterializationResponsibility
Definition Core.h:1360
LLVM_ABI void registerResourceManager(ResourceManager &RM)
Register the given ResourceManager with this ExecutionSession.
Definition Core.cpp:1626
LLVM_ABI ~ExecutionSession()
Destroy an ExecutionSession.
Definition Core.cpp:1592
void setWaitingOnGraphOpRecorder(WaitingOnGraph::OpRecorder &R)
Set a WaitingOnGraph::Recorder to capture WaitingOnGraph operations.
Definition Core.h:1422
LLVM_ABI void deregisterResourceManager(ResourceManager &RM)
Deregister the given ResourceManager with this ExecutionSession.
Definition Core.cpp:1630
LLVM_ABI ExecutionSession(std::unique_ptr< ExecutorProcessControl > EPC)
Construct an ExecutionSession with the given ExecutorProcessControl object.
Definition Core.cpp:1579
decltype(auto) runSessionLocked(Func &&F)
Run the given lambda with the session mutex locked.
Definition Core.h:1435
unique_function< void( SendResultFunction SendResult, const char *ArgData, size_t ArgSize)> JITDispatchHandlerFunction
An asynchronous wrapper-function callable from the executor via jit-dispatch.
Definition Core.h:1372
LLVM_ABI void dump(raw_ostream &OS)
Dump the state of all the JITDylibs in this session.
Definition Core.cpp:1945
unique_function< void(shared::WrapperFunctionBuffer)> SendResultFunction
Send a result to the remote.
Definition Core.h:1368
friend class ResourceTracker
Definition Core.h:1361
ExecutionSession & setErrorReporter(ErrorReporter ReportError)
Set the error reporter function.
Definition Core.h:1498
LLVM_ABI Error removeJITDylibs(std::vector< JITDylibSP > JDsToRemove)
Removes the given JITDylibs from the ExecutionSession.
Definition Core.cpp:1669
size_t getPageSize() const
Definition Core.h:1401
LLVM_ABI Expected< JITDylib & > createJITDylib(std::string Name)
Add a new JITDylib to this ExecutionSession.
Definition Core.cpp:1661
void dispatchTask(std::unique_ptr< Task > T)
Materialize the given unit.
Definition Core.h:1580
unique_function< void(Error)> ErrorReporter
For reporting errors.
Definition Core.h:1365
Error removeJITDylib(JITDylib &JD)
Calls removeJTIDylibs on the gives JITDylib.
Definition Core.h:1493
void callWrapperAsync(ExecutorAddr WrapperFnAddr, FnT &&OnComplete, ArrayRef< char > ArgBuffer)
Run a wrapper function in the executor.
Definition Core.h:1636
DenseMap< SymbolStringPtr, JITDispatchHandlerFunction > JITDispatchHandlerAssociationMap
A map associating tag names with asynchronous wrapper function implementations in the JIT.
Definition Core.h:1378
Represents an address in the executor process.
A handler or incoming WrapperFunctionBuffers – either return values from callWrapper* calls,...
ExecutorProcessControl supports interaction with a JIT target process.
Represents a defining location for a JIT symbol.
FailedToMaterialize(std::shared_ptr< SymbolStringPool > SSP, std::shared_ptr< SymbolDependenceMap > Symbols)
Definition Core.cpp:93
const SymbolDependenceMap & getSymbols() const
Definition Core.h:467
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
JITDylibDefunct(JITDylibSP JD)
Definition Core.h:448
Represents a JIT'd dynamic library.
Definition Core.h:919
LLVM_ABI ~JITDylib()
Definition Core.cpp:663
LLVM_ABI Error remove(const SymbolNameSet &Names)
Tries to remove the given symbols.
Definition Core.cpp:1065
LLVM_ABI Error clear()
Calls remove on all trackers currently associated with this JITDylib.
Definition Core.cpp:667
JITDylib & operator=(JITDylib &&)=delete
LLVM_ABI void dump(raw_ostream &OS)
Dump current JITDylib state to OS.
Definition Core.cpp:1126
friend class AsynchronousSymbolQuery
Definition Core.h:920
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:1041
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:1897
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
Definition Core.h:938
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:1025
LLVM_ABI ResourceTrackerSP createResourceTracker()
Create a resource tracker for this JITDylib.
Definition Core.cpp:691
auto withLinkOrderDo(Func &&F) -> decltype(F(std::declval< const JITDylibSearchOrder & >()))
Do something with the link order (run under the session lock).
Definition Core.h:1890
friend class MaterializationResponsibility
Definition Core.h:923
friend class Platform
Definition Core.h:922
LLVM_ABI void removeFromLinkOrder(JITDylib &JD)
Remove the given JITDylib from the link order for this JITDylib if it is present.
Definition Core.cpp:1053
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:1010
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:1760
friend class ExecutionSession
Definition Core.h:921
LLVM_ABI ResourceTrackerSP getDefaultResourceTracker()
Get the default resource tracker for this JITDylib.
Definition Core.cpp:682
GeneratorT & addGenerator(std::unique_ptr< GeneratorT > DefGenerator)
Adds a definition generator to this JITDylib and returns a referenece to it.
Definition Core.h:1880
JITDylib(const JITDylib &)=delete
JITDylib & operator=(const JITDylib &)=delete
JITDylib(JITDylib &&)=delete
LLVM_ABI void removeGenerator(DefinitionGenerator &G)
Remove a definition generator from this JITDylib.
Definition Core.cpp:699
LLVM_ABI Expected< std::vector< JITDylibSP > > getDFSLinkOrder()
Return this JITDylib and its transitive dependencies in DFS order based on linkage relationships.
Definition Core.cpp:1756
Wraps state for a lookup-in-progress.
Definition Core.h:851
LLVM_ABI void continueLookup(Error Err)
Continue the lookup.
Definition Core.cpp:643
LLVM_ABI LookupState & operator=(LookupState &&)
friend class ExecutionSession
Definition Core.h:853
friend class OrcV2CAPIHelper
Definition Core.h:852
LLVM_ABI LookupState(LookupState &&)
LookupTask(LookupState LS)
Definition Core.h:1346
static char ID
Definition Core.h:1344
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition Core.h:593
MaterializationResponsibility & operator=(MaterializationResponsibility &&)=delete
ExecutionSession & getExecutionSession() const
Returns the ExecutionSession for this instance.
Definition Core.h:1875
Error notifyResolved(const SymbolMap &Symbols)
Notifies the target JITDylib that the given symbols have been resolved.
Definition Core.h:2018
~MaterializationResponsibility()
Destruct a MaterializationResponsibility instance.
Definition Core.h:2010
Error replace(std::unique_ptr< MaterializationUnit > MU)
Transfers responsibility to the given MaterializationUnit for all symbols defined by that Materializa...
Definition Core.h:2038
Error withResourceKeyDo(Func &&F) const
Runs the given callback under the session lock, passing in the associated ResourceKey.
Definition Core.h:612
Error defineMaterializing(SymbolFlagsMap SymbolFlags)
Attempt to claim responsibility for new definitions.
Definition Core.h:2028
SymbolNameSet getRequestedSymbols() const
Returns the names of any symbols covered by this MaterializationResponsibility object that have queri...
Definition Core.h:2014
Expected< std::unique_ptr< MaterializationResponsibility > > delegate(const SymbolNameSet &Symbols)
Delegates responsibility for the given symbols to the returned materialization responsibility.
Definition Core.h:2044
const ResourceTrackerSP & getResourceTracker() const
Return the ResourceTracker associated with this instance.
Definition Core.h:608
const SymbolStringPtr & getInitializerSymbol() const
Returns the initialization pseudo-symbol, if any.
Definition Core.h:632
MaterializationResponsibility(MaterializationResponsibility &&)=delete
Error notifyEmitted(ArrayRef< SymbolDependenceGroup > DepGroups)
Notifies the target JITDylib (and any pending queries on that JITDylib) that all symbols covered by t...
Definition Core.h:2023
void failMaterialization()
Notify all not-yet-emitted covered by this MaterializationResponsibility instance that an error has o...
Definition Core.h:2034
JITDylib & getTargetJITDylib() const
Returns the target JITDylib that these symbols are being materialized into.
Definition Core.h:618
const SymbolFlagsMap & getSymbols() const
Returns the symbol flags map for this responsibility instance.
Definition Core.h:627
A materialization task.
Definition Core.h:1323
MaterializationTask(std::unique_ptr< MaterializationUnit > MU, std::unique_ptr< MaterializationResponsibility > MR)
Definition Core.h:1327
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
const SymbolNameVector & getSymbols() const
Definition Core.h:548
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition Core.h:546
MissingSymbolDefinitions(std::shared_ptr< SymbolStringPool > SSP, std::string ModuleName, SymbolNameVector Symbols)
Definition Core.h:540
const std::string & getModuleName() const
Definition Core.h:547
Platforms set up standard symbols and mediate interactions between dynamic initializers (e....
Definition Core.h:1282
virtual Error teardownJITDylib(JITDylib &JD)=0
This method will be called outside the session lock each time a JITDylib is removed to allow the Plat...
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:1515
virtual Error notifyRemoving(ResourceTracker &RT)=0
This method will be called under the ExecutionSession lock when a ResourceTracker is removed.
static Expected< DenseMap< JITDylib *, SymbolMap > > lookupInitSymbols(ExecutionSession &ES, const DenseMap< JITDylib *, SymbolLookupSet > &InitSyms)
A utility function for looking up initializer symbols.
Definition Core.cpp:1466
virtual Error notifyAdding(ResourceTracker &RT, const MaterializationUnit &MU)=0
This method will be called under the ExecutionSession lock each time a MaterializationUnit is added t...
virtual Error setupJITDylib(JITDylib &JD)=0
This method will be called outside the session lock each time a JITDylib is created (unless it is cre...
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:311
std::function< bool(SymbolStringPtr)> SymbolPredicate
Definition Core.h:1987
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:608
ReexportsGenerator(JITDylib &SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolPredicate Allow=SymbolPredicate())
Create a reexports generator.
Definition Core.cpp:602
Listens for ResourceTracker operations.
Definition Core.h:130
virtual Error handleRemoveResources(JITDylib &JD, ResourceKey K)=0
This function will be called outside the session lock.
virtual void handleTransferResources(JITDylib &JD, ResourceKey DstK, ResourceKey SrcK)=0
This function will be called inside the session lock.
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:82
JITDylib & getJITDylib() const
Return the JITDylib targeted by this tracker.
Definition Core.h:97
friend class JITDylib
Definition Core.h:85
ResourceTracker & operator=(const ResourceTracker &)=delete
ResourceKey getKeyUnsafe() const
Returns the key associated with this tracker.
Definition Core.h:119
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
ResourceTracker & operator=(ResourceTracker &&)=delete
LLVM_ABI ~ResourceTracker()
Definition Core.cpp:52
ResourceTracker(const ResourceTracker &)=delete
friend class MaterializationResponsibility
Definition Core.h:86
bool isDefunct() const
Return true if this tracker has become defunct.
Definition Core.h:114
ResourceTracker(ResourceTracker &&)=delete
Error withResourceKeyDo(Func &&F)
Runs the given callback under the session lock, passing in the associated ResourceKey.
Definition Core.h:1865
friend class ExecutionSession
Definition Core.h:84
LLVM_ABI Error remove()
Remove all resources associated with this key.
Definition Core.cpp:57
Expected< ExecutorSymbolDef > lookup() const
Definition Core.h:1861
SymbolInstance(JITDylibSP JD, SymbolStringPtr Name)
Definition Core.h:65
LLVM_ABI void lookupAsync(LookupAsyncOnCompleteFn OnComplete) const
Definition Core.cpp:191
unique_function< void(Expected< ExecutorSymbolDef >)> LookupAsyncOnCompleteFn
Definition Core.h:62
const JITDylib & getJITDylib() const
Definition Core.h:68
const SymbolStringPtr & getName() const
Definition Core.h:69
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition Core.h:199
std::pair< SymbolStringPtr, SymbolLookupFlags > value_type
Definition Core.h:201
const_iterator begin() const
Definition Core.h:283
void removeDuplicates()
Remove any duplicate elements.
Definition Core.h:383
UnderlyingVector::const_iterator const_iterator
Definition Core.h:204
void sortByAddress()
Sort the lookup set by pointer value.
Definition Core.h:371
SymbolLookupSet(std::initializer_list< SymbolStringPtr > Names, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Construct a SymbolLookupSet from an initializer list of SymbolStringPtrs.
Definition Core.h:220
UnderlyingVector::size_type size() const
Definition Core.h:280
SymbolLookupSet & add(SymbolStringPtr Name, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Add an element to the set.
Definition Core.h:265
static SymbolLookupSet fromMapKeys(const DenseMap< SymbolStringPtr, ValT > &M, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Construct a SymbolLookupSet from DenseMap keys.
Definition Core.h:253
SymbolLookupSet & append(SymbolLookupSet Other)
Quickly append one lookup set to another.
Definition Core.h:272
SymbolLookupSet(ArrayRef< SymbolStringPtr > Names, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Construct a SymbolLookupSet from a vector of symbols with the given Flags used for each value.
Definition Core.h:242
SymbolLookupSet(std::initializer_list< value_type > Elems)
Definition Core.h:208
void sortByName()
Sort the lookup set lexicographically.
Definition Core.h:375
void remove(iterator I)
Removes the element pointed to by the given iterator.
Definition Core.h:294
auto forEachWithRemoval(BodyFn &&Body) -> std::enable_if_t< std::is_same< decltype(Body(std::declval< const SymbolStringPtr & >(), std::declval< SymbolLookupFlags >())), bool >::value >
Loop over the elements of this SymbolLookupSet, applying the Body function to each one.
Definition Core.h:316
bool containsDuplicates()
Returns true if this set contains any duplicates.
Definition Core.h:392
UnderlyingVector::iterator iterator
Definition Core.h:203
bool empty() const
Definition Core.h:279
void remove_if(PredFn &&Pred)
Removes all elements matching the given predicate, which must be callable as bool(const SymbolStringP...
Definition Core.h:298
SymbolLookupSet(const SymbolNameSet &Names, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Construct a SymbolLookupSet from a SymbolNameSet with the given Flags used for each value.
Definition Core.h:230
SymbolLookupSet(SymbolStringPtr Name, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Definition Core.h:213
SymbolNameVector getSymbolNames() const
Construct a SymbolNameVector from this instance by dropping the Flags values.
Definition Core.h:360
const_iterator end() const
Definition Core.h:284
auto forEachWithRemoval(BodyFn &&Body) -> std::enable_if_t< std::is_same< decltype(Body(std::declval< const SymbolStringPtr & >(), std::declval< SymbolLookupFlags >())), Expected< bool > >::value, Error >
Loop over the elements of this SymbolLookupSet, applying the Body function to each one.
Definition Core.h:338
void remove(UnderlyingVector::size_type I)
Removes the Ith element of the vector, replacing it with the last element.
Definition Core.h:287
std::vector< value_type > UnderlyingVector
Definition Core.h:202
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
const SymbolNameSet & getSymbols() const
Definition Core.h:524
SymbolsCouldNotBeRemoved(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
Definition Core.cpp:159
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition Core.h:523
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
const SymbolNameVector & getSymbols() const
Definition Core.h:506
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:151
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition Core.h:505
UnexpectedSymbolDefinitions(std::shared_ptr< SymbolStringPool > SSP, std::string ModuleName, SymbolNameVector Symbols)
Definition Core.h:564
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition Core.h:570
const std::string & getModuleName() const
Definition Core.h:571
const SymbolNameVector & getSymbols() const
Definition Core.h:572
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
WaitingOnGraph class template.
C++ wrapper function buffer: Same as CWrapperFunctionBuffer but auto-releases memory.
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.
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:182
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:177
IntrusiveRefCntPtr< JITDylib > JITDylibSP
Definition Core.h:57
IntrusiveRefCntPtr< ResourceTracker > ResourceTrackerSP
Definition Core.h:56
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
Definition Core.h:767
std::function< void(const SymbolDependenceMap &)> RegisterDependenciesFunction
Callback to register the dependencies for a given query.
Definition Core.h:423
uintptr_t ResourceKey
Definition Core.h:79
SymbolLookupFlags
Lookup flags that apply to each symbol in a lookup.
Definition Core.h:161
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:776
LLVM_ABI Expected< SymbolAliasMap > buildSimpleReexportsAliasMap(JITDylib &SourceJD, const SymbolNameSet &Symbols)
Build a SymbolAliasMap for the common case where you want to re-export symbols from another JITDylib ...
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
Definition Core.h:151
detail::WaitingOnGraph< JITDylib *, NonOwningSymbolStringPtr > WaitingOnGraph
Definition Core.h:53
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
static std::unique_ptr< UnwindInfoManager > Instance
LookupKind
Describes the kind of lookup being performed.
Definition Core.h:173
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:789
@ Materializing
Added to the symbol table, never queried.
Definition Core.h:792
@ NeverSearched
No symbol should be in this state.
Definition Core.h:791
@ Ready
Emitted to memory, but waiting on transitive dependencies.
Definition Core.h:795
@ Emitted
Assigned address, still materializing.
Definition Core.h:794
@ Resolved
Queried, materialization begun.
Definition Core.h:793
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
Definition Core.h:417
unique_function< void(Expected< SymbolMap >)> SymbolsResolvedCallback
Callback to notify client that symbols have been resolved.
Definition Core.h:420
DenseMap< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition Error.cpp:61
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2134
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:207
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
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.
@ Other
Any other memory.
Definition ModRef.h:68
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
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1439
JITSymbolFlags AliasFlags
Definition Core.h:413
SymbolAliasMapEntry(SymbolStringPtr Aliasee, JITSymbolFlags AliasFlags)
Definition Core.h:409
SymbolStringPtr Aliasee
Definition Core.h:412
A set of symbols and the their dependencies.
Definition Core.h:581
SymbolDependenceMap Dependencies
Definition Core.h:583