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 Triple TT, SubtargetFeatures Features,
1011 GetEdgeKindNameFunction GetEdgeKindName)
1012 : Name(std::move(Name)), SSP(std::move(SSP)), TT(std::move(TT)),
1013 Features(std::move(Features)),
1014 GetEdgeKindName(std::move(GetEdgeKindName)) {
1015 assert(!(Triple::getArchPointerBitWidth(this->TT.getArch()) % 8) &&
1016 "Arch bitwidth is not a multiple of 8");
1017 }
1018
1019 LinkGraph(const LinkGraph &) = delete;
1020 LinkGraph &operator=(const LinkGraph &) = delete;
1021 LinkGraph(LinkGraph &&) = delete;
1023 ~LinkGraph();
1024
1025 /// Returns the name of this graph (usually the name of the original
1026 /// underlying MemoryBuffer).
1027 const std::string &getName() const { return Name; }
1028
1029 /// Returns the target triple for this Graph.
1030 const Triple &getTargetTriple() const { return TT; }
1031
1032 /// Return the subtarget features for this Graph.
1033 const SubtargetFeatures &getFeatures() const { return Features; }
1034
1035 /// Returns the pointer size for use in this graph.
1036 unsigned getPointerSize() const { return TT.getArchPointerBitWidth() / 8; }
1037
1038 /// Returns the endianness of content in this graph.
1041 }
1042
1043 const char *getEdgeKindName(Edge::Kind K) const { return GetEdgeKindName(K); }
1044
1045 std::shared_ptr<orc::SymbolStringPool> getSymbolStringPool() { return SSP; }
1046
1047 /// Allocate a mutable buffer of the given size using the LinkGraph's
1048 /// allocator.
1050 return {Allocator.Allocate<char>(Size), Size};
1051 }
1052
1053 /// Allocate a copy of the given string using the LinkGraph's allocator.
1054 /// This can be useful when renaming symbols or adding new content to the
1055 /// graph.
1057 auto *AllocatedBuffer = Allocator.Allocate<char>(Source.size());
1058 llvm::copy(Source, AllocatedBuffer);
1059 return MutableArrayRef<char>(AllocatedBuffer, Source.size());
1060 }
1061
1062 /// Allocate a copy of the given string using the LinkGraph's allocator.
1063 /// This can be useful when renaming symbols or adding new content to the
1064 /// graph.
1065 ///
1066 /// Note: This Twine-based overload requires an extra string copy and an
1067 /// extra heap allocation for large strings. The ArrayRef<char> overload
1068 /// should be preferred where possible.
1070 SmallString<256> TmpBuffer;
1071 auto SourceStr = Source.toStringRef(TmpBuffer);
1072 auto *AllocatedBuffer = Allocator.Allocate<char>(SourceStr.size());
1073 llvm::copy(SourceStr, AllocatedBuffer);
1074 return MutableArrayRef<char>(AllocatedBuffer, SourceStr.size());
1075 }
1076
1077 /// Allocate a copy of the given string using the LinkGraph's allocator
1078 /// and return it as a StringRef.
1079 ///
1080 /// This is a convenience wrapper around allocateContent(Twine) that is
1081 /// handy when creating new symbol names within the graph.
1083 auto Buf = allocateContent(Source);
1084 return {Buf.data(), Buf.size()};
1085 }
1086
1087 /// Allocate a copy of the given string using the LinkGraph's allocator.
1088 ///
1089 /// The allocated string will be terminated with a null character, and the
1090 /// returned MutableArrayRef will include this null character in the last
1091 /// position.
1093 char *AllocatedBuffer = Allocator.Allocate<char>(Source.size() + 1);
1094 llvm::copy(Source, AllocatedBuffer);
1095 AllocatedBuffer[Source.size()] = '\0';
1096 return MutableArrayRef<char>(AllocatedBuffer, Source.size() + 1);
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.
1104 ///
1105 /// Note: This Twine-based overload requires an extra string copy and an
1106 /// extra heap allocation for large strings. The ArrayRef<char> overload
1107 /// should be preferred where possible.
1109 SmallString<256> TmpBuffer;
1110 auto SourceStr = Source.toStringRef(TmpBuffer);
1111 auto *AllocatedBuffer = Allocator.Allocate<char>(SourceStr.size() + 1);
1112 llvm::copy(SourceStr, AllocatedBuffer);
1113 AllocatedBuffer[SourceStr.size()] = '\0';
1114 return MutableArrayRef<char>(AllocatedBuffer, SourceStr.size() + 1);
1115 }
1116
1117 /// Create a section with the given name, protection flags, and alignment.
1119 assert(!Sections.count(Name) && "Duplicate section name");
1120 std::unique_ptr<Section> Sec(new Section(Name, Prot, Sections.size()));
1121 return *Sections.insert(std::make_pair(Name, std::move(Sec))).first->second;
1122 }
1123
1124 /// Create a content block.
1127 uint64_t AlignmentOffset) {
1128 return createBlock(Parent, Content, Address, Alignment, AlignmentOffset);
1129 }
1130
1131 /// Create a content block with initially mutable data.
1133 MutableArrayRef<char> MutableContent,
1135 uint64_t Alignment,
1136 uint64_t AlignmentOffset) {
1137 return createBlock(Parent, MutableContent, Address, Alignment,
1138 AlignmentOffset);
1139 }
1140
1141 /// Create a content block with initially mutable data of the given size.
1142 /// Content will be allocated via the LinkGraph's allocateBuffer method.
1143 /// By default the memory will be zero-initialized. Passing false for
1144 /// ZeroInitialize will prevent this.
1145 Block &createMutableContentBlock(Section &Parent, size_t ContentSize,
1147 uint64_t Alignment, uint64_t AlignmentOffset,
1148 bool ZeroInitialize = true) {
1149 auto Content = allocateBuffer(ContentSize);
1150 if (ZeroInitialize)
1151 memset(Content.data(), 0, Content.size());
1152 return createBlock(Parent, Content, Address, Alignment, AlignmentOffset);
1153 }
1154
1155 /// Create a zero-fill block.
1158 uint64_t AlignmentOffset) {
1159 return createBlock(Parent, Size, Address, Alignment, AlignmentOffset);
1160 }
1161
1162 /// Returns a BinaryStreamReader for the given block.
1165 reinterpret_cast<const uint8_t *>(B.getContent().data()), B.getSize());
1167 }
1168
1169 /// Returns a BinaryStreamWriter for the given block.
1170 /// This will call getMutableContent to obtain mutable content for the block.
1173 reinterpret_cast<uint8_t *>(B.getMutableContent(*this).data()),
1174 B.getSize());
1176 }
1177
1178 /// Cache type for the splitBlock function.
1179 using SplitBlockCache = std::optional<SmallVector<Symbol *, 8>>;
1180
1181 /// Splits block B into a sequence of smaller blocks.
1182 ///
1183 /// SplitOffsets should be a sequence of ascending offsets in B. The starting
1184 /// offset should be greater than zero, and the final offset less than
1185 /// B.getSize() - 1.
1186 ///
1187 /// The resulting seqeunce of blocks will start with the original block B
1188 /// (truncated to end at the first split offset) followed by newly introduced
1189 /// blocks starting at the subsequent split points.
1190 ///
1191 /// The optional Cache parameter can be used to speed up repeated calls to
1192 /// splitBlock for blocks within a single Section. If the value is None then
1193 /// the cache will be treated as uninitialized and splitBlock will populate
1194 /// it. Otherwise it is assumed to contain the list of Symbols pointing at B,
1195 /// sorted in descending order of offset.
1196 ///
1197 ///
1198 /// Notes:
1199 ///
1200 /// 1. splitBlock must be used with care. Splitting a block may cause
1201 /// incoming edges to become invalid if the edge target subexpression
1202 /// points outside the bounds of the newly split target block (E.g. an
1203 /// edge 'S + 10 : Pointer64' where S points to a newly split block
1204 /// whose size is less than 10). No attempt is made to detect invalidation
1205 /// of incoming edges, as in general this requires context that the
1206 /// LinkGraph does not have. Clients are responsible for ensuring that
1207 /// splitBlock is not used in a way that invalidates edges.
1208 ///
1209 /// 2. The newly introduced blocks will have new ordinals that will be higher
1210 /// than any other ordinals in the section. Clients are responsible for
1211 /// re-assigning block ordinals to restore a compatible order if needed.
1212 ///
1213 /// 3. The cache is not automatically updated if new symbols are introduced
1214 /// between calls to splitBlock. Any newly introduced symbols may be
1215 /// added to the cache manually (descending offset order must be
1216 /// preserved), or the cache can be set to None and rebuilt by
1217 /// splitBlock on the next call.
1218 template <typename SplitOffsetRange>
1219 std::vector<Block *> splitBlock(Block &B, SplitOffsetRange &&SplitOffsets,
1220 LinkGraph::SplitBlockCache *Cache = nullptr) {
1221 std::vector<Block *> Blocks;
1222 Blocks.push_back(&B);
1223
1224 if (std::empty(SplitOffsets))
1225 return Blocks;
1226
1227 // Special case zero-fill:
1228 if (B.isZeroFill()) {
1229 size_t OrigSize = B.getSize();
1230 for (Edge::OffsetT Offset : SplitOffsets) {
1231 assert(Offset > 0 && Offset < B.getSize() &&
1232 "Split offset must be inside block content");
1233 Blocks.back()->setZeroFillSize(
1234 Offset - (Blocks.back()->getAddress() - B.getAddress()));
1235 Blocks.push_back(&createZeroFillBlock(
1236 B.getSection(), B.getSize(), B.getAddress() + Offset,
1237 B.getAlignment(),
1238 (B.getAlignmentOffset() + Offset) % B.getAlignment()));
1239 }
1240 Blocks.back()->setZeroFillSize(
1241 OrigSize - (Blocks.back()->getAddress() - B.getAddress()));
1242 return Blocks;
1243 }
1244
1245 // Handle content blocks. We'll just create the blocks with their starting
1246 // address and no content here. The bulk of the work is deferred to
1247 // splitBlockImpl.
1248 for (Edge::OffsetT Offset : SplitOffsets) {
1249 assert(Offset > 0 && Offset < B.getSize() &&
1250 "Split offset must be inside block content");
1251 Blocks.push_back(&createContentBlock(
1252 B.getSection(), ArrayRef<char>(), B.getAddress() + Offset,
1253 B.getAlignment(),
1254 (B.getAlignmentOffset() + Offset) % B.getAlignment()));
1255 }
1256
1257 return splitBlockImpl(std::move(Blocks), Cache);
1258 }
1259
1260 /// Intern the given string in the LinkGraph's SymbolStringPool.
1262 return SSP->intern(SymbolName);
1263 }
1264
1265 /// Add an external symbol.
1266 /// Some formats (e.g. ELF) allow Symbols to have sizes. For Symbols whose
1267 /// size is not known, you should substitute '0'.
1268 /// The IsWeaklyReferenced argument determines whether the symbol must be
1269 /// present during lookup: Externals that are strongly referenced must be
1270 /// found or an error will be emitted. Externals that are weakly referenced
1271 /// are permitted to be undefined, in which case they are assigned an address
1272 /// of 0.
1275 bool IsWeaklyReferenced) {
1276 assert(!ExternalSymbols.contains(*Name) && "Duplicate external symbol");
1277 auto &Sym = Symbol::constructExternal(
1278 Allocator, createAddressable(orc::ExecutorAddr(), false),
1279 std::move(Name), Size, Linkage::Strong, IsWeaklyReferenced);
1280 ExternalSymbols.insert({*Sym.getName(), &Sym});
1281 return Sym;
1282 }
1283
1285 bool IsWeaklyReferenced) {
1286 return addExternalSymbol(SSP->intern(Name), Size, IsWeaklyReferenced);
1287 }
1288
1289 /// Add an absolute symbol.
1293 bool IsLive) {
1294 assert((S == Scope::Local || llvm::count_if(AbsoluteSymbols,
1295 [&](const Symbol *Sym) {
1296 return Sym->getName() == Name;
1297 }) == 0) &&
1298 "Duplicate absolute symbol");
1299 auto &Sym = Symbol::constructAbsolute(Allocator, createAddressable(Address),
1300 std::move(Name), Size, L, S, IsLive);
1301 AbsoluteSymbols.insert(&Sym);
1302 return Sym;
1303 }
1304
1307 bool IsLive) {
1308
1309 return addAbsoluteSymbol(SSP->intern(Name), Address, Size, L, S, IsLive);
1310 }
1311
1312 /// Add an anonymous symbol.
1314 orc::ExecutorAddrDiff Size, bool IsCallable,
1315 bool IsLive) {
1316 auto &Sym = Symbol::constructAnonDef(Allocator, Content, Offset, Size,
1317 IsCallable, IsLive);
1318 Content.getSection().addSymbol(Sym);
1319 return Sym;
1320 }
1321
1322 /// Add a named symbol.
1325 Linkage L, Scope S, bool IsCallable, bool IsLive) {
1326 return addDefinedSymbol(Content, Offset, SSP->intern(Name), Size, L, S,
1327 IsCallable, IsLive);
1328 }
1329
1333 bool IsCallable, bool IsLive) {
1335 [&](const Symbol *Sym) {
1336 return Sym->getName() == Name;
1337 }) == 0) &&
1338 "Duplicate defined symbol");
1339 auto &Sym =
1340 Symbol::constructNamedDef(Allocator, Content, Offset, std::move(Name),
1341 Size, L, S, IsLive, IsCallable);
1342 Content.getSection().addSymbol(Sym);
1343 return Sym;
1344 }
1345
1347 return make_range(
1348 section_iterator(Sections.begin(), GetSectionMapEntryValue()),
1349 section_iterator(Sections.end(), GetSectionMapEntryValue()));
1350 }
1351
1353 return make_range(
1354 const_section_iterator(Sections.begin(),
1355 GetSectionMapEntryConstValue()),
1356 const_section_iterator(Sections.end(), GetSectionMapEntryConstValue()));
1357 }
1358
1359 size_t sections_size() const { return Sections.size(); }
1360
1361 /// Returns the section with the given name if it exists, otherwise returns
1362 /// null.
1364 auto I = Sections.find(Name);
1365 if (I == Sections.end())
1366 return nullptr;
1367 return I->second.get();
1368 }
1369
1371 auto Secs = sections();
1372 return make_range(block_iterator(Secs.begin(), Secs.end()),
1373 block_iterator(Secs.end(), Secs.end()));
1374 }
1375
1377 auto Secs = sections();
1378 return make_range(const_block_iterator(Secs.begin(), Secs.end()),
1379 const_block_iterator(Secs.end(), Secs.end()));
1380 }
1381
1383 return make_range(
1384 external_symbol_iterator(ExternalSymbols.begin(),
1385 GetExternalSymbolMapEntryValue()),
1386 external_symbol_iterator(ExternalSymbols.end(),
1387 GetExternalSymbolMapEntryValue()));
1388 }
1389
1390 /// Returns the external symbol with the given name if one exists, otherwise
1391 /// returns nullptr.
1393 for (auto *Sym : external_symbols())
1394 if (Sym->getName() == Name)
1395 return Sym;
1396 return nullptr;
1397 }
1398
1400 return make_range(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1401 }
1402
1404 for (auto *Sym : absolute_symbols())
1405 if (Sym->getName() == Name)
1406 return Sym;
1407 return nullptr;
1408 }
1409
1411 auto Secs = sections();
1412 return make_range(defined_symbol_iterator(Secs.begin(), Secs.end()),
1413 defined_symbol_iterator(Secs.end(), Secs.end()));
1414 }
1415
1417 auto Secs = sections();
1418 return make_range(const_defined_symbol_iterator(Secs.begin(), Secs.end()),
1419 const_defined_symbol_iterator(Secs.end(), Secs.end()));
1420 }
1421
1422 /// Returns the defined symbol with the given name if one exists, otherwise
1423 /// returns nullptr.
1425 for (auto *Sym : defined_symbols())
1426 if (Sym->hasName() && Sym->getName() == Name)
1427 return Sym;
1428 return nullptr;
1429 }
1430
1431 /// Make the given symbol external (must not already be external).
1432 ///
1433 /// Symbol size, linkage and callability will be left unchanged. Symbol scope
1434 /// will be set to Default, and offset will be reset to 0.
1436 assert(!Sym.isExternal() && "Symbol is already external");
1437 if (Sym.isAbsolute()) {
1438 assert(AbsoluteSymbols.count(&Sym) &&
1439 "Sym is not in the absolute symbols set");
1440 assert(Sym.getOffset() == 0 && "Absolute not at offset 0");
1441 AbsoluteSymbols.erase(&Sym);
1442 auto &A = Sym.getAddressable();
1443 A.setAbsolute(false);
1444 A.setAddress(orc::ExecutorAddr());
1445 } else {
1446 assert(Sym.isDefined() && "Sym is not a defined symbol");
1447 Section &Sec = Sym.getBlock().getSection();
1448 Sec.removeSymbol(Sym);
1449 Sym.makeExternal(createAddressable(orc::ExecutorAddr(), false));
1450 }
1451 ExternalSymbols.insert({*Sym.getName(), &Sym});
1452 }
1453
1454 /// Make the given symbol an absolute with the given address (must not already
1455 /// be absolute).
1456 ///
1457 /// The symbol's size, linkage, and callability, and liveness will be left
1458 /// unchanged, and its offset will be reset to 0.
1459 ///
1460 /// If the symbol was external then its scope will be set to local, otherwise
1461 /// it will be left unchanged.
1463 assert(!Sym.isAbsolute() && "Symbol is already absolute");
1464 if (Sym.isExternal()) {
1465 assert(ExternalSymbols.contains(*Sym.getName()) &&
1466 "Sym is not in the absolute symbols set");
1467 assert(Sym.getOffset() == 0 && "External is not at offset 0");
1468 ExternalSymbols.erase(*Sym.getName());
1469 auto &A = Sym.getAddressable();
1470 A.setAbsolute(true);
1471 A.setAddress(Address);
1472 Sym.setScope(Scope::Local);
1473 } else {
1474 assert(Sym.isDefined() && "Sym is not a defined symbol");
1475 Section &Sec = Sym.getBlock().getSection();
1476 Sec.removeSymbol(Sym);
1477 Sym.makeAbsolute(createAddressable(Address));
1478 }
1479 AbsoluteSymbols.insert(&Sym);
1480 }
1481
1482 /// Turn an absolute or external symbol into a defined one by attaching it to
1483 /// a block. Symbol must not already be defined.
1486 bool IsLive) {
1487 assert(!Sym.isDefined() && "Sym is already a defined symbol");
1488 if (Sym.isAbsolute()) {
1489 assert(AbsoluteSymbols.count(&Sym) &&
1490 "Symbol is not in the absolutes set");
1491 AbsoluteSymbols.erase(&Sym);
1492 } else {
1493 assert(ExternalSymbols.contains(*Sym.getName()) &&
1494 "Symbol is not in the externals set");
1495 ExternalSymbols.erase(*Sym.getName());
1496 }
1497 Addressable &OldBase = *Sym.Base;
1498 Sym.setBlock(Content);
1499 Sym.setOffset(Offset);
1500 Sym.setSize(Size);
1501 Sym.setLinkage(L);
1502 Sym.setScope(S);
1503 Sym.setLive(IsLive);
1504 Content.getSection().addSymbol(Sym);
1505 destroyAddressable(OldBase);
1506 }
1507
1508 /// Transfer a defined symbol from one block to another.
1509 ///
1510 /// The symbol's offset within DestBlock is set to NewOffset.
1511 ///
1512 /// If ExplicitNewSize is given as None then the size of the symbol will be
1513 /// checked and auto-truncated to at most the size of the remainder (from the
1514 /// given offset) of the size of the new block.
1515 ///
1516 /// All other symbol attributes are unchanged.
1517 void
1519 orc::ExecutorAddrDiff NewOffset,
1520 std::optional<orc::ExecutorAddrDiff> ExplicitNewSize) {
1521 auto &OldSection = Sym.getBlock().getSection();
1522 Sym.setBlock(DestBlock);
1523 Sym.setOffset(NewOffset);
1524 if (ExplicitNewSize)
1525 Sym.setSize(*ExplicitNewSize);
1526 else {
1527 auto RemainingBlockSize = DestBlock.getSize() - NewOffset;
1528 if (Sym.getSize() > RemainingBlockSize)
1529 Sym.setSize(RemainingBlockSize);
1530 }
1531 if (&DestBlock.getSection() != &OldSection) {
1532 OldSection.removeSymbol(Sym);
1533 DestBlock.getSection().addSymbol(Sym);
1534 }
1535 }
1536
1537 /// Transfers the given Block and all Symbols pointing to it to the given
1538 /// Section.
1539 ///
1540 /// No attempt is made to check compatibility of the source and destination
1541 /// sections. Blocks may be moved between sections with incompatible
1542 /// permissions (e.g. from data to text). The client is responsible for
1543 /// ensuring that this is safe.
1544 void transferBlock(Block &B, Section &NewSection) {
1545 auto &OldSection = B.getSection();
1546 if (&OldSection == &NewSection)
1547 return;
1548 SmallVector<Symbol *> AttachedSymbols;
1549 for (auto *S : OldSection.symbols())
1550 if (&S->getBlock() == &B)
1551 AttachedSymbols.push_back(S);
1552 for (auto *S : AttachedSymbols) {
1553 OldSection.removeSymbol(*S);
1554 NewSection.addSymbol(*S);
1555 }
1556 OldSection.removeBlock(B);
1557 NewSection.addBlock(B);
1558 }
1559
1560 /// Move all blocks and symbols from the source section to the destination
1561 /// section.
1562 ///
1563 /// If PreserveSrcSection is true (or SrcSection and DstSection are the same)
1564 /// then SrcSection is preserved, otherwise it is removed (the default).
1565 void mergeSections(Section &DstSection, Section &SrcSection,
1566 bool PreserveSrcSection = false) {
1567 if (&DstSection == &SrcSection)
1568 return;
1569 for (auto *B : SrcSection.blocks())
1570 B->setSection(DstSection);
1571 SrcSection.transferContentTo(DstSection);
1572 if (!PreserveSrcSection)
1573 removeSection(SrcSection);
1574 }
1575
1576 /// Removes an external symbol. Also removes the underlying Addressable.
1578 assert(!Sym.isDefined() && !Sym.isAbsolute() &&
1579 "Sym is not an external symbol");
1580 assert(ExternalSymbols.contains(*Sym.getName()) &&
1581 "Symbol is not in the externals set");
1582 ExternalSymbols.erase(*Sym.getName());
1583 Addressable &Base = *Sym.Base;
1585 [&](Symbol *AS) { return AS->Base == &Base; }) &&
1586 "Base addressable still in use");
1587 destroySymbol(Sym);
1588 destroyAddressable(Base);
1589 }
1590
1591 /// Remove an absolute symbol. Also removes the underlying Addressable.
1593 assert(!Sym.isDefined() && Sym.isAbsolute() &&
1594 "Sym is not an absolute symbol");
1595 assert(AbsoluteSymbols.count(&Sym) &&
1596 "Symbol is not in the absolute symbols set");
1597 AbsoluteSymbols.erase(&Sym);
1598 Addressable &Base = *Sym.Base;
1600 [&](Symbol *AS) { return AS->Base == &Base; }) &&
1601 "Base addressable still in use");
1602 destroySymbol(Sym);
1603 destroyAddressable(Base);
1604 }
1605
1606 /// Removes defined symbols. Does not remove the underlying block.
1608 assert(Sym.isDefined() && "Sym is not a defined symbol");
1609 Sym.getBlock().getSection().removeSymbol(Sym);
1610 destroySymbol(Sym);
1611 }
1612
1613 /// Remove a block. The block reference is defunct after calling this
1614 /// function and should no longer be used.
1616 assert(llvm::none_of(B.getSection().symbols(),
1617 [&](const Symbol *Sym) {
1618 return &Sym->getBlock() == &B;
1619 }) &&
1620 "Block still has symbols attached");
1621 B.getSection().removeBlock(B);
1622 destroyBlock(B);
1623 }
1624
1625 /// Remove a section. The section reference is defunct after calling this
1626 /// function and should no longer be used.
1628 assert(Sections.count(Sec.getName()) && "Section not found");
1629 assert(Sections.find(Sec.getName())->second.get() == &Sec &&
1630 "Section map entry invalid");
1631 Sections.erase(Sec.getName());
1632 }
1633
1634 /// Accessor for the AllocActions object for this graph. This can be used to
1635 /// register allocation action calls prior to finalization.
1636 ///
1637 /// Accessing this object after finalization will result in undefined
1638 /// behavior.
1640
1641 /// Dump the graph.
1642 void dump(raw_ostream &OS);
1643
1644private:
1645 std::vector<Block *> splitBlockImpl(std::vector<Block *> Blocks,
1646 SplitBlockCache *Cache);
1647
1648 // Put the BumpPtrAllocator first so that we don't free any of the underlying
1649 // memory until the Symbol/Addressable destructors have been run.
1651
1652 std::string Name;
1653 std::shared_ptr<orc::SymbolStringPool> SSP;
1654 Triple TT;
1655 SubtargetFeatures Features;
1656 GetEdgeKindNameFunction GetEdgeKindName = nullptr;
1658 // FIXME(jared): these should become dense maps
1659 ExternalSymbolMap ExternalSymbols;
1660 AbsoluteSymbolSet AbsoluteSymbols;
1662};
1663
1665 if (!ContentMutable)
1666 setMutableContent(G.allocateContent({Data, Size}));
1667 return MutableArrayRef<char>(const_cast<char *>(Data), Size);
1668}
1669
1670/// Enables easy lookup of blocks by addresses.
1672public:
1673 using AddrToBlockMap = std::map<orc::ExecutorAddr, Block *>;
1674 using const_iterator = AddrToBlockMap::const_iterator;
1675
1676 /// A block predicate that always adds all blocks.
1677 static bool includeAllBlocks(const Block &B) { return true; }
1678
1679 /// A block predicate that always includes blocks with non-null addresses.
1680 static bool includeNonNull(const Block &B) { return !!B.getAddress(); }
1681
1682 BlockAddressMap() = default;
1683
1684 /// Add a block to the map. Returns an error if the block overlaps with any
1685 /// existing block.
1686 template <typename PredFn = decltype(includeAllBlocks)>
1688 if (!Pred(B))
1689 return Error::success();
1690
1691 auto I = AddrToBlock.upper_bound(B.getAddress());
1692
1693 // If we're not at the end of the map, check for overlap with the next
1694 // element.
1695 if (I != AddrToBlock.end()) {
1696 if (B.getAddress() + B.getSize() > I->second->getAddress())
1697 return overlapError(B, *I->second);
1698 }
1699
1700 // If we're not at the start of the map, check for overlap with the previous
1701 // element.
1702 if (I != AddrToBlock.begin()) {
1703 auto &PrevBlock = *std::prev(I)->second;
1704 if (PrevBlock.getAddress() + PrevBlock.getSize() > B.getAddress())
1705 return overlapError(B, PrevBlock);
1706 }
1707
1708 AddrToBlock.insert(I, std::make_pair(B.getAddress(), &B));
1709 return Error::success();
1710 }
1711
1712 /// Add a block to the map without checking for overlap with existing blocks.
1713 /// The client is responsible for ensuring that the block added does not
1714 /// overlap with any existing block.
1715 void addBlockWithoutChecking(Block &B) { AddrToBlock[B.getAddress()] = &B; }
1716
1717 /// Add a range of blocks to the map. Returns an error if any block in the
1718 /// range overlaps with any other block in the range, or with any existing
1719 /// block in the map.
1720 template <typename BlockPtrRange,
1721 typename PredFn = decltype(includeAllBlocks)>
1722 Error addBlocks(BlockPtrRange &&Blocks, PredFn Pred = includeAllBlocks) {
1723 for (auto *B : Blocks)
1724 if (auto Err = addBlock(*B, Pred))
1725 return Err;
1726 return Error::success();
1727 }
1728
1729 /// Add a range of blocks to the map without checking for overlap with
1730 /// existing blocks. The client is responsible for ensuring that the block
1731 /// added does not overlap with any existing block.
1732 template <typename BlockPtrRange>
1733 void addBlocksWithoutChecking(BlockPtrRange &&Blocks) {
1734 for (auto *B : Blocks)
1736 }
1737
1738 /// Iterates over (Address, Block*) pairs in ascending order of address.
1739 const_iterator begin() const { return AddrToBlock.begin(); }
1740 const_iterator end() const { return AddrToBlock.end(); }
1741
1742 /// Returns the block starting at the given address, or nullptr if no such
1743 /// block exists.
1745 auto I = AddrToBlock.find(Addr);
1746 if (I == AddrToBlock.end())
1747 return nullptr;
1748 return I->second;
1749 }
1750
1751 /// Returns the block covering the given address, or nullptr if no such block
1752 /// exists.
1754 auto I = AddrToBlock.upper_bound(Addr);
1755 if (I == AddrToBlock.begin())
1756 return nullptr;
1757 auto *B = std::prev(I)->second;
1758 if (Addr < B->getAddress() + B->getSize())
1759 return B;
1760 return nullptr;
1761 }
1762
1763private:
1764 Error overlapError(Block &NewBlock, Block &ExistingBlock) {
1765 auto NewBlockEnd = NewBlock.getAddress() + NewBlock.getSize();
1766 auto ExistingBlockEnd =
1767 ExistingBlock.getAddress() + ExistingBlock.getSize();
1768 return make_error<JITLinkError>(
1769 "Block at " +
1770 formatv("{0:x16} -- {1:x16}", NewBlock.getAddress().getValue(),
1771 NewBlockEnd.getValue()) +
1772 " overlaps " +
1773 formatv("{0:x16} -- {1:x16}", ExistingBlock.getAddress().getValue(),
1774 ExistingBlockEnd.getValue()));
1775 }
1776
1777 AddrToBlockMap AddrToBlock;
1778};
1779
1780/// A map of addresses to Symbols.
1782public:
1784
1785 /// Add a symbol to the SymbolAddressMap.
1787 AddrToSymbols[Sym.getAddress()].push_back(&Sym);
1788 }
1789
1790 /// Add all symbols in a given range to the SymbolAddressMap.
1791 template <typename SymbolPtrCollection>
1792 void addSymbols(SymbolPtrCollection &&Symbols) {
1793 for (auto *Sym : Symbols)
1794 addSymbol(*Sym);
1795 }
1796
1797 /// Returns the list of symbols that start at the given address, or nullptr if
1798 /// no such symbols exist.
1800 auto I = AddrToSymbols.find(Addr);
1801 if (I == AddrToSymbols.end())
1802 return nullptr;
1803 return &I->second;
1804 }
1805
1806private:
1807 std::map<orc::ExecutorAddr, SymbolVector> AddrToSymbols;
1808};
1809
1810/// A function for mutating LinkGraphs.
1812
1813/// A list of LinkGraph passes.
1814using LinkGraphPassList = std::vector<LinkGraphPassFunction>;
1815
1816/// An LinkGraph pass configuration, consisting of a list of pre-prune,
1817/// post-prune, and post-fixup passes.
1819
1820 /// Pre-prune passes.
1821 ///
1822 /// These passes are called on the graph after it is built, and before any
1823 /// symbols have been pruned. Graph nodes still have their original vmaddrs.
1824 ///
1825 /// Notable use cases: Marking symbols live or should-discard.
1827
1828 /// Post-prune passes.
1829 ///
1830 /// These passes are called on the graph after dead stripping, but before
1831 /// memory is allocated or nodes assigned their final addresses.
1832 ///
1833 /// Notable use cases: Building GOT, stub, and TLV symbols.
1835
1836 /// Post-allocation passes.
1837 ///
1838 /// These passes are called on the graph after memory has been allocated and
1839 /// defined nodes have been assigned their final addresses, but before the
1840 /// context has been notified of these addresses. At this point externals
1841 /// have not been resolved, and symbol content has not yet been copied into
1842 /// working memory.
1843 ///
1844 /// Notable use cases: Setting up data structures associated with addresses
1845 /// of defined symbols (e.g. a mapping of __dso_handle to JITDylib* for the
1846 /// JIT runtime) -- using a PostAllocationPass for this ensures that the
1847 /// data structures are in-place before any query for resolved symbols
1848 /// can complete.
1850
1851 /// Pre-fixup passes.
1852 ///
1853 /// These passes are called on the graph after memory has been allocated,
1854 /// content copied into working memory, and all nodes (including externals)
1855 /// have been assigned their final addresses, but before any fixups have been
1856 /// applied.
1857 ///
1858 /// Notable use cases: Late link-time optimizations like GOT and stub
1859 /// elimination.
1861
1862 /// Post-fixup passes.
1863 ///
1864 /// These passes are called on the graph after block contents has been copied
1865 /// to working memory, and fixups applied. Blocks have been updated to point
1866 /// to their fixed up content.
1867 ///
1868 /// Notable use cases: Testing and validation.
1870};
1871
1872/// Flags for symbol lookup.
1873///
1874/// FIXME: These basically duplicate orc::SymbolLookupFlags -- We should merge
1875/// the two types once we have an OrcSupport library.
1877
1879
1880/// A map of symbol names to resolved addresses.
1883
1884/// A function object to call with a resolved symbol map (See AsyncLookupResult)
1885/// or an error if resolution failed.
1887public:
1889 virtual void run(Expected<AsyncLookupResult> LR) = 0;
1890
1891private:
1892 virtual void anchor();
1893};
1894
1895/// Create a lookup continuation from a function object.
1896template <typename Continuation>
1897std::unique_ptr<JITLinkAsyncLookupContinuation>
1898createLookupContinuation(Continuation Cont) {
1899
1900 class Impl final : public JITLinkAsyncLookupContinuation {
1901 public:
1902 Impl(Continuation C) : C(std::move(C)) {}
1903 void run(Expected<AsyncLookupResult> LR) override { C(std::move(LR)); }
1904
1905 private:
1906 Continuation C;
1907 };
1908
1909 return std::make_unique<Impl>(std::move(Cont));
1910}
1911
1912/// Holds context for a single jitLink invocation.
1914public:
1916
1917 /// Create a JITLinkContext.
1918 JITLinkContext(const JITLinkDylib *JD) : JD(JD) {}
1919
1920 /// Destroy a JITLinkContext.
1922
1923 /// Return the JITLinkDylib that this link is targeting, if any.
1924 const JITLinkDylib *getJITLinkDylib() const { return JD; }
1925
1926 /// Return the MemoryManager to be used for this link.
1928
1929 /// Notify this context that linking failed.
1930 /// Called by JITLink if linking cannot be completed.
1931 virtual void notifyFailed(Error Err) = 0;
1932
1933 /// Called by JITLink to resolve external symbols. This method is passed a
1934 /// lookup continutation which it must call with a result to continue the
1935 /// linking process.
1936 virtual void lookup(const LookupMap &Symbols,
1937 std::unique_ptr<JITLinkAsyncLookupContinuation> LC) = 0;
1938
1939 /// Called by JITLink once all defined symbols in the graph have been assigned
1940 /// their final memory locations in the target process. At this point the
1941 /// LinkGraph can be inspected to build a symbol table, however the block
1942 /// content will not generally have been copied to the target location yet.
1943 ///
1944 /// If the client detects an error in the LinkGraph state (e.g. unexpected or
1945 /// missing symbols) they may return an error here. The error will be
1946 /// propagated to notifyFailed and the linker will bail out.
1948
1949 /// Called by JITLink to notify the context that the object has been
1950 /// finalized (i.e. emitted to memory and memory permissions set). If all of
1951 /// this objects dependencies have also been finalized then the code is ready
1952 /// to run.
1954
1955 /// Called by JITLink prior to linking to determine whether default passes for
1956 /// the target should be added. The default implementation returns true.
1957 /// If subclasses override this method to return false for any target then
1958 /// they are required to fully configure the pass pipeline for that target.
1959 virtual bool shouldAddDefaultTargetPasses(const Triple &TT) const;
1960
1961 /// Returns the mark-live pass to be used for this link. If no pass is
1962 /// returned (the default) then the target-specific linker implementation will
1963 /// choose a conservative default (usually marking all symbols live).
1964 /// This function is only called if shouldAddDefaultTargetPasses returns true,
1965 /// otherwise the JITContext is responsible for adding a mark-live pass in
1966 /// modifyPassConfig.
1967 virtual LinkGraphPassFunction getMarkLivePass(const Triple &TT) const;
1968
1969 /// Called by JITLink to modify the pass pipeline prior to linking.
1970 /// The default version performs no modification.
1972
1973private:
1974 const JITLinkDylib *JD = nullptr;
1975};
1976
1977/// Marks all symbols in a graph live. This can be used as a default,
1978/// conservative mark-live implementation.
1980
1981/// Create an out of range error for the given edge in the given block.
1983 const Edge &E);
1984
1986 const Edge &E);
1987
1988/// Creates a new pointer block in the given section and returns an
1989/// Anonymous symbol pointing to it.
1990///
1991/// The pointer block will have the following default values:
1992/// alignment: PointerSize
1993/// alignment-offset: 0
1994/// address: highest allowable
1996 unique_function<Symbol &(LinkGraph &G, Section &PointerSection,
1997 Symbol *InitialTarget, uint64_t InitialAddend)>;
1998
1999/// Get target-specific AnonymousPointerCreator
2001
2002/// Create a jump stub that jumps via the pointer at the given symbol and
2003/// an anonymous symbol pointing to it. Return the anonymous symbol.
2004///
2005/// The stub block will be created by createPointerJumpStubBlock.
2007 LinkGraph &G, Section &StubSection, Symbol &PointerSymbol)>;
2008
2009/// Get target-specific PointerJumpStubCreator
2011
2012/// Base case for edge-visitors where the visitor-list is empty.
2013inline void visitEdge(LinkGraph &G, Block *B, Edge &E) {}
2014
2015/// Applies the first visitor in the list to the given edge. If the visitor's
2016/// visitEdge method returns true then we return immediately, otherwise we
2017/// apply the next visitor.
2018template <typename VisitorT, typename... VisitorTs>
2019void visitEdge(LinkGraph &G, Block *B, Edge &E, VisitorT &&V,
2020 VisitorTs &&...Vs) {
2021 if (!V.visitEdge(G, B, E))
2022 visitEdge(G, B, E, std::forward<VisitorTs>(Vs)...);
2023}
2024
2025/// For each edge in the given graph, apply a list of visitors to the edge,
2026/// stopping when the first visitor's visitEdge method returns true.
2027///
2028/// Only visits edges that were in the graph at call time: if any visitor
2029/// adds new edges those will not be visited. Visitors are not allowed to
2030/// remove edges (though they can change their kind, target, and addend).
2031template <typename... VisitorTs>
2032void visitExistingEdges(LinkGraph &G, VisitorTs &&...Vs) {
2033 // We may add new blocks during this process, but we don't want to iterate
2034 // over them, so build a worklist.
2035 std::vector<Block *> Worklist(G.blocks().begin(), G.blocks().end());
2036
2037 for (auto *B : Worklist)
2038 for (auto &E : B->edges())
2039 visitEdge(G, B, E, std::forward<VisitorTs>(Vs)...);
2040}
2041
2042/// Create a LinkGraph from the given object buffer.
2043///
2044/// Note: The graph does not take ownership of the underlying buffer, nor copy
2045/// its contents. The caller is responsible for ensuring that the object buffer
2046/// outlives the graph.
2049 std::shared_ptr<orc::SymbolStringPool> SSP);
2050
2051/// Create a \c LinkGraph defining the given absolute symbols.
2052std::unique_ptr<LinkGraph>
2053absoluteSymbolsLinkGraph(Triple TT, std::shared_ptr<orc::SymbolStringPool> SSP,
2054 orc::SymbolMap Symbols);
2055
2056/// Link the given graph.
2057void link(std::unique_ptr<LinkGraph> G, std::unique_ptr<JITLinkContext> Ctx);
2058
2059} // end namespace jitlink
2060} // end namespace llvm
2061
2062#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:497
bool isLittleEndian() const
Tests whether the target triple is little endian.
Definition: Triple.cpp:1987
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition: Triple.h:395
static unsigned getArchPointerBitWidth(llvm::Triple::ArchType Arch)
Returns the pointer width of this architecture.
Definition: Triple.cpp:1641
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
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: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.