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