JITLink.h 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===------------ JITLink.h - JIT linker functionality ----------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // Contains generic JIT-linker types.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_EXECUTIONENGINE_JITLINK_JITLINK_H
  18. #define LLVM_EXECUTIONENGINE_JITLINK_JITLINK_H
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/DenseSet.h"
  21. #include "llvm/ADT/Optional.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/Triple.h"
  24. #include "llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h"
  25. #include "llvm/ExecutionEngine/JITLink/MemoryFlags.h"
  26. #include "llvm/ExecutionEngine/JITSymbol.h"
  27. #include "llvm/Support/Allocator.h"
  28. #include "llvm/Support/Endian.h"
  29. #include "llvm/Support/Error.h"
  30. #include "llvm/Support/FormatVariadic.h"
  31. #include "llvm/Support/MathExtras.h"
  32. #include "llvm/Support/MemoryBuffer.h"
  33. #include <map>
  34. #include <string>
  35. #include <system_error>
  36. namespace llvm {
  37. namespace jitlink {
  38. class LinkGraph;
  39. class Symbol;
  40. class Section;
  41. /// Base class for errors originating in JIT linker, e.g. missing relocation
  42. /// support.
  43. class JITLinkError : public ErrorInfo<JITLinkError> {
  44. public:
  45. static char ID;
  46. JITLinkError(Twine ErrMsg) : ErrMsg(ErrMsg.str()) {}
  47. void log(raw_ostream &OS) const override;
  48. const std::string &getErrorMessage() const { return ErrMsg; }
  49. std::error_code convertToErrorCode() const override;
  50. private:
  51. std::string ErrMsg;
  52. };
  53. /// Represents fixups and constraints in the LinkGraph.
  54. class Edge {
  55. public:
  56. using Kind = uint8_t;
  57. enum GenericEdgeKind : Kind {
  58. Invalid, // Invalid edge value.
  59. FirstKeepAlive, // Keeps target alive. Offset/addend zero.
  60. KeepAlive = FirstKeepAlive, // Tag first edge kind that preserves liveness.
  61. FirstRelocation // First architecture specific relocation.
  62. };
  63. using OffsetT = uint32_t;
  64. using AddendT = int64_t;
  65. Edge(Kind K, OffsetT Offset, Symbol &Target, AddendT Addend)
  66. : Target(&Target), Offset(Offset), Addend(Addend), K(K) {}
  67. OffsetT getOffset() const { return Offset; }
  68. void setOffset(OffsetT Offset) { this->Offset = Offset; }
  69. Kind getKind() const { return K; }
  70. void setKind(Kind K) { this->K = K; }
  71. bool isRelocation() const { return K >= FirstRelocation; }
  72. Kind getRelocation() const {
  73. assert(isRelocation() && "Not a relocation edge");
  74. return K - FirstRelocation;
  75. }
  76. bool isKeepAlive() const { return K >= FirstKeepAlive; }
  77. Symbol &getTarget() const { return *Target; }
  78. void setTarget(Symbol &Target) { this->Target = &Target; }
  79. AddendT getAddend() const { return Addend; }
  80. void setAddend(AddendT Addend) { this->Addend = Addend; }
  81. private:
  82. Symbol *Target = nullptr;
  83. OffsetT Offset = 0;
  84. AddendT Addend = 0;
  85. Kind K = 0;
  86. };
  87. /// Returns the string name of the given generic edge kind, or "unknown"
  88. /// otherwise. Useful for debugging.
  89. const char *getGenericEdgeKindName(Edge::Kind K);
  90. /// Base class for Addressable entities (externals, absolutes, blocks).
  91. class Addressable {
  92. friend class LinkGraph;
  93. protected:
  94. Addressable(orc::ExecutorAddr Address, bool IsDefined)
  95. : Address(Address), IsDefined(IsDefined), IsAbsolute(false) {}
  96. Addressable(orc::ExecutorAddr Address)
  97. : Address(Address), IsDefined(false), IsAbsolute(true) {
  98. assert(!(IsDefined && IsAbsolute) &&
  99. "Block cannot be both defined and absolute");
  100. }
  101. public:
  102. Addressable(const Addressable &) = delete;
  103. Addressable &operator=(const Addressable &) = default;
  104. Addressable(Addressable &&) = delete;
  105. Addressable &operator=(Addressable &&) = default;
  106. orc::ExecutorAddr getAddress() const { return Address; }
  107. void setAddress(orc::ExecutorAddr Address) { this->Address = Address; }
  108. /// Returns true if this is a defined addressable, in which case you
  109. /// can downcast this to a Block.
  110. bool isDefined() const { return static_cast<bool>(IsDefined); }
  111. bool isAbsolute() const { return static_cast<bool>(IsAbsolute); }
  112. private:
  113. void setAbsolute(bool IsAbsolute) {
  114. assert(!IsDefined && "Cannot change the Absolute flag on a defined block");
  115. this->IsAbsolute = IsAbsolute;
  116. }
  117. orc::ExecutorAddr Address;
  118. uint64_t IsDefined : 1;
  119. uint64_t IsAbsolute : 1;
  120. protected:
  121. // bitfields for Block, allocated here to improve packing.
  122. uint64_t ContentMutable : 1;
  123. uint64_t P2Align : 5;
  124. uint64_t AlignmentOffset : 56;
  125. };
  126. using SectionOrdinal = unsigned;
  127. /// An Addressable with content and edges.
  128. class Block : public Addressable {
  129. friend class LinkGraph;
  130. private:
  131. /// Create a zero-fill defined addressable.
  132. Block(Section &Parent, orc::ExecutorAddrDiff Size, orc::ExecutorAddr Address,
  133. uint64_t Alignment, uint64_t AlignmentOffset)
  134. : Addressable(Address, true), Parent(&Parent), Size(Size) {
  135. assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
  136. assert(AlignmentOffset < Alignment &&
  137. "Alignment offset cannot exceed alignment");
  138. assert(AlignmentOffset <= MaxAlignmentOffset &&
  139. "Alignment offset exceeds maximum");
  140. ContentMutable = false;
  141. P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
  142. this->AlignmentOffset = AlignmentOffset;
  143. }
  144. /// Create a defined addressable for the given content.
  145. /// The Content is assumed to be non-writable, and will be copied when
  146. /// mutations are required.
  147. Block(Section &Parent, ArrayRef<char> Content, orc::ExecutorAddr Address,
  148. uint64_t Alignment, uint64_t AlignmentOffset)
  149. : Addressable(Address, true), Parent(&Parent), Data(Content.data()),
  150. Size(Content.size()) {
  151. assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
  152. assert(AlignmentOffset < Alignment &&
  153. "Alignment offset cannot exceed alignment");
  154. assert(AlignmentOffset <= MaxAlignmentOffset &&
  155. "Alignment offset exceeds maximum");
  156. ContentMutable = false;
  157. P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
  158. this->AlignmentOffset = AlignmentOffset;
  159. }
  160. /// Create a defined addressable for the given content.
  161. /// The content is assumed to be writable, and the caller is responsible
  162. /// for ensuring that it lives for the duration of the Block's lifetime.
  163. /// The standard way to achieve this is to allocate it on the Graph's
  164. /// allocator.
  165. Block(Section &Parent, MutableArrayRef<char> Content,
  166. orc::ExecutorAddr Address, uint64_t Alignment, uint64_t AlignmentOffset)
  167. : Addressable(Address, true), Parent(&Parent), Data(Content.data()),
  168. Size(Content.size()) {
  169. assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
  170. assert(AlignmentOffset < Alignment &&
  171. "Alignment offset cannot exceed alignment");
  172. assert(AlignmentOffset <= MaxAlignmentOffset &&
  173. "Alignment offset exceeds maximum");
  174. ContentMutable = true;
  175. P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
  176. this->AlignmentOffset = AlignmentOffset;
  177. }
  178. public:
  179. using EdgeVector = std::vector<Edge>;
  180. using edge_iterator = EdgeVector::iterator;
  181. using const_edge_iterator = EdgeVector::const_iterator;
  182. Block(const Block &) = delete;
  183. Block &operator=(const Block &) = delete;
  184. Block(Block &&) = delete;
  185. Block &operator=(Block &&) = delete;
  186. /// Return the parent section for this block.
  187. Section &getSection() const { return *Parent; }
  188. /// Returns true if this is a zero-fill block.
  189. ///
  190. /// If true, getSize is callable but getContent is not (the content is
  191. /// defined to be a sequence of zero bytes of length Size).
  192. bool isZeroFill() const { return !Data; }
  193. /// Returns the size of this defined addressable.
  194. size_t getSize() const { return Size; }
  195. /// Get the content for this block. Block must not be a zero-fill block.
  196. ArrayRef<char> getContent() const {
  197. assert(Data && "Block does not contain content");
  198. return ArrayRef<char>(Data, Size);
  199. }
  200. /// Set the content for this block.
  201. /// Caller is responsible for ensuring the underlying bytes are not
  202. /// deallocated while pointed to by this block.
  203. void setContent(ArrayRef<char> Content) {
  204. assert(Content.data() && "Setting null content");
  205. Data = Content.data();
  206. Size = Content.size();
  207. ContentMutable = false;
  208. }
  209. /// Get mutable content for this block.
  210. ///
  211. /// If this Block's content is not already mutable this will trigger a copy
  212. /// of the existing immutable content to a new, mutable buffer allocated using
  213. /// LinkGraph::allocateContent.
  214. MutableArrayRef<char> getMutableContent(LinkGraph &G);
  215. /// Get mutable content for this block.
  216. ///
  217. /// This block's content must already be mutable. It is a programmatic error
  218. /// to call this on a block with immutable content -- consider using
  219. /// getMutableContent instead.
  220. MutableArrayRef<char> getAlreadyMutableContent() {
  221. assert(Data && "Block does not contain content");
  222. assert(ContentMutable && "Content is not mutable");
  223. return MutableArrayRef<char>(const_cast<char *>(Data), Size);
  224. }
  225. /// Set mutable content for this block.
  226. ///
  227. /// The caller is responsible for ensuring that the memory pointed to by
  228. /// MutableContent is not deallocated while pointed to by this block.
  229. void setMutableContent(MutableArrayRef<char> MutableContent) {
  230. assert(MutableContent.data() && "Setting null content");
  231. Data = MutableContent.data();
  232. Size = MutableContent.size();
  233. ContentMutable = true;
  234. }
  235. /// Returns true if this block's content is mutable.
  236. ///
  237. /// This is primarily useful for asserting that a block is already in a
  238. /// mutable state prior to modifying the content. E.g. when applying
  239. /// fixups we expect the block to already be mutable as it should have been
  240. /// copied to working memory.
  241. bool isContentMutable() const { return ContentMutable; }
  242. /// Get the alignment for this content.
  243. uint64_t getAlignment() const { return 1ull << P2Align; }
  244. /// Set the alignment for this content.
  245. void setAlignment(uint64_t Alignment) {
  246. assert(isPowerOf2_64(Alignment) && "Alignment must be a power of two");
  247. P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
  248. }
  249. /// Get the alignment offset for this content.
  250. uint64_t getAlignmentOffset() const { return AlignmentOffset; }
  251. /// Set the alignment offset for this content.
  252. void setAlignmentOffset(uint64_t AlignmentOffset) {
  253. assert(AlignmentOffset < (1ull << P2Align) &&
  254. "Alignment offset can't exceed alignment");
  255. this->AlignmentOffset = AlignmentOffset;
  256. }
  257. /// Add an edge to this block.
  258. void addEdge(Edge::Kind K, Edge::OffsetT Offset, Symbol &Target,
  259. Edge::AddendT Addend) {
  260. assert(!isZeroFill() && "Adding edge to zero-fill block?");
  261. Edges.push_back(Edge(K, Offset, Target, Addend));
  262. }
  263. /// Add an edge by copying an existing one. This is typically used when
  264. /// moving edges between blocks.
  265. void addEdge(const Edge &E) { Edges.push_back(E); }
  266. /// Return the list of edges attached to this content.
  267. iterator_range<edge_iterator> edges() {
  268. return make_range(Edges.begin(), Edges.end());
  269. }
  270. /// Returns the list of edges attached to this content.
  271. iterator_range<const_edge_iterator> edges() const {
  272. return make_range(Edges.begin(), Edges.end());
  273. }
  274. /// Return the size of the edges list.
  275. size_t edges_size() const { return Edges.size(); }
  276. /// Returns true if the list of edges is empty.
  277. bool edges_empty() const { return Edges.empty(); }
  278. /// Remove the edge pointed to by the given iterator.
  279. /// Returns an iterator to the new next element.
  280. edge_iterator removeEdge(edge_iterator I) { return Edges.erase(I); }
  281. /// Returns the address of the fixup for the given edge, which is equal to
  282. /// this block's address plus the edge's offset.
  283. orc::ExecutorAddr getFixupAddress(const Edge &E) const {
  284. return getAddress() + E.getOffset();
  285. }
  286. private:
  287. static constexpr uint64_t MaxAlignmentOffset = (1ULL << 56) - 1;
  288. void setSection(Section &Parent) { this->Parent = &Parent; }
  289. Section *Parent;
  290. const char *Data = nullptr;
  291. size_t Size = 0;
  292. std::vector<Edge> Edges;
  293. };
  294. // Align an address to conform with block alignment requirements.
  295. inline uint64_t alignToBlock(uint64_t Addr, Block &B) {
  296. uint64_t Delta = (B.getAlignmentOffset() - Addr) % B.getAlignment();
  297. return Addr + Delta;
  298. }
  299. // Align a orc::ExecutorAddr to conform with block alignment requirements.
  300. inline orc::ExecutorAddr alignToBlock(orc::ExecutorAddr Addr, Block &B) {
  301. return orc::ExecutorAddr(alignToBlock(Addr.getValue(), B));
  302. }
  303. /// Describes symbol linkage. This can be used to make resolve definition
  304. /// clashes.
  305. enum class Linkage : uint8_t {
  306. Strong,
  307. Weak,
  308. };
  309. /// For errors and debugging output.
  310. const char *getLinkageName(Linkage L);
  311. /// Defines the scope in which this symbol should be visible:
  312. /// Default -- Visible in the public interface of the linkage unit.
  313. /// Hidden -- Visible within the linkage unit, but not exported from it.
  314. /// Local -- Visible only within the LinkGraph.
  315. enum class Scope : uint8_t {
  316. Default,
  317. Hidden,
  318. Local
  319. };
  320. /// For debugging output.
  321. const char *getScopeName(Scope S);
  322. raw_ostream &operator<<(raw_ostream &OS, const Block &B);
  323. /// Symbol representation.
  324. ///
  325. /// Symbols represent locations within Addressable objects.
  326. /// They can be either Named or Anonymous.
  327. /// Anonymous symbols have neither linkage nor visibility, and must point at
  328. /// ContentBlocks.
  329. /// Named symbols may be in one of four states:
  330. /// - Null: Default initialized. Assignable, but otherwise unusable.
  331. /// - Defined: Has both linkage and visibility and points to a ContentBlock
  332. /// - Common: Has both linkage and visibility, points to a null Addressable.
  333. /// - External: Has neither linkage nor visibility, points to an external
  334. /// Addressable.
  335. ///
  336. class Symbol {
  337. friend class LinkGraph;
  338. private:
  339. Symbol(Addressable &Base, orc::ExecutorAddrDiff Offset, StringRef Name,
  340. orc::ExecutorAddrDiff Size, Linkage L, Scope S, bool IsLive,
  341. bool IsCallable)
  342. : Name(Name), Base(&Base), Offset(Offset), Size(Size) {
  343. assert(Offset <= MaxOffset && "Offset out of range");
  344. setLinkage(L);
  345. setScope(S);
  346. setLive(IsLive);
  347. setCallable(IsCallable);
  348. }
  349. static Symbol &constructCommon(void *SymStorage, Block &Base, StringRef Name,
  350. orc::ExecutorAddrDiff Size, Scope S,
  351. bool IsLive) {
  352. assert(SymStorage && "Storage cannot be null");
  353. assert(!Name.empty() && "Common symbol name cannot be empty");
  354. assert(Base.isDefined() &&
  355. "Cannot create common symbol from undefined block");
  356. assert(static_cast<Block &>(Base).getSize() == Size &&
  357. "Common symbol size should match underlying block size");
  358. auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
  359. new (Sym) Symbol(Base, 0, Name, Size, Linkage::Weak, S, IsLive, false);
  360. return *Sym;
  361. }
  362. static Symbol &constructExternal(void *SymStorage, Addressable &Base,
  363. StringRef Name, orc::ExecutorAddrDiff Size,
  364. Linkage L) {
  365. assert(SymStorage && "Storage cannot be null");
  366. assert(!Base.isDefined() &&
  367. "Cannot create external symbol from defined block");
  368. assert(!Name.empty() && "External symbol name cannot be empty");
  369. auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
  370. new (Sym) Symbol(Base, 0, Name, Size, L, Scope::Default, false, false);
  371. return *Sym;
  372. }
  373. static Symbol &constructAbsolute(void *SymStorage, Addressable &Base,
  374. StringRef Name, orc::ExecutorAddrDiff Size,
  375. Linkage L, Scope S, bool IsLive) {
  376. assert(SymStorage && "Storage cannot be null");
  377. assert(!Base.isDefined() &&
  378. "Cannot create absolute symbol from a defined block");
  379. auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
  380. new (Sym) Symbol(Base, 0, Name, Size, L, S, IsLive, false);
  381. return *Sym;
  382. }
  383. static Symbol &constructAnonDef(void *SymStorage, Block &Base,
  384. orc::ExecutorAddrDiff Offset,
  385. orc::ExecutorAddrDiff Size, bool IsCallable,
  386. bool IsLive) {
  387. assert(SymStorage && "Storage cannot be null");
  388. assert((Offset + Size) <= Base.getSize() &&
  389. "Symbol extends past end of block");
  390. auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
  391. new (Sym) Symbol(Base, Offset, StringRef(), Size, Linkage::Strong,
  392. Scope::Local, IsLive, IsCallable);
  393. return *Sym;
  394. }
  395. static Symbol &constructNamedDef(void *SymStorage, Block &Base,
  396. orc::ExecutorAddrDiff Offset, StringRef Name,
  397. orc::ExecutorAddrDiff Size, Linkage L,
  398. Scope S, bool IsLive, bool IsCallable) {
  399. assert(SymStorage && "Storage cannot be null");
  400. assert((Offset + Size) <= Base.getSize() &&
  401. "Symbol extends past end of block");
  402. assert(!Name.empty() && "Name cannot be empty");
  403. auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
  404. new (Sym) Symbol(Base, Offset, Name, Size, L, S, IsLive, IsCallable);
  405. return *Sym;
  406. }
  407. public:
  408. /// Create a null Symbol. This allows Symbols to be default initialized for
  409. /// use in containers (e.g. as map values). Null symbols are only useful for
  410. /// assigning to.
  411. Symbol() = default;
  412. // Symbols are not movable or copyable.
  413. Symbol(const Symbol &) = delete;
  414. Symbol &operator=(const Symbol &) = delete;
  415. Symbol(Symbol &&) = delete;
  416. Symbol &operator=(Symbol &&) = delete;
  417. /// Returns true if this symbol has a name.
  418. bool hasName() const { return !Name.empty(); }
  419. /// Returns the name of this symbol (empty if the symbol is anonymous).
  420. StringRef getName() const {
  421. assert((!Name.empty() || getScope() == Scope::Local) &&
  422. "Anonymous symbol has non-local scope");
  423. return Name;
  424. }
  425. /// Rename this symbol. The client is responsible for updating scope and
  426. /// linkage if this name-change requires it.
  427. void setName(StringRef Name) { this->Name = Name; }
  428. /// Returns true if this Symbol has content (potentially) defined within this
  429. /// object file (i.e. is anything but an external or absolute symbol).
  430. bool isDefined() const {
  431. assert(Base && "Attempt to access null symbol");
  432. return Base->isDefined();
  433. }
  434. /// Returns true if this symbol is live (i.e. should be treated as a root for
  435. /// dead stripping).
  436. bool isLive() const {
  437. assert(Base && "Attempting to access null symbol");
  438. return IsLive;
  439. }
  440. /// Set this symbol's live bit.
  441. void setLive(bool IsLive) { this->IsLive = IsLive; }
  442. /// Returns true is this symbol is callable.
  443. bool isCallable() const { return IsCallable; }
  444. /// Set this symbol's callable bit.
  445. void setCallable(bool IsCallable) { this->IsCallable = IsCallable; }
  446. /// Returns true if the underlying addressable is an unresolved external.
  447. bool isExternal() const {
  448. assert(Base && "Attempt to access null symbol");
  449. return !Base->isDefined() && !Base->isAbsolute();
  450. }
  451. /// Returns true if the underlying addressable is an absolute symbol.
  452. bool isAbsolute() const {
  453. assert(Base && "Attempt to access null symbol");
  454. return Base->isAbsolute();
  455. }
  456. /// Return the addressable that this symbol points to.
  457. Addressable &getAddressable() {
  458. assert(Base && "Cannot get underlying addressable for null symbol");
  459. return *Base;
  460. }
  461. /// Return the addressable that thsi symbol points to.
  462. const Addressable &getAddressable() const {
  463. assert(Base && "Cannot get underlying addressable for null symbol");
  464. return *Base;
  465. }
  466. /// Return the Block for this Symbol (Symbol must be defined).
  467. Block &getBlock() {
  468. assert(Base && "Cannot get block for null symbol");
  469. assert(Base->isDefined() && "Not a defined symbol");
  470. return static_cast<Block &>(*Base);
  471. }
  472. /// Return the Block for this Symbol (Symbol must be defined).
  473. const Block &getBlock() const {
  474. assert(Base && "Cannot get block for null symbol");
  475. assert(Base->isDefined() && "Not a defined symbol");
  476. return static_cast<const Block &>(*Base);
  477. }
  478. /// Returns the offset for this symbol within the underlying addressable.
  479. orc::ExecutorAddrDiff getOffset() const { return Offset; }
  480. /// Returns the address of this symbol.
  481. orc::ExecutorAddr getAddress() const { return Base->getAddress() + Offset; }
  482. /// Returns the size of this symbol.
  483. orc::ExecutorAddrDiff getSize() const { return Size; }
  484. /// Set the size of this symbol.
  485. void setSize(orc::ExecutorAddrDiff Size) {
  486. assert(Base && "Cannot set size for null Symbol");
  487. assert((Size == 0 || Base->isDefined()) &&
  488. "Non-zero size can only be set for defined symbols");
  489. assert((Offset + Size <= static_cast<const Block &>(*Base).getSize()) &&
  490. "Symbol size cannot extend past the end of its containing block");
  491. this->Size = Size;
  492. }
  493. /// Returns true if this symbol is backed by a zero-fill block.
  494. /// This method may only be called on defined symbols.
  495. bool isSymbolZeroFill() const { return getBlock().isZeroFill(); }
  496. /// Returns the content in the underlying block covered by this symbol.
  497. /// This method may only be called on defined non-zero-fill symbols.
  498. ArrayRef<char> getSymbolContent() const {
  499. return getBlock().getContent().slice(Offset, Size);
  500. }
  501. /// Get the linkage for this Symbol.
  502. Linkage getLinkage() const { return static_cast<Linkage>(L); }
  503. /// Set the linkage for this Symbol.
  504. void setLinkage(Linkage L) {
  505. assert((L == Linkage::Strong || (!Base->isAbsolute() && !Name.empty())) &&
  506. "Linkage can only be applied to defined named symbols");
  507. this->L = static_cast<uint8_t>(L);
  508. }
  509. /// Get the visibility for this Symbol.
  510. Scope getScope() const { return static_cast<Scope>(S); }
  511. /// Set the visibility for this Symbol.
  512. void setScope(Scope S) {
  513. assert((!Name.empty() || S == Scope::Local) &&
  514. "Can not set anonymous symbol to non-local scope");
  515. assert((S == Scope::Default || Base->isDefined() || Base->isAbsolute()) &&
  516. "Invalid visibility for symbol type");
  517. this->S = static_cast<uint8_t>(S);
  518. }
  519. private:
  520. void makeExternal(Addressable &A) {
  521. assert(!A.isDefined() && !A.isAbsolute() &&
  522. "Attempting to make external with defined or absolute block");
  523. Base = &A;
  524. Offset = 0;
  525. setScope(Scope::Default);
  526. IsLive = 0;
  527. // note: Size, Linkage and IsCallable fields left unchanged.
  528. }
  529. void makeAbsolute(Addressable &A) {
  530. assert(!A.isDefined() && A.isAbsolute() &&
  531. "Attempting to make absolute with defined or external block");
  532. Base = &A;
  533. Offset = 0;
  534. }
  535. void setBlock(Block &B) { Base = &B; }
  536. void setOffset(orc::ExecutorAddrDiff NewOffset) {
  537. assert(NewOffset <= MaxOffset && "Offset out of range");
  538. Offset = NewOffset;
  539. }
  540. static constexpr uint64_t MaxOffset = (1ULL << 59) - 1;
  541. // FIXME: A char* or SymbolStringPtr may pack better.
  542. StringRef Name;
  543. Addressable *Base = nullptr;
  544. uint64_t Offset : 59;
  545. uint64_t L : 1;
  546. uint64_t S : 2;
  547. uint64_t IsLive : 1;
  548. uint64_t IsCallable : 1;
  549. orc::ExecutorAddrDiff Size = 0;
  550. };
  551. raw_ostream &operator<<(raw_ostream &OS, const Symbol &A);
  552. void printEdge(raw_ostream &OS, const Block &B, const Edge &E,
  553. StringRef EdgeKindName);
  554. /// Represents an object file section.
  555. class Section {
  556. friend class LinkGraph;
  557. private:
  558. Section(StringRef Name, MemProt Prot, SectionOrdinal SecOrdinal)
  559. : Name(Name), Prot(Prot), SecOrdinal(SecOrdinal) {}
  560. using SymbolSet = DenseSet<Symbol *>;
  561. using BlockSet = DenseSet<Block *>;
  562. public:
  563. using symbol_iterator = SymbolSet::iterator;
  564. using const_symbol_iterator = SymbolSet::const_iterator;
  565. using block_iterator = BlockSet::iterator;
  566. using const_block_iterator = BlockSet::const_iterator;
  567. ~Section();
  568. // Sections are not movable or copyable.
  569. Section(const Section &) = delete;
  570. Section &operator=(const Section &) = delete;
  571. Section(Section &&) = delete;
  572. Section &operator=(Section &&) = delete;
  573. /// Returns the name of this section.
  574. StringRef getName() const { return Name; }
  575. /// Returns the protection flags for this section.
  576. MemProt getMemProt() const { return Prot; }
  577. /// Set the protection flags for this section.
  578. void setMemProt(MemProt Prot) { this->Prot = Prot; }
  579. /// Get the deallocation policy for this section.
  580. MemDeallocPolicy getMemDeallocPolicy() const { return MDP; }
  581. /// Set the deallocation policy for this section.
  582. void setMemDeallocPolicy(MemDeallocPolicy MDP) { this->MDP = MDP; }
  583. /// Returns the ordinal for this section.
  584. SectionOrdinal getOrdinal() const { return SecOrdinal; }
  585. /// Returns an iterator over the blocks defined in this section.
  586. iterator_range<block_iterator> blocks() {
  587. return make_range(Blocks.begin(), Blocks.end());
  588. }
  589. /// Returns an iterator over the blocks defined in this section.
  590. iterator_range<const_block_iterator> blocks() const {
  591. return make_range(Blocks.begin(), Blocks.end());
  592. }
  593. /// Returns the number of blocks in this section.
  594. BlockSet::size_type blocks_size() const { return Blocks.size(); }
  595. /// Returns an iterator over the symbols defined in this section.
  596. iterator_range<symbol_iterator> symbols() {
  597. return make_range(Symbols.begin(), Symbols.end());
  598. }
  599. /// Returns an iterator over the symbols defined in this section.
  600. iterator_range<const_symbol_iterator> symbols() const {
  601. return make_range(Symbols.begin(), Symbols.end());
  602. }
  603. /// Return the number of symbols in this section.
  604. SymbolSet::size_type symbols_size() const { return Symbols.size(); }
  605. private:
  606. void addSymbol(Symbol &Sym) {
  607. assert(!Symbols.count(&Sym) && "Symbol is already in this section");
  608. Symbols.insert(&Sym);
  609. }
  610. void removeSymbol(Symbol &Sym) {
  611. assert(Symbols.count(&Sym) && "symbol is not in this section");
  612. Symbols.erase(&Sym);
  613. }
  614. void addBlock(Block &B) {
  615. assert(!Blocks.count(&B) && "Block is already in this section");
  616. Blocks.insert(&B);
  617. }
  618. void removeBlock(Block &B) {
  619. assert(Blocks.count(&B) && "Block is not in this section");
  620. Blocks.erase(&B);
  621. }
  622. void transferContentTo(Section &DstSection) {
  623. if (&DstSection == this)
  624. return;
  625. for (auto *S : Symbols)
  626. DstSection.addSymbol(*S);
  627. for (auto *B : Blocks)
  628. DstSection.addBlock(*B);
  629. Symbols.clear();
  630. Blocks.clear();
  631. }
  632. StringRef Name;
  633. MemProt Prot;
  634. MemDeallocPolicy MDP = MemDeallocPolicy::Standard;
  635. SectionOrdinal SecOrdinal = 0;
  636. BlockSet Blocks;
  637. SymbolSet Symbols;
  638. };
  639. /// Represents a section address range via a pair of Block pointers
  640. /// to the first and last Blocks in the section.
  641. class SectionRange {
  642. public:
  643. SectionRange() = default;
  644. SectionRange(const Section &Sec) {
  645. if (llvm::empty(Sec.blocks()))
  646. return;
  647. First = Last = *Sec.blocks().begin();
  648. for (auto *B : Sec.blocks()) {
  649. if (B->getAddress() < First->getAddress())
  650. First = B;
  651. if (B->getAddress() > Last->getAddress())
  652. Last = B;
  653. }
  654. }
  655. Block *getFirstBlock() const {
  656. assert((!Last || First) && "First can not be null if end is non-null");
  657. return First;
  658. }
  659. Block *getLastBlock() const {
  660. assert((First || !Last) && "Last can not be null if start is non-null");
  661. return Last;
  662. }
  663. bool empty() const {
  664. assert((First || !Last) && "Last can not be null if start is non-null");
  665. return !First;
  666. }
  667. orc::ExecutorAddr getStart() const {
  668. return First ? First->getAddress() : orc::ExecutorAddr();
  669. }
  670. orc::ExecutorAddr getEnd() const {
  671. return Last ? Last->getAddress() + Last->getSize() : orc::ExecutorAddr();
  672. }
  673. orc::ExecutorAddrDiff getSize() const { return getEnd() - getStart(); }
  674. orc::ExecutorAddrRange getRange() const {
  675. return orc::ExecutorAddrRange(getStart(), getEnd());
  676. }
  677. private:
  678. Block *First = nullptr;
  679. Block *Last = nullptr;
  680. };
  681. class LinkGraph {
  682. private:
  683. using SectionList = std::vector<std::unique_ptr<Section>>;
  684. using ExternalSymbolSet = DenseSet<Symbol *>;
  685. using BlockSet = DenseSet<Block *>;
  686. template <typename... ArgTs>
  687. Addressable &createAddressable(ArgTs &&... Args) {
  688. Addressable *A =
  689. reinterpret_cast<Addressable *>(Allocator.Allocate<Addressable>());
  690. new (A) Addressable(std::forward<ArgTs>(Args)...);
  691. return *A;
  692. }
  693. void destroyAddressable(Addressable &A) {
  694. A.~Addressable();
  695. Allocator.Deallocate(&A);
  696. }
  697. template <typename... ArgTs> Block &createBlock(ArgTs &&... Args) {
  698. Block *B = reinterpret_cast<Block *>(Allocator.Allocate<Block>());
  699. new (B) Block(std::forward<ArgTs>(Args)...);
  700. B->getSection().addBlock(*B);
  701. return *B;
  702. }
  703. void destroyBlock(Block &B) {
  704. B.~Block();
  705. Allocator.Deallocate(&B);
  706. }
  707. void destroySymbol(Symbol &S) {
  708. S.~Symbol();
  709. Allocator.Deallocate(&S);
  710. }
  711. static iterator_range<Section::block_iterator> getSectionBlocks(Section &S) {
  712. return S.blocks();
  713. }
  714. static iterator_range<Section::const_block_iterator>
  715. getSectionConstBlocks(Section &S) {
  716. return S.blocks();
  717. }
  718. static iterator_range<Section::symbol_iterator>
  719. getSectionSymbols(Section &S) {
  720. return S.symbols();
  721. }
  722. static iterator_range<Section::const_symbol_iterator>
  723. getSectionConstSymbols(Section &S) {
  724. return S.symbols();
  725. }
  726. public:
  727. using external_symbol_iterator = ExternalSymbolSet::iterator;
  728. using section_iterator = pointee_iterator<SectionList::iterator>;
  729. using const_section_iterator = pointee_iterator<SectionList::const_iterator>;
  730. template <typename OuterItrT, typename InnerItrT, typename T,
  731. iterator_range<InnerItrT> getInnerRange(
  732. typename OuterItrT::reference)>
  733. class nested_collection_iterator
  734. : public iterator_facade_base<
  735. nested_collection_iterator<OuterItrT, InnerItrT, T, getInnerRange>,
  736. std::forward_iterator_tag, T> {
  737. public:
  738. nested_collection_iterator() = default;
  739. nested_collection_iterator(OuterItrT OuterI, OuterItrT OuterE)
  740. : OuterI(OuterI), OuterE(OuterE),
  741. InnerI(getInnerBegin(OuterI, OuterE)) {
  742. moveToNonEmptyInnerOrEnd();
  743. }
  744. bool operator==(const nested_collection_iterator &RHS) const {
  745. return (OuterI == RHS.OuterI) && (InnerI == RHS.InnerI);
  746. }
  747. T operator*() const {
  748. assert(InnerI != getInnerRange(*OuterI).end() && "Dereferencing end?");
  749. return *InnerI;
  750. }
  751. nested_collection_iterator operator++() {
  752. ++InnerI;
  753. moveToNonEmptyInnerOrEnd();
  754. return *this;
  755. }
  756. private:
  757. static InnerItrT getInnerBegin(OuterItrT OuterI, OuterItrT OuterE) {
  758. return OuterI != OuterE ? getInnerRange(*OuterI).begin() : InnerItrT();
  759. }
  760. void moveToNonEmptyInnerOrEnd() {
  761. while (OuterI != OuterE && InnerI == getInnerRange(*OuterI).end()) {
  762. ++OuterI;
  763. InnerI = getInnerBegin(OuterI, OuterE);
  764. }
  765. }
  766. OuterItrT OuterI, OuterE;
  767. InnerItrT InnerI;
  768. };
  769. using defined_symbol_iterator =
  770. nested_collection_iterator<const_section_iterator,
  771. Section::symbol_iterator, Symbol *,
  772. getSectionSymbols>;
  773. using const_defined_symbol_iterator =
  774. nested_collection_iterator<const_section_iterator,
  775. Section::const_symbol_iterator, const Symbol *,
  776. getSectionConstSymbols>;
  777. using block_iterator = nested_collection_iterator<const_section_iterator,
  778. Section::block_iterator,
  779. Block *, getSectionBlocks>;
  780. using const_block_iterator =
  781. nested_collection_iterator<const_section_iterator,
  782. Section::const_block_iterator, const Block *,
  783. getSectionConstBlocks>;
  784. using GetEdgeKindNameFunction = const char *(*)(Edge::Kind);
  785. LinkGraph(std::string Name, const Triple &TT, unsigned PointerSize,
  786. support::endianness Endianness,
  787. GetEdgeKindNameFunction GetEdgeKindName)
  788. : Name(std::move(Name)), TT(TT), PointerSize(PointerSize),
  789. Endianness(Endianness), GetEdgeKindName(std::move(GetEdgeKindName)) {}
  790. LinkGraph(const LinkGraph &) = delete;
  791. LinkGraph &operator=(const LinkGraph &) = delete;
  792. LinkGraph(LinkGraph &&) = delete;
  793. LinkGraph &operator=(LinkGraph &&) = delete;
  794. /// Returns the name of this graph (usually the name of the original
  795. /// underlying MemoryBuffer).
  796. const std::string &getName() const { return Name; }
  797. /// Returns the target triple for this Graph.
  798. const Triple &getTargetTriple() const { return TT; }
  799. /// Returns the pointer size for use in this graph.
  800. unsigned getPointerSize() const { return PointerSize; }
  801. /// Returns the endianness of content in this graph.
  802. support::endianness getEndianness() const { return Endianness; }
  803. const char *getEdgeKindName(Edge::Kind K) const { return GetEdgeKindName(K); }
  804. /// Allocate a mutable buffer of the given size using the LinkGraph's
  805. /// allocator.
  806. MutableArrayRef<char> allocateBuffer(size_t Size) {
  807. return {Allocator.Allocate<char>(Size), Size};
  808. }
  809. /// Allocate a copy of the given string using the LinkGraph's allocator.
  810. /// This can be useful when renaming symbols or adding new content to the
  811. /// graph.
  812. MutableArrayRef<char> allocateContent(ArrayRef<char> Source) {
  813. auto *AllocatedBuffer = Allocator.Allocate<char>(Source.size());
  814. llvm::copy(Source, AllocatedBuffer);
  815. return MutableArrayRef<char>(AllocatedBuffer, Source.size());
  816. }
  817. /// Allocate a copy of the given string using the LinkGraph's allocator.
  818. /// This can be useful when renaming symbols or adding new content to the
  819. /// graph.
  820. ///
  821. /// Note: This Twine-based overload requires an extra string copy and an
  822. /// extra heap allocation for large strings. The ArrayRef<char> overload
  823. /// should be preferred where possible.
  824. MutableArrayRef<char> allocateString(Twine Source) {
  825. SmallString<256> TmpBuffer;
  826. auto SourceStr = Source.toStringRef(TmpBuffer);
  827. auto *AllocatedBuffer = Allocator.Allocate<char>(SourceStr.size());
  828. llvm::copy(SourceStr, AllocatedBuffer);
  829. return MutableArrayRef<char>(AllocatedBuffer, SourceStr.size());
  830. }
  831. /// Create a section with the given name, protection flags, and alignment.
  832. Section &createSection(StringRef Name, MemProt Prot) {
  833. assert(llvm::find_if(Sections,
  834. [&](std::unique_ptr<Section> &Sec) {
  835. return Sec->getName() == Name;
  836. }) == Sections.end() &&
  837. "Duplicate section name");
  838. std::unique_ptr<Section> Sec(new Section(Name, Prot, Sections.size()));
  839. Sections.push_back(std::move(Sec));
  840. return *Sections.back();
  841. }
  842. /// Create a content block.
  843. Block &createContentBlock(Section &Parent, ArrayRef<char> Content,
  844. orc::ExecutorAddr Address, uint64_t Alignment,
  845. uint64_t AlignmentOffset) {
  846. return createBlock(Parent, Content, Address, Alignment, AlignmentOffset);
  847. }
  848. /// Create a content block with initially mutable data.
  849. Block &createMutableContentBlock(Section &Parent,
  850. MutableArrayRef<char> MutableContent,
  851. orc::ExecutorAddr Address,
  852. uint64_t Alignment,
  853. uint64_t AlignmentOffset) {
  854. return createBlock(Parent, MutableContent, Address, Alignment,
  855. AlignmentOffset);
  856. }
  857. /// Create a zero-fill block.
  858. Block &createZeroFillBlock(Section &Parent, orc::ExecutorAddrDiff Size,
  859. orc::ExecutorAddr Address, uint64_t Alignment,
  860. uint64_t AlignmentOffset) {
  861. return createBlock(Parent, Size, Address, Alignment, AlignmentOffset);
  862. }
  863. /// Cache type for the splitBlock function.
  864. using SplitBlockCache = Optional<SmallVector<Symbol *, 8>>;
  865. /// Splits block B at the given index which must be greater than zero.
  866. /// If SplitIndex == B.getSize() then this function is a no-op and returns B.
  867. /// If SplitIndex < B.getSize() then this function returns a new block
  868. /// covering the range [ 0, SplitIndex ), and B is modified to cover the range
  869. /// [ SplitIndex, B.size() ).
  870. ///
  871. /// The optional Cache parameter can be used to speed up repeated calls to
  872. /// splitBlock for a single block. If the value is None the cache will be
  873. /// treated as uninitialized and splitBlock will populate it. Otherwise it
  874. /// is assumed to contain the list of Symbols pointing at B, sorted in
  875. /// descending order of offset.
  876. ///
  877. /// Notes:
  878. ///
  879. /// 1. splitBlock must be used with care. Splitting a block may cause
  880. /// incoming edges to become invalid if the edge target subexpression
  881. /// points outside the bounds of the newly split target block (E.g. an
  882. /// edge 'S + 10 : Pointer64' where S points to a newly split block
  883. /// whose size is less than 10). No attempt is made to detect invalidation
  884. /// of incoming edges, as in general this requires context that the
  885. /// LinkGraph does not have. Clients are responsible for ensuring that
  886. /// splitBlock is not used in a way that invalidates edges.
  887. ///
  888. /// 2. The newly introduced block will have a new ordinal which will be
  889. /// higher than any other ordinals in the section. Clients are responsible
  890. /// for re-assigning block ordinals to restore a compatible order if
  891. /// needed.
  892. ///
  893. /// 3. The cache is not automatically updated if new symbols are introduced
  894. /// between calls to splitBlock. Any newly introduced symbols may be
  895. /// added to the cache manually (descending offset order must be
  896. /// preserved), or the cache can be set to None and rebuilt by
  897. /// splitBlock on the next call.
  898. Block &splitBlock(Block &B, size_t SplitIndex,
  899. SplitBlockCache *Cache = nullptr);
  900. /// Add an external symbol.
  901. /// Some formats (e.g. ELF) allow Symbols to have sizes. For Symbols whose
  902. /// size is not known, you should substitute '0'.
  903. /// For external symbols Linkage determines whether the symbol must be
  904. /// present during lookup: Externals with strong linkage must be found or
  905. /// an error will be emitted. Externals with weak linkage are permitted to
  906. /// be undefined, in which case they are assigned a value of 0.
  907. Symbol &addExternalSymbol(StringRef Name, orc::ExecutorAddrDiff Size,
  908. Linkage L) {
  909. assert(llvm::count_if(ExternalSymbols,
  910. [&](const Symbol *Sym) {
  911. return Sym->getName() == Name;
  912. }) == 0 &&
  913. "Duplicate external symbol");
  914. auto &Sym = Symbol::constructExternal(
  915. Allocator.Allocate<Symbol>(),
  916. createAddressable(orc::ExecutorAddr(), false), Name, Size, L);
  917. ExternalSymbols.insert(&Sym);
  918. return Sym;
  919. }
  920. /// Add an absolute symbol.
  921. Symbol &addAbsoluteSymbol(StringRef Name, orc::ExecutorAddr Address,
  922. orc::ExecutorAddrDiff Size, Linkage L, Scope S,
  923. bool IsLive) {
  924. assert(llvm::count_if(AbsoluteSymbols,
  925. [&](const Symbol *Sym) {
  926. return Sym->getName() == Name;
  927. }) == 0 &&
  928. "Duplicate absolute symbol");
  929. auto &Sym = Symbol::constructAbsolute(Allocator.Allocate<Symbol>(),
  930. createAddressable(Address), Name,
  931. Size, L, S, IsLive);
  932. AbsoluteSymbols.insert(&Sym);
  933. return Sym;
  934. }
  935. /// Convenience method for adding a weak zero-fill symbol.
  936. Symbol &addCommonSymbol(StringRef Name, Scope S, Section &Section,
  937. orc::ExecutorAddr Address, orc::ExecutorAddrDiff Size,
  938. uint64_t Alignment, bool IsLive) {
  939. assert(llvm::count_if(defined_symbols(),
  940. [&](const Symbol *Sym) {
  941. return Sym->getName() == Name;
  942. }) == 0 &&
  943. "Duplicate defined symbol");
  944. auto &Sym = Symbol::constructCommon(
  945. Allocator.Allocate<Symbol>(),
  946. createBlock(Section, Size, Address, Alignment, 0), Name, Size, S,
  947. IsLive);
  948. Section.addSymbol(Sym);
  949. return Sym;
  950. }
  951. /// Add an anonymous symbol.
  952. Symbol &addAnonymousSymbol(Block &Content, orc::ExecutorAddrDiff Offset,
  953. orc::ExecutorAddrDiff Size, bool IsCallable,
  954. bool IsLive) {
  955. auto &Sym = Symbol::constructAnonDef(Allocator.Allocate<Symbol>(), Content,
  956. Offset, Size, IsCallable, IsLive);
  957. Content.getSection().addSymbol(Sym);
  958. return Sym;
  959. }
  960. /// Add a named symbol.
  961. Symbol &addDefinedSymbol(Block &Content, orc::ExecutorAddrDiff Offset,
  962. StringRef Name, orc::ExecutorAddrDiff Size,
  963. Linkage L, Scope S, bool IsCallable, bool IsLive) {
  964. assert((S == Scope::Local || llvm::count_if(defined_symbols(),
  965. [&](const Symbol *Sym) {
  966. return Sym->getName() == Name;
  967. }) == 0) &&
  968. "Duplicate defined symbol");
  969. auto &Sym =
  970. Symbol::constructNamedDef(Allocator.Allocate<Symbol>(), Content, Offset,
  971. Name, Size, L, S, IsLive, IsCallable);
  972. Content.getSection().addSymbol(Sym);
  973. return Sym;
  974. }
  975. iterator_range<section_iterator> sections() {
  976. return make_range(section_iterator(Sections.begin()),
  977. section_iterator(Sections.end()));
  978. }
  979. SectionList::size_type sections_size() const { return Sections.size(); }
  980. /// Returns the section with the given name if it exists, otherwise returns
  981. /// null.
  982. Section *findSectionByName(StringRef Name) {
  983. for (auto &S : sections())
  984. if (S.getName() == Name)
  985. return &S;
  986. return nullptr;
  987. }
  988. iterator_range<block_iterator> blocks() {
  989. return make_range(block_iterator(Sections.begin(), Sections.end()),
  990. block_iterator(Sections.end(), Sections.end()));
  991. }
  992. iterator_range<const_block_iterator> blocks() const {
  993. return make_range(const_block_iterator(Sections.begin(), Sections.end()),
  994. const_block_iterator(Sections.end(), Sections.end()));
  995. }
  996. iterator_range<external_symbol_iterator> external_symbols() {
  997. return make_range(ExternalSymbols.begin(), ExternalSymbols.end());
  998. }
  999. iterator_range<external_symbol_iterator> absolute_symbols() {
  1000. return make_range(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
  1001. }
  1002. iterator_range<defined_symbol_iterator> defined_symbols() {
  1003. return make_range(defined_symbol_iterator(Sections.begin(), Sections.end()),
  1004. defined_symbol_iterator(Sections.end(), Sections.end()));
  1005. }
  1006. iterator_range<const_defined_symbol_iterator> defined_symbols() const {
  1007. return make_range(
  1008. const_defined_symbol_iterator(Sections.begin(), Sections.end()),
  1009. const_defined_symbol_iterator(Sections.end(), Sections.end()));
  1010. }
  1011. /// Make the given symbol external (must not already be external).
  1012. ///
  1013. /// Symbol size, linkage and callability will be left unchanged. Symbol scope
  1014. /// will be set to Default, and offset will be reset to 0.
  1015. void makeExternal(Symbol &Sym) {
  1016. assert(!Sym.isExternal() && "Symbol is already external");
  1017. if (Sym.isAbsolute()) {
  1018. assert(AbsoluteSymbols.count(&Sym) &&
  1019. "Sym is not in the absolute symbols set");
  1020. assert(Sym.getOffset() == 0 && "Absolute not at offset 0");
  1021. AbsoluteSymbols.erase(&Sym);
  1022. Sym.getAddressable().setAbsolute(false);
  1023. } else {
  1024. assert(Sym.isDefined() && "Sym is not a defined symbol");
  1025. Section &Sec = Sym.getBlock().getSection();
  1026. Sec.removeSymbol(Sym);
  1027. Sym.makeExternal(createAddressable(orc::ExecutorAddr(), false));
  1028. }
  1029. ExternalSymbols.insert(&Sym);
  1030. }
  1031. /// Make the given symbol an absolute with the given address (must not already
  1032. /// be absolute).
  1033. ///
  1034. /// Symbol size, linkage, scope, and callability, and liveness will be left
  1035. /// unchanged. Symbol offset will be reset to 0.
  1036. void makeAbsolute(Symbol &Sym, orc::ExecutorAddr Address) {
  1037. assert(!Sym.isAbsolute() && "Symbol is already absolute");
  1038. if (Sym.isExternal()) {
  1039. assert(ExternalSymbols.count(&Sym) &&
  1040. "Sym is not in the absolute symbols set");
  1041. assert(Sym.getOffset() == 0 && "External is not at offset 0");
  1042. ExternalSymbols.erase(&Sym);
  1043. Sym.getAddressable().setAbsolute(true);
  1044. } else {
  1045. assert(Sym.isDefined() && "Sym is not a defined symbol");
  1046. Section &Sec = Sym.getBlock().getSection();
  1047. Sec.removeSymbol(Sym);
  1048. Sym.makeAbsolute(createAddressable(Address));
  1049. }
  1050. AbsoluteSymbols.insert(&Sym);
  1051. }
  1052. /// Turn an absolute or external symbol into a defined one by attaching it to
  1053. /// a block. Symbol must not already be defined.
  1054. void makeDefined(Symbol &Sym, Block &Content, orc::ExecutorAddrDiff Offset,
  1055. orc::ExecutorAddrDiff Size, Linkage L, Scope S,
  1056. bool IsLive) {
  1057. assert(!Sym.isDefined() && "Sym is already a defined symbol");
  1058. if (Sym.isAbsolute()) {
  1059. assert(AbsoluteSymbols.count(&Sym) &&
  1060. "Symbol is not in the absolutes set");
  1061. AbsoluteSymbols.erase(&Sym);
  1062. } else {
  1063. assert(ExternalSymbols.count(&Sym) &&
  1064. "Symbol is not in the externals set");
  1065. ExternalSymbols.erase(&Sym);
  1066. }
  1067. Addressable &OldBase = *Sym.Base;
  1068. Sym.setBlock(Content);
  1069. Sym.setOffset(Offset);
  1070. Sym.setSize(Size);
  1071. Sym.setLinkage(L);
  1072. Sym.setScope(S);
  1073. Sym.setLive(IsLive);
  1074. Content.getSection().addSymbol(Sym);
  1075. destroyAddressable(OldBase);
  1076. }
  1077. /// Transfer a defined symbol from one block to another.
  1078. ///
  1079. /// The symbol's offset within DestBlock is set to NewOffset.
  1080. ///
  1081. /// If ExplicitNewSize is given as None then the size of the symbol will be
  1082. /// checked and auto-truncated to at most the size of the remainder (from the
  1083. /// given offset) of the size of the new block.
  1084. ///
  1085. /// All other symbol attributes are unchanged.
  1086. void transferDefinedSymbol(Symbol &Sym, Block &DestBlock,
  1087. orc::ExecutorAddrDiff NewOffset,
  1088. Optional<orc::ExecutorAddrDiff> ExplicitNewSize) {
  1089. auto &OldSection = Sym.getBlock().getSection();
  1090. Sym.setBlock(DestBlock);
  1091. Sym.setOffset(NewOffset);
  1092. if (ExplicitNewSize)
  1093. Sym.setSize(*ExplicitNewSize);
  1094. else {
  1095. auto RemainingBlockSize = DestBlock.getSize() - NewOffset;
  1096. if (Sym.getSize() > RemainingBlockSize)
  1097. Sym.setSize(RemainingBlockSize);
  1098. }
  1099. if (&DestBlock.getSection() != &OldSection) {
  1100. OldSection.removeSymbol(Sym);
  1101. DestBlock.getSection().addSymbol(Sym);
  1102. }
  1103. }
  1104. /// Transfers the given Block and all Symbols pointing to it to the given
  1105. /// Section.
  1106. ///
  1107. /// No attempt is made to check compatibility of the source and destination
  1108. /// sections. Blocks may be moved between sections with incompatible
  1109. /// permissions (e.g. from data to text). The client is responsible for
  1110. /// ensuring that this is safe.
  1111. void transferBlock(Block &B, Section &NewSection) {
  1112. auto &OldSection = B.getSection();
  1113. if (&OldSection == &NewSection)
  1114. return;
  1115. SmallVector<Symbol *> AttachedSymbols;
  1116. for (auto *S : OldSection.symbols())
  1117. if (&S->getBlock() == &B)
  1118. AttachedSymbols.push_back(S);
  1119. for (auto *S : AttachedSymbols) {
  1120. OldSection.removeSymbol(*S);
  1121. NewSection.addSymbol(*S);
  1122. }
  1123. OldSection.removeBlock(B);
  1124. NewSection.addBlock(B);
  1125. }
  1126. /// Move all blocks and symbols from the source section to the destination
  1127. /// section.
  1128. ///
  1129. /// If PreserveSrcSection is true (or SrcSection and DstSection are the same)
  1130. /// then SrcSection is preserved, otherwise it is removed (the default).
  1131. void mergeSections(Section &DstSection, Section &SrcSection,
  1132. bool PreserveSrcSection = false) {
  1133. if (&DstSection == &SrcSection)
  1134. return;
  1135. for (auto *B : SrcSection.blocks())
  1136. B->setSection(DstSection);
  1137. SrcSection.transferContentTo(DstSection);
  1138. if (!PreserveSrcSection)
  1139. removeSection(SrcSection);
  1140. }
  1141. /// Removes an external symbol. Also removes the underlying Addressable.
  1142. void removeExternalSymbol(Symbol &Sym) {
  1143. assert(!Sym.isDefined() && !Sym.isAbsolute() &&
  1144. "Sym is not an external symbol");
  1145. assert(ExternalSymbols.count(&Sym) && "Symbol is not in the externals set");
  1146. ExternalSymbols.erase(&Sym);
  1147. Addressable &Base = *Sym.Base;
  1148. assert(llvm::find_if(ExternalSymbols,
  1149. [&](Symbol *AS) { return AS->Base == &Base; }) ==
  1150. ExternalSymbols.end() &&
  1151. "Base addressable still in use");
  1152. destroySymbol(Sym);
  1153. destroyAddressable(Base);
  1154. }
  1155. /// Remove an absolute symbol. Also removes the underlying Addressable.
  1156. void removeAbsoluteSymbol(Symbol &Sym) {
  1157. assert(!Sym.isDefined() && Sym.isAbsolute() &&
  1158. "Sym is not an absolute symbol");
  1159. assert(AbsoluteSymbols.count(&Sym) &&
  1160. "Symbol is not in the absolute symbols set");
  1161. AbsoluteSymbols.erase(&Sym);
  1162. Addressable &Base = *Sym.Base;
  1163. assert(llvm::find_if(ExternalSymbols,
  1164. [&](Symbol *AS) { return AS->Base == &Base; }) ==
  1165. ExternalSymbols.end() &&
  1166. "Base addressable still in use");
  1167. destroySymbol(Sym);
  1168. destroyAddressable(Base);
  1169. }
  1170. /// Removes defined symbols. Does not remove the underlying block.
  1171. void removeDefinedSymbol(Symbol &Sym) {
  1172. assert(Sym.isDefined() && "Sym is not a defined symbol");
  1173. Sym.getBlock().getSection().removeSymbol(Sym);
  1174. destroySymbol(Sym);
  1175. }
  1176. /// Remove a block. The block reference is defunct after calling this
  1177. /// function and should no longer be used.
  1178. void removeBlock(Block &B) {
  1179. assert(llvm::none_of(B.getSection().symbols(),
  1180. [&](const Symbol *Sym) {
  1181. return &Sym->getBlock() == &B;
  1182. }) &&
  1183. "Block still has symbols attached");
  1184. B.getSection().removeBlock(B);
  1185. destroyBlock(B);
  1186. }
  1187. /// Remove a section. The section reference is defunct after calling this
  1188. /// function and should no longer be used.
  1189. void removeSection(Section &Sec) {
  1190. auto I = llvm::find_if(Sections, [&Sec](const std::unique_ptr<Section> &S) {
  1191. return S.get() == &Sec;
  1192. });
  1193. assert(I != Sections.end() && "Section does not appear in this graph");
  1194. Sections.erase(I);
  1195. }
  1196. /// Accessor for the AllocActions object for this graph. This can be used to
  1197. /// register allocation action calls prior to finalization.
  1198. ///
  1199. /// Accessing this object after finalization will result in undefined
  1200. /// behavior.
  1201. orc::shared::AllocActions &allocActions() { return AAs; }
  1202. /// Dump the graph.
  1203. void dump(raw_ostream &OS);
  1204. private:
  1205. // Put the BumpPtrAllocator first so that we don't free any of the underlying
  1206. // memory until the Symbol/Addressable destructors have been run.
  1207. BumpPtrAllocator Allocator;
  1208. std::string Name;
  1209. Triple TT;
  1210. unsigned PointerSize;
  1211. support::endianness Endianness;
  1212. GetEdgeKindNameFunction GetEdgeKindName = nullptr;
  1213. SectionList Sections;
  1214. ExternalSymbolSet ExternalSymbols;
  1215. ExternalSymbolSet AbsoluteSymbols;
  1216. orc::shared::AllocActions AAs;
  1217. };
  1218. inline MutableArrayRef<char> Block::getMutableContent(LinkGraph &G) {
  1219. if (!ContentMutable)
  1220. setMutableContent(G.allocateContent({Data, Size}));
  1221. return MutableArrayRef<char>(const_cast<char *>(Data), Size);
  1222. }
  1223. /// Enables easy lookup of blocks by addresses.
  1224. class BlockAddressMap {
  1225. public:
  1226. using AddrToBlockMap = std::map<orc::ExecutorAddr, Block *>;
  1227. using const_iterator = AddrToBlockMap::const_iterator;
  1228. /// A block predicate that always adds all blocks.
  1229. static bool includeAllBlocks(const Block &B) { return true; }
  1230. /// A block predicate that always includes blocks with non-null addresses.
  1231. static bool includeNonNull(const Block &B) { return !!B.getAddress(); }
  1232. BlockAddressMap() = default;
  1233. /// Add a block to the map. Returns an error if the block overlaps with any
  1234. /// existing block.
  1235. template <typename PredFn = decltype(includeAllBlocks)>
  1236. Error addBlock(Block &B, PredFn Pred = includeAllBlocks) {
  1237. if (!Pred(B))
  1238. return Error::success();
  1239. auto I = AddrToBlock.upper_bound(B.getAddress());
  1240. // If we're not at the end of the map, check for overlap with the next
  1241. // element.
  1242. if (I != AddrToBlock.end()) {
  1243. if (B.getAddress() + B.getSize() > I->second->getAddress())
  1244. return overlapError(B, *I->second);
  1245. }
  1246. // If we're not at the start of the map, check for overlap with the previous
  1247. // element.
  1248. if (I != AddrToBlock.begin()) {
  1249. auto &PrevBlock = *std::prev(I)->second;
  1250. if (PrevBlock.getAddress() + PrevBlock.getSize() > B.getAddress())
  1251. return overlapError(B, PrevBlock);
  1252. }
  1253. AddrToBlock.insert(I, std::make_pair(B.getAddress(), &B));
  1254. return Error::success();
  1255. }
  1256. /// Add a block to the map without checking for overlap with existing blocks.
  1257. /// The client is responsible for ensuring that the block added does not
  1258. /// overlap with any existing block.
  1259. void addBlockWithoutChecking(Block &B) { AddrToBlock[B.getAddress()] = &B; }
  1260. /// Add a range of blocks to the map. Returns an error if any block in the
  1261. /// range overlaps with any other block in the range, or with any existing
  1262. /// block in the map.
  1263. template <typename BlockPtrRange,
  1264. typename PredFn = decltype(includeAllBlocks)>
  1265. Error addBlocks(BlockPtrRange &&Blocks, PredFn Pred = includeAllBlocks) {
  1266. for (auto *B : Blocks)
  1267. if (auto Err = addBlock(*B, Pred))
  1268. return Err;
  1269. return Error::success();
  1270. }
  1271. /// Add a range of blocks to the map without checking for overlap with
  1272. /// existing blocks. The client is responsible for ensuring that the block
  1273. /// added does not overlap with any existing block.
  1274. template <typename BlockPtrRange>
  1275. void addBlocksWithoutChecking(BlockPtrRange &&Blocks) {
  1276. for (auto *B : Blocks)
  1277. addBlockWithoutChecking(*B);
  1278. }
  1279. /// Iterates over (Address, Block*) pairs in ascending order of address.
  1280. const_iterator begin() const { return AddrToBlock.begin(); }
  1281. const_iterator end() const { return AddrToBlock.end(); }
  1282. /// Returns the block starting at the given address, or nullptr if no such
  1283. /// block exists.
  1284. Block *getBlockAt(orc::ExecutorAddr Addr) const {
  1285. auto I = AddrToBlock.find(Addr);
  1286. if (I == AddrToBlock.end())
  1287. return nullptr;
  1288. return I->second;
  1289. }
  1290. /// Returns the block covering the given address, or nullptr if no such block
  1291. /// exists.
  1292. Block *getBlockCovering(orc::ExecutorAddr Addr) const {
  1293. auto I = AddrToBlock.upper_bound(Addr);
  1294. if (I == AddrToBlock.begin())
  1295. return nullptr;
  1296. auto *B = std::prev(I)->second;
  1297. if (Addr < B->getAddress() + B->getSize())
  1298. return B;
  1299. return nullptr;
  1300. }
  1301. private:
  1302. Error overlapError(Block &NewBlock, Block &ExistingBlock) {
  1303. auto NewBlockEnd = NewBlock.getAddress() + NewBlock.getSize();
  1304. auto ExistingBlockEnd =
  1305. ExistingBlock.getAddress() + ExistingBlock.getSize();
  1306. return make_error<JITLinkError>(
  1307. "Block at " +
  1308. formatv("{0:x16} -- {1:x16}", NewBlock.getAddress().getValue(),
  1309. NewBlockEnd.getValue()) +
  1310. " overlaps " +
  1311. formatv("{0:x16} -- {1:x16}", ExistingBlock.getAddress().getValue(),
  1312. ExistingBlockEnd.getValue()));
  1313. }
  1314. AddrToBlockMap AddrToBlock;
  1315. };
  1316. /// A map of addresses to Symbols.
  1317. class SymbolAddressMap {
  1318. public:
  1319. using SymbolVector = SmallVector<Symbol *, 1>;
  1320. /// Add a symbol to the SymbolAddressMap.
  1321. void addSymbol(Symbol &Sym) {
  1322. AddrToSymbols[Sym.getAddress()].push_back(&Sym);
  1323. }
  1324. /// Add all symbols in a given range to the SymbolAddressMap.
  1325. template <typename SymbolPtrCollection>
  1326. void addSymbols(SymbolPtrCollection &&Symbols) {
  1327. for (auto *Sym : Symbols)
  1328. addSymbol(*Sym);
  1329. }
  1330. /// Returns the list of symbols that start at the given address, or nullptr if
  1331. /// no such symbols exist.
  1332. const SymbolVector *getSymbolsAt(orc::ExecutorAddr Addr) const {
  1333. auto I = AddrToSymbols.find(Addr);
  1334. if (I == AddrToSymbols.end())
  1335. return nullptr;
  1336. return &I->second;
  1337. }
  1338. private:
  1339. std::map<orc::ExecutorAddr, SymbolVector> AddrToSymbols;
  1340. };
  1341. /// A function for mutating LinkGraphs.
  1342. using LinkGraphPassFunction = std::function<Error(LinkGraph &)>;
  1343. /// A list of LinkGraph passes.
  1344. using LinkGraphPassList = std::vector<LinkGraphPassFunction>;
  1345. /// An LinkGraph pass configuration, consisting of a list of pre-prune,
  1346. /// post-prune, and post-fixup passes.
  1347. struct PassConfiguration {
  1348. /// Pre-prune passes.
  1349. ///
  1350. /// These passes are called on the graph after it is built, and before any
  1351. /// symbols have been pruned. Graph nodes still have their original vmaddrs.
  1352. ///
  1353. /// Notable use cases: Marking symbols live or should-discard.
  1354. LinkGraphPassList PrePrunePasses;
  1355. /// Post-prune passes.
  1356. ///
  1357. /// These passes are called on the graph after dead stripping, but before
  1358. /// memory is allocated or nodes assigned their final addresses.
  1359. ///
  1360. /// Notable use cases: Building GOT, stub, and TLV symbols.
  1361. LinkGraphPassList PostPrunePasses;
  1362. /// Post-allocation passes.
  1363. ///
  1364. /// These passes are called on the graph after memory has been allocated and
  1365. /// defined nodes have been assigned their final addresses, but before the
  1366. /// context has been notified of these addresses. At this point externals
  1367. /// have not been resolved, and symbol content has not yet been copied into
  1368. /// working memory.
  1369. ///
  1370. /// Notable use cases: Setting up data structures associated with addresses
  1371. /// of defined symbols (e.g. a mapping of __dso_handle to JITDylib* for the
  1372. /// JIT runtime) -- using a PostAllocationPass for this ensures that the
  1373. /// data structures are in-place before any query for resolved symbols
  1374. /// can complete.
  1375. LinkGraphPassList PostAllocationPasses;
  1376. /// Pre-fixup passes.
  1377. ///
  1378. /// These passes are called on the graph after memory has been allocated,
  1379. /// content copied into working memory, and all nodes (including externals)
  1380. /// have been assigned their final addresses, but before any fixups have been
  1381. /// applied.
  1382. ///
  1383. /// Notable use cases: Late link-time optimizations like GOT and stub
  1384. /// elimination.
  1385. LinkGraphPassList PreFixupPasses;
  1386. /// Post-fixup passes.
  1387. ///
  1388. /// These passes are called on the graph after block contents has been copied
  1389. /// to working memory, and fixups applied. Blocks have been updated to point
  1390. /// to their fixed up content.
  1391. ///
  1392. /// Notable use cases: Testing and validation.
  1393. LinkGraphPassList PostFixupPasses;
  1394. };
  1395. /// Flags for symbol lookup.
  1396. ///
  1397. /// FIXME: These basically duplicate orc::SymbolLookupFlags -- We should merge
  1398. /// the two types once we have an OrcSupport library.
  1399. enum class SymbolLookupFlags { RequiredSymbol, WeaklyReferencedSymbol };
  1400. raw_ostream &operator<<(raw_ostream &OS, const SymbolLookupFlags &LF);
  1401. /// A map of symbol names to resolved addresses.
  1402. using AsyncLookupResult = DenseMap<StringRef, JITEvaluatedSymbol>;
  1403. /// A function object to call with a resolved symbol map (See AsyncLookupResult)
  1404. /// or an error if resolution failed.
  1405. class JITLinkAsyncLookupContinuation {
  1406. public:
  1407. virtual ~JITLinkAsyncLookupContinuation() = default;
  1408. virtual void run(Expected<AsyncLookupResult> LR) = 0;
  1409. private:
  1410. virtual void anchor();
  1411. };
  1412. /// Create a lookup continuation from a function object.
  1413. template <typename Continuation>
  1414. std::unique_ptr<JITLinkAsyncLookupContinuation>
  1415. createLookupContinuation(Continuation Cont) {
  1416. class Impl final : public JITLinkAsyncLookupContinuation {
  1417. public:
  1418. Impl(Continuation C) : C(std::move(C)) {}
  1419. void run(Expected<AsyncLookupResult> LR) override { C(std::move(LR)); }
  1420. private:
  1421. Continuation C;
  1422. };
  1423. return std::make_unique<Impl>(std::move(Cont));
  1424. }
  1425. /// Holds context for a single jitLink invocation.
  1426. class JITLinkContext {
  1427. public:
  1428. using LookupMap = DenseMap<StringRef, SymbolLookupFlags>;
  1429. /// Create a JITLinkContext.
  1430. JITLinkContext(const JITLinkDylib *JD) : JD(JD) {}
  1431. /// Destroy a JITLinkContext.
  1432. virtual ~JITLinkContext();
  1433. /// Return the JITLinkDylib that this link is targeting, if any.
  1434. const JITLinkDylib *getJITLinkDylib() const { return JD; }
  1435. /// Return the MemoryManager to be used for this link.
  1436. virtual JITLinkMemoryManager &getMemoryManager() = 0;
  1437. /// Notify this context that linking failed.
  1438. /// Called by JITLink if linking cannot be completed.
  1439. virtual void notifyFailed(Error Err) = 0;
  1440. /// Called by JITLink to resolve external symbols. This method is passed a
  1441. /// lookup continutation which it must call with a result to continue the
  1442. /// linking process.
  1443. virtual void lookup(const LookupMap &Symbols,
  1444. std::unique_ptr<JITLinkAsyncLookupContinuation> LC) = 0;
  1445. /// Called by JITLink once all defined symbols in the graph have been assigned
  1446. /// their final memory locations in the target process. At this point the
  1447. /// LinkGraph can be inspected to build a symbol table, however the block
  1448. /// content will not generally have been copied to the target location yet.
  1449. ///
  1450. /// If the client detects an error in the LinkGraph state (e.g. unexpected or
  1451. /// missing symbols) they may return an error here. The error will be
  1452. /// propagated to notifyFailed and the linker will bail out.
  1453. virtual Error notifyResolved(LinkGraph &G) = 0;
  1454. /// Called by JITLink to notify the context that the object has been
  1455. /// finalized (i.e. emitted to memory and memory permissions set). If all of
  1456. /// this objects dependencies have also been finalized then the code is ready
  1457. /// to run.
  1458. virtual void notifyFinalized(JITLinkMemoryManager::FinalizedAlloc Alloc) = 0;
  1459. /// Called by JITLink prior to linking to determine whether default passes for
  1460. /// the target should be added. The default implementation returns true.
  1461. /// If subclasses override this method to return false for any target then
  1462. /// they are required to fully configure the pass pipeline for that target.
  1463. virtual bool shouldAddDefaultTargetPasses(const Triple &TT) const;
  1464. /// Returns the mark-live pass to be used for this link. If no pass is
  1465. /// returned (the default) then the target-specific linker implementation will
  1466. /// choose a conservative default (usually marking all symbols live).
  1467. /// This function is only called if shouldAddDefaultTargetPasses returns true,
  1468. /// otherwise the JITContext is responsible for adding a mark-live pass in
  1469. /// modifyPassConfig.
  1470. virtual LinkGraphPassFunction getMarkLivePass(const Triple &TT) const;
  1471. /// Called by JITLink to modify the pass pipeline prior to linking.
  1472. /// The default version performs no modification.
  1473. virtual Error modifyPassConfig(LinkGraph &G, PassConfiguration &Config);
  1474. private:
  1475. const JITLinkDylib *JD = nullptr;
  1476. };
  1477. /// Marks all symbols in a graph live. This can be used as a default,
  1478. /// conservative mark-live implementation.
  1479. Error markAllSymbolsLive(LinkGraph &G);
  1480. /// Create an out of range error for the given edge in the given block.
  1481. Error makeTargetOutOfRangeError(const LinkGraph &G, const Block &B,
  1482. const Edge &E);
  1483. /// Base case for edge-visitors where the visitor-list is empty.
  1484. inline void visitEdge(LinkGraph &G, Block *B, Edge &E) {}
  1485. /// Applies the first visitor in the list to the given edge. If the visitor's
  1486. /// visitEdge method returns true then we return immediately, otherwise we
  1487. /// apply the next visitor.
  1488. template <typename VisitorT, typename... VisitorTs>
  1489. void visitEdge(LinkGraph &G, Block *B, Edge &E, VisitorT &&V,
  1490. VisitorTs &&...Vs) {
  1491. if (!V.visitEdge(G, B, E))
  1492. visitEdge(G, B, E, std::forward<VisitorTs>(Vs)...);
  1493. }
  1494. /// For each edge in the given graph, apply a list of visitors to the edge,
  1495. /// stopping when the first visitor's visitEdge method returns true.
  1496. ///
  1497. /// Only visits edges that were in the graph at call time: if any visitor
  1498. /// adds new edges those will not be visited. Visitors are not allowed to
  1499. /// remove edges (though they can change their kind, target, and addend).
  1500. template <typename... VisitorTs>
  1501. void visitExistingEdges(LinkGraph &G, VisitorTs &&...Vs) {
  1502. // We may add new blocks during this process, but we don't want to iterate
  1503. // over them, so build a worklist.
  1504. std::vector<Block *> Worklist(G.blocks().begin(), G.blocks().end());
  1505. for (auto *B : Worklist)
  1506. for (auto &E : B->edges())
  1507. visitEdge(G, B, E, std::forward<VisitorTs>(Vs)...);
  1508. }
  1509. /// Create a LinkGraph from the given object buffer.
  1510. ///
  1511. /// Note: The graph does not take ownership of the underlying buffer, nor copy
  1512. /// its contents. The caller is responsible for ensuring that the object buffer
  1513. /// outlives the graph.
  1514. Expected<std::unique_ptr<LinkGraph>>
  1515. createLinkGraphFromObject(MemoryBufferRef ObjectBuffer);
  1516. /// Link the given graph.
  1517. void link(std::unique_ptr<LinkGraph> G, std::unique_ptr<JITLinkContext> Ctx);
  1518. } // end namespace jitlink
  1519. } // end namespace llvm
  1520. #endif // LLVM_EXECUTIONENGINE_JITLINK_JITLINK_H
  1521. #ifdef __GNUC__
  1522. #pragma GCC diagnostic pop
  1523. #endif