LLVM 24.0.0git
JITLink.h
Go to the documentation of this file.
1//===------------ JITLink.h - JIT linker functionality ----------*- 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 generic JIT-linker types.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_EXECUTIONENGINE_JITLINK_JITLINK_H
14#define LLVM_EXECUTIONENGINE_JITLINK_JITLINK_H
15
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/STLExtras.h"
31#include "llvm/Support/Endian.h"
32#include "llvm/Support/Error.h"
38#include <optional>
39
40#include <map>
41#include <string>
42#include <system_error>
43
44namespace llvm {
45namespace jitlink {
46
47class LinkGraph;
48class Symbol;
49class Section;
50
51/// Base class for errors originating in JIT linker, e.g. missing relocation
52/// support.
53class LLVM_ABI JITLinkError : public ErrorInfo<JITLinkError> {
54public:
55 static char ID;
56
57 JITLinkError(Twine ErrMsg) : ErrMsg(ErrMsg.str()) {}
58
59 void log(raw_ostream &OS) const override;
60 const std::string &getErrorMessage() const { return ErrMsg; }
61 std::error_code convertToErrorCode() const override;
62
63private:
64 std::string ErrMsg;
65};
66
67/// Represents fixups and constraints in the LinkGraph.
68class Edge {
69public:
70 using Kind = uint8_t;
71
73 Invalid, // Invalid edge value.
74 FirstKeepAlive, // Keeps target alive. Offset/addend zero.
75 KeepAlive = FirstKeepAlive, // Tag first edge kind that preserves liveness.
76 FirstRelocation // First architecture specific relocation.
77 };
78
80 using AddendT = int64_t;
81
82 Edge(Kind K, OffsetT Offset, Symbol &Target, AddendT Addend)
83 : Target(&Target), Offset(Offset), Addend(Addend), K(K) {}
84
85 OffsetT getOffset() const { return Offset; }
86 void setOffset(OffsetT Offset) { this->Offset = Offset; }
87 Kind getKind() const { return K; }
88 void setKind(Kind K) { this->K = K; }
89 bool isRelocation() const { return K >= FirstRelocation; }
91 assert(isRelocation() && "Not a relocation edge");
92 return K - FirstRelocation;
93 }
94 bool isKeepAlive() const { return K >= FirstKeepAlive; }
95 Symbol &getTarget() const { return *Target; }
96 void setTarget(Symbol &Target) { this->Target = &Target; }
97 AddendT getAddend() const { return Addend; }
98 void setAddend(AddendT Addend) { this->Addend = Addend; }
99
100private:
101 Symbol *Target = nullptr;
102 OffsetT Offset = 0;
103 AddendT Addend = 0;
104 Kind K = 0;
105};
106
107/// Returns the string name of the given generic edge kind, or "unknown"
108/// otherwise. Useful for debugging.
109LLVM_ABI const char *getGenericEdgeKindName(Edge::Kind K);
110
111/// Base class for Addressable entities (externals, absolutes, blocks).
113 friend class LinkGraph;
114
115protected:
116 Addressable(orc::ExecutorAddr Address, bool IsDefined)
117 : Address(Address), IsDefined(IsDefined), IsAbsolute(false) {}
118
120 : Address(Address), IsDefined(false), IsAbsolute(true) {
121 assert(!(IsDefined && IsAbsolute) &&
122 "Block cannot be both defined and absolute");
123 }
124
125public:
126 Addressable(const Addressable &) = delete;
127 Addressable &operator=(const Addressable &) = default;
130
131 orc::ExecutorAddr getAddress() const { return Address; }
132 void setAddress(orc::ExecutorAddr Address) { this->Address = Address; }
133
134 /// Returns true if this is a defined addressable, in which case you
135 /// can downcast this to a Block.
136 bool isDefined() const { return static_cast<bool>(IsDefined); }
137 bool isAbsolute() const { return static_cast<bool>(IsAbsolute); }
138
139private:
140 void setAbsolute(bool IsAbsolute) {
141 assert(!IsDefined && "Cannot change the Absolute flag on a defined block");
142 this->IsAbsolute = IsAbsolute;
143 }
144
146 uint64_t IsDefined : 1;
147 uint64_t IsAbsolute : 1;
148
149protected:
150 // bitfields for Block, allocated here to improve packing.
154};
155
157
158/// An Addressable with content and edges.
159class Block : public Addressable {
160 friend class LinkGraph;
161
162private:
163 /// Create a zero-fill defined addressable.
166 : Addressable(Address, true), Parent(&Parent), Size(Size) {
167 assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
168 assert(AlignmentOffset < Alignment &&
169 "Alignment offset cannot exceed alignment");
170 assert(AlignmentOffset <= MaxAlignmentOffset &&
171 "Alignment offset exceeds maximum");
172 ContentMutable = false;
173 P2Align = Alignment ? llvm::countr_zero(Alignment) : 0;
174 this->AlignmentOffset = AlignmentOffset;
175 }
176
177 /// Create a defined addressable for the given content.
178 /// The Content is assumed to be non-writable, and will be copied when
179 /// mutations are required.
182 : Addressable(Address, true), Parent(&Parent), Data(Content.data()),
183 Size(Content.size()) {
184 assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
185 assert(AlignmentOffset < Alignment &&
186 "Alignment offset cannot exceed alignment");
187 assert(AlignmentOffset <= MaxAlignmentOffset &&
188 "Alignment offset exceeds maximum");
189 ContentMutable = false;
190 P2Align = Alignment ? llvm::countr_zero(Alignment) : 0;
191 this->AlignmentOffset = AlignmentOffset;
192 }
193
194 /// Create a defined addressable for the given content.
195 /// The content is assumed to be writable, and the caller is responsible
196 /// for ensuring that it lives for the duration of the Block's lifetime.
197 /// The standard way to achieve this is to allocate it on the Graph's
198 /// allocator.
199 Block(Section &Parent, MutableArrayRef<char> Content,
201 : Addressable(Address, true), Parent(&Parent), Data(Content.data()),
202 Size(Content.size()) {
203 assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
204 assert(AlignmentOffset < Alignment &&
205 "Alignment offset cannot exceed alignment");
206 assert(AlignmentOffset <= MaxAlignmentOffset &&
207 "Alignment offset exceeds maximum");
208 ContentMutable = true;
209 P2Align = Alignment ? llvm::countr_zero(Alignment) : 0;
210 this->AlignmentOffset = AlignmentOffset;
211 }
212
213public:
214 using EdgeVector = std::vector<Edge>;
215 using edge_iterator = EdgeVector::iterator;
216 using const_edge_iterator = EdgeVector::const_iterator;
217
218 Block(const Block &) = delete;
219 Block &operator=(const Block &) = delete;
220 Block(Block &&) = delete;
221 Block &operator=(Block &&) = delete;
222
223 /// Return the parent section for this block.
224 Section &getSection() const { return *Parent; }
225
226 /// Returns true if this is a zero-fill block.
227 ///
228 /// If true, getSize is callable but getContent is not (the content is
229 /// defined to be a sequence of zero bytes of length Size).
230 bool isZeroFill() const { return !Data; }
231
232 /// Returns the size of this defined addressable.
233 size_t getSize() const { return Size; }
234
235 /// Turns this block into a zero-fill block of the given size.
236 void setZeroFillSize(size_t Size) {
237 Data = nullptr;
238 this->Size = Size;
239 }
240
241 /// Returns the address range of this defined addressable.
245
246 /// Get the content for this block. Block must not be a zero-fill block.
248 assert(Data && "Block does not contain content");
249 return ArrayRef<char>(Data, Size);
250 }
251
252 /// Set the content for this block.
253 /// Caller is responsible for ensuring the underlying bytes are not
254 /// deallocated while pointed to by this block.
256 assert(Content.data() && "Setting null content");
257 Data = Content.data();
258 Size = Content.size();
259 ContentMutable = false;
260 }
261
262 /// Get mutable content for this block.
263 ///
264 /// If this Block's content is not already mutable this will trigger a copy
265 /// of the existing immutable content to a new, mutable buffer allocated using
266 /// LinkGraph::allocateContent.
268
269 /// Get mutable content for this block.
270 ///
271 /// This block's content must already be mutable. It is a programmatic error
272 /// to call this on a block with immutable content -- consider using
273 /// getMutableContent instead.
275 assert(Data && "Block does not contain content");
276 assert(ContentMutable && "Content is not mutable");
277 return MutableArrayRef<char>(const_cast<char *>(Data), Size);
278 }
279
280 /// Set mutable content for this block.
281 ///
282 /// The caller is responsible for ensuring that the memory pointed to by
283 /// MutableContent is not deallocated while pointed to by this block.
285 assert(MutableContent.data() && "Setting null content");
286 Data = MutableContent.data();
287 Size = MutableContent.size();
288 ContentMutable = true;
289 }
290
291 /// Returns true if this block's content is mutable.
292 ///
293 /// This is primarily useful for asserting that a block is already in a
294 /// mutable state prior to modifying the content. E.g. when applying
295 /// fixups we expect the block to already be mutable as it should have been
296 /// copied to working memory.
297 bool isContentMutable() const { return ContentMutable; }
298
299 /// Get the alignment for this content.
300 uint64_t getAlignment() const { return 1ull << P2Align; }
301
302 /// Set the alignment for this content.
303 void setAlignment(uint64_t Alignment) {
304 assert(isPowerOf2_64(Alignment) && "Alignment must be a power of two");
305 P2Align = Alignment ? llvm::countr_zero(Alignment) : 0;
306 }
307
308 /// Get the alignment offset for this content.
310
311 /// Set the alignment offset for this content.
313 assert(AlignmentOffset < (1ull << P2Align) &&
314 "Alignment offset can't exceed alignment");
315 this->AlignmentOffset = AlignmentOffset;
316 }
317
318 /// Add an edge to this block.
319 void addEdge(Edge::Kind K, Edge::OffsetT Offset, Symbol &Target,
320 Edge::AddendT Addend) {
321 assert((K == Edge::KeepAlive || !isZeroFill()) &&
322 "Adding edge to zero-fill block?");
323 Edges.push_back(Edge(K, Offset, Target, Addend));
324 }
325
326 /// Add an edge by copying an existing one. This is typically used when
327 /// moving edges between blocks.
328 void addEdge(const Edge &E) { Edges.push_back(E); }
329
330 /// Return the list of edges attached to this content.
332 return make_range(Edges.begin(), Edges.end());
333 }
334
335 /// Returns the list of edges attached to this content.
337 return make_range(Edges.begin(), Edges.end());
338 }
339
340 /// Returns an iterator over all edges at the given offset within the block.
341 auto edges_at(Edge::OffsetT O) {
342 return make_filter_range(edges(),
343 [O](const Edge &E) { return E.getOffset() == O; });
344 }
345
346 /// Returns an iterator over all edges at the given offset within the block.
347 auto edges_at(Edge::OffsetT O) const {
348 return make_filter_range(edges(),
349 [O](const Edge &E) { return E.getOffset() == O; });
350 }
351
352 /// Return the size of the edges list.
353 size_t edges_size() const { return Edges.size(); }
354
355 /// Returns true if the list of edges is empty.
356 bool edges_empty() const { return Edges.empty(); }
357
358 /// Remove the edge pointed to by the given iterator.
359 /// Returns an iterator to the new next element.
360 edge_iterator removeEdge(edge_iterator I) { return Edges.erase(I); }
361
362 /// Returns the address of the fixup for the given edge, which is equal to
363 /// this block's address plus the edge's offset.
365 return getAddress() + E.getOffset();
366 }
367
368private:
369 static constexpr uint64_t MaxAlignmentOffset = (1ULL << 56) - 1;
370
371 void setSection(Section &Parent) { this->Parent = &Parent; }
372
373 Section *Parent;
374 const char *Data = nullptr;
375 size_t Size = 0;
376 std::vector<Edge> Edges;
377};
378
379// Align an address to conform with block alignment requirements.
380inline uint64_t alignToBlock(uint64_t Addr, const Block &B) {
381 uint64_t Delta = (B.getAlignmentOffset() - Addr) % B.getAlignment();
382 return Addr + Delta;
383}
384
385// Align a orc::ExecutorAddr to conform with block alignment requirements.
389
390// Returns true if the given blocks contains exactly one valid c-string.
391// Zero-fill blocks of size 1 count as valid empty strings. Content blocks
392// must end with a zero, and contain no zeros before the end.
394
395/// Describes symbol linkage. This can be used to resolve definition clashes.
396enum class Linkage : uint8_t {
399};
400
401/// Holds target-specific properties for a symbol.
403
404/// For errors and debugging output.
405LLVM_ABI const char *getLinkageName(Linkage L);
406
407/// Defines the scope in which this symbol should be visible:
408/// Default -- Visible in the public interface of the linkage unit.
409/// Hidden -- Visible within the linkage unit, but not exported from it.
410/// SideEffectsOnly -- Like hidden, but symbol can only be looked up once
411/// to trigger materialization of the containing graph.
412/// Local -- Visible only within the LinkGraph.
414
415/// For debugging output.
416LLVM_ABI const char *getScopeName(Scope S);
417
419
420/// Symbol representation.
421///
422/// Symbols represent locations within Addressable objects.
423/// They can be either Named or Anonymous.
424/// Anonymous symbols have neither linkage nor visibility, and must point at
425/// ContentBlocks.
426/// Named symbols may be in one of four states:
427/// - Null: Default initialized. Assignable, but otherwise unusable.
428/// - Defined: Has both linkage and visibility and points to a ContentBlock
429/// - Common: Has both linkage and visibility, points to a null Addressable.
430/// - External: Has neither linkage nor visibility, points to an external
431/// Addressable.
432///
433class Symbol {
434 friend class LinkGraph;
435
436private:
439 Scope S, bool IsLive, bool IsCallable)
440 : Name(std::move(Name)), Base(&Base), Offset(Offset), WeakRef(0),
441 Size(Size) {
442 assert(Offset <= MaxOffset && "Offset out of range");
443 setLinkage(L);
444 setScope(S);
445 setLive(IsLive);
446 setCallable(IsCallable);
448 }
449
450 static Symbol &constructExternal(BumpPtrAllocator &Allocator,
451 Addressable &Base,
454 bool WeaklyReferenced) {
455 assert(!Base.isDefined() &&
456 "Cannot create external symbol from defined block");
457 assert(Name && "External symbol name cannot be empty");
458 auto *Sym = Allocator.Allocate<Symbol>();
459 new (Sym)
460 Symbol(Base, 0, std::move(Name), Size, L, Scope::Default, false, false);
461 Sym->setWeaklyReferenced(WeaklyReferenced);
462 return *Sym;
463 }
464
465 static Symbol &constructAbsolute(BumpPtrAllocator &Allocator,
466 Addressable &Base,
467 orc::SymbolStringPtr &&Name,
469 Scope S, bool IsLive) {
470 assert(!Base.isDefined() &&
471 "Cannot create absolute symbol from a defined block");
472 auto *Sym = Allocator.Allocate<Symbol>();
473 new (Sym) Symbol(Base, 0, std::move(Name), Size, L, S, IsLive, false);
474 return *Sym;
475 }
476
477 static Symbol &constructAnonDef(BumpPtrAllocator &Allocator, Block &Base,
479 orc::ExecutorAddrDiff Size, bool IsCallable,
480 bool IsLive) {
481 assert((Offset + Size) <= Base.getSize() &&
482 "Symbol extends past end of block");
483 auto *Sym = Allocator.Allocate<Symbol>();
484 new (Sym) Symbol(Base, Offset, nullptr, Size, Linkage::Strong, Scope::Local,
485 IsLive, IsCallable);
486 return *Sym;
487 }
488
489 static Symbol &constructNamedDef(BumpPtrAllocator &Allocator, Block &Base,
491 orc::SymbolStringPtr Name,
493 Scope S, bool IsLive, bool IsCallable) {
494 assert((Offset + Size) <= Base.getSize() &&
495 "Symbol extends past end of block");
496 assert(Name && "Name cannot be empty");
497 auto *Sym = Allocator.Allocate<Symbol>();
498 new (Sym)
499 Symbol(Base, Offset, std::move(Name), Size, L, S, IsLive, IsCallable);
500 return *Sym;
501 }
502
503public:
504 /// Create a null Symbol. This allows Symbols to be default initialized for
505 /// use in containers (e.g. as map values). Null symbols are only useful for
506 /// assigning to.
507 Symbol() = default;
508
509 // Symbols are not movable or copyable.
510 Symbol(const Symbol &) = delete;
511 Symbol &operator=(const Symbol &) = delete;
512 Symbol(Symbol &&) = delete;
513 Symbol &operator=(Symbol &&) = delete;
514
515 /// Returns true if this symbol has a name.
516 bool hasName() const { return Name != nullptr; }
517
518 /// Returns the name of this symbol (empty if the symbol is anonymous).
520 assert((hasName() || getScope() == Scope::Local) &&
521 "Anonymous symbol has non-local scope");
522
523 return Name;
524 }
525
526 /// Rename this symbol. The client is responsible for updating scope and
527 /// linkage if this name-change requires it.
528 void setName(orc::SymbolStringPtr Name) { this->Name = std::move(Name); }
529
530 /// Returns true if this Symbol has content (potentially) defined within this
531 /// object file (i.e. is anything but an external or absolute symbol).
532 bool isDefined() const {
533 assert(Base && "Attempt to access null symbol");
534 return Base->isDefined();
535 }
536
537 /// Returns true if this symbol is live (i.e. should be treated as a root for
538 /// dead stripping).
539 bool isLive() const {
540 assert(Base && "Attempting to access null symbol");
541 return IsLive;
542 }
543
544 /// Set this symbol's live bit.
545 void setLive(bool IsLive) { this->IsLive = IsLive; }
546
547 /// Returns true is this symbol is callable.
548 bool isCallable() const { return IsCallable; }
549
550 /// Set this symbol's callable bit.
551 void setCallable(bool IsCallable) { this->IsCallable = IsCallable; }
552
553 /// Returns true if the underlying addressable is an unresolved external.
554 bool isExternal() const {
555 assert(Base && "Attempt to access null symbol");
556 return !Base->isDefined() && !Base->isAbsolute();
557 }
558
559 /// Returns true if the underlying addressable is an absolute symbol.
560 bool isAbsolute() const {
561 assert(Base && "Attempt to access null symbol");
562 return Base->isAbsolute();
563 }
564
565 /// Return the addressable that this symbol points to.
567 assert(Base && "Cannot get underlying addressable for null symbol");
568 return *Base;
569 }
570
571 /// Return the addressable that this symbol points to.
573 assert(Base && "Cannot get underlying addressable for null symbol");
574 return *Base;
575 }
576
577 /// Return the Block for this Symbol (Symbol must be defined).
579 assert(Base && "Cannot get block for null symbol");
580 assert(Base->isDefined() && "Not a defined symbol");
581 return static_cast<Block &>(*Base);
582 }
583
584 /// Return the Block for this Symbol (Symbol must be defined).
585 const Block &getBlock() const {
586 assert(Base && "Cannot get block for null symbol");
587 assert(Base->isDefined() && "Not a defined symbol");
588 return static_cast<const Block &>(*Base);
589 }
590
591 /// Return the Section for this Symbol (Symbol must be defined).
592 Section &getSection() const { return getBlock().getSection(); }
593
594 /// Returns the offset for this symbol within the underlying addressable.
595 orc::ExecutorAddrDiff getOffset() const { return Offset; }
596
598 assert(NewOffset <= getBlock().getSize() && "Offset out of range");
599 Offset = NewOffset;
600 }
601
602 /// Returns the address of this symbol.
603 orc::ExecutorAddr getAddress() const { return Base->getAddress() + Offset; }
604
605 /// Returns the size of this symbol.
606 orc::ExecutorAddrDiff getSize() const { return Size; }
607
608 /// Set the size of this symbol.
610 assert(Base && "Cannot set size for null Symbol");
611 assert((Size == 0 || Base->isDefined()) &&
612 "Non-zero size can only be set for defined symbols");
613 assert((Offset + Size <= static_cast<const Block &>(*Base).getSize()) &&
614 "Symbol size cannot extend past the end of its containing block");
615 this->Size = Size;
616 }
617
618 /// Returns the address range of this symbol.
622
623 /// Returns true if this symbol is backed by a zero-fill block.
624 /// This method may only be called on defined symbols.
625 bool isSymbolZeroFill() const { return getBlock().isZeroFill(); }
626
627 /// Returns the content in the underlying block covered by this symbol.
628 /// This method may only be called on defined non-zero-fill symbols.
630 return getBlock().getContent().slice(Offset, Size);
631 }
632
633 /// Get the linkage for this Symbol.
634 Linkage getLinkage() const { return static_cast<Linkage>(L); }
635
636 /// Set the linkage for this Symbol.
638 assert((L == Linkage::Strong || (!Base->isAbsolute() && Name)) &&
639 "Linkage can only be applied to defined named symbols");
640 this->L = static_cast<uint8_t>(L);
641 }
642
643 /// Get the visibility for this Symbol.
644 Scope getScope() const { return static_cast<Scope>(S); }
645
646 /// Set the visibility for this Symbol.
647 void setScope(Scope S) {
648 assert((hasName() || S == Scope::Local) &&
649 "Can not set anonymous symbol to non-local scope");
650 assert((S != Scope::Local || Base->isDefined() || Base->isAbsolute()) &&
651 "Invalid visibility for symbol type");
652 this->S = static_cast<uint8_t>(S);
653 }
654
655 /// Get the target flags of this Symbol.
656 TargetFlagsType getTargetFlags() const { return TargetFlags; }
657
658 /// Set the target flags for this Symbol.
660 assert(Flags <= 1 && "Add more bits to store more than single flag");
661 TargetFlags = Flags;
662 }
663
664 /// Returns true if this is a weakly referenced external symbol.
665 /// This method may only be called on external symbols.
666 bool isWeaklyReferenced() const {
667 assert(isExternal() && "isWeaklyReferenced called on non-external");
668 return WeakRef;
669 }
670
671 /// Set the WeaklyReferenced value for this symbol.
672 /// This method may only be called on external symbols.
673 void setWeaklyReferenced(bool WeakRef) {
674 assert(isExternal() && "setWeaklyReferenced called on non-external");
675 this->WeakRef = WeakRef;
676 }
677
678private:
679 void makeExternal(Addressable &A) {
680 assert(!A.isDefined() && !A.isAbsolute() &&
681 "Attempting to make external with defined or absolute block");
682 Base = &A;
683 Offset = 0;
685 IsLive = 0;
686 // note: Size, Linkage and IsCallable fields left unchanged.
687 }
688
689 void makeAbsolute(Addressable &A) {
690 assert(!A.isDefined() && A.isAbsolute() &&
691 "Attempting to make absolute with defined or external block");
692 Base = &A;
693 Offset = 0;
694 }
695
696 void setBlock(Block &B) { Base = &B; }
697
698 static constexpr uint64_t MaxOffset = (1ULL << 59) - 1;
699
700 orc::SymbolStringPtr Name = nullptr;
701 Addressable *Base = nullptr;
702 uint64_t Offset : 57;
703 uint64_t L : 1;
704 uint64_t S : 2;
705 uint64_t IsLive : 1;
706 uint64_t IsCallable : 1;
707 uint64_t WeakRef : 1;
708 uint64_t TargetFlags : 1;
709 size_t Size = 0;
710};
711
712LLVM_ABI raw_ostream &operator<<(raw_ostream &OS, const Symbol &A);
713
714LLVM_ABI void printEdge(raw_ostream &OS, const Block &B, const Edge &E,
715 StringRef EdgeKindName);
716
717/// Represents an object file section.
718class Section {
719 friend class LinkGraph;
720
721private:
722 Section(StringRef Name, orc::MemProt Prot, SectionOrdinal SecOrdinal)
723 : Name(Name), Prot(Prot), SecOrdinal(SecOrdinal) {}
724
725 using SymbolSet = DenseSet<Symbol *>;
727
728public:
731
734
736
737 // Sections are not movable or copyable.
738 Section(const Section &) = delete;
739 Section &operator=(const Section &) = delete;
740 Section(Section &&) = delete;
741 Section &operator=(Section &&) = delete;
742
743 /// Returns the name of this section.
744 StringRef getName() const { return Name; }
745
746 /// Returns the protection flags for this section.
747 orc::MemProt getMemProt() const { return Prot; }
748
749 /// Set the protection flags for this section.
750 void setMemProt(orc::MemProt Prot) { this->Prot = Prot; }
751
752 /// Get the memory lifetime policy for this section.
753 orc::MemLifetime getMemLifetime() const { return ML; }
754
755 /// Set the memory lifetime policy for this section.
756 void setMemLifetime(orc::MemLifetime ML) { this->ML = ML; }
757
758 /// Returns the ordinal for this section.
759 SectionOrdinal getOrdinal() const { return SecOrdinal; }
760
761 /// Set the ordinal for this section. Ordinals are used to order the layout
762 /// of sections with the same permissions.
763 void setOrdinal(SectionOrdinal SecOrdinal) { this->SecOrdinal = SecOrdinal; }
764
765 /// Returns true if this section is empty (contains no blocks or symbols).
766 bool empty() const { return Blocks.empty(); }
767
768 /// Returns an iterator over the blocks defined in this section.
770 return make_range(Blocks.begin(), Blocks.end());
771 }
772
773 /// Returns an iterator over the blocks defined in this section.
775 return make_range(Blocks.begin(), Blocks.end());
776 }
777
778 /// Returns the number of blocks in this section.
779 BlockSet::size_type blocks_size() const { return Blocks.size(); }
780
781 /// Returns an iterator over the symbols defined in this section.
783 return make_range(Symbols.begin(), Symbols.end());
784 }
785
786 /// Returns an iterator over the symbols defined in this section.
788 return make_range(Symbols.begin(), Symbols.end());
789 }
790
791 /// Return the number of symbols in this section.
792 SymbolSet::size_type symbols_size() const { return Symbols.size(); }
793
794private:
795 void addSymbol(Symbol &Sym) {
796 assert(!Symbols.count(&Sym) && "Symbol is already in this section");
797 Symbols.insert(&Sym);
798 }
799
800 void removeSymbol(Symbol &Sym) {
801 assert(Symbols.count(&Sym) && "symbol is not in this section");
802 Symbols.erase(&Sym);
803 }
804
805 void addBlock(Block &B) {
806 assert(!Blocks.count(&B) && "Block is already in this section");
807 Blocks.insert(&B);
808 }
809
810 void removeBlock(Block &B) {
811 assert(Blocks.count(&B) && "Block is not in this section");
812 Blocks.erase(&B);
813 }
814
815 void transferContentTo(Section &DstSection) {
816 if (&DstSection == this)
817 return;
818 for (auto *S : Symbols)
819 DstSection.addSymbol(*S);
820 for (auto *B : Blocks)
821 DstSection.addBlock(*B);
822 Symbols.clear();
823 Blocks.clear();
824 }
825
826 StringRef Name;
827 orc::MemProt Prot;
829 SectionOrdinal SecOrdinal = 0;
830 BlockSet Blocks;
831 SymbolSet Symbols;
832};
833
834/// Represents a section address range via a pair of Block pointers
835/// to the first and last Blocks in the section.
837public:
838 SectionRange() = default;
839 SectionRange(const Section &Sec) {
840 if (Sec.blocks().empty())
841 return;
842 First = Last = *Sec.blocks().begin();
843 for (auto *B : Sec.blocks()) {
844 if (B->getAddress() < First->getAddress())
845 First = B;
846 if (B->getAddress() > Last->getAddress())
847 Last = B;
848 }
849 }
851 assert((!Last || First) && "First can not be null if end is non-null");
852 return First;
853 }
855 assert((First || !Last) && "Last can not be null if start is non-null");
856 return Last;
857 }
858 bool empty() const {
859 assert((First || !Last) && "Last can not be null if start is non-null");
860 return !First;
861 }
863 return First ? First->getAddress() : orc::ExecutorAddr();
864 }
866 return Last ? Last->getAddress() + Last->getSize() : orc::ExecutorAddr();
867 }
869
873
874private:
875 Block *First = nullptr;
876 Block *Last = nullptr;
877};
878
880private:
883 using AbsoluteSymbolSet = DenseSet<Symbol *>;
884 using BlockSet = DenseSet<Block *>;
885
886 template <typename... ArgTs>
887 Addressable &createAddressable(ArgTs &&... Args) {
888 Addressable *A =
889 reinterpret_cast<Addressable *>(Allocator.Allocate<Addressable>());
890 new (A) Addressable(std::forward<ArgTs>(Args)...);
891 return *A;
892 }
893
894 void destroyAddressable(Addressable &A) {
895 A.~Addressable();
896 Allocator.Deallocate(&A);
897 }
898
899 template <typename... ArgTs> Block &createBlock(ArgTs &&... Args) {
900 Block *B = reinterpret_cast<Block *>(Allocator.Allocate<Block>());
901 new (B) Block(std::forward<ArgTs>(Args)...);
902 B->getSection().addBlock(*B);
903 return *B;
904 }
905
906 void destroyBlock(Block &B) {
907 B.~Block();
908 Allocator.Deallocate(&B);
909 }
910
911 void destroySymbol(Symbol &S) {
912 S.~Symbol();
913 Allocator.Deallocate(&S);
914 }
915
916 static iterator_range<Section::block_iterator> getSectionBlocks(Section &S) {
917 return S.blocks();
918 }
919
921 getSectionConstBlocks(const Section &S) {
922 return S.blocks();
923 }
924
926 getSectionSymbols(Section &S) {
927 return S.symbols();
928 }
929
931 getSectionConstSymbols(const Section &S) {
932 return S.symbols();
933 }
934
935 struct GetExternalSymbolMapEntryValue {
936 Symbol *operator()(ExternalSymbolMap::value_type &KV) const {
937 return KV.second;
938 }
939 };
940
941 struct GetSectionMapEntryValue {
942 Section &operator()(SectionMap::value_type &KV) const { return *KV.second; }
943 };
944
945 struct GetSectionMapEntryConstValue {
946 const Section &operator()(const SectionMap::value_type &KV) const {
947 return *KV.second;
948 }
949 };
950
951public:
954 GetExternalSymbolMapEntryValue>;
956
961
962 template <typename OuterItrT, typename InnerItrT, typename T,
963 iterator_range<InnerItrT> getInnerRange(
964 typename OuterItrT::reference)>
966 : public iterator_facade_base<
967 nested_collection_iterator<OuterItrT, InnerItrT, T, getInnerRange>,
968 std::forward_iterator_tag, T> {
969 public:
971
972 nested_collection_iterator(OuterItrT OuterI, OuterItrT OuterE)
973 : OuterI(OuterI), OuterE(OuterE),
974 InnerI(getInnerBegin(OuterI, OuterE)) {
975 moveToNonEmptyInnerOrEnd();
976 }
977
979 return (OuterI == RHS.OuterI) && (InnerI == RHS.InnerI);
980 }
981
982 T operator*() const {
983 assert(InnerI != getInnerRange(*OuterI).end() && "Dereferencing end?");
984 return *InnerI;
985 }
986
988 ++InnerI;
989 moveToNonEmptyInnerOrEnd();
990 return *this;
991 }
992
993 private:
994 static InnerItrT getInnerBegin(OuterItrT OuterI, OuterItrT OuterE) {
995 return OuterI != OuterE ? getInnerRange(*OuterI).begin() : InnerItrT();
996 }
997
998 void moveToNonEmptyInnerOrEnd() {
999 while (OuterI != OuterE && InnerI == getInnerRange(*OuterI).end()) {
1000 ++OuterI;
1001 InnerI = getInnerBegin(OuterI, OuterE);
1002 }
1003 }
1004
1005 OuterItrT OuterI, OuterE;
1006 InnerItrT InnerI;
1007 };
1008
1011 Symbol *, getSectionSymbols>;
1012
1016 getSectionConstSymbols>;
1017
1020 Block *, getSectionBlocks>;
1021
1025 getSectionConstBlocks>;
1026
1027 using GetEdgeKindNameFunction = const char *(*)(Edge::Kind);
1028
1029 LinkGraph(std::string Name, std::shared_ptr<orc::SymbolStringPool> SSP,
1030 Triple TT, unsigned PointerSize, SubtargetFeatures Features,
1031 GetEdgeKindNameFunction GetEdgeKindName)
1032 : Name(std::move(Name)), SSP(std::move(SSP)), TT(std::move(TT)),
1033 PointerSize(PointerSize), Features(std::move(Features)),
1034 GetEdgeKindName(std::move(GetEdgeKindName)) {}
1035
1036 LinkGraph(const LinkGraph &) = delete;
1037 LinkGraph &operator=(const LinkGraph &) = delete;
1038 LinkGraph(LinkGraph &&) = delete;
1041
1042 /// Returns the name of this graph (usually the name of the original
1043 /// underlying MemoryBuffer).
1044 const std::string &getName() const { return Name; }
1045
1046 /// Returns the target triple for this Graph.
1047 const Triple &getTargetTriple() const { return TT; }
1048
1049 /// Return the subtarget features for this Graph.
1050 const SubtargetFeatures &getFeatures() const { return Features; }
1051
1052 /// Returns the pointer size for use in this graph.
1053 unsigned getPointerSize() const { return PointerSize; }
1054
1055 /// Returns the endianness of content in this graph.
1057 return TT.isLittleEndian() ? endianness::little : endianness::big;
1058 }
1059
1060 const char *getEdgeKindName(Edge::Kind K) const { return GetEdgeKindName(K); }
1061
1062 std::shared_ptr<orc::SymbolStringPool> getSymbolStringPool() { return SSP; }
1063
1064 /// Allocate a mutable buffer of the given size using the LinkGraph's
1065 /// allocator.
1067 return {Allocator.Allocate<char>(Size), Size};
1068 }
1069
1070 /// Allocate a copy of the given string using the LinkGraph's allocator.
1071 /// This can be useful when renaming symbols or adding new content to the
1072 /// graph.
1074 auto *AllocatedBuffer = Allocator.Allocate<char>(Source.size());
1075 llvm::copy(Source, AllocatedBuffer);
1076 return MutableArrayRef<char>(AllocatedBuffer, Source.size());
1077 }
1078
1079 /// Allocate a copy of the given string using the LinkGraph's allocator.
1080 /// This can be useful when renaming symbols or adding new content to the
1081 /// graph.
1082 ///
1083 /// Note: This Twine-based overload requires an extra string copy and an
1084 /// extra heap allocation for large strings. The ArrayRef<char> overload
1085 /// should be preferred where possible.
1087 SmallString<256> TmpBuffer;
1088 auto SourceStr = Source.toStringRef(TmpBuffer);
1089 auto *AllocatedBuffer = Allocator.Allocate<char>(SourceStr.size());
1090 llvm::copy(SourceStr, AllocatedBuffer);
1091 return MutableArrayRef<char>(AllocatedBuffer, SourceStr.size());
1092 }
1093
1094 /// Allocate a copy of the given string using the LinkGraph's allocator
1095 /// and return it as a StringRef.
1096 ///
1097 /// This is a convenience wrapper around allocateContent(Twine) that is
1098 /// handy when creating new symbol names within the graph.
1100 auto Buf = allocateContent(Source);
1101 return {Buf.data(), Buf.size()};
1102 }
1103
1104 /// Allocate a copy of the given string using the LinkGraph's allocator.
1105 ///
1106 /// The allocated string will be terminated with a null character, and the
1107 /// returned MutableArrayRef will include this null character in the last
1108 /// position.
1110 char *AllocatedBuffer = Allocator.Allocate<char>(Source.size() + 1);
1111 llvm::copy(Source, AllocatedBuffer);
1112 AllocatedBuffer[Source.size()] = '\0';
1113 return MutableArrayRef<char>(AllocatedBuffer, Source.size() + 1);
1114 }
1115
1116 /// Allocate a copy of the given string using the LinkGraph's allocator.
1117 ///
1118 /// The allocated string will be terminated with a null character, and the
1119 /// returned MutableArrayRef will include this null character in the last
1120 /// position.
1121 ///
1122 /// Note: This Twine-based overload requires an extra string copy and an
1123 /// extra heap allocation for large strings. The ArrayRef<char> overload
1124 /// should be preferred where possible.
1126 SmallString<256> TmpBuffer;
1127 auto SourceStr = Source.toStringRef(TmpBuffer);
1128 auto *AllocatedBuffer = Allocator.Allocate<char>(SourceStr.size() + 1);
1129 llvm::copy(SourceStr, AllocatedBuffer);
1130 AllocatedBuffer[SourceStr.size()] = '\0';
1131 return MutableArrayRef<char>(AllocatedBuffer, SourceStr.size() + 1);
1132 }
1133
1134 /// Create a section with the given name, protection flags.
1136 assert(!Sections.count(Name) && "Duplicate section name");
1137 std::unique_ptr<Section> Sec(new Section(Name, Prot, Sections.size()));
1138 return *Sections.insert(std::make_pair(Name, std::move(Sec))).first->second;
1139 }
1140
1141 /// Create a content block.
1144 uint64_t AlignmentOffset) {
1145 return createBlock(Parent, Content, Address, Alignment, AlignmentOffset);
1146 }
1147
1148 /// Create a content block with initially mutable data.
1150 MutableArrayRef<char> MutableContent,
1152 uint64_t Alignment,
1153 uint64_t AlignmentOffset) {
1154 return createBlock(Parent, MutableContent, Address, Alignment,
1155 AlignmentOffset);
1156 }
1157
1158 /// Create a content block with initially mutable data of the given size.
1159 /// Content will be allocated via the LinkGraph's allocateBuffer method.
1160 /// By default the memory will be zero-initialized. Passing false for
1161 /// ZeroInitialize will prevent this.
1162 Block &createMutableContentBlock(Section &Parent, size_t ContentSize,
1164 uint64_t Alignment, uint64_t AlignmentOffset,
1165 bool ZeroInitialize = true) {
1166 auto Content = allocateBuffer(ContentSize);
1167 if (ZeroInitialize)
1168 memset(Content.data(), 0, Content.size());
1169 return createBlock(Parent, Content, Address, Alignment, AlignmentOffset);
1170 }
1171
1172 /// Create a zero-fill block.
1175 uint64_t AlignmentOffset) {
1176 return createBlock(Parent, Size, Address, Alignment, AlignmentOffset);
1177 }
1178
1179 /// Returns a BinaryStreamReader for the given block.
1182 reinterpret_cast<const uint8_t *>(B.getContent().data()), B.getSize());
1184 }
1185
1186 /// Returns a BinaryStreamWriter for the given block.
1187 /// This will call getMutableContent to obtain mutable content for the block.
1190 reinterpret_cast<uint8_t *>(B.getMutableContent(*this).data()),
1191 B.getSize());
1193 }
1194
1195 /// Cache type for the splitBlock function.
1196 using SplitBlockCache = std::optional<SmallVector<Symbol *, 8>>;
1197
1198 /// Splits block B into a sequence of smaller blocks.
1199 ///
1200 /// SplitOffsets should be a sequence of ascending offsets in B. The starting
1201 /// offset should be greater than zero, and the final offset less than
1202 /// B.getSize() - 1.
1203 ///
1204 /// The resulting seqeunce of blocks will start with the original block B
1205 /// (truncated to end at the first split offset) followed by newly introduced
1206 /// blocks starting at the subsequent split points.
1207 ///
1208 /// The optional Cache parameter can be used to speed up repeated calls to
1209 /// splitBlock for blocks within a single Section. If the value is None then
1210 /// the cache will be treated as uninitialized and splitBlock will populate
1211 /// it. Otherwise it is assumed to contain the list of Symbols pointing at B,
1212 /// sorted in descending order of offset.
1213 ///
1214 ///
1215 /// Notes:
1216 ///
1217 /// 1. splitBlock must be used with care. Splitting a block may cause
1218 /// incoming edges to become invalid if the edge target subexpression
1219 /// points outside the bounds of the newly split target block (E.g. an
1220 /// edge 'S + 10 : Pointer64' where S points to a newly split block
1221 /// whose size is less than 10). No attempt is made to detect invalidation
1222 /// of incoming edges, as in general this requires context that the
1223 /// LinkGraph does not have. Clients are responsible for ensuring that
1224 /// splitBlock is not used in a way that invalidates edges.
1225 ///
1226 /// 2. The newly introduced blocks will have new ordinals that will be higher
1227 /// than any other ordinals in the section. Clients are responsible for
1228 /// re-assigning block ordinals to restore a compatible order if needed.
1229 ///
1230 /// 3. The cache is not automatically updated if new symbols are introduced
1231 /// between calls to splitBlock. Any newly introduced symbols may be
1232 /// added to the cache manually (descending offset order must be
1233 /// preserved), or the cache can be set to None and rebuilt by
1234 /// splitBlock on the next call.
1235 template <typename SplitOffsetRange>
1236 std::vector<Block *> splitBlock(Block &B, SplitOffsetRange &&SplitOffsets,
1237 LinkGraph::SplitBlockCache *Cache = nullptr) {
1238 std::vector<Block *> Blocks;
1239 Blocks.push_back(&B);
1240
1241 if (std::empty(SplitOffsets))
1242 return Blocks;
1243
1244 // Special case zero-fill:
1245 if (B.isZeroFill()) {
1246 size_t OrigSize = B.getSize();
1247 for (Edge::OffsetT Offset : SplitOffsets) {
1248 assert(Offset > 0 && Offset < B.getSize() &&
1249 "Split offset must be inside block content");
1250 Blocks.back()->setZeroFillSize(
1251 Offset - (Blocks.back()->getAddress() - B.getAddress()));
1252 Blocks.push_back(&createZeroFillBlock(
1253 B.getSection(), B.getSize(), B.getAddress() + Offset,
1254 B.getAlignment(),
1255 (B.getAlignmentOffset() + Offset) % B.getAlignment()));
1256 }
1257 Blocks.back()->setZeroFillSize(
1258 OrigSize - (Blocks.back()->getAddress() - B.getAddress()));
1259 return Blocks;
1260 }
1261
1262 // Handle content blocks. We'll just create the blocks with their starting
1263 // address and no content here. The bulk of the work is deferred to
1264 // splitBlockImpl.
1265 for (Edge::OffsetT Offset : SplitOffsets) {
1266 assert(Offset > 0 && Offset < B.getSize() &&
1267 "Split offset must be inside block content");
1268 Blocks.push_back(&createContentBlock(
1269 B.getSection(), ArrayRef<char>(), B.getAddress() + Offset,
1270 B.getAlignment(),
1271 (B.getAlignmentOffset() + Offset) % B.getAlignment()));
1272 }
1273
1274 return splitBlockImpl(std::move(Blocks), Cache);
1275 }
1276
1277 /// Intern the given string in the LinkGraph's SymbolStringPool.
1279 return SSP->intern(SymbolName);
1280 }
1281
1282 /// Add an external symbol.
1283 /// Some formats (e.g. ELF) allow Symbols to have sizes. For Symbols whose
1284 /// size is not known, you should substitute '0'.
1285 /// The IsWeaklyReferenced argument determines whether the symbol must be
1286 /// present during lookup: Externals that are strongly referenced must be
1287 /// found or an error will be emitted. Externals that are weakly referenced
1288 /// are permitted to be undefined, in which case they are assigned an address
1289 /// of 0.
1292 bool IsWeaklyReferenced) {
1293 assert(!ExternalSymbols.contains(orc::NonOwningSymbolStringPtr(Name)) &&
1294 "Duplicate external symbol");
1295 auto &Sym = Symbol::constructExternal(
1296 Allocator, createAddressable(orc::ExecutorAddr(), false),
1297 std::move(Name), Size, Linkage::Strong, IsWeaklyReferenced);
1298 ExternalSymbols.insert(
1299 {orc::NonOwningSymbolStringPtr(Sym.getName()), &Sym});
1300 return Sym;
1301 }
1302
1304 bool IsWeaklyReferenced) {
1305 return addExternalSymbol(SSP->intern(Name), Size, IsWeaklyReferenced);
1306 }
1307
1308 /// Add an absolute symbol.
1312 bool IsLive) {
1313 assert((S == Scope::Local || llvm::none_of(AbsoluteSymbols,
1314 [&](const Symbol *Sym) {
1315 return Sym->getName() == Name;
1316 })) &&
1317 "Duplicate absolute symbol");
1318 auto &Sym = Symbol::constructAbsolute(Allocator, createAddressable(Address),
1319 std::move(Name), Size, L, S, IsLive);
1320 AbsoluteSymbols.insert(&Sym);
1321 return Sym;
1322 }
1323
1326 bool IsLive) {
1327
1328 return addAbsoluteSymbol(SSP->intern(Name), Address, Size, L, S, IsLive);
1329 }
1330
1331 /// Add an anonymous symbol.
1333 orc::ExecutorAddrDiff Size, bool IsCallable,
1334 bool IsLive) {
1335 auto &Sym = Symbol::constructAnonDef(Allocator, Content, Offset, Size,
1336 IsCallable, IsLive);
1337 Content.getSection().addSymbol(Sym);
1338 return Sym;
1339 }
1340
1341 /// Add a named symbol.
1344 Linkage L, Scope S, bool IsCallable, bool IsLive) {
1345 return addDefinedSymbol(Content, Offset, SSP->intern(Name), Size, L, S,
1346 IsCallable, IsLive);
1347 }
1348
1352 bool IsCallable, bool IsLive) {
1354 [&](const Symbol *Sym) {
1355 return Sym->getName() == Name;
1356 })) &&
1357 "Duplicate defined symbol");
1358 auto &Sym =
1359 Symbol::constructNamedDef(Allocator, Content, Offset, std::move(Name),
1360 Size, L, S, IsLive, IsCallable);
1361 Content.getSection().addSymbol(Sym);
1362 return Sym;
1363 }
1364
1366 return make_range(
1367 section_iterator(Sections.begin(), GetSectionMapEntryValue()),
1368 section_iterator(Sections.end(), GetSectionMapEntryValue()));
1369 }
1370
1372 return make_range(
1373 const_section_iterator(Sections.begin(),
1374 GetSectionMapEntryConstValue()),
1375 const_section_iterator(Sections.end(), GetSectionMapEntryConstValue()));
1376 }
1377
1378 size_t sections_size() const { return Sections.size(); }
1379
1380 /// Returns the section with the given name if it exists, otherwise returns
1381 /// null.
1383 auto I = Sections.find(Name);
1384 if (I == Sections.end())
1385 return nullptr;
1386 return I->second.get();
1387 }
1388
1390 auto Secs = sections();
1391 return make_range(block_iterator(Secs.begin(), Secs.end()),
1392 block_iterator(Secs.end(), Secs.end()));
1393 }
1394
1396 auto Secs = sections();
1397 return make_range(const_block_iterator(Secs.begin(), Secs.end()),
1398 const_block_iterator(Secs.end(), Secs.end()));
1399 }
1400
1402 return make_range(
1403 external_symbol_iterator(ExternalSymbols.begin(),
1404 GetExternalSymbolMapEntryValue()),
1405 external_symbol_iterator(ExternalSymbols.end(),
1406 GetExternalSymbolMapEntryValue()));
1407 }
1408
1409 /// Returns the external symbol with the given name if one exists, otherwise
1410 /// returns nullptr.
1412 for (auto *Sym : external_symbols())
1413 if (Sym->getName() == Name)
1414 return Sym;
1415 return nullptr;
1416 }
1417
1419 return make_range(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1420 }
1421
1423 for (auto *Sym : absolute_symbols())
1424 if (Sym->getName() == Name)
1425 return Sym;
1426 return nullptr;
1427 }
1428
1430 auto Secs = sections();
1431 return make_range(defined_symbol_iterator(Secs.begin(), Secs.end()),
1432 defined_symbol_iterator(Secs.end(), Secs.end()));
1433 }
1434
1436 auto Secs = sections();
1437 return make_range(const_defined_symbol_iterator(Secs.begin(), Secs.end()),
1438 const_defined_symbol_iterator(Secs.end(), Secs.end()));
1439 }
1440
1441 /// Returns the defined symbol with the given name if one exists, otherwise
1442 /// returns nullptr.
1444 for (auto *Sym : defined_symbols())
1445 if (Sym->hasName() && Sym->getName() == Name)
1446 return Sym;
1447 return nullptr;
1448 }
1449
1450 /// Make the given symbol external (must not already be external).
1451 ///
1452 /// Symbol size, linkage and callability will be left unchanged. Symbol scope
1453 /// will be set to Default, and offset will be reset to 0.
1455 assert(!Sym.isExternal() && "Symbol is already external");
1456 if (Sym.isAbsolute()) {
1457 assert(AbsoluteSymbols.count(&Sym) &&
1458 "Sym is not in the absolute symbols set");
1459 assert(Sym.getOffset() == 0 && "Absolute not at offset 0");
1460 AbsoluteSymbols.erase(&Sym);
1461 auto &A = Sym.getAddressable();
1462 A.setAbsolute(false);
1463 A.setAddress(orc::ExecutorAddr());
1464 } else {
1465 assert(Sym.isDefined() && "Sym is not a defined symbol");
1466 Section &Sec = Sym.getSection();
1467 Sec.removeSymbol(Sym);
1468 Sym.makeExternal(createAddressable(orc::ExecutorAddr(), false));
1469 }
1470 ExternalSymbols.insert(
1471 {orc::NonOwningSymbolStringPtr(Sym.getName()), &Sym});
1472 }
1473
1474 /// Make the given symbol an absolute with the given address (must not already
1475 /// be absolute).
1476 ///
1477 /// The symbol's size, linkage, and callability, and liveness will be left
1478 /// unchanged, and its offset will be reset to 0.
1479 ///
1480 /// If the symbol was external then its scope will be set to local, otherwise
1481 /// it will be left unchanged.
1483 assert(!Sym.isAbsolute() && "Symbol is already absolute");
1484 if (Sym.isExternal()) {
1485 assert(ExternalSymbols.contains(
1487 "Sym is not in the absolute symbols set");
1488 assert(Sym.getOffset() == 0 && "External is not at offset 0");
1489 ExternalSymbols.erase(orc::NonOwningSymbolStringPtr(Sym.getName()));
1490 auto &A = Sym.getAddressable();
1491 A.setAbsolute(true);
1492 A.setAddress(Address);
1494 } else {
1495 assert(Sym.isDefined() && "Sym is not a defined symbol");
1496 Section &Sec = Sym.getSection();
1497 Sec.removeSymbol(Sym);
1498 Sym.makeAbsolute(createAddressable(Address));
1499 }
1500 AbsoluteSymbols.insert(&Sym);
1501 }
1502
1503 /// Turn an absolute or external symbol into a defined one by attaching it to
1504 /// a block. Symbol must not already be defined.
1507 bool IsLive) {
1508 assert(!Sym.isDefined() && "Sym is already a defined symbol");
1509 if (Sym.isAbsolute()) {
1510 assert(AbsoluteSymbols.count(&Sym) &&
1511 "Symbol is not in the absolutes set");
1512 AbsoluteSymbols.erase(&Sym);
1513 } else {
1514 assert(ExternalSymbols.contains(
1516 "Symbol is not in the externals set");
1517 ExternalSymbols.erase(orc::NonOwningSymbolStringPtr(Sym.getName()));
1518 }
1519 Addressable &OldBase = *Sym.Base;
1520 Sym.setBlock(Content);
1521 Sym.setOffset(Offset);
1522 Sym.setSize(Size);
1523 Sym.setLinkage(L);
1524 Sym.setScope(S);
1525 Sym.setLive(IsLive);
1526 Content.getSection().addSymbol(Sym);
1527 destroyAddressable(OldBase);
1528 }
1529
1530 /// Transfer a defined symbol from one block to another.
1531 ///
1532 /// The symbol's offset within DestBlock is set to NewOffset.
1533 ///
1534 /// If ExplicitNewSize is given as None then the size of the symbol will be
1535 /// checked and auto-truncated to at most the size of the remainder (from the
1536 /// given offset) of the size of the new block.
1537 ///
1538 /// All other symbol attributes are unchanged.
1539 void
1541 orc::ExecutorAddrDiff NewOffset,
1542 std::optional<orc::ExecutorAddrDiff> ExplicitNewSize) {
1543 auto &OldSection = Sym.getSection();
1544 Sym.setBlock(DestBlock);
1545 Sym.setOffset(NewOffset);
1546 if (ExplicitNewSize)
1547 Sym.setSize(*ExplicitNewSize);
1548 else {
1549 auto RemainingBlockSize = DestBlock.getSize() - NewOffset;
1550 if (Sym.getSize() > RemainingBlockSize)
1551 Sym.setSize(RemainingBlockSize);
1552 }
1553 if (&DestBlock.getSection() != &OldSection) {
1554 OldSection.removeSymbol(Sym);
1555 DestBlock.getSection().addSymbol(Sym);
1556 }
1557 }
1558
1559 /// Transfers the given Block and all Symbols pointing to it to the given
1560 /// Section.
1561 ///
1562 /// No attempt is made to check compatibility of the source and destination
1563 /// sections. Blocks may be moved between sections with incompatible
1564 /// permissions (e.g. from data to text). The client is responsible for
1565 /// ensuring that this is safe.
1566 void transferBlock(Block &B, Section &NewSection) {
1567 auto &OldSection = B.getSection();
1568 if (&OldSection == &NewSection)
1569 return;
1570 SmallVector<Symbol *> AttachedSymbols;
1571 for (auto *S : OldSection.symbols())
1572 if (&S->getBlock() == &B)
1573 AttachedSymbols.push_back(S);
1574 for (auto *S : AttachedSymbols) {
1575 OldSection.removeSymbol(*S);
1576 NewSection.addSymbol(*S);
1577 }
1578 OldSection.removeBlock(B);
1579 NewSection.addBlock(B);
1580 }
1581
1582 /// Move all blocks and symbols from the source section to the destination
1583 /// section.
1584 ///
1585 /// If PreserveSrcSection is true (or SrcSection and DstSection are the same)
1586 /// then SrcSection is preserved, otherwise it is removed (the default).
1587 void mergeSections(Section &DstSection, Section &SrcSection,
1588 bool PreserveSrcSection = false) {
1589 if (&DstSection == &SrcSection)
1590 return;
1591 for (auto *B : SrcSection.blocks())
1592 B->setSection(DstSection);
1593 SrcSection.transferContentTo(DstSection);
1594 if (!PreserveSrcSection)
1595 removeSection(SrcSection);
1596 }
1597
1598 /// Removes an external symbol. Also removes the underlying Addressable.
1600 assert(!Sym.isDefined() && !Sym.isAbsolute() &&
1601 "Sym is not an external symbol");
1602 assert(ExternalSymbols.contains(
1604 "Symbol is not in the externals set");
1605 ExternalSymbols.erase(orc::NonOwningSymbolStringPtr(Sym.getName()));
1606 Addressable &Base = *Sym.Base;
1608 [&](Symbol *AS) { return AS->Base == &Base; }) &&
1609 "Base addressable still in use");
1610 destroySymbol(Sym);
1611 destroyAddressable(Base);
1612 }
1613
1614 /// Remove an absolute symbol. Also removes the underlying Addressable.
1616 assert(!Sym.isDefined() && Sym.isAbsolute() &&
1617 "Sym is not an absolute symbol");
1618 assert(AbsoluteSymbols.count(&Sym) &&
1619 "Symbol is not in the absolute symbols set");
1620 AbsoluteSymbols.erase(&Sym);
1621 Addressable &Base = *Sym.Base;
1623 [&](Symbol *AS) { return AS->Base == &Base; }) &&
1624 "Base addressable still in use");
1625 destroySymbol(Sym);
1626 destroyAddressable(Base);
1627 }
1628
1629 /// Removes defined symbols. Does not remove the underlying block.
1631 assert(Sym.isDefined() && "Sym is not a defined symbol");
1632 Sym.getSection().removeSymbol(Sym);
1633 destroySymbol(Sym);
1634 }
1635
1636 /// Remove a block. The block reference is defunct after calling this
1637 /// function and should no longer be used.
1639 assert(llvm::none_of(B.getSection().symbols(),
1640 [&](const Symbol *Sym) {
1641 return &Sym->getBlock() == &B;
1642 }) &&
1643 "Block still has symbols attached");
1644 B.getSection().removeBlock(B);
1645 destroyBlock(B);
1646 }
1647
1648 /// Remove a section. The section reference is defunct after calling this
1649 /// function and should no longer be used.
1651 assert(Sections.count(Sec.getName()) && "Section not found");
1652 assert(Sections.find(Sec.getName())->second.get() == &Sec &&
1653 "Section map entry invalid");
1654 Sections.erase(Sec.getName());
1655 }
1656
1657 /// Accessor for the AllocActions object for this graph. This can be used to
1658 /// register allocation action calls prior to finalization.
1659 ///
1660 /// Accessing this object after finalization will result in undefined
1661 /// behavior.
1663
1664 /// Dump the graph.
1665 LLVM_ABI void dump(raw_ostream &OS);
1666
1667private:
1668 LLVM_ABI std::vector<Block *> splitBlockImpl(std::vector<Block *> Blocks,
1669 SplitBlockCache *Cache);
1670
1671 // Put the BumpPtrAllocator first so that we don't free any of the underlying
1672 // memory until the Symbol/Addressable destructors have been run.
1674
1675 std::string Name;
1676 std::shared_ptr<orc::SymbolStringPool> SSP;
1677 Triple TT;
1678 unsigned PointerSize;
1679 SubtargetFeatures Features;
1680 GetEdgeKindNameFunction GetEdgeKindName = nullptr;
1682 ExternalSymbolMap ExternalSymbols;
1683 AbsoluteSymbolSet AbsoluteSymbols;
1685};
1686
1688 if (!ContentMutable)
1689 setMutableContent(G.allocateContent({Data, Size}));
1690 return MutableArrayRef<char>(const_cast<char *>(Data), Size);
1691}
1692
1693/// Enables easy lookup of blocks by addresses.
1695public:
1696 using AddrToBlockMap = std::map<orc::ExecutorAddr, Block *>;
1697 using const_iterator = AddrToBlockMap::const_iterator;
1698
1699 /// A block predicate that always adds all blocks.
1700 static bool includeAllBlocks(const Block &B) { return true; }
1701
1702 /// A block predicate that always includes blocks with non-null addresses.
1703 static bool includeNonNull(const Block &B) { return !!B.getAddress(); }
1704
1705 BlockAddressMap() = default;
1706
1707 /// Add a block to the map. Returns an error if the block overlaps with any
1708 /// existing block.
1709 template <typename PredFn = decltype(includeAllBlocks)>
1711 if (!Pred(B))
1712 return Error::success();
1713
1714 auto I = AddrToBlock.upper_bound(B.getAddress());
1715
1716 // If we're not at the end of the map, check for overlap with the next
1717 // element.
1718 if (I != AddrToBlock.end()) {
1719 if (B.getAddress() + B.getSize() > I->second->getAddress())
1720 return overlapError(B, *I->second);
1721 }
1722
1723 // If we're not at the start of the map, check for overlap with the previous
1724 // element.
1725 if (I != AddrToBlock.begin()) {
1726 auto &PrevBlock = *std::prev(I)->second;
1727 if (PrevBlock.getAddress() + PrevBlock.getSize() > B.getAddress())
1728 return overlapError(B, PrevBlock);
1729 }
1730
1731 AddrToBlock.insert(I, std::make_pair(B.getAddress(), &B));
1732 return Error::success();
1733 }
1734
1735 /// Add a block to the map without checking for overlap with existing blocks.
1736 /// The client is responsible for ensuring that the block added does not
1737 /// overlap with any existing block.
1738 void addBlockWithoutChecking(Block &B) { AddrToBlock[B.getAddress()] = &B; }
1739
1740 /// Add a range of blocks to the map. Returns an error if any block in the
1741 /// range overlaps with any other block in the range, or with any existing
1742 /// block in the map.
1743 template <typename BlockPtrRange,
1744 typename PredFn = decltype(includeAllBlocks)>
1745 Error addBlocks(BlockPtrRange &&Blocks, PredFn Pred = includeAllBlocks) {
1746 for (auto *B : Blocks)
1747 if (auto Err = addBlock(*B, Pred))
1748 return Err;
1749 return Error::success();
1750 }
1751
1752 /// Add a range of blocks to the map without checking for overlap with
1753 /// existing blocks. The client is responsible for ensuring that the block
1754 /// added does not overlap with any existing block.
1755 template <typename BlockPtrRange>
1756 void addBlocksWithoutChecking(BlockPtrRange &&Blocks) {
1757 for (auto *B : Blocks)
1759 }
1760
1761 /// Iterates over (Address, Block*) pairs in ascending order of address.
1762 const_iterator begin() const { return AddrToBlock.begin(); }
1763 const_iterator end() const { return AddrToBlock.end(); }
1764
1765 /// Returns the block starting at the given address, or nullptr if no such
1766 /// block exists.
1768 auto I = AddrToBlock.find(Addr);
1769 if (I == AddrToBlock.end())
1770 return nullptr;
1771 return I->second;
1772 }
1773
1774 /// Returns the block covering the given address, or nullptr if no such block
1775 /// exists.
1777 auto I = AddrToBlock.upper_bound(Addr);
1778 if (I == AddrToBlock.begin())
1779 return nullptr;
1780 auto *B = std::prev(I)->second;
1781 if (Addr < B->getAddress() + B->getSize())
1782 return B;
1783 return nullptr;
1784 }
1785
1786private:
1787 Error overlapError(Block &NewBlock, Block &ExistingBlock) {
1788 auto NewBlockEnd = NewBlock.getAddress() + NewBlock.getSize();
1789 auto ExistingBlockEnd =
1790 ExistingBlock.getAddress() + ExistingBlock.getSize();
1792 "Block at " +
1793 formatv("{0:x16} -- {1:x16}", NewBlock.getAddress().getValue(),
1794 NewBlockEnd.getValue()) +
1795 " overlaps " +
1796 formatv("{0:x16} -- {1:x16}", ExistingBlock.getAddress().getValue(),
1797 ExistingBlockEnd.getValue()));
1798 }
1799
1800 AddrToBlockMap AddrToBlock;
1801};
1802
1803/// A map of addresses to Symbols.
1805public:
1807
1808 /// Add a symbol to the SymbolAddressMap.
1809 void addSymbol(Symbol &Sym) {
1810 AddrToSymbols[Sym.getAddress()].push_back(&Sym);
1811 }
1812
1813 /// Add all symbols in a given range to the SymbolAddressMap.
1814 template <typename SymbolPtrCollection>
1815 void addSymbols(SymbolPtrCollection &&Symbols) {
1816 for (auto *Sym : Symbols)
1817 addSymbol(*Sym);
1818 }
1819
1820 /// Returns the list of symbols that start at the given address, or nullptr if
1821 /// no such symbols exist.
1823 auto I = AddrToSymbols.find(Addr);
1824 if (I == AddrToSymbols.end())
1825 return nullptr;
1826 return &I->second;
1827 }
1828
1829private:
1830 std::map<orc::ExecutorAddr, SymbolVector> AddrToSymbols;
1831};
1832
1833/// A function for mutating LinkGraphs.
1835
1836/// A list of LinkGraph passes.
1837using LinkGraphPassList = std::vector<LinkGraphPassFunction>;
1838
1839/// An LinkGraph pass configuration, consisting of a list of pre-prune,
1840/// post-prune, and post-fixup passes.
1842
1843 /// Pre-prune passes.
1844 ///
1845 /// These passes are called on the graph after it is built, and before any
1846 /// symbols have been pruned. Graph nodes still have their original vmaddrs.
1847 ///
1848 /// Notable use cases: Marking symbols live or should-discard.
1850
1851 /// Post-prune passes.
1852 ///
1853 /// These passes are called on the graph after dead stripping, but before
1854 /// memory is allocated or nodes assigned their final addresses.
1855 ///
1856 /// Notable use cases: Building GOT, stub, and TLV symbols.
1858
1859 /// Post-allocation passes.
1860 ///
1861 /// These passes are called on the graph after memory has been allocated and
1862 /// defined nodes have been assigned their final addresses, but before the
1863 /// context has been notified of these addresses. At this point externals
1864 /// have not been resolved, and symbol content has not yet been copied into
1865 /// working memory.
1866 ///
1867 /// Notable use cases: Setting up data structures associated with addresses
1868 /// of defined symbols (e.g. a mapping of __dso_handle to JITDylib* for the
1869 /// JIT runtime) -- using a PostAllocationPass for this ensures that the
1870 /// data structures are in-place before any query for resolved symbols
1871 /// can complete.
1873
1874 /// Pre-fixup passes.
1875 ///
1876 /// These passes are called on the graph after memory has been allocated,
1877 /// content copied into working memory, and all nodes (including externals)
1878 /// have been assigned their final addresses, but before any fixups have been
1879 /// applied.
1880 ///
1881 /// Notable use cases: Late link-time optimizations like GOT and stub
1882 /// elimination.
1884
1885 /// Post-fixup passes.
1886 ///
1887 /// These passes are called on the graph after block contents has been copied
1888 /// to working memory, and fixups applied. Blocks have been updated to point
1889 /// to their fixed up content.
1890 ///
1891 /// Notable use cases: Testing and validation.
1893};
1894
1895/// Flags for symbol lookup.
1896///
1897/// FIXME: These basically duplicate orc::SymbolLookupFlags -- We should merge
1898/// the two types once we have an OrcSupport library.
1900
1901LLVM_ABI raw_ostream &operator<<(raw_ostream &OS, const SymbolLookupFlags &LF);
1902
1903/// A map of symbol names to resolved addresses.
1906
1907/// A function object to call with a resolved symbol map (See AsyncLookupResult)
1908/// or an error if resolution failed.
1910public:
1912 virtual void run(Expected<AsyncLookupResult> LR) = 0;
1913
1914private:
1915 virtual void anchor();
1916};
1917
1918/// Create a lookup continuation from a function object.
1919template <typename Continuation>
1920std::unique_ptr<JITLinkAsyncLookupContinuation>
1921createLookupContinuation(Continuation Cont) {
1922
1923 class Impl final : public JITLinkAsyncLookupContinuation {
1924 public:
1925 Impl(Continuation C) : C(std::move(C)) {}
1926 void run(Expected<AsyncLookupResult> LR) override { C(std::move(LR)); }
1927
1928 private:
1929 Continuation C;
1930 };
1931
1932 return std::make_unique<Impl>(std::move(Cont));
1933}
1934
1935/// Holds context for a single jitLink invocation.
1937public:
1939
1940 /// Create a JITLinkContext.
1941 JITLinkContext(const JITLinkDylib *JD) : JD(JD) {}
1942
1943 /// Destroy a JITLinkContext.
1945
1946 /// Return the JITLinkDylib that this link is targeting, if any.
1947 const JITLinkDylib *getJITLinkDylib() const { return JD; }
1948
1949 /// Return the MemoryManager to be used for this link.
1951
1952 /// Notify this context that linking failed.
1953 /// Called by JITLink if linking cannot be completed.
1954 virtual void notifyFailed(Error Err) = 0;
1955
1956 /// Called by JITLink to resolve external symbols. This method is passed a
1957 /// lookup continutation which it must call with a result to continue the
1958 /// linking process.
1959 virtual void lookup(const LookupMap &Symbols,
1960 std::unique_ptr<JITLinkAsyncLookupContinuation> LC) = 0;
1961
1962 /// Called by JITLink once all defined symbols in the graph have been assigned
1963 /// their final memory locations in the target process. At this point the
1964 /// LinkGraph can be inspected to build a symbol table, however the block
1965 /// content will not generally have been copied to the target location yet.
1966 ///
1967 /// If the client detects an error in the LinkGraph state (e.g. unexpected or
1968 /// missing symbols) they may return an error here. The error will be
1969 /// propagated to notifyFailed and the linker will bail out.
1971
1972 /// Called by JITLink to notify the context that the object has been
1973 /// finalized (i.e. emitted to memory and memory permissions set). If all of
1974 /// this objects dependencies have also been finalized then the code is ready
1975 /// to run.
1977
1978 /// Called by JITLink prior to linking to determine whether default passes for
1979 /// the target should be added. The default implementation returns true.
1980 /// If subclasses override this method to return false for any target then
1981 /// they are required to fully configure the pass pipeline for that target.
1982 virtual bool shouldAddDefaultTargetPasses(const Triple &TT) const;
1983
1984 /// Returns the mark-live pass to be used for this link. If no pass is
1985 /// returned (the default) then the target-specific linker implementation will
1986 /// choose a conservative default (usually marking all symbols live).
1987 /// This function is only called if shouldAddDefaultTargetPasses returns true,
1988 /// otherwise the JITContext is responsible for adding a mark-live pass in
1989 /// modifyPassConfig.
1990 virtual LinkGraphPassFunction getMarkLivePass(const Triple &TT) const;
1991
1992 /// Called by JITLink to modify the pass pipeline prior to linking.
1993 /// The default version performs no modification.
1995
1996private:
1997 const JITLinkDylib *JD = nullptr;
1998};
1999
2000/// Marks all symbols in a graph live. This can be used as a default,
2001/// conservative mark-live implementation.
2003
2004/// Create an out of range error for the given edge in the given block.
2006 const Edge &E);
2007
2009 int N, const Edge &E);
2010
2011/// Creates a new pointer block in the given section and returns an
2012/// Anonymous symbol pointing to it.
2013///
2014/// The pointer block will have the following default values:
2015/// alignment: PointerSize
2016/// alignment-offset: 0
2017/// address: highest allowable
2019 unique_function<Symbol &(LinkGraph &G, Section &PointerSection,
2020 Symbol *InitialTarget, uint64_t InitialAddend)>;
2021
2022/// Get target-specific AnonymousPointerCreator
2024
2025/// Create a jump stub that jumps via the pointer at the given symbol and
2026/// an anonymous symbol pointing to it. Return the anonymous symbol.
2027///
2028/// The stub block will be created by createPointerJumpStubBlock.
2030 LinkGraph &G, Section &StubSection, Symbol &PointerSymbol)>;
2031
2032/// Get target-specific PointerJumpStubCreator
2034
2035/// Base case for edge-visitors where the visitor-list is empty.
2036inline void visitEdge(LinkGraph &G, Block *B, Edge &E) {}
2037
2038/// Applies the first visitor in the list to the given edge. If the visitor's
2039/// visitEdge method returns true then we return immediately, otherwise we
2040/// apply the next visitor.
2041template <typename VisitorT, typename... VisitorTs>
2042void visitEdge(LinkGraph &G, Block *B, Edge &E, VisitorT &&V,
2043 VisitorTs &&...Vs) {
2044 if (!V.visitEdge(G, B, E))
2045 visitEdge(G, B, E, std::forward<VisitorTs>(Vs)...);
2046}
2047
2048/// For each edge in the given graph, apply a list of visitors to the edge,
2049/// stopping when the first visitor's visitEdge method returns true.
2050///
2051/// Only visits edges that were in the graph at call time: if any visitor
2052/// adds new edges those will not be visited. Visitors are not allowed to
2053/// remove edges (though they can change their kind, target, and addend).
2054template <typename... VisitorTs>
2055void visitExistingEdges(LinkGraph &G, VisitorTs &&...Vs) {
2056 // We may add new blocks during this process, but we don't want to iterate
2057 // over them, so build a worklist.
2058 std::vector<Block *> Worklist(G.blocks().begin(), G.blocks().end());
2059
2060 for (auto *B : Worklist)
2061 for (auto &E : B->edges())
2062 visitEdge(G, B, E, std::forward<VisitorTs>(Vs)...);
2063}
2064
2065/// Create a LinkGraph from the given object buffer.
2066///
2067/// Note: The graph does not take ownership of the underlying buffer, nor copy
2068/// its contents. The caller is responsible for ensuring that the object buffer
2069/// outlives the graph.
2072 std::shared_ptr<orc::SymbolStringPool> SSP);
2073
2074/// Create a \c LinkGraph defining the given absolute symbols.
2075LLVM_ABI std::unique_ptr<LinkGraph>
2076absoluteSymbolsLinkGraph(Triple TT, std::shared_ptr<orc::SymbolStringPool> SSP,
2077 orc::SymbolMap Symbols);
2078
2079/// Link the given graph.
2080LLVM_ABI void link(std::unique_ptr<LinkGraph> G,
2081 std::unique_ptr<JITLinkContext> Ctx);
2082
2083} // end namespace jitlink
2084} // end namespace llvm
2085
2086#endif // LLVM_EXECUTIONENGINE_JITLINK_JITLINK_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
DXIL Finalize Linkage
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
static void addSymbol(Object &Obj, const NewSymbolInfo &SymInfo, uint8_t DefaultVisibility)
static void makeAbsolute(vfs::FileSystem &VFS, SmallVectorImpl< char > &Path)
Make Path absolute.
This file provides a collection of function (or more generally, callable) type erasure utilities supp...
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define T
Basic Register Allocator
SmallPtrSet< BasicBlock *, 0 > BlockSet
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
static Split data
Value * RHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
const T * data() const
Definition ArrayRef.h:138
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
Provides read only access to a subclass of BinaryStream.
Provides write only access to a subclass of WritableBinaryStream.
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:683
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Base class for user error types.
Definition Error.h:354
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Manages the enabling and disabling of subtarget specific features.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool erase(const ValueT &V)
Definition DenseSet.h:97
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition iterator.h:80
A range adaptor for a pair of iterators.
IteratorT begin() const
Represents an address in the executor process.
uint64_t getValue() const
Non-owning SymbolStringPool entry pointer.
Base class for both owning and non-owning symbol-string ptrs.
Pointer to a pooled string representing a symbol name.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
unique_function is a type-erasing functor similar to std::function.
std::vector< AllocActionCallPair > AllocActions
A vector of allocation actions to be run for this allocation.
MemProt
Describes Read/Write/Exec permissions for memory.
Definition MemoryFlags.h:27
uint64_t ExecutorAddrDiff
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
MemLifetime
Describes a memory lifetime policy for memory to be allocated by a JITLinkMemoryManager.
Definition MemoryFlags.h:75
@ Standard
Standard memory should be allocated by the allocator and then deallocated when the deallocate method ...
Definition MemoryFlags.h:78
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:552
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
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:1933
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:390
endianness
Definition bit.h:71
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define N
Represents an address range in the exceutor process.