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