LLVM 18.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 notify clients when symbols can not be found during a lookup.
440class SymbolsNotFound : public ErrorInfo<SymbolsNotFound> {
441public:
442 static char ID;
443
444 SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP, SymbolNameSet Symbols);
445 SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
446 SymbolNameVector Symbols);
447 std::error_code convertToErrorCode() const override;
448 void log(raw_ostream &OS) const override;
449 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
450 const SymbolNameVector &getSymbols() const { return Symbols; }
451
452private:
453 std::shared_ptr<SymbolStringPool> SSP;
454 SymbolNameVector Symbols;
455};
456
457/// Used to notify clients that a set of symbols could not be removed.
458class SymbolsCouldNotBeRemoved : public ErrorInfo<SymbolsCouldNotBeRemoved> {
459public:
460 static char ID;
461
462 SymbolsCouldNotBeRemoved(std::shared_ptr<SymbolStringPool> SSP,
463 SymbolNameSet Symbols);
464 std::error_code convertToErrorCode() const override;
465 void log(raw_ostream &OS) const override;
466 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
467 const SymbolNameSet &getSymbols() const { return Symbols; }
468
469private:
470 std::shared_ptr<SymbolStringPool> SSP;
471 SymbolNameSet Symbols;
472};
473
474/// Errors of this type should be returned if a module fails to include
475/// definitions that are claimed by the module's associated
476/// MaterializationResponsibility. If this error is returned it is indicative of
477/// a broken transformation / compiler / object cache.
478class MissingSymbolDefinitions : public ErrorInfo<MissingSymbolDefinitions> {
479public:
480 static char ID;
481
482 MissingSymbolDefinitions(std::shared_ptr<SymbolStringPool> SSP,
483 std::string ModuleName, SymbolNameVector Symbols)
484 : SSP(std::move(SSP)), ModuleName(std::move(ModuleName)),
485 Symbols(std::move(Symbols)) {}
486 std::error_code convertToErrorCode() const override;
487 void log(raw_ostream &OS) const override;
488 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
489 const std::string &getModuleName() const { return ModuleName; }
490 const SymbolNameVector &getSymbols() const { return Symbols; }
491private:
492 std::shared_ptr<SymbolStringPool> SSP;
493 std::string ModuleName;
494 SymbolNameVector Symbols;
495};
496
497/// Errors of this type should be returned if a module contains definitions for
498/// symbols that are not claimed by the module's associated
499/// MaterializationResponsibility. If this error is returned it is indicative of
500/// a broken transformation / compiler / object cache.
501class UnexpectedSymbolDefinitions : public ErrorInfo<UnexpectedSymbolDefinitions> {
502public:
503 static char ID;
504
505 UnexpectedSymbolDefinitions(std::shared_ptr<SymbolStringPool> SSP,
506 std::string ModuleName, SymbolNameVector Symbols)
507 : SSP(std::move(SSP)), ModuleName(std::move(ModuleName)),
508 Symbols(std::move(Symbols)) {}
509 std::error_code convertToErrorCode() const override;
510 void log(raw_ostream &OS) const override;
511 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
512 const std::string &getModuleName() const { return ModuleName; }
513 const SymbolNameVector &getSymbols() const { return Symbols; }
514private:
515 std::shared_ptr<SymbolStringPool> SSP;
516 std::string ModuleName;
517 SymbolNameVector Symbols;
518};
519
520/// Tracks responsibility for materialization, and mediates interactions between
521/// MaterializationUnits and JDs.
522///
523/// An instance of this class is passed to MaterializationUnits when their
524/// materialize method is called. It allows MaterializationUnits to resolve and
525/// emit symbols, or abandon materialization by notifying any unmaterialized
526/// symbols of an error.
528 friend class ExecutionSession;
529 friend class JITDylib;
530
531public:
535
536 /// Destruct a MaterializationResponsibility instance. In debug mode
537 /// this asserts that all symbols being tracked have been either
538 /// emitted or notified of an error.
540
541 /// Runs the given callback under the session lock, passing in the associated
542 /// ResourceKey. This is the safe way to associate resources with trackers.
543 template <typename Func> Error withResourceKeyDo(Func &&F) const {
544 return RT->withResourceKeyDo(std::forward<Func>(F));
545 }
546
547 /// Returns the target JITDylib that these symbols are being materialized
548 /// into.
549 JITDylib &getTargetJITDylib() const { return JD; }
550
551 /// Returns the ExecutionSession for this instance.
553
554 /// Returns the symbol flags map for this responsibility instance.
555 /// Note: The returned flags may have transient flags (Lazy, Materializing)
556 /// set. These should be stripped with JITSymbolFlags::stripTransientFlags
557 /// before using.
558 const SymbolFlagsMap &getSymbols() const { return SymbolFlags; }
559
560 /// Returns the initialization pseudo-symbol, if any. This symbol will also
561 /// be present in the SymbolFlagsMap for this MaterializationResponsibility
562 /// object.
563 const SymbolStringPtr &getInitializerSymbol() const { return InitSymbol; }
564
565 /// Returns the names of any symbols covered by this
566 /// MaterializationResponsibility object that have queries pending. This
567 /// information can be used to return responsibility for unrequested symbols
568 /// back to the JITDylib via the delegate method.
570
571 /// Notifies the target JITDylib that the given symbols have been resolved.
572 /// This will update the given symbols' addresses in the JITDylib, and notify
573 /// any pending queries on the given symbols of their resolution. The given
574 /// symbols must be ones covered by this MaterializationResponsibility
575 /// instance. Individual calls to this method may resolve a subset of the
576 /// symbols, but all symbols must have been resolved prior to calling emit.
577 ///
578 /// This method will return an error if any symbols being resolved have been
579 /// moved to the error state due to the failure of a dependency. If this
580 /// method returns an error then clients should log it and call
581 /// failMaterialize. If no dependencies have been registered for the
582 /// symbols covered by this MaterializationResponsibility then this method
583 /// is guaranteed to return Error::success() and can be wrapped with cantFail.
584 Error notifyResolved(const SymbolMap &Symbols);
585
586 /// Notifies the target JITDylib (and any pending queries on that JITDylib)
587 /// that all symbols covered by this MaterializationResponsibility instance
588 /// have been emitted.
589 ///
590 /// This method will return an error if any symbols being resolved have been
591 /// moved to the error state due to the failure of a dependency. If this
592 /// method returns an error then clients should log it and call
593 /// failMaterialize. If no dependencies have been registered for the
594 /// symbols covered by this MaterializationResponsibility then this method
595 /// is guaranteed to return Error::success() and can be wrapped with cantFail.
597
598 /// Attempt to claim responsibility for new definitions. This method can be
599 /// used to claim responsibility for symbols that are added to a
600 /// materialization unit during the compilation process (e.g. literal pool
601 /// symbols). Symbol linkage rules are the same as for symbols that are
602 /// defined up front: duplicate strong definitions will result in errors.
603 /// Duplicate weak definitions will be discarded (in which case they will
604 /// not be added to this responsibility instance).
605 ///
606 /// This method can be used by materialization units that want to add
607 /// additional symbols at materialization time (e.g. stubs, compile
608 /// callbacks, metadata).
610
611 /// Notify all not-yet-emitted covered by this MaterializationResponsibility
612 /// instance that an error has occurred.
613 /// This will remove all symbols covered by this MaterializationResponsibility
614 /// from the target JITDylib, and send an error to any queries waiting on
615 /// these symbols.
616 void failMaterialization();
617
618 /// Transfers responsibility to the given MaterializationUnit for all
619 /// symbols defined by that MaterializationUnit. This allows
620 /// materializers to break up work based on run-time information (e.g.
621 /// by introspecting which symbols have actually been looked up and
622 /// materializing only those).
623 Error replace(std::unique_ptr<MaterializationUnit> MU);
624
625 /// Delegates responsibility for the given symbols to the returned
626 /// materialization responsibility. Useful for breaking up work between
627 /// threads, or different kinds of materialization processes.
629 delegate(const SymbolNameSet &Symbols);
630
632 const SymbolDependenceMap &Dependencies);
633
634 /// Add dependencies that apply to all symbols covered by this instance.
635 void addDependenciesForAll(const SymbolDependenceMap &Dependencies);
636
637private:
638 /// Create a MaterializationResponsibility for the given JITDylib and
639 /// initial symbols.
641 SymbolFlagsMap SymbolFlags,
642 SymbolStringPtr InitSymbol)
643 : JD(RT->getJITDylib()), RT(std::move(RT)),
644 SymbolFlags(std::move(SymbolFlags)), InitSymbol(std::move(InitSymbol)) {
645 assert(!this->SymbolFlags.empty() && "Materializing nothing?");
646 }
647
648 JITDylib &JD;
650 SymbolFlagsMap SymbolFlags;
651 SymbolStringPtr InitSymbol;
652};
653
654/// A MaterializationUnit represents a set of symbol definitions that can
655/// be materialized as a group, or individually discarded (when
656/// overriding definitions are encountered).
657///
658/// MaterializationUnits are used when providing lazy definitions of symbols to
659/// JITDylibs. The JITDylib will call materialize when the address of a symbol
660/// is requested via the lookup method. The JITDylib will call discard if a
661/// stronger definition is added or already present.
663 friend class ExecutionSession;
664 friend class JITDylib;
665
666public:
667 static char ID;
668
669 struct Interface {
670 Interface() = default;
672 : SymbolFlags(std::move(InitalSymbolFlags)),
674 assert((!this->InitSymbol || this->SymbolFlags.count(this->InitSymbol)) &&
675 "If set, InitSymbol should appear in InitialSymbolFlags map");
676 }
677
680 };
681
685 virtual ~MaterializationUnit() = default;
686
687 /// Return the name of this materialization unit. Useful for debugging
688 /// output.
689 virtual StringRef getName() const = 0;
690
691 /// Return the set of symbols that this source provides.
692 const SymbolFlagsMap &getSymbols() const { return SymbolFlags; }
693
694 /// Returns the initialization symbol for this MaterializationUnit (if any).
696
697 /// Implementations of this method should materialize all symbols
698 /// in the materialzation unit, except for those that have been
699 /// previously discarded.
700 virtual void
701 materialize(std::unique_ptr<MaterializationResponsibility> R) = 0;
702
703 /// Called by JITDylibs to notify MaterializationUnits that the given symbol
704 /// has been overridden.
705 void doDiscard(const JITDylib &JD, const SymbolStringPtr &Name) {
707 if (InitSymbol == Name) {
708 DEBUG_WITH_TYPE("orc", {
709 dbgs() << "In " << getName() << ": discarding init symbol \""
710 << *Name << "\"\n";
711 });
712 InitSymbol = nullptr;
713 }
714 discard(JD, std::move(Name));
715 }
716
717protected:
720
721private:
722 virtual void anchor();
723
724 /// Implementations of this method should discard the given symbol
725 /// from the source (e.g. if the source is an LLVM IR Module and the
726 /// symbol is a function, delete the function body or mark it available
727 /// externally).
728 virtual void discard(const JITDylib &JD, const SymbolStringPtr &Name) = 0;
729};
730
731/// A MaterializationUnit implementation for pre-existing absolute symbols.
732///
733/// All symbols will be resolved and marked ready as soon as the unit is
734/// materialized.
736public:
738
739 StringRef getName() const override;
740
741private:
742 void materialize(std::unique_ptr<MaterializationResponsibility> R) override;
743 void discard(const JITDylib &JD, const SymbolStringPtr &Name) override;
744 static MaterializationUnit::Interface extractFlags(const SymbolMap &Symbols);
745
746 SymbolMap Symbols;
747};
748
749/// Create an AbsoluteSymbolsMaterializationUnit with the given symbols.
750/// Useful for inserting absolute symbols into a JITDylib. E.g.:
751/// \code{.cpp}
752/// JITDylib &JD = ...;
753/// SymbolStringPtr Foo = ...;
754/// ExecutorSymbolDef FooSym = ...;
755/// if (auto Err = JD.define(absoluteSymbols({{Foo, FooSym}})))
756/// return Err;
757/// \endcode
758///
759inline std::unique_ptr<AbsoluteSymbolsMaterializationUnit>
761 return std::make_unique<AbsoluteSymbolsMaterializationUnit>(
762 std::move(Symbols));
763}
764
765/// A materialization unit for symbol aliases. Allows existing symbols to be
766/// aliased with alternate flags.
768public:
769 /// SourceJD is allowed to be nullptr, in which case the source JITDylib is
770 /// taken to be whatever JITDylib these definitions are materialized in (and
771 /// MatchNonExported has no effect). This is useful for defining aliases
772 /// within a JITDylib.
773 ///
774 /// Note: Care must be taken that no sets of aliases form a cycle, as such
775 /// a cycle will result in a deadlock when any symbol in the cycle is
776 /// resolved.
778 JITDylibLookupFlags SourceJDLookupFlags,
779 SymbolAliasMap Aliases);
780
781 StringRef getName() const override;
782
783private:
784 void materialize(std::unique_ptr<MaterializationResponsibility> R) override;
785 void discard(const JITDylib &JD, const SymbolStringPtr &Name) override;
787 extractFlags(const SymbolAliasMap &Aliases);
788
789 JITDylib *SourceJD = nullptr;
790 JITDylibLookupFlags SourceJDLookupFlags;
791 SymbolAliasMap Aliases;
792};
793
794/// Create a ReExportsMaterializationUnit with the given aliases.
795/// Useful for defining symbol aliases.: E.g., given a JITDylib JD containing
796/// symbols "foo" and "bar", we can define aliases "baz" (for "foo") and "qux"
797/// (for "bar") with: \code{.cpp}
798/// SymbolStringPtr Baz = ...;
799/// SymbolStringPtr Qux = ...;
800/// if (auto Err = JD.define(symbolAliases({
801/// {Baz, { Foo, JITSymbolFlags::Exported }},
802/// {Qux, { Bar, JITSymbolFlags::Weak }}}))
803/// return Err;
804/// \endcode
805inline std::unique_ptr<ReExportsMaterializationUnit>
807 return std::make_unique<ReExportsMaterializationUnit>(
808 nullptr, JITDylibLookupFlags::MatchAllSymbols, std::move(Aliases));
809}
810
811/// Create a materialization unit for re-exporting symbols from another JITDylib
812/// with alternative names/flags.
813/// SourceJD will be searched using the given JITDylibLookupFlags.
814inline std::unique_ptr<ReExportsMaterializationUnit>
816 JITDylibLookupFlags SourceJDLookupFlags =
818 return std::make_unique<ReExportsMaterializationUnit>(
819 &SourceJD, SourceJDLookupFlags, std::move(Aliases));
820}
821
822/// Build a SymbolAliasMap for the common case where you want to re-export
823/// symbols from another JITDylib with the same linkage/flags.
826
827/// Represents the state that a symbol has reached during materialization.
828enum class SymbolState : uint8_t {
829 Invalid, /// No symbol should be in this state.
830 NeverSearched, /// Added to the symbol table, never queried.
831 Materializing, /// Queried, materialization begun.
832 Resolved, /// Assigned address, still materializing.
833 Emitted, /// Emitted to memory, but waiting on transitive dependencies.
834 Ready = 0x3f /// Ready and safe for clients to access.
835};
836
837/// A symbol query that returns results via a callback when results are
838/// ready.
839///
840/// makes a callback when all symbols are available.
842 friend class ExecutionSession;
844 friend class JITDylib;
847
848public:
849 /// Create a query for the given symbols. The NotifyComplete
850 /// callback will be called once all queried symbols reach the given
851 /// minimum state.
853 SymbolState RequiredState,
854 SymbolsResolvedCallback NotifyComplete);
855
856 /// Notify the query that a requested symbol has reached the required state.
859
860 /// Returns true if all symbols covered by this query have been
861 /// resolved.
862 bool isComplete() const { return OutstandingSymbolsCount == 0; }
863
864
865private:
866 void handleComplete(ExecutionSession &ES);
867
868 SymbolState getRequiredState() { return RequiredState; }
869
870 void addQueryDependence(JITDylib &JD, SymbolStringPtr Name);
871
872 void removeQueryDependence(JITDylib &JD, const SymbolStringPtr &Name);
873
874 void dropSymbol(const SymbolStringPtr &Name);
875
876 void handleFailed(Error Err);
877
878 void detach();
879
880 SymbolsResolvedCallback NotifyComplete;
881 SymbolDependenceMap QueryRegistrations;
882 SymbolMap ResolvedSymbols;
883 size_t OutstandingSymbolsCount;
884 SymbolState RequiredState;
885};
886
887/// Wraps state for a lookup-in-progress.
888/// DefinitionGenerators can optionally take ownership of a LookupState object
889/// to suspend a lookup-in-progress while they search for definitions.
891 friend class OrcV2CAPIHelper;
892 friend class ExecutionSession;
893
894public:
899
900 /// Continue the lookup. This can be called by DefinitionGenerators
901 /// to re-start a captured query-application operation.
902 void continueLookup(Error Err);
903
904private:
905 LookupState(std::unique_ptr<InProgressLookupState> IPLS);
906
907 // For C API.
908 void reset(InProgressLookupState *IPLS);
909
910 std::unique_ptr<InProgressLookupState> IPLS;
911};
912
913/// Definition generators can be attached to JITDylibs to generate new
914/// definitions for otherwise unresolved symbols during lookup.
916 friend class ExecutionSession;
917
918public:
919 virtual ~DefinitionGenerator();
920
921 /// DefinitionGenerators should override this method to insert new
922 /// definitions into the parent JITDylib. K specifies the kind of this
923 /// lookup. JD specifies the target JITDylib being searched, and
924 /// JDLookupFlags specifies whether the search should match against
925 /// hidden symbols. Finally, Symbols describes the set of unresolved
926 /// symbols and their associated lookup flags.
928 JITDylibLookupFlags JDLookupFlags,
929 const SymbolLookupSet &LookupSet) = 0;
930
931private:
932 std::mutex M;
933 bool InUse = false;
934 std::deque<LookupState> PendingLookups;
935};
936
937/// Represents a JIT'd dynamic library.
938///
939/// This class aims to mimic the behavior of a regular dylib or shared object,
940/// but without requiring the contained program representations to be compiled
941/// up-front. The JITDylib's content is defined by adding MaterializationUnits,
942/// and contained MaterializationUnits will typically rely on the JITDylib's
943/// links-against order to resolve external references (similar to a regular
944/// dylib).
945///
946/// The JITDylib object is a thin wrapper that references state held by the
947/// ExecutionSession. JITDylibs can be removed, clearing this underlying state
948/// and leaving the JITDylib object in a defunct state. In this state the
949/// JITDylib's name is guaranteed to remain accessible. If the ExecutionSession
950/// is still alive then other operations are callable but will return an Error
951/// or null result (depending on the API). It is illegal to call any operation
952/// other than getName on a JITDylib after the ExecutionSession has been torn
953/// down.
954///
955/// JITDylibs cannot be moved or copied. Their address is stable, and useful as
956/// a key in some JIT data structures.
957class JITDylib : public ThreadSafeRefCountedBase<JITDylib>,
958 public jitlink::JITLinkDylib {
960 friend class ExecutionSession;
961 friend class Platform;
963public:
964
965 JITDylib(const JITDylib &) = delete;
966 JITDylib &operator=(const JITDylib &) = delete;
967 JITDylib(JITDylib &&) = delete;
969 ~JITDylib();
970
971 /// Get a reference to the ExecutionSession for this JITDylib.
972 ///
973 /// It is legal to call this method on a defunct JITDylib, however the result
974 /// will only usable if the ExecutionSession is still alive. If this JITDylib
975 /// is held by an error that may have torn down the JIT then the result
976 /// should not be used.
977 ExecutionSession &getExecutionSession() const { return ES; }
978
979 /// Dump current JITDylib state to OS.
980 ///
981 /// It is legal to call this method on a defunct JITDylib.
982 void dump(raw_ostream &OS);
983
984 /// Calls remove on all trackers currently associated with this JITDylib.
985 /// Does not run static deinits.
986 ///
987 /// Note that removal happens outside the session lock, so new code may be
988 /// added concurrently while the clear is underway, and the newly added
989 /// code will *not* be cleared. Adding new code concurrently with a clear
990 /// is usually a bug and should be avoided.
991 ///
992 /// It is illegal to call this method on a defunct JITDylib and the client
993 /// is responsible for ensuring that they do not do so.
994 Error clear();
995
996 /// Get the default resource tracker for this JITDylib.
997 ///
998 /// It is illegal to call this method on a defunct JITDylib and the client
999 /// is responsible for ensuring that they do not do so.
1001
1002 /// Create a resource tracker for this JITDylib.
1003 ///
1004 /// It is illegal to call this method on a defunct JITDylib and the client
1005 /// is responsible for ensuring that they do not do so.
1007
1008 /// Adds a definition generator to this JITDylib and returns a referenece to
1009 /// it.
1010 ///
1011 /// When JITDylibs are searched during lookup, if no existing definition of
1012 /// a symbol is found, then any generators that have been added are run (in
1013 /// the order that they were added) to potentially generate a definition.
1014 ///
1015 /// It is illegal to call this method on a defunct JITDylib and the client
1016 /// is responsible for ensuring that they do not do so.
1017 template <typename GeneratorT>
1018 GeneratorT &addGenerator(std::unique_ptr<GeneratorT> DefGenerator);
1019
1020 /// Remove a definition generator from this JITDylib.
1021 ///
1022 /// The given generator must exist in this JITDylib's generators list (i.e.
1023 /// have been added and not yet removed).
1024 ///
1025 /// It is illegal to call this method on a defunct JITDylib and the client
1026 /// is responsible for ensuring that they do not do so.
1028
1029 /// Set the link order to be used when fixing up definitions in JITDylib.
1030 /// This will replace the previous link order, and apply to any symbol
1031 /// resolutions made for definitions in this JITDylib after the call to
1032 /// setLinkOrder (even if the definition itself was added before the
1033 /// call).
1034 ///
1035 /// If LinkAgainstThisJITDylibFirst is true (the default) then this JITDylib
1036 /// will add itself to the beginning of the LinkOrder (Clients should not
1037 /// put this JITDylib in the list in this case, to avoid redundant lookups).
1038 ///
1039 /// If LinkAgainstThisJITDylibFirst is false then the link order will be used
1040 /// as-is. The primary motivation for this feature is to support deliberate
1041 /// shadowing of symbols in this JITDylib by a facade JITDylib. For example,
1042 /// the facade may resolve function names to stubs, and the stubs may compile
1043 /// lazily by looking up symbols in this dylib. Adding the facade dylib
1044 /// as the first in the link order (instead of this dylib) ensures that
1045 /// definitions within this dylib resolve to the lazy-compiling stubs,
1046 /// rather than immediately materializing the definitions in this dylib.
1047 ///
1048 /// It is illegal to call this method on a defunct JITDylib and the client
1049 /// is responsible for ensuring that they do not do so.
1050 void setLinkOrder(JITDylibSearchOrder NewSearchOrder,
1051 bool LinkAgainstThisJITDylibFirst = true);
1052
1053 /// Append the given JITDylibSearchOrder to the link order for this
1054 /// JITDylib (discarding any elements already present in this JITDylib's
1055 /// link order).
1056 void addToLinkOrder(const JITDylibSearchOrder &NewLinks);
1057
1058 /// Add the given JITDylib to the link order for definitions in this
1059 /// JITDylib.
1060 ///
1061 /// It is illegal to call this method on a defunct JITDylib and the client
1062 /// is responsible for ensuring that they do not do so.
1063 void addToLinkOrder(JITDylib &JD,
1064 JITDylibLookupFlags JDLookupFlags =
1066
1067 /// Replace OldJD with NewJD in the link order if OldJD is present.
1068 /// Otherwise this operation is a no-op.
1069 ///
1070 /// It is illegal to call this method on a defunct JITDylib and the client
1071 /// is responsible for ensuring that they do not do so.
1072 void replaceInLinkOrder(JITDylib &OldJD, JITDylib &NewJD,
1073 JITDylibLookupFlags JDLookupFlags =
1075
1076 /// Remove the given JITDylib from the link order for this JITDylib if it is
1077 /// present. Otherwise this operation is a no-op.
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 removeFromLinkOrder(JITDylib &JD);
1082
1083 /// Do something with the link order (run under the session lock).
1084 ///
1085 /// It is illegal to call this method on a defunct JITDylib and the client
1086 /// is responsible for ensuring that they do not do so.
1087 template <typename Func>
1088 auto withLinkOrderDo(Func &&F)
1089 -> decltype(F(std::declval<const JITDylibSearchOrder &>()));
1090
1091 /// Define all symbols provided by the materialization unit to be part of this
1092 /// JITDylib.
1093 ///
1094 /// If RT is not specified then the default resource tracker will be used.
1095 ///
1096 /// This overload always takes ownership of the MaterializationUnit. If any
1097 /// errors occur, the MaterializationUnit consumed.
1098 ///
1099 /// It is illegal to call this method on a defunct JITDylib and the client
1100 /// is responsible for ensuring that they do not do so.
1101 template <typename MaterializationUnitType>
1102 Error define(std::unique_ptr<MaterializationUnitType> &&MU,
1103 ResourceTrackerSP RT = nullptr);
1104
1105 /// Define all symbols provided by the materialization unit to be part of this
1106 /// JITDylib.
1107 ///
1108 /// This overload only takes ownership of the MaterializationUnit no error is
1109 /// generated. If an error occurs, ownership remains with the caller. This
1110 /// may allow the caller to modify the MaterializationUnit to correct the
1111 /// issue, then re-call define.
1112 ///
1113 /// It is illegal to call this method on a defunct JITDylib and the client
1114 /// is responsible for ensuring that they do not do so.
1115 template <typename MaterializationUnitType>
1116 Error define(std::unique_ptr<MaterializationUnitType> &MU,
1117 ResourceTrackerSP RT = nullptr);
1118
1119 /// Tries to remove the given symbols.
1120 ///
1121 /// If any symbols are not defined in this JITDylib this method will return
1122 /// a SymbolsNotFound error covering the missing symbols.
1123 ///
1124 /// If all symbols are found but some symbols are in the process of being
1125 /// materialized this method will return a SymbolsCouldNotBeRemoved error.
1126 ///
1127 /// On success, all symbols are removed. On failure, the JITDylib state is
1128 /// left unmodified (no symbols are removed).
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 Error remove(const SymbolNameSet &Names);
1133
1134 /// Returns the given JITDylibs and all of their transitive dependencies in
1135 /// DFS order (based on linkage relationships). Each JITDylib will appear
1136 /// only once.
1137 ///
1138 /// If any JITDylib in the order is defunct then this method will return an
1139 /// error, otherwise returns the order.
1142
1143 /// Returns the given JITDylibs and all of their transitive dependencies in
1144 /// reverse DFS order (based on linkage relationships). Each JITDylib will
1145 /// appear only once.
1146 ///
1147 /// If any JITDylib in the order is defunct then this method will return an
1148 /// error, otherwise returns the order.
1151
1152 /// Return this JITDylib and its transitive dependencies in DFS order
1153 /// based on linkage relationships.
1154 ///
1155 /// If any JITDylib in the order is defunct then this method will return an
1156 /// error, otherwise returns the order.
1158
1159 /// Rteurn this JITDylib and its transitive dependencies in reverse DFS order
1160 /// based on linkage relationships.
1161 ///
1162 /// If any JITDylib in the order is defunct then this method will return an
1163 /// error, otherwise returns the order.
1165
1166private:
1167 using AsynchronousSymbolQuerySet =
1168 std::set<std::shared_ptr<AsynchronousSymbolQuery>>;
1169
1170 using AsynchronousSymbolQueryList =
1171 std::vector<std::shared_ptr<AsynchronousSymbolQuery>>;
1172
1173 struct UnmaterializedInfo {
1174 UnmaterializedInfo(std::unique_ptr<MaterializationUnit> MU,
1175 ResourceTracker *RT)
1176 : MU(std::move(MU)), RT(RT) {}
1177
1178 std::unique_ptr<MaterializationUnit> MU;
1179 ResourceTracker *RT;
1180 };
1181
1182 using UnmaterializedInfosMap =
1183 DenseMap<SymbolStringPtr, std::shared_ptr<UnmaterializedInfo>>;
1184
1185 using UnmaterializedInfosList =
1186 std::vector<std::shared_ptr<UnmaterializedInfo>>;
1187
1188 struct MaterializingInfo {
1189 SymbolDependenceMap Dependants;
1190 SymbolDependenceMap UnemittedDependencies;
1191
1192 void addQuery(std::shared_ptr<AsynchronousSymbolQuery> Q);
1193 void removeQuery(const AsynchronousSymbolQuery &Q);
1194 AsynchronousSymbolQueryList takeQueriesMeeting(SymbolState RequiredState);
1195 AsynchronousSymbolQueryList takeAllPendingQueries() {
1196 return std::move(PendingQueries);
1197 }
1198 bool hasQueriesPending() const { return !PendingQueries.empty(); }
1199 const AsynchronousSymbolQueryList &pendingQueries() const {
1200 return PendingQueries;
1201 }
1202 private:
1203 AsynchronousSymbolQueryList PendingQueries;
1204 };
1205
1206 using MaterializingInfosMap = DenseMap<SymbolStringPtr, MaterializingInfo>;
1207
1208 class SymbolTableEntry {
1209 public:
1210 SymbolTableEntry() = default;
1211 SymbolTableEntry(JITSymbolFlags Flags)
1212 : Flags(Flags), State(static_cast<uint8_t>(SymbolState::NeverSearched)),
1213 MaterializerAttached(false), PendingRemoval(false) {}
1214
1215 ExecutorAddr getAddress() const { return Addr; }
1216 JITSymbolFlags getFlags() const { return Flags; }
1217 SymbolState getState() const { return static_cast<SymbolState>(State); }
1218
1219 bool hasMaterializerAttached() const { return MaterializerAttached; }
1220 bool isPendingRemoval() const { return PendingRemoval; }
1221
1222 void setAddress(ExecutorAddr Addr) { this->Addr = Addr; }
1223 void setFlags(JITSymbolFlags Flags) { this->Flags = Flags; }
1224 void setState(SymbolState State) {
1225 assert(static_cast<uint8_t>(State) < (1 << 6) &&
1226 "State does not fit in bitfield");
1227 this->State = static_cast<uint8_t>(State);
1228 }
1229
1230 void setMaterializerAttached(bool MaterializerAttached) {
1231 this->MaterializerAttached = MaterializerAttached;
1232 }
1233
1234 void setPendingRemoval(bool PendingRemoval) {
1235 this->PendingRemoval = PendingRemoval;
1236 }
1237
1238 ExecutorSymbolDef getSymbol() const { return {Addr, Flags}; }
1239
1240 private:
1241 ExecutorAddr Addr;
1242 JITSymbolFlags Flags;
1243 uint8_t State : 6;
1244 uint8_t MaterializerAttached : 1;
1245 uint8_t PendingRemoval : 1;
1246 };
1247
1248 using SymbolTable = DenseMap<SymbolStringPtr, SymbolTableEntry>;
1249
1250 JITDylib(ExecutionSession &ES, std::string Name);
1251
1252 std::pair<AsynchronousSymbolQuerySet, std::shared_ptr<SymbolDependenceMap>>
1253 removeTracker(ResourceTracker &RT);
1254
1255 void transferTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT);
1256
1257 Error defineImpl(MaterializationUnit &MU);
1258
1259 void installMaterializationUnit(std::unique_ptr<MaterializationUnit> MU,
1260 ResourceTracker &RT);
1261
1262 void detachQueryHelper(AsynchronousSymbolQuery &Q,
1263 const SymbolNameSet &QuerySymbols);
1264
1265 void transferEmittedNodeDependencies(MaterializingInfo &DependantMI,
1266 const SymbolStringPtr &DependantName,
1267 MaterializingInfo &EmittedMI);
1268
1269 Expected<SymbolFlagsMap>
1270 defineMaterializing(MaterializationResponsibility &FromMR,
1271 SymbolFlagsMap SymbolFlags);
1272
1273 Error replace(MaterializationResponsibility &FromMR,
1274 std::unique_ptr<MaterializationUnit> MU);
1275
1276 Expected<std::unique_ptr<MaterializationResponsibility>>
1277 delegate(MaterializationResponsibility &FromMR, SymbolFlagsMap SymbolFlags,
1278 SymbolStringPtr InitSymbol);
1279
1280 SymbolNameSet getRequestedSymbols(const SymbolFlagsMap &SymbolFlags) const;
1281
1282 void addDependencies(const SymbolStringPtr &Name,
1283 const SymbolDependenceMap &Dependants);
1284
1286
1288
1289 void unlinkMaterializationResponsibility(MaterializationResponsibility &MR);
1290
1291 using FailedSymbolsWorklist =
1292 std::vector<std::pair<JITDylib *, SymbolStringPtr>>;
1293
1294 static std::pair<AsynchronousSymbolQuerySet,
1295 std::shared_ptr<SymbolDependenceMap>>
1296 failSymbols(FailedSymbolsWorklist);
1297
1298 ExecutionSession &ES;
1299 enum { Open, Closing, Closed } State = Open;
1300 std::mutex GeneratorsMutex;
1301 SymbolTable Symbols;
1302 UnmaterializedInfosMap UnmaterializedInfos;
1303 MaterializingInfosMap MaterializingInfos;
1304 std::vector<std::shared_ptr<DefinitionGenerator>> DefGenerators;
1305 JITDylibSearchOrder LinkOrder;
1306 ResourceTrackerSP DefaultTracker;
1307
1308 // Map trackers to sets of symbols tracked.
1309 DenseMap<ResourceTracker *, SymbolNameVector> TrackerSymbols;
1310 DenseMap<ResourceTracker *, DenseSet<MaterializationResponsibility *>>
1311 TrackerMRs;
1312};
1313
1314/// Platforms set up standard symbols and mediate interactions between dynamic
1315/// initializers (e.g. C++ static constructors) and ExecutionSession state.
1316/// Note that Platforms do not automatically run initializers: clients are still
1317/// responsible for doing this.
1319public:
1320 virtual ~Platform();
1321
1322 /// This method will be called outside the session lock each time a JITDylib
1323 /// is created (unless it is created with EmptyJITDylib set) to allow the
1324 /// Platform to install any JITDylib specific standard symbols (e.g
1325 /// __dso_handle).
1326 virtual Error setupJITDylib(JITDylib &JD) = 0;
1327
1328 /// This method will be called outside the session lock each time a JITDylib
1329 /// is removed to allow the Platform to remove any JITDylib-specific data.
1331
1332 /// This method will be called under the ExecutionSession lock each time a
1333 /// MaterializationUnit is added to a JITDylib.
1335 const MaterializationUnit &MU) = 0;
1336
1337 /// This method will be called under the ExecutionSession lock when a
1338 /// ResourceTracker is removed.
1340
1341 /// A utility function for looking up initializer symbols. Performs a blocking
1342 /// lookup for the given symbols in each of the given JITDylibs.
1343 ///
1344 /// Note: This function is deprecated and will be removed in the near future.
1348
1349 /// Performs an async lookup for the given symbols in each of the given
1350 /// JITDylibs, calling the given handler once all lookups have completed.
1351 static void
1353 ExecutionSession &ES,
1355};
1356
1357/// A materialization task.
1358class MaterializationTask : public RTTIExtends<MaterializationTask, Task> {
1359public:
1360 static char ID;
1361
1362 MaterializationTask(std::unique_ptr<MaterializationUnit> MU,
1363 std::unique_ptr<MaterializationResponsibility> MR)
1364 : MU(std::move(MU)), MR(std::move(MR)) {}
1365 void printDescription(raw_ostream &OS) override;
1366 void run() override;
1367
1368private:
1369 std::unique_ptr<MaterializationUnit> MU;
1370 std::unique_ptr<MaterializationResponsibility> MR;
1371};
1372
1373/// Lookups are usually run on the current thread, but in some cases they may
1374/// be run as tasks, e.g. if the lookup has been continued from a suspended
1375/// state.
1376class LookupTask : public RTTIExtends<LookupTask, Task> {
1377public:
1378 static char ID;
1379
1380 LookupTask(LookupState LS) : LS(std::move(LS)) {}
1381 void printDescription(raw_ostream &OS) override;
1382 void run() override;
1383
1384private:
1385 LookupState LS;
1386};
1387
1388/// An ExecutionSession represents a running JIT program.
1392 friend class JITDylib;
1393 friend class LookupState;
1395 friend class ResourceTracker;
1396
1397public:
1398 /// For reporting errors.
1399 using ErrorReporter = std::function<void(Error)>;
1400
1401 /// Send a result to the remote.
1403
1404 /// For dispatching ORC tasks (typically materialization tasks).
1405 using DispatchTaskFunction = unique_function<void(std::unique_ptr<Task> T)>;
1406
1407 /// An asynchronous wrapper-function callable from the executor via
1408 /// jit-dispatch.
1410 SendResultFunction SendResult,
1411 const char *ArgData, size_t ArgSize)>;
1412
1413 /// A map associating tag names with asynchronous wrapper function
1414 /// implementations in the JIT.
1417
1418 /// Construct an ExecutionSession with the given ExecutorProcessControl
1419 /// object.
1420 ExecutionSession(std::unique_ptr<ExecutorProcessControl> EPC);
1421
1422 /// Destroy an ExecutionSession. Verifies that endSession was called prior to
1423 /// destruction.
1425
1426 /// End the session. Closes all JITDylibs and disconnects from the
1427 /// executor. Clients must call this method before destroying the session.
1428 Error endSession();
1429
1430 /// Get the ExecutorProcessControl object associated with this
1431 /// ExecutionSession.
1433
1434 /// Return the triple for the executor.
1435 const Triple &getTargetTriple() const { return EPC->getTargetTriple(); }
1436
1437 // Return the page size for the executor.
1438 size_t getPageSize() const { return EPC->getPageSize(); }
1439
1440 /// Get the SymbolStringPool for this instance.
1441 std::shared_ptr<SymbolStringPool> getSymbolStringPool() {
1442 return EPC->getSymbolStringPool();
1443 }
1444
1445 /// Add a symbol name to the SymbolStringPool and return a pointer to it.
1446 SymbolStringPtr intern(StringRef SymName) { return EPC->intern(SymName); }
1447
1448 /// Set the Platform for this ExecutionSession.
1449 void setPlatform(std::unique_ptr<Platform> P) { this->P = std::move(P); }
1450
1451 /// Get the Platform for this session.
1452 /// Will return null if no Platform has been set for this ExecutionSession.
1453 Platform *getPlatform() { return P.get(); }
1454
1455 /// Run the given lambda with the session mutex locked.
1456 template <typename Func> decltype(auto) runSessionLocked(Func &&F) {
1457 std::lock_guard<std::recursive_mutex> Lock(SessionMutex);
1458 return F();
1459 }
1460
1461 /// Register the given ResourceManager with this ExecutionSession.
1462 /// Managers will be notified of events in reverse order of registration.
1464
1465 /// Deregister the given ResourceManager with this ExecutionSession.
1466 /// Manager must have been previously registered.
1468
1469 /// Return a pointer to the "name" JITDylib.
1470 /// Ownership of JITDylib remains within Execution Session
1472
1473 /// Add a new bare JITDylib to this ExecutionSession.
1474 ///
1475 /// The JITDylib Name is required to be unique. Clients should verify that
1476 /// names are not being re-used (E.g. by calling getJITDylibByName) if names
1477 /// are based on user input.
1478 ///
1479 /// This call does not install any library code or symbols into the newly
1480 /// created JITDylib. The client is responsible for all configuration.
1481 JITDylib &createBareJITDylib(std::string Name);
1482
1483 /// Add a new JITDylib to this ExecutionSession.
1484 ///
1485 /// The JITDylib Name is required to be unique. Clients should verify that
1486 /// names are not being re-used (e.g. by calling getJITDylibByName) if names
1487 /// are based on user input.
1488 ///
1489 /// If a Platform is attached then Platform::setupJITDylib will be called to
1490 /// install standard platform symbols (e.g. standard library interposes).
1491 /// If no Platform is attached this call is equivalent to createBareJITDylib.
1493
1494 /// Removes the given JITDylibs from the ExecutionSession.
1495 ///
1496 /// This method clears all resources held for the JITDylibs, puts them in the
1497 /// closed state, and clears all references to them that are held by the
1498 /// ExecutionSession or other JITDylibs. No further code can be added to the
1499 /// removed JITDylibs, and the JITDylib objects will be freed once any
1500 /// remaining JITDylibSPs pointing to them are destroyed.
1501 ///
1502 /// This method does *not* run static destructors for code contained in the
1503 /// JITDylibs, and each JITDylib can only be removed once.
1504 ///
1505 /// JITDylibs will be removed in the order given. Teardown is usually
1506 /// independent for each JITDylib, but not always. In particular, where the
1507 /// ORC runtime is used it is expected that teardown off all JITDylibs will
1508 /// depend on it, so the JITDylib containing the ORC runtime must be removed
1509 /// last. If the client has introduced any other dependencies they should be
1510 /// accounted for in the removal order too.
1511 Error removeJITDylibs(std::vector<JITDylibSP> JDsToRemove);
1512
1513 /// Calls removeJTIDylibs on the gives JITDylib.
1515 return removeJITDylibs(std::vector<JITDylibSP>({&JD}));
1516 }
1517
1518 /// Set the error reporter function.
1520 this->ReportError = std::move(ReportError);
1521 return *this;
1522 }
1523
1524 /// Report a error for this execution session.
1525 ///
1526 /// Unhandled errors can be sent here to log them.
1527 void reportError(Error Err) { ReportError(std::move(Err)); }
1528
1529 /// Set the task dispatch function.
1531 this->DispatchTask = std::move(DispatchTask);
1532 return *this;
1533 }
1534
1535 /// Search the given JITDylibs to find the flags associated with each of the
1536 /// given symbols.
1537 void lookupFlags(LookupKind K, JITDylibSearchOrder SearchOrder,
1538 SymbolLookupSet Symbols,
1539 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete);
1540
1541 /// Blocking version of lookupFlags.
1543 JITDylibSearchOrder SearchOrder,
1544 SymbolLookupSet Symbols);
1545
1546 /// Search the given JITDylibs for the given symbols.
1547 ///
1548 /// SearchOrder lists the JITDylibs to search. For each dylib, the associated
1549 /// boolean indicates whether the search should match against non-exported
1550 /// (hidden visibility) symbols in that dylib (true means match against
1551 /// non-exported symbols, false means do not match).
1552 ///
1553 /// The NotifyComplete callback will be called once all requested symbols
1554 /// reach the required state.
1555 ///
1556 /// If all symbols are found, the RegisterDependencies function will be called
1557 /// while the session lock is held. This gives clients a chance to register
1558 /// dependencies for on the queried symbols for any symbols they are
1559 /// materializing (if a MaterializationResponsibility instance is present,
1560 /// this can be implemented by calling
1561 /// MaterializationResponsibility::addDependencies). If there are no
1562 /// dependenant symbols for this query (e.g. it is being made by a top level
1563 /// client to get an address to call) then the value NoDependenciesToRegister
1564 /// can be used.
1565 void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder,
1566 SymbolLookupSet Symbols, SymbolState RequiredState,
1567 SymbolsResolvedCallback NotifyComplete,
1568 RegisterDependenciesFunction RegisterDependencies);
1569
1570 /// Blocking version of lookup above. Returns the resolved symbol map.
1571 /// If WaitUntilReady is true (the default), will not return until all
1572 /// requested symbols are ready (or an error occurs). If WaitUntilReady is
1573 /// false, will return as soon as all requested symbols are resolved,
1574 /// or an error occurs. If WaitUntilReady is false and an error occurs
1575 /// after resolution, the function will return a success value, but the
1576 /// error will be reported via reportErrors.
1578 SymbolLookupSet Symbols,
1580 SymbolState RequiredState = SymbolState::Ready,
1581 RegisterDependenciesFunction RegisterDependencies =
1583
1584 /// Convenience version of blocking lookup.
1585 /// Searches each of the JITDylibs in the search order in turn for the given
1586 /// symbol.
1588 lookup(const JITDylibSearchOrder &SearchOrder, SymbolStringPtr Symbol,
1589 SymbolState RequiredState = SymbolState::Ready);
1590
1591 /// Convenience version of blocking lookup.
1592 /// Searches each of the JITDylibs in the search order in turn for the given
1593 /// symbol. The search will not find non-exported symbols.
1595 lookup(ArrayRef<JITDylib *> SearchOrder, SymbolStringPtr Symbol,
1596 SymbolState RequiredState = SymbolState::Ready);
1597
1598 /// Convenience version of blocking lookup.
1599 /// Searches each of the JITDylibs in the search order in turn for the given
1600 /// symbol. The search will not find non-exported symbols.
1602 lookup(ArrayRef<JITDylib *> SearchOrder, StringRef Symbol,
1603 SymbolState RequiredState = SymbolState::Ready);
1604
1605 /// Materialize the given unit.
1606 void dispatchTask(std::unique_ptr<Task> T) {
1607 assert(T && "T must be non-null");
1608 DEBUG_WITH_TYPE("orc", dumpDispatchInfo(*T));
1609 DispatchTask(std::move(T));
1610 }
1611
1612 /// Run a wrapper function in the executor.
1613 ///
1614 /// The wrapper function should be callable as:
1615 ///
1616 /// \code{.cpp}
1617 /// CWrapperFunctionResult fn(uint8_t *Data, uint64_t Size);
1618 /// \endcode{.cpp}
1619 ///
1620 /// The given OnComplete function will be called to return the result.
1621 template <typename... ArgTs>
1622 void callWrapperAsync(ArgTs &&... Args) {
1623 EPC->callWrapperAsync(std::forward<ArgTs>(Args)...);
1624 }
1625
1626 /// Run a wrapper function in the executor. The wrapper function should be
1627 /// callable as:
1628 ///
1629 /// \code{.cpp}
1630 /// CWrapperFunctionResult fn(uint8_t *Data, uint64_t Size);
1631 /// \endcode{.cpp}
1633 ArrayRef<char> ArgBuffer) {
1634 return EPC->callWrapper(WrapperFnAddr, ArgBuffer);
1635 }
1636
1637 /// Run a wrapper function using SPS to serialize the arguments and
1638 /// deserialize the results.
1639 template <typename SPSSignature, typename SendResultT, typename... ArgTs>
1640 void callSPSWrapperAsync(ExecutorAddr WrapperFnAddr, SendResultT &&SendResult,
1641 const ArgTs &...Args) {
1642 EPC->callSPSWrapperAsync<SPSSignature, SendResultT, ArgTs...>(
1643 WrapperFnAddr, std::forward<SendResultT>(SendResult), Args...);
1644 }
1645
1646 /// Run a wrapper function using SPS to serialize the arguments and
1647 /// deserialize the results.
1648 ///
1649 /// If SPSSignature is a non-void function signature then the second argument
1650 /// (the first in the Args list) should be a reference to a return value.
1651 template <typename SPSSignature, typename... WrapperCallArgTs>
1653 WrapperCallArgTs &&...WrapperCallArgs) {
1654 return EPC->callSPSWrapper<SPSSignature, WrapperCallArgTs...>(
1655 WrapperFnAddr, std::forward<WrapperCallArgTs>(WrapperCallArgs)...);
1656 }
1657
1658 /// Wrap a handler that takes concrete argument types (and a sender for a
1659 /// concrete return type) to produce an AsyncHandlerWrapperFunction. Uses SPS
1660 /// to unpack the arguments and pack the result.
1661 ///
1662 /// This function is intended to support easy construction of
1663 /// AsyncHandlerWrapperFunctions that can be associated with a tag
1664 /// (using registerJITDispatchHandler) and called from the executor.
1665 template <typename SPSSignature, typename HandlerT>
1667 return [H = std::forward<HandlerT>(H)](
1668 SendResultFunction SendResult,
1669 const char *ArgData, size_t ArgSize) mutable {
1671 std::move(SendResult));
1672 };
1673 }
1674
1675 /// Wrap a class method that takes concrete argument types (and a sender for
1676 /// a concrete return type) to produce an AsyncHandlerWrapperFunction. Uses
1677 /// SPS to unpack the arguments and pack the result.
1678 ///
1679 /// This function is intended to support easy construction of
1680 /// AsyncHandlerWrapperFunctions that can be associated with a tag
1681 /// (using registerJITDispatchHandler) and called from the executor.
1682 template <typename SPSSignature, typename ClassT, typename... MethodArgTs>
1684 wrapAsyncWithSPS(ClassT *Instance, void (ClassT::*Method)(MethodArgTs...)) {
1685 return wrapAsyncWithSPS<SPSSignature>(
1686 [Instance, Method](MethodArgTs &&...MethodArgs) {
1687 (Instance->*Method)(std::forward<MethodArgTs>(MethodArgs)...);
1688 });
1689 }
1690
1691 /// For each tag symbol name, associate the corresponding
1692 /// AsyncHandlerWrapperFunction with the address of that symbol. The
1693 /// handler becomes callable from the executor using the ORC runtime
1694 /// __orc_rt_jit_dispatch function and the given tag.
1695 ///
1696 /// Tag symbols will be looked up in JD using LookupKind::Static,
1697 /// JITDylibLookupFlags::MatchAllSymbols (hidden tags will be found), and
1698 /// LookupFlags::WeaklyReferencedSymbol. Missing tag definitions will not
1699 /// cause an error, the handler will simply be dropped.
1702
1703 /// Run a registered jit-side wrapper function.
1704 /// This should be called by the ExecutorProcessControl instance in response
1705 /// to incoming jit-dispatch requests from the executor.
1707 ExecutorAddr HandlerFnTagAddr,
1708 ArrayRef<char> ArgBuffer);
1709
1710 /// Dump the state of all the JITDylibs in this session.
1711 void dump(raw_ostream &OS);
1712
1713private:
1714 static void logErrorsToStdErr(Error Err) {
1715 logAllUnhandledErrors(std::move(Err), errs(), "JIT session error: ");
1716 }
1717
1718 static void runOnCurrentThread(std::unique_ptr<Task> T) { T->run(); }
1719
1720 void dispatchOutstandingMUs();
1721
1722 static std::unique_ptr<MaterializationResponsibility>
1723 createMaterializationResponsibility(ResourceTracker &RT,
1724 SymbolFlagsMap Symbols,
1725 SymbolStringPtr InitSymbol) {
1726 auto &JD = RT.getJITDylib();
1727 std::unique_ptr<MaterializationResponsibility> MR(
1728 new MaterializationResponsibility(&RT, std::move(Symbols),
1729 std::move(InitSymbol)));
1730 JD.TrackerMRs[&RT].insert(MR.get());
1731 return MR;
1732 }
1733
1734 Error removeResourceTracker(ResourceTracker &RT);
1735 void transferResourceTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT);
1736 void destroyResourceTracker(ResourceTracker &RT);
1737
1738 // State machine functions for query application..
1739
1740 /// IL_updateCandidatesFor is called to remove already-defined symbols that
1741 /// match a given query from the set of candidate symbols to generate
1742 /// definitions for (no need to generate a definition if one already exists).
1743 Error IL_updateCandidatesFor(JITDylib &JD, JITDylibLookupFlags JDLookupFlags,
1744 SymbolLookupSet &Candidates,
1745 SymbolLookupSet *NonCandidates);
1746
1747 /// Handle resumption of a lookup after entering a generator.
1748 void OL_resumeLookupAfterGeneration(InProgressLookupState &IPLS);
1749
1750 /// OL_applyQueryPhase1 is an optionally re-startable loop for triggering
1751 /// definition generation. It is called when a lookup is performed, and again
1752 /// each time that LookupState::continueLookup is called.
1753 void OL_applyQueryPhase1(std::unique_ptr<InProgressLookupState> IPLS,
1754 Error Err);
1755
1756 /// OL_completeLookup is run once phase 1 successfully completes for a lookup
1757 /// call. It attempts to attach the symbol to all symbol table entries and
1758 /// collect all MaterializationUnits to dispatch. If this method fails then
1759 /// all MaterializationUnits will be left un-materialized.
1760 void OL_completeLookup(std::unique_ptr<InProgressLookupState> IPLS,
1761 std::shared_ptr<AsynchronousSymbolQuery> Q,
1762 RegisterDependenciesFunction RegisterDependencies);
1763
1764 /// OL_completeLookupFlags is run once phase 1 successfully completes for a
1765 /// lookupFlags call.
1766 void OL_completeLookupFlags(
1767 std::unique_ptr<InProgressLookupState> IPLS,
1768 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete);
1769
1770 // State machine functions for MaterializationResponsibility.
1771 void OL_destroyMaterializationResponsibility(
1773 SymbolNameSet OL_getRequestedSymbols(const MaterializationResponsibility &MR);
1774 Error OL_notifyResolved(MaterializationResponsibility &MR,
1775 const SymbolMap &Symbols);
1776 Error OL_notifyEmitted(MaterializationResponsibility &MR);
1777 Error OL_defineMaterializing(MaterializationResponsibility &MR,
1778 SymbolFlagsMap SymbolFlags);
1779 void OL_notifyFailed(MaterializationResponsibility &MR);
1780 Error OL_replace(MaterializationResponsibility &MR,
1781 std::unique_ptr<MaterializationUnit> MU);
1782 Expected<std::unique_ptr<MaterializationResponsibility>>
1783 OL_delegate(MaterializationResponsibility &MR, const SymbolNameSet &Symbols);
1784 void OL_addDependencies(MaterializationResponsibility &MR,
1785 const SymbolStringPtr &Name,
1786 const SymbolDependenceMap &Dependencies);
1787 void OL_addDependenciesForAll(MaterializationResponsibility &MR,
1788 const SymbolDependenceMap &Dependencies);
1789
1790#ifndef NDEBUG
1791 void dumpDispatchInfo(Task &T);
1792#endif // NDEBUG
1793
1794 mutable std::recursive_mutex SessionMutex;
1795 bool SessionOpen = true;
1796 std::unique_ptr<ExecutorProcessControl> EPC;
1797 std::unique_ptr<Platform> P;
1798 ErrorReporter ReportError = logErrorsToStdErr;
1799 DispatchTaskFunction DispatchTask = runOnCurrentThread;
1800
1801 std::vector<ResourceManager *> ResourceManagers;
1802
1803 std::vector<JITDylibSP> JDs;
1804
1805 // FIXME: Remove this (and runOutstandingMUs) once the linking layer works
1806 // with callbacks from asynchronous queries.
1807 mutable std::recursive_mutex OutstandingMUsMutex;
1808 std::vector<std::pair<std::unique_ptr<MaterializationUnit>,
1809 std::unique_ptr<MaterializationResponsibility>>>
1810 OutstandingMUs;
1811
1812 mutable std::mutex JITDispatchHandlersMutex;
1813 DenseMap<ExecutorAddr, std::shared_ptr<JITDispatchHandlerFunction>>
1814 JITDispatchHandlers;
1815};
1816
1817template <typename Func> Error ResourceTracker::withResourceKeyDo(Func &&F) {
1819 if (isDefunct())
1820 return make_error<ResourceTrackerDefunct>(this);
1821 F(getKeyUnsafe());
1822 return Error::success();
1823 });
1824}
1825
1826inline ExecutionSession &
1828 return JD.getExecutionSession();
1829}
1830
1831template <typename GeneratorT>
1832GeneratorT &JITDylib::addGenerator(std::unique_ptr<GeneratorT> DefGenerator) {
1833 auto &G = *DefGenerator;
1834 ES.runSessionLocked([&] {
1835 assert(State == Open && "Cannot add generator to closed JITDylib");
1836 DefGenerators.push_back(std::move(DefGenerator));
1837 });
1838 return G;
1839}
1840
1841template <typename Func>
1843 -> decltype(F(std::declval<const JITDylibSearchOrder &>())) {
1844 assert(State == Open && "Cannot use link order of closed JITDylib");
1845 return ES.runSessionLocked([&]() { return F(LinkOrder); });
1846}
1847
1848template <typename MaterializationUnitType>
1849Error JITDylib::define(std::unique_ptr<MaterializationUnitType> &&MU,
1850 ResourceTrackerSP RT) {
1851 assert(MU && "Can not define with a null MU");
1852
1853 if (MU->getSymbols().empty()) {
1854 // Empty MUs are allowable but pathological, so issue a warning.
1855 DEBUG_WITH_TYPE("orc", {
1856 dbgs() << "Warning: Discarding empty MU " << MU->getName() << " for "
1857 << getName() << "\n";
1858 });
1859 return Error::success();
1860 } else
1861 DEBUG_WITH_TYPE("orc", {
1862 dbgs() << "Defining MU " << MU->getName() << " for " << getName()
1863 << " (tracker: ";
1864 if (RT == getDefaultResourceTracker())
1865 dbgs() << "default)";
1866 else if (RT)
1867 dbgs() << RT.get() << ")\n";
1868 else
1869 dbgs() << "0x0, default will be used)\n";
1870 });
1871
1872 return ES.runSessionLocked([&, this]() -> Error {
1873 assert(State == Open && "JD is defunct");
1874
1875 if (auto Err = defineImpl(*MU))
1876 return Err;
1877
1878 if (!RT)
1880
1881 if (auto *P = ES.getPlatform()) {
1882 if (auto Err = P->notifyAdding(*RT, *MU))
1883 return Err;
1884 }
1885
1886 installMaterializationUnit(std::move(MU), *RT);
1887 return Error::success();
1888 });
1889}
1890
1891template <typename MaterializationUnitType>
1892Error JITDylib::define(std::unique_ptr<MaterializationUnitType> &MU,
1893 ResourceTrackerSP RT) {
1894 assert(MU && "Can not define with a null MU");
1895
1896 if (MU->getSymbols().empty()) {
1897 // Empty MUs are allowable but pathological, so issue a warning.
1898 DEBUG_WITH_TYPE("orc", {
1899 dbgs() << "Warning: Discarding empty MU " << MU->getName() << getName()
1900 << "\n";
1901 });
1902 return Error::success();
1903 } else
1904 DEBUG_WITH_TYPE("orc", {
1905 dbgs() << "Defining MU " << MU->getName() << " for " << getName()
1906 << " (tracker: ";
1907 if (RT == getDefaultResourceTracker())
1908 dbgs() << "default)";
1909 else if (RT)
1910 dbgs() << RT.get() << ")\n";
1911 else
1912 dbgs() << "0x0, default will be used)\n";
1913 });
1914
1915 return ES.runSessionLocked([&, this]() -> Error {
1916 assert(State == Open && "JD is defunct");
1917
1918 if (auto Err = defineImpl(*MU))
1919 return Err;
1920
1921 if (!RT)
1923
1924 if (auto *P = ES.getPlatform()) {
1925 if (auto Err = P->notifyAdding(*RT, *MU))
1926 return Err;
1927 }
1928
1929 installMaterializationUnit(std::move(MU), *RT);
1930 return Error::success();
1931 });
1932}
1933
1934/// ReexportsGenerator can be used with JITDylib::addGenerator to automatically
1935/// re-export a subset of the source JITDylib's symbols in the target.
1937public:
1938 using SymbolPredicate = std::function<bool(SymbolStringPtr)>;
1939
1940 /// Create a reexports generator. If an Allow predicate is passed, only
1941 /// symbols for which the predicate returns true will be reexported. If no
1942 /// Allow predicate is passed, all symbols will be exported.
1943 ReexportsGenerator(JITDylib &SourceJD,
1944 JITDylibLookupFlags SourceJDLookupFlags,
1946
1948 JITDylibLookupFlags JDLookupFlags,
1949 const SymbolLookupSet &LookupSet) override;
1950
1951private:
1952 JITDylib &SourceJD;
1953 JITDylibLookupFlags SourceJDLookupFlags;
1954 SymbolPredicate Allow;
1955};
1956
1957// --------------- IMPLEMENTATION --------------
1958// Implementations for inline functions/methods.
1959// ---------------------------------------------
1960
1962 getExecutionSession().OL_destroyMaterializationResponsibility(*this);
1963}
1964
1966 return getExecutionSession().OL_getRequestedSymbols(*this);
1967}
1968
1970 const SymbolMap &Symbols) {
1971 return getExecutionSession().OL_notifyResolved(*this, Symbols);
1972}
1973
1975 return getExecutionSession().OL_notifyEmitted(*this);
1976}
1977
1979 SymbolFlagsMap SymbolFlags) {
1980 return getExecutionSession().OL_defineMaterializing(*this,
1981 std::move(SymbolFlags));
1982}
1983
1985 getExecutionSession().OL_notifyFailed(*this);
1986}
1987
1989 std::unique_ptr<MaterializationUnit> MU) {
1990 return getExecutionSession().OL_replace(*this, std::move(MU));
1991}
1992
1995 return getExecutionSession().OL_delegate(*this, Symbols);
1996}
1997
1999 const SymbolStringPtr &Name, const SymbolDependenceMap &Dependencies) {
2000 getExecutionSession().OL_addDependencies(*this, Name, Dependencies);
2001}
2002
2004 const SymbolDependenceMap &Dependencies) {
2005 getExecutionSession().OL_addDependenciesForAll(*this, Dependencies);
2006}
2007
2008} // End namespace orc
2009} // End namespace llvm
2010
2011#endif // LLVM_EXECUTIONENGINE_ORC_CORE_H
dxil metadata emit
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:468
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:735
StringRef getName() const override
Return the name of this materialization unit.
Definition: Core.cpp:263
A symbol query that returns results via a callback when results are ready.
Definition: Core.h:841
bool isComplete() const
Returns true if all symbols covered by this query have been resolved.
Definition: Core.h:862
void notifySymbolMetRequiredState(const SymbolStringPtr &Name, ExecutorSymbolDef Sym)
Notify the query that a requested symbol has reached the required state.
Definition: Core.cpp:174
friend class JITSymbolResolverAdapter
Definition: Core.h:845
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
Definition: Core.h:915
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:1389
Error endSession()
End the session.
Definition: Core.cpp:1939
ExecutorProcessControl & getExecutorProcessControl()
Get the ExecutorProcessControl object associated with this ExecutionSession.
Definition: Core.h:1432
unique_function< void(shared::WrapperFunctionResult)> SendResultFunction
Send a result to the remote.
Definition: Core.h:1402
void reportError(Error Err)
Report a error for this execution session.
Definition: Core.h:1527
friend class JITDylib
Definition: Core.h:1392
void setPlatform(std::unique_ptr< Platform > P)
Set the Platform for this ExecutionSession.
Definition: Core.h:1449
const Triple & getTargetTriple() const
Return the triple for the executor.
Definition: Core.h:1435
std::function< void(Error)> ErrorReporter
For reporting errors.
Definition: Core.h:1399
ExecutionSession & setDispatchTask(DispatchTaskFunction DispatchTask)
Set the task dispatch function.
Definition: Core.h:1530
Platform * getPlatform()
Get the Platform for this session.
Definition: Core.h:1453
Error callSPSWrapper(ExecutorAddr WrapperFnAddr, WrapperCallArgTs &&...WrapperCallArgs)
Run a wrapper function using SPS to serialize the arguments and deserialize the results.
Definition: Core.h:1652
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:2095
shared::WrapperFunctionResult callWrapper(ExecutorAddr WrapperFnAddr, ArrayRef< char > ArgBuffer)
Run a wrapper function in the executor.
Definition: Core.h:1632
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition: Core.h:1446
JITDylib * getJITDylibByName(StringRef Name)
Return a pointer to the "name" JITDylib.
Definition: Core.cpp:1973
void callWrapperAsync(ArgTs &&... Args)
Run a wrapper function in the executor.
Definition: Core.h:1622
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:1684
JITDylib & createBareJITDylib(std::string Name)
Add a new bare JITDylib to this ExecutionSession.
Definition: Core.cpp:1982
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:1666
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:1640
DenseMap< SymbolStringPtr, JITDispatchHandlerFunction > JITDispatchHandlerAssociationMap
A map associating tag names with asynchronous wrapper function implementations in the JIT.
Definition: Core.h:1416
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
Definition: Core.h:1441
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:2121
Error registerJITDispatchHandlers(JITDylib &JD, JITDispatchHandlerAssociationMap WFs)
For each tag symbol name, associate the corresponding AsyncHandlerWrapperFunction with the address of...
Definition: Core.cpp:2230
friend class MaterializationResponsibility
Definition: Core.h:1394
void registerResourceManager(ResourceManager &RM)
Register the given ResourceManager with this ExecutionSession.
Definition: Core.cpp:1956
~ExecutionSession()
Destroy an ExecutionSession.
Definition: Core.cpp:1933
void runJITDispatchHandler(SendResultFunction SendResult, ExecutorAddr HandlerFnTagAddr, ArrayRef< char > ArgBuffer)
Run a registered jit-side wrapper function.
Definition: Core.cpp:2261
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:1411
void deregisterResourceManager(ResourceManager &RM)
Deregister the given ResourceManager with this ExecutionSession.
Definition: Core.cpp:1960
decltype(auto) runSessionLocked(Func &&F)
Run the given lambda with the session mutex locked.
Definition: Core.h:1456
void dump(raw_ostream &OS)
Dump the state of all the JITDylibs in this session.
Definition: Core.cpp:2282
friend class ResourceTracker
Definition: Core.h:1395
ExecutionSession & setErrorReporter(ErrorReporter ReportError)
Set the error reporter function.
Definition: Core.h:1519
Error removeJITDylibs(std::vector< JITDylibSP > JDsToRemove)
Removes the given JITDylibs from the ExecutionSession.
Definition: Core.cpp:1999
size_t getPageSize() const
Definition: Core.h:1438
Expected< JITDylib & > createJITDylib(std::string Name)
Add a new JITDylib to this ExecutionSession.
Definition: Core.cpp:1991
void dispatchTask(std::unique_ptr< Task > T)
Materialize the given unit.
Definition: Core.h:1606
unique_function< void(std::unique_ptr< Task > T)> DispatchTaskFunction
For dispatching ORC tasks (typically materialization tasks).
Definition: Core.h:1405
Error removeJITDylib(JITDylib &JD)
Calls removeJTIDylibs on the gives JITDylib.
Definition: Core.h:1514
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:98
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:102
Represents a JIT'd dynamic library.
Definition: Core.h:958
Error remove(const SymbolNameSet &Names)
Tries to remove the given symbols.
Definition: Core.cpp:1392
Error clear()
Calls remove on all trackers currently associated with this JITDylib.
Definition: Core.cpp:659
JITDylib & operator=(JITDylib &&)=delete
void dump(raw_ostream &OS)
Dump current JITDylib state to OS.
Definition: Core.cpp:1451
friend class AsynchronousSymbolQuery
Definition: Core.h:959
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:1368
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:1849
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
Definition: Core.h:977
void addToLinkOrder(const JITDylibSearchOrder &NewLinks)
Append the given JITDylibSearchOrder to the link order for this JITDylib (discarding any elements alr...
Definition: Core.cpp:1352
ResourceTrackerSP createResourceTracker()
Create a resource tracker for this JITDylib.
Definition: Core.cpp:683
auto withLinkOrderDo(Func &&F) -> decltype(F(std::declval< const JITDylibSearchOrder & >()))
Do something with the link order (run under the session lock).
Definition: Core.h:1842
friend class MaterializationResponsibility
Definition: Core.h:962
void removeFromLinkOrder(JITDylib &JD)
Remove the given JITDylib from the link order for this JITDylib if it is present.
Definition: Core.cpp:1380
void setLinkOrder(JITDylibSearchOrder NewSearchOrder, bool LinkAgainstThisJITDylibFirst=true)
Set the link order to be used when fixing up definitions in JITDylib.
Definition: Core.cpp:1337
Expected< std::vector< JITDylibSP > > getReverseDFSLinkOrder()
Rteurn this JITDylib and its transitive dependencies in reverse DFS order based on linkage relationsh...
Definition: Core.cpp:2091
friend class ExecutionSession
Definition: Core.h:960
ResourceTrackerSP getDefaultResourceTracker()
Get the default resource tracker for this JITDylib.
Definition: Core.cpp:674
GeneratorT & addGenerator(std::unique_ptr< GeneratorT > DefGenerator)
Adds a definition generator to this JITDylib and returns a referenece to it.
Definition: Core.h:1832
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:691
Expected< std::vector< JITDylibSP > > getDFSLinkOrder()
Return this JITDylib and its transitive dependencies in DFS order based on linkage relationships.
Definition: Core.cpp:2087
Wraps state for a lookup-in-progress.
Definition: Core.h:890
void continueLookup(Error Err)
Continue the lookup.
Definition: Core.cpp:635
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:1376
LookupTask(LookupState LS)
Definition: Core.h:1380
void run() override
Definition: Core.cpp:1925
static char ID
Definition: Core.h:1378
void printDescription(raw_ostream &OS) override
Definition: Core.cpp:1923
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition: Core.h:527
MaterializationResponsibility & operator=(MaterializationResponsibility &&)=delete
ExecutionSession & getExecutionSession() const
Returns the ExecutionSession for this instance.
Definition: Core.h:1827
Error notifyResolved(const SymbolMap &Symbols)
Notifies the target JITDylib that the given symbols have been resolved.
Definition: Core.h:1969
Error notifyEmitted()
Notifies the target JITDylib (and any pending queries on that JITDylib) that all symbols covered by t...
Definition: Core.h:1974
void addDependenciesForAll(const SymbolDependenceMap &Dependencies)
Add dependencies that apply to all symbols covered by this instance.
Definition: Core.h:2003
~MaterializationResponsibility()
Destruct a MaterializationResponsibility instance.
Definition: Core.h:1961
void addDependencies(const SymbolStringPtr &Name, const SymbolDependenceMap &Dependencies)
Definition: Core.h:1998
Error replace(std::unique_ptr< MaterializationUnit > MU)
Transfers responsibility to the given MaterializationUnit for all symbols defined by that Materializa...
Definition: Core.h:1988
Error withResourceKeyDo(Func &&F) const
Runs the given callback under the session lock, passing in the associated ResourceKey.
Definition: Core.h:543
Error defineMaterializing(SymbolFlagsMap SymbolFlags)
Attempt to claim responsibility for new definitions.
Definition: Core.h:1978
SymbolNameSet getRequestedSymbols() const
Returns the names of any symbols covered by this MaterializationResponsibility object that have queri...
Definition: Core.h:1965
Expected< std::unique_ptr< MaterializationResponsibility > > delegate(const SymbolNameSet &Symbols)
Delegates responsibility for the given symbols to the returned materialization responsibility.
Definition: Core.h:1994
const SymbolStringPtr & getInitializerSymbol() const
Returns the initialization pseudo-symbol, if any.
Definition: Core.h:563
MaterializationResponsibility(MaterializationResponsibility &&)=delete
void failMaterialization()
Notify all not-yet-emitted covered by this MaterializationResponsibility instance that an error has o...
Definition: Core.h:1984
JITDylib & getTargetJITDylib() const
Returns the target JITDylib that these symbols are being materialized into.
Definition: Core.h:549
const SymbolFlagsMap & getSymbols() const
Returns the symbol flags map for this responsibility instance.
Definition: Core.h:558
A materialization task.
Definition: Core.h:1358
void printDescription(raw_ostream &OS) override
Definition: Core.cpp:1916
MaterializationTask(std::unique_ptr< MaterializationUnit > MU, std::unique_ptr< MaterializationResponsibility > MR)
Definition: Core.h:1362
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
Definition: Core.h:662
MaterializationUnit(Interface I)
Definition: Core.h:682
virtual StringRef getName() const =0
Return the name of this materialization unit.
SymbolStringPtr InitSymbol
Definition: Core.h:719
SymbolFlagsMap SymbolFlags
Definition: Core.h:718
const SymbolFlagsMap & getSymbols() const
Return the set of symbols that this source provides.
Definition: Core.h:692
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:695
void doDiscard(const JITDylib &JD, const SymbolStringPtr &Name)
Called by JITDylibs to notify MaterializationUnits that the given symbol has been overridden.
Definition: Core.h:705
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:478
const SymbolNameVector & getSymbols() const
Definition: Core.h:490
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition: Core.h:488
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:142
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:146
MissingSymbolDefinitions(std::shared_ptr< SymbolStringPool > SSP, std::string ModuleName, SymbolNameVector Symbols)
Definition: Core.h:482
const std::string & getModuleName() const
Definition: Core.h:489
Platforms set up standard symbols and mediate interactions between dynamic initializers (e....
Definition: Core.h:1318
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:1873
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:1824
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:767
StringRef getName() const override
Return the name of this materialization unit.
Definition: Core.cpp:306
ReexportsGenerator can be used with JITDylib::addGenerator to automatically re-export a subset of the...
Definition: Core.h:1936
std::function< bool(SymbolStringPtr)> SymbolPredicate
Definition: Core.h:1938
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:600
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:76
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:72
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:57
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:1817
Error remove()
Remove all resources associated with this key.
Definition: Core.cpp:53
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:458
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:134
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:138
const SymbolNameSet & getSymbols() const
Definition: Core.h:467
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition: Core.h:466
Used to notify clients when symbols can not be found during a lookup.
Definition: Core.h:440
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:124
const SymbolNameVector & getSymbols() const
Definition: Core.h:450
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:120
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition: Core.h:449
Errors of this type should be returned if a module contains definitions for symbols that are not clai...
Definition: Core.h:501
UnexpectedSymbolDefinitions(std::shared_ptr< SymbolStringPool > SSP, std::string ModuleName, SymbolNameVector Symbols)
Definition: Core.h:505
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:151
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:155
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition: Core.h:511
const std::string & getModuleName() const
Definition: Core.h:512
const SymbolNameVector & getSymbols() const
Definition: Core.h:513
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:806
std::unique_ptr< AbsoluteSymbolsMaterializationUnit > absoluteSymbols(SymbolMap Symbols)
Create an AbsoluteSymbolsMaterializationUnit with the given symbols.
Definition: Core.h:760
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:815
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:36
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:828
@ 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:1652
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:1854
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:1455
Interface(SymbolFlagsMap InitalSymbolFlags, SymbolStringPtr InitSymbol)
Definition: Core.h:671
JITSymbolFlags AliasFlags
Definition: Core.h:392
SymbolAliasMapEntry(SymbolStringPtr Aliasee, JITSymbolFlags AliasFlags)
Definition: Core.h:388
SymbolStringPtr Aliasee
Definition: Core.h:391