LLVM 21.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 /// Returns an iterator over all edges at the given offset within the block.
341 return make_filter_range(edges(),
342 [O](const Edge &E) { return E.getOffset() == O; });
343 }
344
345 /// Returns an iterator over all edges at the given offset within the block.
346 auto edges_at(Edge::OffsetT O) const {
347 return make_filter_range(edges(),
348 [O](const Edge &E) { return E.getOffset() == O; });
349 }
350
351 /// Return the size of the edges list.
352 size_t edges_size() const { return Edges.size(); }
353
354 /// Returns true if the list of edges is empty.
355 bool edges_empty() const { return Edges.empty(); }
356
357 /// Remove the edge pointed to by the given iterator.
358 /// Returns an iterator to the new next element.
359 edge_iterator removeEdge(edge_iterator I) { return Edges.erase(I); }
360
361 /// Returns the address of the fixup for the given edge, which is equal to
362 /// this block's address plus the edge's offset.
364 return getAddress() + E.getOffset();
365 }
366
367private:
368 static constexpr uint64_t MaxAlignmentOffset = (1ULL << 56) - 1;
369
370 void setSection(Section &Parent) { this->Parent = &Parent; }
371
372 Section *Parent;
373 const char *Data = nullptr;
374 size_t Size = 0;
375 std::vector<Edge> Edges;
376};
377
378// Align an address to conform with block alignment requirements.
380 uint64_t Delta = (B.getAlignmentOffset() - Addr) % B.getAlignment();
381 return Addr + Delta;
382}
383
384// Align a orc::ExecutorAddr to conform with block alignment requirements.
386 return orc::ExecutorAddr(alignToBlock(Addr.getValue(), B));
387}
388
389// Returns true if the given blocks contains exactly one valid c-string.
390// Zero-fill blocks of size 1 count as valid empty strings. Content blocks
391// must end with a zero, and contain no zeros before the end.
392bool isCStringBlock(Block &B);
393
394/// Describes symbol linkage. This can be used to resolve definition clashes.
395enum class Linkage : uint8_t {
396 Strong,
397 Weak,
398};
399
400/// Holds target-specific properties for a symbol.
402
403/// For errors and debugging output.
404const char *getLinkageName(Linkage L);
405
406/// Defines the scope in which this symbol should be visible:
407/// Default -- Visible in the public interface of the linkage unit.
408/// Hidden -- Visible within the linkage unit, but not exported from it.
409/// SideEffectsOnly -- Like hidden, but symbol can only be looked up once
410/// to trigger materialization of the containing graph.
411/// Local -- Visible only within the LinkGraph.
413
414/// For debugging output.
415const char *getScopeName(Scope S);
416
417raw_ostream &operator<<(raw_ostream &OS, const Block &B);
418
419/// Symbol representation.
420///
421/// Symbols represent locations within Addressable objects.
422/// They can be either Named or Anonymous.
423/// Anonymous symbols have neither linkage nor visibility, and must point at
424/// ContentBlocks.
425/// Named symbols may be in one of four states:
426/// - Null: Default initialized. Assignable, but otherwise unusable.
427/// - Defined: Has both linkage and visibility and points to a ContentBlock
428/// - Common: Has both linkage and visibility, points to a null Addressable.
429/// - External: Has neither linkage nor visibility, points to an external
430/// Addressable.
431///
432class Symbol {
433 friend class LinkGraph;
434
435private:
438 Scope S, bool IsLive, bool IsCallable)
439 : Name(std::move(Name)), Base(&Base), Offset(Offset), WeakRef(0),
440 Size(Size) {
441 assert(Offset <= MaxOffset && "Offset out of range");
442 setLinkage(L);
443 setScope(S);
444 setLive(IsLive);
445 setCallable(IsCallable);
447 }
448
449 static Symbol &constructExternal(BumpPtrAllocator &Allocator,
450 Addressable &Base,
453 bool WeaklyReferenced) {
454 assert(!Base.isDefined() &&
455 "Cannot create external symbol from defined block");
456 assert(Name && "External symbol name cannot be empty");
457 auto *Sym = Allocator.Allocate<Symbol>();
458 new (Sym)
459 Symbol(Base, 0, std::move(Name), Size, L, Scope::Default, false, false);
460 Sym->setWeaklyReferenced(WeaklyReferenced);
461 return *Sym;
462 }
463
464 static Symbol &constructAbsolute(BumpPtrAllocator &Allocator,
465 Addressable &Base,
466 orc::SymbolStringPtr &&Name,
468 Scope S, bool IsLive) {
469 assert(!Base.isDefined() &&
470 "Cannot create absolute symbol from a defined block");
471 auto *Sym = Allocator.Allocate<Symbol>();
472 new (Sym) Symbol(Base, 0, std::move(Name), Size, L, S, IsLive, false);
473 return *Sym;
474 }
475
476 static Symbol &constructAnonDef(BumpPtrAllocator &Allocator, Block &Base,
478 orc::ExecutorAddrDiff Size, bool IsCallable,
479 bool IsLive) {
480 assert((Offset + Size) <= Base.getSize() &&
481 "Symbol extends past end of block");
482 auto *Sym = Allocator.Allocate<Symbol>();
483 new (Sym) Symbol(Base, Offset, nullptr, Size, Linkage::Strong, Scope::Local,
484 IsLive, IsCallable);
485 return *Sym;
486 }
487
488 static Symbol &constructNamedDef(BumpPtrAllocator &Allocator, Block &Base,
490 orc::SymbolStringPtr Name,
492 Scope S, bool IsLive, bool IsCallable) {
493 assert((Offset + Size) <= Base.getSize() &&
494 "Symbol extends past end of block");
495 assert(Name && "Name cannot be empty");
496 auto *Sym = Allocator.Allocate<Symbol>();
497 new (Sym)
498 Symbol(Base, Offset, std::move(Name), Size, L, S, IsLive, IsCallable);
499 return *Sym;
500 }
501
502public:
503 /// Create a null Symbol. This allows Symbols to be default initialized for
504 /// use in containers (e.g. as map values). Null symbols are only useful for
505 /// assigning to.
506 Symbol() = default;
507
508 // Symbols are not movable or copyable.
509 Symbol(const Symbol &) = delete;
510 Symbol &operator=(const Symbol &) = delete;
511 Symbol(Symbol &&) = delete;
512 Symbol &operator=(Symbol &&) = delete;
513
514 /// Returns true if this symbol has a name.
515 bool hasName() const { return Name != nullptr; }
516
517 /// Returns the name of this symbol (empty if the symbol is anonymous).
519 assert((hasName() || getScope() == Scope::Local) &&
520 "Anonymous symbol has non-local scope");
521
522 return Name;
523 }
524
525 /// Rename this symbol. The client is responsible for updating scope and
526 /// linkage if this name-change requires it.
527 void setName(const orc::SymbolStringPtr Name) { this->Name = Name; }
528
529 /// Returns true if this Symbol has content (potentially) defined within this
530 /// object file (i.e. is anything but an external or absolute symbol).
531 bool isDefined() const {
532 assert(Base && "Attempt to access null symbol");
533 return Base->isDefined();
534 }
535
536 /// Returns true if this symbol is live (i.e. should be treated as a root for
537 /// dead stripping).
538 bool isLive() const {
539 assert(Base && "Attempting to access null symbol");
540 return IsLive;
541 }
542
543 /// Set this symbol's live bit.
544 void setLive(bool IsLive) { this->IsLive = IsLive; }
545
546 /// Returns true is this symbol is callable.
547 bool isCallable() const { return IsCallable; }
548
549 /// Set this symbol's callable bit.
550 void setCallable(bool IsCallable) { this->IsCallable = IsCallable; }
551
552 /// Returns true if the underlying addressable is an unresolved external.
553 bool isExternal() const {
554 assert(Base && "Attempt to access null symbol");
555 return !Base->isDefined() && !Base->isAbsolute();
556 }
557
558 /// Returns true if the underlying addressable is an absolute symbol.
559 bool isAbsolute() const {
560 assert(Base && "Attempt to access null symbol");
561 return Base->isAbsolute();
562 }
563
564 /// Return the addressable that this symbol points to.
566 assert(Base && "Cannot get underlying addressable for null symbol");
567 return *Base;
568 }
569
570 /// Return the addressable that this symbol points to.
572 assert(Base && "Cannot get underlying addressable for null symbol");
573 return *Base;
574 }
575
576 /// Return the Block for this Symbol (Symbol must be defined).
578 assert(Base && "Cannot get block for null symbol");
579 assert(Base->isDefined() && "Not a defined symbol");
580 return static_cast<Block &>(*Base);
581 }
582
583 /// Return the Block for this Symbol (Symbol must be defined).
584 const Block &getBlock() const {
585 assert(Base && "Cannot get block for null symbol");
586 assert(Base->isDefined() && "Not a defined symbol");
587 return static_cast<const Block &>(*Base);
588 }
589
590 /// Return the Section for this Symbol (Symbol must be defined).
591 Section &getSection() const { return getBlock().getSection(); }
592
593 /// Returns the offset for this symbol within the underlying addressable.
595
597 assert(NewOffset <= getBlock().getSize() && "Offset out of range");
598 Offset = NewOffset;
599 }
600
601 /// Returns the address of this symbol.
602 orc::ExecutorAddr getAddress() const { return Base->getAddress() + Offset; }
603
604 /// Returns the size of this symbol.
606
607 /// Set the size of this symbol.
609 assert(Base && "Cannot set size for null Symbol");
610 assert((Size == 0 || Base->isDefined()) &&
611 "Non-zero size can only be set for defined symbols");
612 assert((Offset + Size <= static_cast<const Block &>(*Base).getSize()) &&
613 "Symbol size cannot extend past the end of its containing block");
614 this->Size = Size;
615 }
616
617 /// Returns the address range of this symbol.
620 }
621
622 /// Returns true if this symbol is backed by a zero-fill block.
623 /// This method may only be called on defined symbols.
624 bool isSymbolZeroFill() const { return getBlock().isZeroFill(); }
625
626 /// Returns the content in the underlying block covered by this symbol.
627 /// This method may only be called on defined non-zero-fill symbols.
629 return getBlock().getContent().slice(Offset, Size);
630 }
631
632 /// Get the linkage for this Symbol.
633 Linkage getLinkage() const { return static_cast<Linkage>(L); }
634
635 /// Set the linkage for this Symbol.
637 assert((L == Linkage::Strong || (!Base->isAbsolute() && Name)) &&
638 "Linkage can only be applied to defined named symbols");
639 this->L = static_cast<uint8_t>(L);
640 }
641
642 /// Get the visibility for this Symbol.
643 Scope getScope() const { return static_cast<Scope>(S); }
644
645 /// Set the visibility for this Symbol.
646 void setScope(Scope S) {
647 assert((hasName() || S == Scope::Local) &&
648 "Can not set anonymous symbol to non-local scope");
649 assert((S != Scope::Local || Base->isDefined() || Base->isAbsolute()) &&
650 "Invalid visibility for symbol type");
651 this->S = static_cast<uint8_t>(S);
652 }
653
654 /// Get the target flags of this Symbol.
655 TargetFlagsType getTargetFlags() const { return TargetFlags; }
656
657 /// Set the target flags for this Symbol.
659 assert(Flags <= 1 && "Add more bits to store more than single flag");
660 TargetFlags = Flags;
661 }
662
663 /// Returns true if this is a weakly referenced external symbol.
664 /// This method may only be called on external symbols.
665 bool isWeaklyReferenced() const {
666 assert(isExternal() && "isWeaklyReferenced called on non-external");
667 return WeakRef;
668 }
669
670 /// Set the WeaklyReferenced value for this symbol.
671 /// This method may only be called on external symbols.
672 void setWeaklyReferenced(bool WeakRef) {
673 assert(isExternal() && "setWeaklyReferenced called on non-external");
674 this->WeakRef = WeakRef;
675 }
676
677private:
678 void makeExternal(Addressable &A) {
679 assert(!A.isDefined() && !A.isAbsolute() &&
680 "Attempting to make external with defined or absolute block");
681 Base = &A;
682 Offset = 0;
684 IsLive = 0;
685 // note: Size, Linkage and IsCallable fields left unchanged.
686 }
687
688 void makeAbsolute(Addressable &A) {
689 assert(!A.isDefined() && A.isAbsolute() &&
690 "Attempting to make absolute with defined or external block");
691 Base = &A;
692 Offset = 0;
693 }
694
695 void setBlock(Block &B) { Base = &B; }
696
697 static constexpr uint64_t MaxOffset = (1ULL << 59) - 1;
698
699 orc::SymbolStringPtr Name = nullptr;
700 Addressable *Base = nullptr;
701 uint64_t Offset : 57;
702 uint64_t L : 1;
703 uint64_t S : 2;
704 uint64_t IsLive : 1;
705 uint64_t IsCallable : 1;
706 uint64_t WeakRef : 1;
707 uint64_t TargetFlags : 1;
708 size_t Size = 0;
709};
710
711raw_ostream &operator<<(raw_ostream &OS, const Symbol &A);
712
713void printEdge(raw_ostream &OS, const Block &B, const Edge &E,
714 StringRef EdgeKindName);
715
716/// Represents an object file section.
717class Section {
718 friend class LinkGraph;
719
720private:
722 : Name(Name), Prot(Prot), SecOrdinal(SecOrdinal) {}
723
724 using SymbolSet = DenseSet<Symbol *>;
725 using BlockSet = DenseSet<Block *>;
726
727public:
730
733
734 ~Section();
735
736 // Sections are not movable or copyable.
737 Section(const Section &) = delete;
738 Section &operator=(const Section &) = delete;
739 Section(Section &&) = delete;
740 Section &operator=(Section &&) = delete;
741
742 /// Returns the name of this section.
743 StringRef getName() const { return Name; }
744
745 /// Returns the protection flags for this section.
746 orc::MemProt getMemProt() const { return Prot; }
747
748 /// Set the protection flags for this section.
749 void setMemProt(orc::MemProt Prot) { this->Prot = Prot; }
750
751 /// Get the memory lifetime policy for this section.
753
754 /// Set the memory lifetime policy for this section.
755 void setMemLifetime(orc::MemLifetime ML) { this->ML = ML; }
756
757 /// Returns the ordinal for this section.
758 SectionOrdinal getOrdinal() const { return SecOrdinal; }
759
760 /// Set the ordinal for this section. Ordinals are used to order the layout
761 /// of sections with the same permissions.
762 void setOrdinal(SectionOrdinal SecOrdinal) { this->SecOrdinal = SecOrdinal; }
763
764 /// Returns true if this section is empty (contains no blocks or symbols).
765 bool empty() const { return Blocks.empty(); }
766
767 /// Returns an iterator over the blocks defined in this section.
769 return make_range(Blocks.begin(), Blocks.end());
770 }
771
772 /// Returns an iterator over the blocks defined in this section.
774 return make_range(Blocks.begin(), Blocks.end());
775 }
776
777 /// Returns the number of blocks in this section.
778 BlockSet::size_type blocks_size() const { return Blocks.size(); }
779
780 /// Returns an iterator over the symbols defined in this section.
782 return make_range(Symbols.begin(), Symbols.end());
783 }
784
785 /// Returns an iterator over the symbols defined in this section.
787 return make_range(Symbols.begin(), Symbols.end());
788 }
789
790 /// Return the number of symbols in this section.
791 SymbolSet::size_type symbols_size() const { return Symbols.size(); }
792
793private:
794 void addSymbol(Symbol &Sym) {
795 assert(!Symbols.count(&Sym) && "Symbol is already in this section");
796 Symbols.insert(&Sym);
797 }
798
799 void removeSymbol(Symbol &Sym) {
800 assert(Symbols.count(&Sym) && "symbol is not in this section");
801 Symbols.erase(&Sym);
802 }
803
804 void addBlock(Block &B) {
805 assert(!Blocks.count(&B) && "Block is already in this section");
806 Blocks.insert(&B);
807 }
808
809 void removeBlock(Block &B) {
810 assert(Blocks.count(&B) && "Block is not in this section");
811 Blocks.erase(&B);
812 }
813
814 void transferContentTo(Section &DstSection) {
815 if (&DstSection == this)
816 return;
817 for (auto *S : Symbols)
818 DstSection.addSymbol(*S);
819 for (auto *B : Blocks)
820 DstSection.addBlock(*B);
821 Symbols.clear();
822 Blocks.clear();
823 }
824
825 StringRef Name;
826 orc::MemProt Prot;
828 SectionOrdinal SecOrdinal = 0;
829 BlockSet Blocks;
830 SymbolSet Symbols;
831};
832
833/// Represents a section address range via a pair of Block pointers
834/// to the first and last Blocks in the section.
836public:
837 SectionRange() = default;
838 SectionRange(const Section &Sec) {
839 if (Sec.blocks().empty())
840 return;
841 First = Last = *Sec.blocks().begin();
842 for (auto *B : Sec.blocks()) {
843 if (B->getAddress() < First->getAddress())
844 First = B;
845 if (B->getAddress() > Last->getAddress())
846 Last = B;
847 }
848 }
850 assert((!Last || First) && "First can not be null if end is non-null");
851 return First;
852 }
854 assert((First || !Last) && "Last can not be null if start is non-null");
855 return Last;
856 }
857 bool empty() const {
858 assert((First || !Last) && "Last can not be null if start is non-null");
859 return !First;
860 }
862 return First ? First->getAddress() : orc::ExecutorAddr();
863 }
865 return Last ? Last->getAddress() + Last->getSize() : orc::ExecutorAddr();
866 }
868
871 }
872
873private:
874 Block *First = nullptr;
875 Block *Last = nullptr;
876};
877
879private:
884
885 template <typename... ArgTs>
886 Addressable &createAddressable(ArgTs &&... Args) {
887 Addressable *A =
888 reinterpret_cast<Addressable *>(Allocator.Allocate<Addressable>());
889 new (A) Addressable(std::forward<ArgTs>(Args)...);
890 return *A;
891 }
892
893 void destroyAddressable(Addressable &A) {
894 A.~Addressable();
895 Allocator.Deallocate(&A);
896 }
897
898 template <typename... ArgTs> Block &createBlock(ArgTs &&... Args) {
899 Block *B = reinterpret_cast<Block *>(Allocator.Allocate<Block>());
900 new (B) Block(std::forward<ArgTs>(Args)...);
901 B->getSection().addBlock(*B);
902 return *B;
903 }
904
905 void destroyBlock(Block &B) {
906 B.~Block();
907 Allocator.Deallocate(&B);
908 }
909
910 void destroySymbol(Symbol &S) {
911 S.~Symbol();
912 Allocator.Deallocate(&S);
913 }
914
915 static iterator_range<Section::block_iterator> getSectionBlocks(Section &S) {
916 return S.blocks();
917 }
918
920 getSectionConstBlocks(const Section &S) {
921 return S.blocks();
922 }
923
925 getSectionSymbols(Section &S) {
926 return S.symbols();
927 }
928
930 getSectionConstSymbols(const Section &S) {
931 return S.symbols();
932 }
933
934 struct GetExternalSymbolMapEntryValue {
935 Symbol *operator()(ExternalSymbolMap::value_type &KV) const {
936 return KV.second;
937 }
938 };
939
940 struct GetSectionMapEntryValue {
941 Section &operator()(SectionMap::value_type &KV) const { return *KV.second; }
942 };
943
944 struct GetSectionMapEntryConstValue {
945 const Section &operator()(const SectionMap::value_type &KV) const {
946 return *KV.second;
947 }
948 };
949
950public:
953 GetExternalSymbolMapEntryValue>;
955
960
961 template <typename OuterItrT, typename InnerItrT, typename T,
962 iterator_range<InnerItrT> getInnerRange(
963 typename OuterItrT::reference)>
965 : public iterator_facade_base<
966 nested_collection_iterator<OuterItrT, InnerItrT, T, getInnerRange>,
967 std::forward_iterator_tag, T> {
968 public:
970
971 nested_collection_iterator(OuterItrT OuterI, OuterItrT OuterE)
972 : OuterI(OuterI), OuterE(OuterE),
973 InnerI(getInnerBegin(OuterI, OuterE)) {
974 moveToNonEmptyInnerOrEnd();
975 }
976
978 return (OuterI == RHS.OuterI) && (InnerI == RHS.InnerI);
979 }
980
981 T operator*() const {
982 assert(InnerI != getInnerRange(*OuterI).end() && "Dereferencing end?");
983 return *InnerI;
984 }
985
987 ++InnerI;
988 moveToNonEmptyInnerOrEnd();
989 return *this;
990 }
991
992 private:
993 static InnerItrT getInnerBegin(OuterItrT OuterI, OuterItrT OuterE) {
994 return OuterI != OuterE ? getInnerRange(*OuterI).begin() : InnerItrT();
995 }
996
997 void moveToNonEmptyInnerOrEnd() {
998 while (OuterI != OuterE && InnerI == getInnerRange(*OuterI).end()) {
999 ++OuterI;
1000 InnerI = getInnerBegin(OuterI, OuterE);
1001 }
1002 }
1003
1004 OuterItrT OuterI, OuterE;
1005 InnerItrT InnerI;
1006 };
1007
1010 Symbol *, getSectionSymbols>;
1011
1015 getSectionConstSymbols>;
1016
1019 Block *, getSectionBlocks>;
1020
1024 getSectionConstBlocks>;
1025
1026 using GetEdgeKindNameFunction = const char *(*)(Edge::Kind);
1027
1028 LinkGraph(std::string Name, std::shared_ptr<orc::SymbolStringPool> SSP,
1029 Triple TT, SubtargetFeatures Features,
1030 GetEdgeKindNameFunction GetEdgeKindName)
1031 : Name(std::move(Name)), SSP(std::move(SSP)), TT(std::move(TT)),
1032 Features(std::move(Features)),
1033 GetEdgeKindName(std::move(GetEdgeKindName)) {
1034 assert(!(Triple::getArchPointerBitWidth(this->TT.getArch()) % 8) &&
1035 "Arch bitwidth is not a multiple of 8");
1036 }
1037
1038 LinkGraph(const LinkGraph &) = delete;
1039 LinkGraph &operator=(const LinkGraph &) = delete;
1040 LinkGraph(LinkGraph &&) = delete;
1042 ~LinkGraph();
1043
1044 /// Returns the name of this graph (usually the name of the original
1045 /// underlying MemoryBuffer).
1046 const std::string &getName() const { return Name; }
1047
1048 /// Returns the target triple for this Graph.
1049 const Triple &getTargetTriple() const { return TT; }
1050
1051 /// Return the subtarget features for this Graph.
1052 const SubtargetFeatures &getFeatures() const { return Features; }
1053
1054 /// Returns the pointer size for use in this graph.
1055 unsigned getPointerSize() const { return TT.getArchPointerBitWidth() / 8; }
1056
1057 /// Returns the endianness of content in this graph.
1060 }
1061
1062 const char *getEdgeKindName(Edge::Kind K) const { return GetEdgeKindName(K); }
1063
1064 std::shared_ptr<orc::SymbolStringPool> getSymbolStringPool() { return SSP; }
1065
1066 /// Allocate a mutable buffer of the given size using the LinkGraph's
1067 /// allocator.
1069 return {Allocator.Allocate<char>(Size), Size};
1070 }
1071
1072 /// Allocate a copy of the given string using the LinkGraph's allocator.
1073 /// This can be useful when renaming symbols or adding new content to the
1074 /// graph.
1076 auto *AllocatedBuffer = Allocator.Allocate<char>(Source.size());
1077 llvm::copy(Source, AllocatedBuffer);
1078 return MutableArrayRef<char>(AllocatedBuffer, Source.size());
1079 }
1080
1081 /// Allocate a copy of the given string using the LinkGraph's allocator.
1082 /// This can be useful when renaming symbols or adding new content to the
1083 /// graph.
1084 ///
1085 /// Note: This Twine-based overload requires an extra string copy and an
1086 /// extra heap allocation for large strings. The ArrayRef<char> overload
1087 /// should be preferred where possible.
1089 SmallString<256> TmpBuffer;
1090 auto SourceStr = Source.toStringRef(TmpBuffer);
1091 auto *AllocatedBuffer = Allocator.Allocate<char>(SourceStr.size());
1092 llvm::copy(SourceStr, AllocatedBuffer);
1093 return MutableArrayRef<char>(AllocatedBuffer, SourceStr.size());
1094 }
1095
1096 /// Allocate a copy of the given string using the LinkGraph's allocator
1097 /// and return it as a StringRef.
1098 ///
1099 /// This is a convenience wrapper around allocateContent(Twine) that is
1100 /// handy when creating new symbol names within the graph.
1102 auto Buf = allocateContent(Source);
1103 return {Buf.data(), Buf.size()};
1104 }
1105
1106 /// Allocate a copy of the given string using the LinkGraph's allocator.
1107 ///
1108 /// The allocated string will be terminated with a null character, and the
1109 /// returned MutableArrayRef will include this null character in the last
1110 /// position.
1112 char *AllocatedBuffer = Allocator.Allocate<char>(Source.size() + 1);
1113 llvm::copy(Source, AllocatedBuffer);
1114 AllocatedBuffer[Source.size()] = '\0';
1115 return MutableArrayRef<char>(AllocatedBuffer, Source.size() + 1);
1116 }
1117
1118 /// Allocate a copy of the given string using the LinkGraph's allocator.
1119 ///
1120 /// The allocated string will be terminated with a null character, and the
1121 /// returned MutableArrayRef will include this null character in the last
1122 /// position.
1123 ///
1124 /// Note: This Twine-based overload requires an extra string copy and an
1125 /// extra heap allocation for large strings. The ArrayRef<char> overload
1126 /// should be preferred where possible.
1128 SmallString<256> TmpBuffer;
1129 auto SourceStr = Source.toStringRef(TmpBuffer);
1130 auto *AllocatedBuffer = Allocator.Allocate<char>(SourceStr.size() + 1);
1131 llvm::copy(SourceStr, AllocatedBuffer);
1132 AllocatedBuffer[SourceStr.size()] = '\0';
1133 return MutableArrayRef<char>(AllocatedBuffer, SourceStr.size() + 1);
1134 }
1135
1136 /// Create a section with the given name, protection flags.
1138 assert(!Sections.count(Name) && "Duplicate section name");
1139 std::unique_ptr<Section> Sec(new Section(Name, Prot, Sections.size()));
1140 return *Sections.insert(std::make_pair(Name, std::move(Sec))).first->second;
1141 }
1142
1143 /// Create a content block.
1146 uint64_t AlignmentOffset) {
1147 return createBlock(Parent, Content, Address, Alignment, AlignmentOffset);
1148 }
1149
1150 /// Create a content block with initially mutable data.
1152 MutableArrayRef<char> MutableContent,
1154 uint64_t Alignment,
1155 uint64_t AlignmentOffset) {
1156 return createBlock(Parent, MutableContent, Address, Alignment,
1157 AlignmentOffset);
1158 }
1159
1160 /// Create a content block with initially mutable data of the given size.
1161 /// Content will be allocated via the LinkGraph's allocateBuffer method.
1162 /// By default the memory will be zero-initialized. Passing false for
1163 /// ZeroInitialize will prevent this.
1164 Block &createMutableContentBlock(Section &Parent, size_t ContentSize,
1166 uint64_t Alignment, uint64_t AlignmentOffset,
1167 bool ZeroInitialize = true) {
1168 auto Content = allocateBuffer(ContentSize);
1169 if (ZeroInitialize)
1170 memset(Content.data(), 0, Content.size());
1171 return createBlock(Parent, Content, Address, Alignment, AlignmentOffset);
1172 }
1173
1174 /// Create a zero-fill block.
1177 uint64_t AlignmentOffset) {
1178 return createBlock(Parent, Size, Address, Alignment, AlignmentOffset);
1179 }
1180
1181 /// Returns a BinaryStreamReader for the given block.
1184 reinterpret_cast<const uint8_t *>(B.getContent().data()), B.getSize());
1186 }
1187
1188 /// Returns a BinaryStreamWriter for the given block.
1189 /// This will call getMutableContent to obtain mutable content for the block.
1192 reinterpret_cast<uint8_t *>(B.getMutableContent(*this).data()),
1193 B.getSize());
1195 }
1196
1197 /// Cache type for the splitBlock function.
1198 using SplitBlockCache = std::optional<SmallVector<Symbol *, 8>>;
1199
1200 /// Splits block B into a sequence of smaller blocks.
1201 ///
1202 /// SplitOffsets should be a sequence of ascending offsets in B. The starting
1203 /// offset should be greater than zero, and the final offset less than
1204 /// B.getSize() - 1.
1205 ///
1206 /// The resulting seqeunce of blocks will start with the original block B
1207 /// (truncated to end at the first split offset) followed by newly introduced
1208 /// blocks starting at the subsequent split points.
1209 ///
1210 /// The optional Cache parameter can be used to speed up repeated calls to
1211 /// splitBlock for blocks within a single Section. If the value is None then
1212 /// the cache will be treated as uninitialized and splitBlock will populate
1213 /// it. Otherwise it is assumed to contain the list of Symbols pointing at B,
1214 /// sorted in descending order of offset.
1215 ///
1216 ///
1217 /// Notes:
1218 ///
1219 /// 1. splitBlock must be used with care. Splitting a block may cause
1220 /// incoming edges to become invalid if the edge target subexpression
1221 /// points outside the bounds of the newly split target block (E.g. an
1222 /// edge 'S + 10 : Pointer64' where S points to a newly split block
1223 /// whose size is less than 10). No attempt is made to detect invalidation
1224 /// of incoming edges, as in general this requires context that the
1225 /// LinkGraph does not have. Clients are responsible for ensuring that
1226 /// splitBlock is not used in a way that invalidates edges.
1227 ///
1228 /// 2. The newly introduced blocks will have new ordinals that will be higher
1229 /// than any other ordinals in the section. Clients are responsible for
1230 /// re-assigning block ordinals to restore a compatible order if needed.
1231 ///
1232 /// 3. The cache is not automatically updated if new symbols are introduced
1233 /// between calls to splitBlock. Any newly introduced symbols may be
1234 /// added to the cache manually (descending offset order must be
1235 /// preserved), or the cache can be set to None and rebuilt by
1236 /// splitBlock on the next call.
1237 template <typename SplitOffsetRange>
1238 std::vector<Block *> splitBlock(Block &B, SplitOffsetRange &&SplitOffsets,
1239 LinkGraph::SplitBlockCache *Cache = nullptr) {
1240 std::vector<Block *> Blocks;
1241 Blocks.push_back(&B);
1242
1243 if (std::empty(SplitOffsets))
1244 return Blocks;
1245
1246 // Special case zero-fill:
1247 if (B.isZeroFill()) {
1248 size_t OrigSize = B.getSize();
1249 for (Edge::OffsetT Offset : SplitOffsets) {
1250 assert(Offset > 0 && Offset < B.getSize() &&
1251 "Split offset must be inside block content");
1252 Blocks.back()->setZeroFillSize(
1253 Offset - (Blocks.back()->getAddress() - B.getAddress()));
1254 Blocks.push_back(&createZeroFillBlock(
1255 B.getSection(), B.getSize(), B.getAddress() + Offset,
1256 B.getAlignment(),
1257 (B.getAlignmentOffset() + Offset) % B.getAlignment()));
1258 }
1259 Blocks.back()->setZeroFillSize(
1260 OrigSize - (Blocks.back()->getAddress() - B.getAddress()));
1261 return Blocks;
1262 }
1263
1264 // Handle content blocks. We'll just create the blocks with their starting
1265 // address and no content here. The bulk of the work is deferred to
1266 // splitBlockImpl.
1267 for (Edge::OffsetT Offset : SplitOffsets) {
1268 assert(Offset > 0 && Offset < B.getSize() &&
1269 "Split offset must be inside block content");
1270 Blocks.push_back(&createContentBlock(
1271 B.getSection(), ArrayRef<char>(), B.getAddress() + Offset,
1272 B.getAlignment(),
1273 (B.getAlignmentOffset() + Offset) % B.getAlignment()));
1274 }
1275
1276 return splitBlockImpl(std::move(Blocks), Cache);
1277 }
1278
1279 /// Intern the given string in the LinkGraph's SymbolStringPool.
1281 return SSP->intern(SymbolName);
1282 }
1283
1284 /// Add an external symbol.
1285 /// Some formats (e.g. ELF) allow Symbols to have sizes. For Symbols whose
1286 /// size is not known, you should substitute '0'.
1287 /// The IsWeaklyReferenced argument determines whether the symbol must be
1288 /// present during lookup: Externals that are strongly referenced must be
1289 /// found or an error will be emitted. Externals that are weakly referenced
1290 /// are permitted to be undefined, in which case they are assigned an address
1291 /// of 0.
1294 bool IsWeaklyReferenced) {
1295 assert(!ExternalSymbols.contains(*Name) && "Duplicate external symbol");
1296 auto &Sym = Symbol::constructExternal(
1297 Allocator, createAddressable(orc::ExecutorAddr(), false),
1298 std::move(Name), Size, Linkage::Strong, IsWeaklyReferenced);
1299 ExternalSymbols.insert({*Sym.getName(), &Sym});
1300 return Sym;
1301 }
1302
1304 bool IsWeaklyReferenced) {
1305 return addExternalSymbol(SSP->intern(Name), Size, IsWeaklyReferenced);
1306 }
1307
1308 /// Add an absolute symbol.
1312 bool IsLive) {
1313 assert((S == Scope::Local || llvm::count_if(AbsoluteSymbols,
1314 [&](const Symbol *Sym) {
1315 return Sym->getName() == Name;
1316 }) == 0) &&
1317 "Duplicate absolute symbol");
1318 auto &Sym = Symbol::constructAbsolute(Allocator, createAddressable(Address),
1319 std::move(Name), Size, L, S, IsLive);
1320 AbsoluteSymbols.insert(&Sym);
1321 return Sym;
1322 }
1323
1326 bool IsLive) {
1327
1328 return addAbsoluteSymbol(SSP->intern(Name), Address, Size, L, S, IsLive);
1329 }
1330
1331 /// Add an anonymous symbol.
1333 orc::ExecutorAddrDiff Size, bool IsCallable,
1334 bool IsLive) {
1335 auto &Sym = Symbol::constructAnonDef(Allocator, Content, Offset, Size,
1336 IsCallable, IsLive);
1337 Content.getSection().addSymbol(Sym);
1338 return Sym;
1339 }
1340
1341 /// Add a named symbol.
1344 Linkage L, Scope S, bool IsCallable, bool IsLive) {
1345 return addDefinedSymbol(Content, Offset, SSP->intern(Name), Size, L, S,
1346 IsCallable, IsLive);
1347 }
1348
1352 bool IsCallable, bool IsLive) {
1354 [&](const Symbol *Sym) {
1355 return Sym->getName() == Name;
1356 }) == 0) &&
1357 "Duplicate defined symbol");
1358 auto &Sym =
1359 Symbol::constructNamedDef(Allocator, Content, Offset, std::move(Name),
1360 Size, L, S, IsLive, IsCallable);
1361 Content.getSection().addSymbol(Sym);
1362 return Sym;
1363 }
1364
1366 return make_range(
1367 section_iterator(Sections.begin(), GetSectionMapEntryValue()),
1368 section_iterator(Sections.end(), GetSectionMapEntryValue()));
1369 }
1370
1372 return make_range(
1373 const_section_iterator(Sections.begin(),
1374 GetSectionMapEntryConstValue()),
1375 const_section_iterator(Sections.end(), GetSectionMapEntryConstValue()));
1376 }
1377
1378 size_t sections_size() const { return Sections.size(); }
1379
1380 /// Returns the section with the given name if it exists, otherwise returns
1381 /// null.
1383 auto I = Sections.find(Name);
1384 if (I == Sections.end())
1385 return nullptr;
1386 return I->second.get();
1387 }
1388
1390 auto Secs = sections();
1391 return make_range(block_iterator(Secs.begin(), Secs.end()),
1392 block_iterator(Secs.end(), Secs.end()));
1393 }
1394
1396 auto Secs = sections();
1397 return make_range(const_block_iterator(Secs.begin(), Secs.end()),
1398 const_block_iterator(Secs.end(), Secs.end()));
1399 }
1400
1402 return make_range(
1403 external_symbol_iterator(ExternalSymbols.begin(),
1404 GetExternalSymbolMapEntryValue()),
1405 external_symbol_iterator(ExternalSymbols.end(),
1406 GetExternalSymbolMapEntryValue()));
1407 }
1408
1409 /// Returns the external symbol with the given name if one exists, otherwise
1410 /// returns nullptr.
1412 for (auto *Sym : external_symbols())
1413 if (Sym->getName() == Name)
1414 return Sym;
1415 return nullptr;
1416 }
1417
1419 return make_range(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1420 }
1421
1423 for (auto *Sym : absolute_symbols())
1424 if (Sym->getName() == Name)
1425 return Sym;
1426 return nullptr;
1427 }
1428
1430 auto Secs = sections();
1431 return make_range(defined_symbol_iterator(Secs.begin(), Secs.end()),
1432 defined_symbol_iterator(Secs.end(), Secs.end()));
1433 }
1434
1436 auto Secs = sections();
1437 return make_range(const_defined_symbol_iterator(Secs.begin(), Secs.end()),
1438 const_defined_symbol_iterator(Secs.end(), Secs.end()));
1439 }
1440
1441 /// Returns the defined symbol with the given name if one exists, otherwise
1442 /// returns nullptr.
1444 for (auto *Sym : defined_symbols())
1445 if (Sym->hasName() && Sym->getName() == Name)
1446 return Sym;
1447 return nullptr;
1448 }
1449
1450 /// Make the given symbol external (must not already be external).
1451 ///
1452 /// Symbol size, linkage and callability will be left unchanged. Symbol scope
1453 /// will be set to Default, and offset will be reset to 0.
1455 assert(!Sym.isExternal() && "Symbol is already external");
1456 if (Sym.isAbsolute()) {
1457 assert(AbsoluteSymbols.count(&Sym) &&
1458 "Sym is not in the absolute symbols set");
1459 assert(Sym.getOffset() == 0 && "Absolute not at offset 0");
1460 AbsoluteSymbols.erase(&Sym);
1461 auto &A = Sym.getAddressable();
1462 A.setAbsolute(false);
1463 A.setAddress(orc::ExecutorAddr());
1464 } else {
1465 assert(Sym.isDefined() && "Sym is not a defined symbol");
1466 Section &Sec = Sym.getSection();
1467 Sec.removeSymbol(Sym);
1468 Sym.makeExternal(createAddressable(orc::ExecutorAddr(), false));
1469 }
1470 ExternalSymbols.insert({*Sym.getName(), &Sym});
1471 }
1472
1473 /// Make the given symbol an absolute with the given address (must not already
1474 /// be absolute).
1475 ///
1476 /// The symbol's size, linkage, and callability, and liveness will be left
1477 /// unchanged, and its offset will be reset to 0.
1478 ///
1479 /// If the symbol was external then its scope will be set to local, otherwise
1480 /// it will be left unchanged.
1482 assert(!Sym.isAbsolute() && "Symbol is already absolute");
1483 if (Sym.isExternal()) {
1484 assert(ExternalSymbols.contains(*Sym.getName()) &&
1485 "Sym is not in the absolute symbols set");
1486 assert(Sym.getOffset() == 0 && "External is not at offset 0");
1487 ExternalSymbols.erase(*Sym.getName());
1488 auto &A = Sym.getAddressable();
1489 A.setAbsolute(true);
1490 A.setAddress(Address);
1491 Sym.setScope(Scope::Local);
1492 } else {
1493 assert(Sym.isDefined() && "Sym is not a defined symbol");
1494 Section &Sec = Sym.getSection();
1495 Sec.removeSymbol(Sym);
1496 Sym.makeAbsolute(createAddressable(Address));
1497 }
1498 AbsoluteSymbols.insert(&Sym);
1499 }
1500
1501 /// Turn an absolute or external symbol into a defined one by attaching it to
1502 /// a block. Symbol must not already be defined.
1505 bool IsLive) {
1506 assert(!Sym.isDefined() && "Sym is already a defined symbol");
1507 if (Sym.isAbsolute()) {
1508 assert(AbsoluteSymbols.count(&Sym) &&
1509 "Symbol is not in the absolutes set");
1510 AbsoluteSymbols.erase(&Sym);
1511 } else {
1512 assert(ExternalSymbols.contains(*Sym.getName()) &&
1513 "Symbol is not in the externals set");
1514 ExternalSymbols.erase(*Sym.getName());
1515 }
1516 Addressable &OldBase = *Sym.Base;
1517 Sym.setBlock(Content);
1518 Sym.setOffset(Offset);
1519 Sym.setSize(Size);
1520 Sym.setLinkage(L);
1521 Sym.setScope(S);
1522 Sym.setLive(IsLive);
1523 Content.getSection().addSymbol(Sym);
1524 destroyAddressable(OldBase);
1525 }
1526
1527 /// Transfer a defined symbol from one block to another.
1528 ///
1529 /// The symbol's offset within DestBlock is set to NewOffset.
1530 ///
1531 /// If ExplicitNewSize is given as None then the size of the symbol will be
1532 /// checked and auto-truncated to at most the size of the remainder (from the
1533 /// given offset) of the size of the new block.
1534 ///
1535 /// All other symbol attributes are unchanged.
1536 void
1538 orc::ExecutorAddrDiff NewOffset,
1539 std::optional<orc::ExecutorAddrDiff> ExplicitNewSize) {
1540 auto &OldSection = Sym.getSection();
1541 Sym.setBlock(DestBlock);
1542 Sym.setOffset(NewOffset);
1543 if (ExplicitNewSize)
1544 Sym.setSize(*ExplicitNewSize);
1545 else {
1546 auto RemainingBlockSize = DestBlock.getSize() - NewOffset;
1547 if (Sym.getSize() > RemainingBlockSize)
1548 Sym.setSize(RemainingBlockSize);
1549 }
1550 if (&DestBlock.getSection() != &OldSection) {
1551 OldSection.removeSymbol(Sym);
1552 DestBlock.getSection().addSymbol(Sym);
1553 }
1554 }
1555
1556 /// Transfers the given Block and all Symbols pointing to it to the given
1557 /// Section.
1558 ///
1559 /// No attempt is made to check compatibility of the source and destination
1560 /// sections. Blocks may be moved between sections with incompatible
1561 /// permissions (e.g. from data to text). The client is responsible for
1562 /// ensuring that this is safe.
1563 void transferBlock(Block &B, Section &NewSection) {
1564 auto &OldSection = B.getSection();
1565 if (&OldSection == &NewSection)
1566 return;
1567 SmallVector<Symbol *> AttachedSymbols;
1568 for (auto *S : OldSection.symbols())
1569 if (&S->getBlock() == &B)
1570 AttachedSymbols.push_back(S);
1571 for (auto *S : AttachedSymbols) {
1572 OldSection.removeSymbol(*S);
1573 NewSection.addSymbol(*S);
1574 }
1575 OldSection.removeBlock(B);
1576 NewSection.addBlock(B);
1577 }
1578
1579 /// Move all blocks and symbols from the source section to the destination
1580 /// section.
1581 ///
1582 /// If PreserveSrcSection is true (or SrcSection and DstSection are the same)
1583 /// then SrcSection is preserved, otherwise it is removed (the default).
1584 void mergeSections(Section &DstSection, Section &SrcSection,
1585 bool PreserveSrcSection = false) {
1586 if (&DstSection == &SrcSection)
1587 return;
1588 for (auto *B : SrcSection.blocks())
1589 B->setSection(DstSection);
1590 SrcSection.transferContentTo(DstSection);
1591 if (!PreserveSrcSection)
1592 removeSection(SrcSection);
1593 }
1594
1595 /// Removes an external symbol. Also removes the underlying Addressable.
1597 assert(!Sym.isDefined() && !Sym.isAbsolute() &&
1598 "Sym is not an external symbol");
1599 assert(ExternalSymbols.contains(*Sym.getName()) &&
1600 "Symbol is not in the externals set");
1601 ExternalSymbols.erase(*Sym.getName());
1602 Addressable &Base = *Sym.Base;
1604 [&](Symbol *AS) { return AS->Base == &Base; }) &&
1605 "Base addressable still in use");
1606 destroySymbol(Sym);
1607 destroyAddressable(Base);
1608 }
1609
1610 /// Remove an absolute symbol. Also removes the underlying Addressable.
1612 assert(!Sym.isDefined() && Sym.isAbsolute() &&
1613 "Sym is not an absolute symbol");
1614 assert(AbsoluteSymbols.count(&Sym) &&
1615 "Symbol is not in the absolute symbols set");
1616 AbsoluteSymbols.erase(&Sym);
1617 Addressable &Base = *Sym.Base;
1619 [&](Symbol *AS) { return AS->Base == &Base; }) &&
1620 "Base addressable still in use");
1621 destroySymbol(Sym);
1622 destroyAddressable(Base);
1623 }
1624
1625 /// Removes defined symbols. Does not remove the underlying block.
1627 assert(Sym.isDefined() && "Sym is not a defined symbol");
1628 Sym.getSection().removeSymbol(Sym);
1629 destroySymbol(Sym);
1630 }
1631
1632 /// Remove a block. The block reference is defunct after calling this
1633 /// function and should no longer be used.
1635 assert(llvm::none_of(B.getSection().symbols(),
1636 [&](const Symbol *Sym) {
1637 return &Sym->getBlock() == &B;
1638 }) &&
1639 "Block still has symbols attached");
1640 B.getSection().removeBlock(B);
1641 destroyBlock(B);
1642 }
1643
1644 /// Remove a section. The section reference is defunct after calling this
1645 /// function and should no longer be used.
1647 assert(Sections.count(Sec.getName()) && "Section not found");
1648 assert(Sections.find(Sec.getName())->second.get() == &Sec &&
1649 "Section map entry invalid");
1650 Sections.erase(Sec.getName());
1651 }
1652
1653 /// Accessor for the AllocActions object for this graph. This can be used to
1654 /// register allocation action calls prior to finalization.
1655 ///
1656 /// Accessing this object after finalization will result in undefined
1657 /// behavior.
1659
1660 /// Dump the graph.
1661 void dump(raw_ostream &OS);
1662
1663private:
1664 std::vector<Block *> splitBlockImpl(std::vector<Block *> Blocks,
1665 SplitBlockCache *Cache);
1666
1667 // Put the BumpPtrAllocator first so that we don't free any of the underlying
1668 // memory until the Symbol/Addressable destructors have been run.
1670
1671 std::string Name;
1672 std::shared_ptr<orc::SymbolStringPool> SSP;
1673 Triple TT;
1674 SubtargetFeatures Features;
1675 GetEdgeKindNameFunction GetEdgeKindName = nullptr;
1677 // FIXME(jared): these should become dense maps
1678 ExternalSymbolMap ExternalSymbols;
1679 AbsoluteSymbolSet AbsoluteSymbols;
1681};
1682
1684 if (!ContentMutable)
1685 setMutableContent(G.allocateContent({Data, Size}));
1686 return MutableArrayRef<char>(const_cast<char *>(Data), Size);
1687}
1688
1689/// Enables easy lookup of blocks by addresses.
1691public:
1692 using AddrToBlockMap = std::map<orc::ExecutorAddr, Block *>;
1693 using const_iterator = AddrToBlockMap::const_iterator;
1694
1695 /// A block predicate that always adds all blocks.
1696 static bool includeAllBlocks(const Block &B) { return true; }
1697
1698 /// A block predicate that always includes blocks with non-null addresses.
1699 static bool includeNonNull(const Block &B) { return !!B.getAddress(); }
1700
1701 BlockAddressMap() = default;
1702
1703 /// Add a block to the map. Returns an error if the block overlaps with any
1704 /// existing block.
1705 template <typename PredFn = decltype(includeAllBlocks)>
1707 if (!Pred(B))
1708 return Error::success();
1709
1710 auto I = AddrToBlock.upper_bound(B.getAddress());
1711
1712 // If we're not at the end of the map, check for overlap with the next
1713 // element.
1714 if (I != AddrToBlock.end()) {
1715 if (B.getAddress() + B.getSize() > I->second->getAddress())
1716 return overlapError(B, *I->second);
1717 }
1718
1719 // If we're not at the start of the map, check for overlap with the previous
1720 // element.
1721 if (I != AddrToBlock.begin()) {
1722 auto &PrevBlock = *std::prev(I)->second;
1723 if (PrevBlock.getAddress() + PrevBlock.getSize() > B.getAddress())
1724 return overlapError(B, PrevBlock);
1725 }
1726
1727 AddrToBlock.insert(I, std::make_pair(B.getAddress(), &B));
1728 return Error::success();
1729 }
1730
1731 /// Add a block to the map without checking for overlap with existing blocks.
1732 /// The client is responsible for ensuring that the block added does not
1733 /// overlap with any existing block.
1734 void addBlockWithoutChecking(Block &B) { AddrToBlock[B.getAddress()] = &B; }
1735
1736 /// Add a range of blocks to the map. Returns an error if any block in the
1737 /// range overlaps with any other block in the range, or with any existing
1738 /// block in the map.
1739 template <typename BlockPtrRange,
1740 typename PredFn = decltype(includeAllBlocks)>
1741 Error addBlocks(BlockPtrRange &&Blocks, PredFn Pred = includeAllBlocks) {
1742 for (auto *B : Blocks)
1743 if (auto Err = addBlock(*B, Pred))
1744 return Err;
1745 return Error::success();
1746 }
1747
1748 /// Add a range of blocks to the map without checking for overlap with
1749 /// existing blocks. The client is responsible for ensuring that the block
1750 /// added does not overlap with any existing block.
1751 template <typename BlockPtrRange>
1752 void addBlocksWithoutChecking(BlockPtrRange &&Blocks) {
1753 for (auto *B : Blocks)
1755 }
1756
1757 /// Iterates over (Address, Block*) pairs in ascending order of address.
1758 const_iterator begin() const { return AddrToBlock.begin(); }
1759 const_iterator end() const { return AddrToBlock.end(); }
1760
1761 /// Returns the block starting at the given address, or nullptr if no such
1762 /// block exists.
1764 auto I = AddrToBlock.find(Addr);
1765 if (I == AddrToBlock.end())
1766 return nullptr;
1767 return I->second;
1768 }
1769
1770 /// Returns the block covering the given address, or nullptr if no such block
1771 /// exists.
1773 auto I = AddrToBlock.upper_bound(Addr);
1774 if (I == AddrToBlock.begin())
1775 return nullptr;
1776 auto *B = std::prev(I)->second;
1777 if (Addr < B->getAddress() + B->getSize())
1778 return B;
1779 return nullptr;
1780 }
1781
1782private:
1783 Error overlapError(Block &NewBlock, Block &ExistingBlock) {
1784 auto NewBlockEnd = NewBlock.getAddress() + NewBlock.getSize();
1785 auto ExistingBlockEnd =
1786 ExistingBlock.getAddress() + ExistingBlock.getSize();
1787 return make_error<JITLinkError>(
1788 "Block at " +
1789 formatv("{0:x16} -- {1:x16}", NewBlock.getAddress().getValue(),
1790 NewBlockEnd.getValue()) +
1791 " overlaps " +
1792 formatv("{0:x16} -- {1:x16}", ExistingBlock.getAddress().getValue(),
1793 ExistingBlockEnd.getValue()));
1794 }
1795
1796 AddrToBlockMap AddrToBlock;
1797};
1798
1799/// A map of addresses to Symbols.
1801public:
1803
1804 /// Add a symbol to the SymbolAddressMap.
1806 AddrToSymbols[Sym.getAddress()].push_back(&Sym);
1807 }
1808
1809 /// Add all symbols in a given range to the SymbolAddressMap.
1810 template <typename SymbolPtrCollection>
1811 void addSymbols(SymbolPtrCollection &&Symbols) {
1812 for (auto *Sym : Symbols)
1813 addSymbol(*Sym);
1814 }
1815
1816 /// Returns the list of symbols that start at the given address, or nullptr if
1817 /// no such symbols exist.
1819 auto I = AddrToSymbols.find(Addr);
1820 if (I == AddrToSymbols.end())
1821 return nullptr;
1822 return &I->second;
1823 }
1824
1825private:
1826 std::map<orc::ExecutorAddr, SymbolVector> AddrToSymbols;
1827};
1828
1829/// A function for mutating LinkGraphs.
1831
1832/// A list of LinkGraph passes.
1833using LinkGraphPassList = std::vector<LinkGraphPassFunction>;
1834
1835/// An LinkGraph pass configuration, consisting of a list of pre-prune,
1836/// post-prune, and post-fixup passes.
1838
1839 /// Pre-prune passes.
1840 ///
1841 /// These passes are called on the graph after it is built, and before any
1842 /// symbols have been pruned. Graph nodes still have their original vmaddrs.
1843 ///
1844 /// Notable use cases: Marking symbols live or should-discard.
1846
1847 /// Post-prune passes.
1848 ///
1849 /// These passes are called on the graph after dead stripping, but before
1850 /// memory is allocated or nodes assigned their final addresses.
1851 ///
1852 /// Notable use cases: Building GOT, stub, and TLV symbols.
1854
1855 /// Post-allocation passes.
1856 ///
1857 /// These passes are called on the graph after memory has been allocated and
1858 /// defined nodes have been assigned their final addresses, but before the
1859 /// context has been notified of these addresses. At this point externals
1860 /// have not been resolved, and symbol content has not yet been copied into
1861 /// working memory.
1862 ///
1863 /// Notable use cases: Setting up data structures associated with addresses
1864 /// of defined symbols (e.g. a mapping of __dso_handle to JITDylib* for the
1865 /// JIT runtime) -- using a PostAllocationPass for this ensures that the
1866 /// data structures are in-place before any query for resolved symbols
1867 /// can complete.
1869
1870 /// Pre-fixup passes.
1871 ///
1872 /// These passes are called on the graph after memory has been allocated,
1873 /// content copied into working memory, and all nodes (including externals)
1874 /// have been assigned their final addresses, but before any fixups have been
1875 /// applied.
1876 ///
1877 /// Notable use cases: Late link-time optimizations like GOT and stub
1878 /// elimination.
1880
1881 /// Post-fixup passes.
1882 ///
1883 /// These passes are called on the graph after block contents has been copied
1884 /// to working memory, and fixups applied. Blocks have been updated to point
1885 /// to their fixed up content.
1886 ///
1887 /// Notable use cases: Testing and validation.
1889};
1890
1891/// Flags for symbol lookup.
1892///
1893/// FIXME: These basically duplicate orc::SymbolLookupFlags -- We should merge
1894/// the two types once we have an OrcSupport library.
1896
1898
1899/// A map of symbol names to resolved addresses.
1902
1903/// A function object to call with a resolved symbol map (See AsyncLookupResult)
1904/// or an error if resolution failed.
1906public:
1908 virtual void run(Expected<AsyncLookupResult> LR) = 0;
1909
1910private:
1911 virtual void anchor();
1912};
1913
1914/// Create a lookup continuation from a function object.
1915template <typename Continuation>
1916std::unique_ptr<JITLinkAsyncLookupContinuation>
1917createLookupContinuation(Continuation Cont) {
1918
1919 class Impl final : public JITLinkAsyncLookupContinuation {
1920 public:
1921 Impl(Continuation C) : C(std::move(C)) {}
1922 void run(Expected<AsyncLookupResult> LR) override { C(std::move(LR)); }
1923
1924 private:
1925 Continuation C;
1926 };
1927
1928 return std::make_unique<Impl>(std::move(Cont));
1929}
1930
1931/// Holds context for a single jitLink invocation.
1933public:
1935
1936 /// Create a JITLinkContext.
1937 JITLinkContext(const JITLinkDylib *JD) : JD(JD) {}
1938
1939 /// Destroy a JITLinkContext.
1941
1942 /// Return the JITLinkDylib that this link is targeting, if any.
1943 const JITLinkDylib *getJITLinkDylib() const { return JD; }
1944
1945 /// Return the MemoryManager to be used for this link.
1947
1948 /// Notify this context that linking failed.
1949 /// Called by JITLink if linking cannot be completed.
1950 virtual void notifyFailed(Error Err) = 0;
1951
1952 /// Called by JITLink to resolve external symbols. This method is passed a
1953 /// lookup continutation which it must call with a result to continue the
1954 /// linking process.
1955 virtual void lookup(const LookupMap &Symbols,
1956 std::unique_ptr<JITLinkAsyncLookupContinuation> LC) = 0;
1957
1958 /// Called by JITLink once all defined symbols in the graph have been assigned
1959 /// their final memory locations in the target process. At this point the
1960 /// LinkGraph can be inspected to build a symbol table, however the block
1961 /// content will not generally have been copied to the target location yet.
1962 ///
1963 /// If the client detects an error in the LinkGraph state (e.g. unexpected or
1964 /// missing symbols) they may return an error here. The error will be
1965 /// propagated to notifyFailed and the linker will bail out.
1967
1968 /// Called by JITLink to notify the context that the object has been
1969 /// finalized (i.e. emitted to memory and memory permissions set). If all of
1970 /// this objects dependencies have also been finalized then the code is ready
1971 /// to run.
1973
1974 /// Called by JITLink prior to linking to determine whether default passes for
1975 /// the target should be added. The default implementation returns true.
1976 /// If subclasses override this method to return false for any target then
1977 /// they are required to fully configure the pass pipeline for that target.
1978 virtual bool shouldAddDefaultTargetPasses(const Triple &TT) const;
1979
1980 /// Returns the mark-live pass to be used for this link. If no pass is
1981 /// returned (the default) then the target-specific linker implementation will
1982 /// choose a conservative default (usually marking all symbols live).
1983 /// This function is only called if shouldAddDefaultTargetPasses returns true,
1984 /// otherwise the JITContext is responsible for adding a mark-live pass in
1985 /// modifyPassConfig.
1986 virtual LinkGraphPassFunction getMarkLivePass(const Triple &TT) const;
1987
1988 /// Called by JITLink to modify the pass pipeline prior to linking.
1989 /// The default version performs no modification.
1991
1992private:
1993 const JITLinkDylib *JD = nullptr;
1994};
1995
1996/// Marks all symbols in a graph live. This can be used as a default,
1997/// conservative mark-live implementation.
1999
2000/// Create an out of range error for the given edge in the given block.
2002 const Edge &E);
2003
2005 const Edge &E);
2006
2007/// Creates a new pointer block in the given section and returns an
2008/// Anonymous symbol pointing to it.
2009///
2010/// The pointer block will have the following default values:
2011/// alignment: PointerSize
2012/// alignment-offset: 0
2013/// address: highest allowable
2015 unique_function<Symbol &(LinkGraph &G, Section &PointerSection,
2016 Symbol *InitialTarget, uint64_t InitialAddend)>;
2017
2018/// Get target-specific AnonymousPointerCreator
2020
2021/// Create a jump stub that jumps via the pointer at the given symbol and
2022/// an anonymous symbol pointing to it. Return the anonymous symbol.
2023///
2024/// The stub block will be created by createPointerJumpStubBlock.
2026 LinkGraph &G, Section &StubSection, Symbol &PointerSymbol)>;
2027
2028/// Get target-specific PointerJumpStubCreator
2030
2031/// Base case for edge-visitors where the visitor-list is empty.
2032inline void visitEdge(LinkGraph &G, Block *B, Edge &E) {}
2033
2034/// Applies the first visitor in the list to the given edge. If the visitor's
2035/// visitEdge method returns true then we return immediately, otherwise we
2036/// apply the next visitor.
2037template <typename VisitorT, typename... VisitorTs>
2038void visitEdge(LinkGraph &G, Block *B, Edge &E, VisitorT &&V,
2039 VisitorTs &&...Vs) {
2040 if (!V.visitEdge(G, B, E))
2041 visitEdge(G, B, E, std::forward<VisitorTs>(Vs)...);
2042}
2043
2044/// For each edge in the given graph, apply a list of visitors to the edge,
2045/// stopping when the first visitor's visitEdge method returns true.
2046///
2047/// Only visits edges that were in the graph at call time: if any visitor
2048/// adds new edges those will not be visited. Visitors are not allowed to
2049/// remove edges (though they can change their kind, target, and addend).
2050template <typename... VisitorTs>
2051void visitExistingEdges(LinkGraph &G, VisitorTs &&...Vs) {
2052 // We may add new blocks during this process, but we don't want to iterate
2053 // over them, so build a worklist.
2054 std::vector<Block *> Worklist(G.blocks().begin(), G.blocks().end());
2055
2056 for (auto *B : Worklist)
2057 for (auto &E : B->edges())
2058 visitEdge(G, B, E, std::forward<VisitorTs>(Vs)...);
2059}
2060
2061/// Create a LinkGraph from the given object buffer.
2062///
2063/// Note: The graph does not take ownership of the underlying buffer, nor copy
2064/// its contents. The caller is responsible for ensuring that the object buffer
2065/// outlives the graph.
2068 std::shared_ptr<orc::SymbolStringPool> SSP);
2069
2070/// Create a \c LinkGraph defining the given absolute symbols.
2071std::unique_ptr<LinkGraph>
2072absoluteSymbolsLinkGraph(Triple TT, std::shared_ptr<orc::SymbolStringPool> SSP,
2073 orc::SymbolMap Symbols);
2074
2075/// Link the given graph.
2076void link(std::unique_ptr<LinkGraph> G, std::unique_ptr<JITLinkContext> Ctx);
2077
2078} // end namespace jitlink
2079} // end namespace llvm
2080
2081#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:560
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
static Split data
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:2007
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:297
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
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition: STLExtras.h:573
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.