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