JITLink.h 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  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 "JITLinkMemoryManager.h"
  20. #include "llvm/ADT/DenseMap.h"
  21. #include "llvm/ADT/DenseSet.h"
  22. #include "llvm/ADT/Optional.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/Triple.h"
  25. #include "llvm/ExecutionEngine/JITSymbol.h"
  26. #include "llvm/Support/Allocator.h"
  27. #include "llvm/Support/Endian.h"
  28. #include "llvm/Support/Error.h"
  29. #include "llvm/Support/FormatVariadic.h"
  30. #include "llvm/Support/MathExtras.h"
  31. #include "llvm/Support/Memory.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 Symbol;
  39. class Section;
  40. /// Base class for errors originating in JIT linker, e.g. missing relocation
  41. /// support.
  42. class JITLinkError : public ErrorInfo<JITLinkError> {
  43. public:
  44. static char ID;
  45. JITLinkError(Twine ErrMsg) : ErrMsg(ErrMsg.str()) {}
  46. void log(raw_ostream &OS) const override;
  47. const std::string &getErrorMessage() const { return ErrMsg; }
  48. std::error_code convertToErrorCode() const override;
  49. private:
  50. std::string ErrMsg;
  51. };
  52. /// Represents fixups and constraints in the LinkGraph.
  53. class Edge {
  54. public:
  55. using Kind = uint8_t;
  56. enum GenericEdgeKind : Kind {
  57. Invalid, // Invalid edge value.
  58. FirstKeepAlive, // Keeps target alive. Offset/addend zero.
  59. KeepAlive = FirstKeepAlive, // Tag first edge kind that preserves liveness.
  60. FirstRelocation // First architecture specific relocation.
  61. };
  62. using OffsetT = uint32_t;
  63. using AddendT = int64_t;
  64. Edge(Kind K, OffsetT Offset, Symbol &Target, AddendT Addend)
  65. : Target(&Target), Offset(Offset), Addend(Addend), K(K) {}
  66. OffsetT getOffset() const { return Offset; }
  67. void setOffset(OffsetT Offset) { this->Offset = Offset; }
  68. Kind getKind() const { return K; }
  69. void setKind(Kind K) { this->K = K; }
  70. bool isRelocation() const { return K >= FirstRelocation; }
  71. Kind getRelocation() const {
  72. assert(isRelocation() && "Not a relocation edge");
  73. return K - FirstRelocation;
  74. }
  75. bool isKeepAlive() const { return K >= FirstKeepAlive; }
  76. Symbol &getTarget() const { return *Target; }
  77. void setTarget(Symbol &Target) { this->Target = &Target; }
  78. AddendT getAddend() const { return Addend; }
  79. void setAddend(AddendT Addend) { this->Addend = Addend; }
  80. private:
  81. Symbol *Target = nullptr;
  82. OffsetT Offset = 0;
  83. AddendT Addend = 0;
  84. Kind K = 0;
  85. };
  86. /// Returns the string name of the given generic edge kind, or "unknown"
  87. /// otherwise. Useful for debugging.
  88. const char *getGenericEdgeKindName(Edge::Kind K);
  89. /// Base class for Addressable entities (externals, absolutes, blocks).
  90. class Addressable {
  91. friend class LinkGraph;
  92. protected:
  93. Addressable(JITTargetAddress Address, bool IsDefined)
  94. : Address(Address), IsDefined(IsDefined), IsAbsolute(false) {}
  95. Addressable(JITTargetAddress Address)
  96. : Address(Address), IsDefined(false), IsAbsolute(true) {
  97. assert(!(IsDefined && IsAbsolute) &&
  98. "Block cannot be both defined and absolute");
  99. }
  100. public:
  101. Addressable(const Addressable &) = delete;
  102. Addressable &operator=(const Addressable &) = default;
  103. Addressable(Addressable &&) = delete;
  104. Addressable &operator=(Addressable &&) = default;
  105. JITTargetAddress getAddress() const { return Address; }
  106. void setAddress(JITTargetAddress Address) { this->Address = Address; }
  107. /// Returns true if this is a defined addressable, in which case you
  108. /// can downcast this to a .
  109. bool isDefined() const { return static_cast<bool>(IsDefined); }
  110. bool isAbsolute() const { return static_cast<bool>(IsAbsolute); }
  111. private:
  112. JITTargetAddress Address = 0;
  113. uint64_t IsDefined : 1;
  114. uint64_t IsAbsolute : 1;
  115. };
  116. using SectionOrdinal = unsigned;
  117. /// An Addressable with content and edges.
  118. class Block : public Addressable {
  119. friend class LinkGraph;
  120. private:
  121. /// Create a zero-fill defined addressable.
  122. Block(Section &Parent, JITTargetAddress Size, JITTargetAddress Address,
  123. uint64_t Alignment, uint64_t AlignmentOffset)
  124. : Addressable(Address, true), Parent(Parent), Size(Size) {
  125. assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
  126. assert(AlignmentOffset < Alignment &&
  127. "Alignment offset cannot exceed alignment");
  128. assert(AlignmentOffset <= MaxAlignmentOffset &&
  129. "Alignment offset exceeds maximum");
  130. P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
  131. this->AlignmentOffset = AlignmentOffset;
  132. }
  133. /// Create a defined addressable for the given content.
  134. Block(Section &Parent, StringRef Content, JITTargetAddress Address,
  135. uint64_t Alignment, uint64_t AlignmentOffset)
  136. : Addressable(Address, true), Parent(Parent), Data(Content.data()),
  137. Size(Content.size()) {
  138. assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
  139. assert(AlignmentOffset < Alignment &&
  140. "Alignment offset cannot exceed alignment");
  141. assert(AlignmentOffset <= MaxAlignmentOffset &&
  142. "Alignment offset exceeds maximum");
  143. P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
  144. this->AlignmentOffset = AlignmentOffset;
  145. }
  146. public:
  147. using EdgeVector = std::vector<Edge>;
  148. using edge_iterator = EdgeVector::iterator;
  149. using const_edge_iterator = EdgeVector::const_iterator;
  150. Block(const Block &) = delete;
  151. Block &operator=(const Block &) = delete;
  152. Block(Block &&) = delete;
  153. Block &operator=(Block &&) = delete;
  154. /// Return the parent section for this block.
  155. Section &getSection() const { return Parent; }
  156. /// Returns true if this is a zero-fill block.
  157. ///
  158. /// If true, getSize is callable but getContent is not (the content is
  159. /// defined to be a sequence of zero bytes of length Size).
  160. bool isZeroFill() const { return !Data; }
  161. /// Returns the size of this defined addressable.
  162. size_t getSize() const { return Size; }
  163. /// Get the content for this block. Block must not be a zero-fill block.
  164. StringRef getContent() const {
  165. assert(Data && "Section does not contain content");
  166. return StringRef(Data, Size);
  167. }
  168. /// Set the content for this block.
  169. /// Caller is responsible for ensuring the underlying bytes are not
  170. /// deallocated while pointed to by this block.
  171. void setContent(StringRef Content) {
  172. Data = Content.data();
  173. Size = Content.size();
  174. }
  175. /// Get the alignment for this content.
  176. uint64_t getAlignment() const { return 1ull << P2Align; }
  177. /// Set the alignment for this content.
  178. void setAlignment(uint64_t Alignment) {
  179. assert(isPowerOf2_64(Alignment) && "Alignment must be a power of two");
  180. P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
  181. }
  182. /// Get the alignment offset for this content.
  183. uint64_t getAlignmentOffset() const { return AlignmentOffset; }
  184. /// Set the alignment offset for this content.
  185. void setAlignmentOffset(uint64_t AlignmentOffset) {
  186. assert(AlignmentOffset < (1ull << P2Align) &&
  187. "Alignment offset can't exceed alignment");
  188. this->AlignmentOffset = AlignmentOffset;
  189. }
  190. /// Add an edge to this block.
  191. void addEdge(Edge::Kind K, Edge::OffsetT Offset, Symbol &Target,
  192. Edge::AddendT Addend) {
  193. Edges.push_back(Edge(K, Offset, Target, Addend));
  194. }
  195. /// Add an edge by copying an existing one. This is typically used when
  196. /// moving edges between blocks.
  197. void addEdge(const Edge &E) { Edges.push_back(E); }
  198. /// Return the list of edges attached to this content.
  199. iterator_range<edge_iterator> edges() {
  200. return make_range(Edges.begin(), Edges.end());
  201. }
  202. /// Returns the list of edges attached to this content.
  203. iterator_range<const_edge_iterator> edges() const {
  204. return make_range(Edges.begin(), Edges.end());
  205. }
  206. /// Return the size of the edges list.
  207. size_t edges_size() const { return Edges.size(); }
  208. /// Returns true if the list of edges is empty.
  209. bool edges_empty() const { return Edges.empty(); }
  210. /// Remove the edge pointed to by the given iterator.
  211. /// Returns an iterator to the new next element.
  212. edge_iterator removeEdge(edge_iterator I) { return Edges.erase(I); }
  213. private:
  214. static constexpr uint64_t MaxAlignmentOffset = (1ULL << 57) - 1;
  215. uint64_t P2Align : 5;
  216. uint64_t AlignmentOffset : 57;
  217. Section &Parent;
  218. const char *Data = nullptr;
  219. size_t Size = 0;
  220. std::vector<Edge> Edges;
  221. };
  222. /// Describes symbol linkage. This can be used to make resolve definition
  223. /// clashes.
  224. enum class Linkage : uint8_t {
  225. Strong,
  226. Weak,
  227. };
  228. /// For errors and debugging output.
  229. const char *getLinkageName(Linkage L);
  230. /// Defines the scope in which this symbol should be visible:
  231. /// Default -- Visible in the public interface of the linkage unit.
  232. /// Hidden -- Visible within the linkage unit, but not exported from it.
  233. /// Local -- Visible only within the LinkGraph.
  234. enum class Scope : uint8_t { Default, Hidden, Local };
  235. /// For debugging output.
  236. const char *getScopeName(Scope S);
  237. raw_ostream &operator<<(raw_ostream &OS, const Block &B);
  238. /// Symbol representation.
  239. ///
  240. /// Symbols represent locations within Addressable objects.
  241. /// They can be either Named or Anonymous.
  242. /// Anonymous symbols have neither linkage nor visibility, and must point at
  243. /// ContentBlocks.
  244. /// Named symbols may be in one of four states:
  245. /// - Null: Default initialized. Assignable, but otherwise unusable.
  246. /// - Defined: Has both linkage and visibility and points to a ContentBlock
  247. /// - Common: Has both linkage and visibility, points to a null Addressable.
  248. /// - External: Has neither linkage nor visibility, points to an external
  249. /// Addressable.
  250. ///
  251. class Symbol {
  252. friend class LinkGraph;
  253. private:
  254. Symbol(Addressable &Base, JITTargetAddress Offset, StringRef Name,
  255. JITTargetAddress Size, Linkage L, Scope S, bool IsLive,
  256. bool IsCallable)
  257. : Name(Name), Base(&Base), Offset(Offset), Size(Size) {
  258. assert(Offset <= MaxOffset && "Offset out of range");
  259. setLinkage(L);
  260. setScope(S);
  261. setLive(IsLive);
  262. setCallable(IsCallable);
  263. }
  264. static Symbol &constructCommon(void *SymStorage, Block &Base, StringRef Name,
  265. JITTargetAddress Size, Scope S, bool IsLive) {
  266. assert(SymStorage && "Storage cannot be null");
  267. assert(!Name.empty() && "Common symbol name cannot be empty");
  268. assert(Base.isDefined() &&
  269. "Cannot create common symbol from undefined block");
  270. assert(static_cast<Block &>(Base).getSize() == Size &&
  271. "Common symbol size should match underlying block size");
  272. auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
  273. new (Sym) Symbol(Base, 0, Name, Size, Linkage::Weak, S, IsLive, false);
  274. return *Sym;
  275. }
  276. static Symbol &constructExternal(void *SymStorage, Addressable &Base,
  277. StringRef Name, JITTargetAddress Size,
  278. Linkage L) {
  279. assert(SymStorage && "Storage cannot be null");
  280. assert(!Base.isDefined() &&
  281. "Cannot create external symbol from defined block");
  282. assert(!Name.empty() && "External symbol name cannot be empty");
  283. auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
  284. new (Sym) Symbol(Base, 0, Name, Size, L, Scope::Default, false, false);
  285. return *Sym;
  286. }
  287. static Symbol &constructAbsolute(void *SymStorage, Addressable &Base,
  288. StringRef Name, JITTargetAddress Size,
  289. Linkage L, Scope S, bool IsLive) {
  290. assert(SymStorage && "Storage cannot be null");
  291. assert(!Base.isDefined() &&
  292. "Cannot create absolute symbol from a defined block");
  293. auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
  294. new (Sym) Symbol(Base, 0, Name, Size, L, S, IsLive, false);
  295. return *Sym;
  296. }
  297. static Symbol &constructAnonDef(void *SymStorage, Block &Base,
  298. JITTargetAddress Offset,
  299. JITTargetAddress Size, bool IsCallable,
  300. bool IsLive) {
  301. assert(SymStorage && "Storage cannot be null");
  302. assert((Offset + Size) <= Base.getSize() &&
  303. "Symbol extends past end of block");
  304. auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
  305. new (Sym) Symbol(Base, Offset, StringRef(), Size, Linkage::Strong,
  306. Scope::Local, IsLive, IsCallable);
  307. return *Sym;
  308. }
  309. static Symbol &constructNamedDef(void *SymStorage, Block &Base,
  310. JITTargetAddress Offset, StringRef Name,
  311. JITTargetAddress Size, Linkage L, Scope S,
  312. bool IsLive, bool IsCallable) {
  313. assert(SymStorage && "Storage cannot be null");
  314. assert((Offset + Size) <= Base.getSize() &&
  315. "Symbol extends past end of block");
  316. assert(!Name.empty() && "Name cannot be empty");
  317. auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
  318. new (Sym) Symbol(Base, Offset, Name, Size, L, S, IsLive, IsCallable);
  319. return *Sym;
  320. }
  321. public:
  322. /// Create a null Symbol. This allows Symbols to be default initialized for
  323. /// use in containers (e.g. as map values). Null symbols are only useful for
  324. /// assigning to.
  325. Symbol() = default;
  326. // Symbols are not movable or copyable.
  327. Symbol(const Symbol &) = delete;
  328. Symbol &operator=(const Symbol &) = delete;
  329. Symbol(Symbol &&) = delete;
  330. Symbol &operator=(Symbol &&) = delete;
  331. /// Returns true if this symbol has a name.
  332. bool hasName() const { return !Name.empty(); }
  333. /// Returns the name of this symbol (empty if the symbol is anonymous).
  334. StringRef getName() const {
  335. assert((!Name.empty() || getScope() == Scope::Local) &&
  336. "Anonymous symbol has non-local scope");
  337. return Name;
  338. }
  339. /// Rename this symbol. The client is responsible for updating scope and
  340. /// linkage if this name-change requires it.
  341. void setName(StringRef Name) { this->Name = Name; }
  342. /// Returns true if this Symbol has content (potentially) defined within this
  343. /// object file (i.e. is anything but an external or absolute symbol).
  344. bool isDefined() const {
  345. assert(Base && "Attempt to access null symbol");
  346. return Base->isDefined();
  347. }
  348. /// Returns true if this symbol is live (i.e. should be treated as a root for
  349. /// dead stripping).
  350. bool isLive() const {
  351. assert(Base && "Attempting to access null symbol");
  352. return IsLive;
  353. }
  354. /// Set this symbol's live bit.
  355. void setLive(bool IsLive) { this->IsLive = IsLive; }
  356. /// Returns true is this symbol is callable.
  357. bool isCallable() const { return IsCallable; }
  358. /// Set this symbol's callable bit.
  359. void setCallable(bool IsCallable) { this->IsCallable = IsCallable; }
  360. /// Returns true if the underlying addressable is an unresolved external.
  361. bool isExternal() const {
  362. assert(Base && "Attempt to access null symbol");
  363. return !Base->isDefined() && !Base->isAbsolute();
  364. }
  365. /// Returns true if the underlying addressable is an absolute symbol.
  366. bool isAbsolute() const {
  367. assert(Base && "Attempt to access null symbol");
  368. return !Base->isDefined() && Base->isAbsolute();
  369. }
  370. /// Return the addressable that this symbol points to.
  371. Addressable &getAddressable() {
  372. assert(Base && "Cannot get underlying addressable for null symbol");
  373. return *Base;
  374. }
  375. /// Return the addressable that thsi symbol points to.
  376. const Addressable &getAddressable() const {
  377. assert(Base && "Cannot get underlying addressable for null symbol");
  378. return *Base;
  379. }
  380. /// Return the Block for this Symbol (Symbol must be defined).
  381. Block &getBlock() {
  382. assert(Base && "Cannot get block for null symbol");
  383. assert(Base->isDefined() && "Not a defined symbol");
  384. return static_cast<Block &>(*Base);
  385. }
  386. /// Return the Block for this Symbol (Symbol must be defined).
  387. const Block &getBlock() const {
  388. assert(Base && "Cannot get block for null symbol");
  389. assert(Base->isDefined() && "Not a defined symbol");
  390. return static_cast<const Block &>(*Base);
  391. }
  392. /// Returns the offset for this symbol within the underlying addressable.
  393. JITTargetAddress getOffset() const { return Offset; }
  394. /// Returns the address of this symbol.
  395. JITTargetAddress getAddress() const { return Base->getAddress() + Offset; }
  396. /// Returns the size of this symbol.
  397. JITTargetAddress getSize() const { return Size; }
  398. /// Returns true if this symbol is backed by a zero-fill block.
  399. /// This method may only be called on defined symbols.
  400. bool isSymbolZeroFill() const { return getBlock().isZeroFill(); }
  401. /// Returns the content in the underlying block covered by this symbol.
  402. /// This method may only be called on defined non-zero-fill symbols.
  403. StringRef getSymbolContent() const {
  404. return getBlock().getContent().substr(Offset, Size);
  405. }
  406. /// Get the linkage for this Symbol.
  407. Linkage getLinkage() const { return static_cast<Linkage>(L); }
  408. /// Set the linkage for this Symbol.
  409. void setLinkage(Linkage L) {
  410. assert((L == Linkage::Strong || (!Base->isAbsolute() && !Name.empty())) &&
  411. "Linkage can only be applied to defined named symbols");
  412. this->L = static_cast<uint8_t>(L);
  413. }
  414. /// Get the visibility for this Symbol.
  415. Scope getScope() const { return static_cast<Scope>(S); }
  416. /// Set the visibility for this Symbol.
  417. void setScope(Scope S) {
  418. assert((!Name.empty() || S == Scope::Local) &&
  419. "Can not set anonymous symbol to non-local scope");
  420. assert((S == Scope::Default || Base->isDefined() || Base->isAbsolute()) &&
  421. "Invalid visibility for symbol type");
  422. this->S = static_cast<uint8_t>(S);
  423. }
  424. private:
  425. void makeExternal(Addressable &A) {
  426. assert(!A.isDefined() && "Attempting to make external with defined block");
  427. Base = &A;
  428. Offset = 0;
  429. setLinkage(Linkage::Strong);
  430. setScope(Scope::Default);
  431. IsLive = 0;
  432. // note: Size and IsCallable fields left unchanged.
  433. }
  434. void setBlock(Block &B) { Base = &B; }
  435. void setOffset(uint64_t NewOffset) {
  436. assert(NewOffset <= MaxOffset && "Offset out of range");
  437. Offset = NewOffset;
  438. }
  439. static constexpr uint64_t MaxOffset = (1ULL << 59) - 1;
  440. // FIXME: A char* or SymbolStringPtr may pack better.
  441. StringRef Name;
  442. Addressable *Base = nullptr;
  443. uint64_t Offset : 59;
  444. uint64_t L : 1;
  445. uint64_t S : 2;
  446. uint64_t IsLive : 1;
  447. uint64_t IsCallable : 1;
  448. JITTargetAddress Size = 0;
  449. };
  450. raw_ostream &operator<<(raw_ostream &OS, const Symbol &A);
  451. void printEdge(raw_ostream &OS, const Block &B, const Edge &E,
  452. StringRef EdgeKindName);
  453. /// Represents an object file section.
  454. class Section {
  455. friend class LinkGraph;
  456. private:
  457. Section(StringRef Name, sys::Memory::ProtectionFlags Prot,
  458. SectionOrdinal SecOrdinal)
  459. : Name(Name), Prot(Prot), SecOrdinal(SecOrdinal) {}
  460. using SymbolSet = DenseSet<Symbol *>;
  461. using BlockSet = DenseSet<Block *>;
  462. public:
  463. using symbol_iterator = SymbolSet::iterator;
  464. using const_symbol_iterator = SymbolSet::const_iterator;
  465. using block_iterator = BlockSet::iterator;
  466. using const_block_iterator = BlockSet::const_iterator;
  467. ~Section();
  468. /// Returns the name of this section.
  469. StringRef getName() const { return Name; }
  470. /// Returns the protection flags for this section.
  471. sys::Memory::ProtectionFlags getProtectionFlags() const { return Prot; }
  472. /// Returns the ordinal for this section.
  473. SectionOrdinal getOrdinal() const { return SecOrdinal; }
  474. /// Returns an iterator over the blocks defined in this section.
  475. iterator_range<block_iterator> blocks() {
  476. return make_range(Blocks.begin(), Blocks.end());
  477. }
  478. /// Returns an iterator over the blocks defined in this section.
  479. iterator_range<const_block_iterator> blocks() const {
  480. return make_range(Blocks.begin(), Blocks.end());
  481. }
  482. /// Returns an iterator over the symbols defined in this section.
  483. iterator_range<symbol_iterator> symbols() {
  484. return make_range(Symbols.begin(), Symbols.end());
  485. }
  486. /// Returns an iterator over the symbols defined in this section.
  487. iterator_range<const_symbol_iterator> symbols() const {
  488. return make_range(Symbols.begin(), Symbols.end());
  489. }
  490. /// Return the number of symbols in this section.
  491. SymbolSet::size_type symbols_size() { return Symbols.size(); }
  492. private:
  493. void addSymbol(Symbol &Sym) {
  494. assert(!Symbols.count(&Sym) && "Symbol is already in this section");
  495. Symbols.insert(&Sym);
  496. }
  497. void removeSymbol(Symbol &Sym) {
  498. assert(Symbols.count(&Sym) && "symbol is not in this section");
  499. Symbols.erase(&Sym);
  500. }
  501. void addBlock(Block &B) {
  502. assert(!Blocks.count(&B) && "Block is already in this section");
  503. Blocks.insert(&B);
  504. }
  505. void removeBlock(Block &B) {
  506. assert(Blocks.count(&B) && "Block is not in this section");
  507. Blocks.erase(&B);
  508. }
  509. StringRef Name;
  510. sys::Memory::ProtectionFlags Prot;
  511. SectionOrdinal SecOrdinal = 0;
  512. BlockSet Blocks;
  513. SymbolSet Symbols;
  514. };
  515. /// Represents a section address range via a pair of Block pointers
  516. /// to the first and last Blocks in the section.
  517. class SectionRange {
  518. public:
  519. SectionRange() = default;
  520. SectionRange(const Section &Sec) {
  521. if (llvm::empty(Sec.blocks()))
  522. return;
  523. First = Last = *Sec.blocks().begin();
  524. for (auto *B : Sec.blocks()) {
  525. if (B->getAddress() < First->getAddress())
  526. First = B;
  527. if (B->getAddress() > Last->getAddress())
  528. Last = B;
  529. }
  530. }
  531. Block *getFirstBlock() const {
  532. assert((!Last || First) && "First can not be null if end is non-null");
  533. return First;
  534. }
  535. Block *getLastBlock() const {
  536. assert((First || !Last) && "Last can not be null if start is non-null");
  537. return Last;
  538. }
  539. bool isEmpty() const {
  540. assert((First || !Last) && "Last can not be null if start is non-null");
  541. return !First;
  542. }
  543. JITTargetAddress getStart() const {
  544. return First ? First->getAddress() : 0;
  545. }
  546. JITTargetAddress getEnd() const {
  547. return Last ? Last->getAddress() + Last->getSize() : 0;
  548. }
  549. uint64_t getSize() const { return getEnd() - getStart(); }
  550. private:
  551. Block *First = nullptr;
  552. Block *Last = nullptr;
  553. };
  554. class LinkGraph {
  555. private:
  556. using SectionList = std::vector<std::unique_ptr<Section>>;
  557. using ExternalSymbolSet = DenseSet<Symbol *>;
  558. using BlockSet = DenseSet<Block *>;
  559. template <typename... ArgTs>
  560. Addressable &createAddressable(ArgTs &&... Args) {
  561. Addressable *A =
  562. reinterpret_cast<Addressable *>(Allocator.Allocate<Addressable>());
  563. new (A) Addressable(std::forward<ArgTs>(Args)...);
  564. return *A;
  565. }
  566. void destroyAddressable(Addressable &A) {
  567. A.~Addressable();
  568. Allocator.Deallocate(&A);
  569. }
  570. template <typename... ArgTs> Block &createBlock(ArgTs &&... Args) {
  571. Block *B = reinterpret_cast<Block *>(Allocator.Allocate<Block>());
  572. new (B) Block(std::forward<ArgTs>(Args)...);
  573. B->getSection().addBlock(*B);
  574. return *B;
  575. }
  576. void destroyBlock(Block &B) {
  577. B.~Block();
  578. Allocator.Deallocate(&B);
  579. }
  580. void destroySymbol(Symbol &S) {
  581. S.~Symbol();
  582. Allocator.Deallocate(&S);
  583. }
  584. static iterator_range<Section::block_iterator> getSectionBlocks(Section &S) {
  585. return S.blocks();
  586. }
  587. static iterator_range<Section::const_block_iterator>
  588. getSectionConstBlocks(Section &S) {
  589. return S.blocks();
  590. }
  591. static iterator_range<Section::symbol_iterator>
  592. getSectionSymbols(Section &S) {
  593. return S.symbols();
  594. }
  595. static iterator_range<Section::const_symbol_iterator>
  596. getSectionConstSymbols(Section &S) {
  597. return S.symbols();
  598. }
  599. public:
  600. using external_symbol_iterator = ExternalSymbolSet::iterator;
  601. using section_iterator = pointee_iterator<SectionList::iterator>;
  602. using const_section_iterator = pointee_iterator<SectionList::const_iterator>;
  603. template <typename OuterItrT, typename InnerItrT, typename T,
  604. iterator_range<InnerItrT> getInnerRange(
  605. typename OuterItrT::reference)>
  606. class nested_collection_iterator
  607. : public iterator_facade_base<
  608. nested_collection_iterator<OuterItrT, InnerItrT, T, getInnerRange>,
  609. std::forward_iterator_tag, T> {
  610. public:
  611. nested_collection_iterator() = default;
  612. nested_collection_iterator(OuterItrT OuterI, OuterItrT OuterE)
  613. : OuterI(OuterI), OuterE(OuterE),
  614. InnerI(getInnerBegin(OuterI, OuterE)) {
  615. moveToNonEmptyInnerOrEnd();
  616. }
  617. bool operator==(const nested_collection_iterator &RHS) const {
  618. return (OuterI == RHS.OuterI) && (InnerI == RHS.InnerI);
  619. }
  620. T operator*() const {
  621. assert(InnerI != getInnerRange(*OuterI).end() && "Dereferencing end?");
  622. return *InnerI;
  623. }
  624. nested_collection_iterator operator++() {
  625. ++InnerI;
  626. moveToNonEmptyInnerOrEnd();
  627. return *this;
  628. }
  629. private:
  630. static InnerItrT getInnerBegin(OuterItrT OuterI, OuterItrT OuterE) {
  631. return OuterI != OuterE ? getInnerRange(*OuterI).begin() : InnerItrT();
  632. }
  633. void moveToNonEmptyInnerOrEnd() {
  634. while (OuterI != OuterE && InnerI == getInnerRange(*OuterI).end()) {
  635. ++OuterI;
  636. InnerI = getInnerBegin(OuterI, OuterE);
  637. }
  638. }
  639. OuterItrT OuterI, OuterE;
  640. InnerItrT InnerI;
  641. };
  642. using defined_symbol_iterator =
  643. nested_collection_iterator<const_section_iterator,
  644. Section::symbol_iterator, Symbol *,
  645. getSectionSymbols>;
  646. using const_defined_symbol_iterator =
  647. nested_collection_iterator<const_section_iterator,
  648. Section::const_symbol_iterator, const Symbol *,
  649. getSectionConstSymbols>;
  650. using block_iterator = nested_collection_iterator<const_section_iterator,
  651. Section::block_iterator,
  652. Block *, getSectionBlocks>;
  653. using const_block_iterator =
  654. nested_collection_iterator<const_section_iterator,
  655. Section::const_block_iterator, const Block *,
  656. getSectionConstBlocks>;
  657. LinkGraph(std::string Name, const Triple &TT, unsigned PointerSize,
  658. support::endianness Endianness)
  659. : Name(std::move(Name)), TT(TT), PointerSize(PointerSize),
  660. Endianness(Endianness) {}
  661. /// Returns the name of this graph (usually the name of the original
  662. /// underlying MemoryBuffer).
  663. const std::string &getName() { return Name; }
  664. /// Returns the target triple for this Graph.
  665. const Triple &getTargetTriple() const { return TT; }
  666. /// Returns the pointer size for use in this graph.
  667. unsigned getPointerSize() const { return PointerSize; }
  668. /// Returns the endianness of content in this graph.
  669. support::endianness getEndianness() const { return Endianness; }
  670. /// Allocate a copy of the given string using the LinkGraph's allocator.
  671. /// This can be useful when renaming symbols or adding new content to the
  672. /// graph.
  673. StringRef allocateString(StringRef Source) {
  674. auto *AllocatedBuffer = Allocator.Allocate<char>(Source.size());
  675. llvm::copy(Source, AllocatedBuffer);
  676. return StringRef(AllocatedBuffer, Source.size());
  677. }
  678. /// Allocate a copy of the given string using the LinkGraph's allocator.
  679. /// This can be useful when renaming symbols or adding new content to the
  680. /// graph.
  681. ///
  682. /// Note: This Twine-based overload requires an extra string copy and an
  683. /// extra heap allocation for large strings. The StringRef overload should
  684. /// be preferred where possible.
  685. StringRef allocateString(Twine Source) {
  686. SmallString<256> TmpBuffer;
  687. auto SourceStr = Source.toStringRef(TmpBuffer);
  688. auto *AllocatedBuffer = Allocator.Allocate<char>(SourceStr.size());
  689. llvm::copy(SourceStr, AllocatedBuffer);
  690. return StringRef(AllocatedBuffer, SourceStr.size());
  691. }
  692. /// Create a section with the given name, protection flags, and alignment.
  693. Section &createSection(StringRef Name, sys::Memory::ProtectionFlags Prot) {
  694. std::unique_ptr<Section> Sec(new Section(Name, Prot, Sections.size()));
  695. Sections.push_back(std::move(Sec));
  696. return *Sections.back();
  697. }
  698. /// Create a content block.
  699. Block &createContentBlock(Section &Parent, StringRef Content,
  700. uint64_t Address, uint64_t Alignment,
  701. uint64_t AlignmentOffset) {
  702. return createBlock(Parent, Content, Address, Alignment, AlignmentOffset);
  703. }
  704. /// Create a zero-fill block.
  705. Block &createZeroFillBlock(Section &Parent, uint64_t Size, uint64_t Address,
  706. uint64_t Alignment, uint64_t AlignmentOffset) {
  707. return createBlock(Parent, Size, Address, Alignment, AlignmentOffset);
  708. }
  709. /// Cache type for the splitBlock function.
  710. using SplitBlockCache = Optional<SmallVector<Symbol *, 8>>;
  711. /// Splits block B at the given index which must be greater than zero.
  712. /// If SplitIndex == B.getSize() then this function is a no-op and returns B.
  713. /// If SplitIndex < B.getSize() then this function returns a new block
  714. /// covering the range [ 0, SplitIndex ), and B is modified to cover the range
  715. /// [ SplitIndex, B.size() ).
  716. ///
  717. /// The optional Cache parameter can be used to speed up repeated calls to
  718. /// splitBlock for a single block. If the value is None the cache will be
  719. /// treated as uninitialized and splitBlock will populate it. Otherwise it
  720. /// is assumed to contain the list of Symbols pointing at B, sorted in
  721. /// descending order of offset.
  722. ///
  723. /// Notes:
  724. ///
  725. /// 1. The newly introduced block will have a new ordinal which will be
  726. /// higher than any other ordinals in the section. Clients are responsible
  727. /// for re-assigning block ordinals to restore a compatible order if
  728. /// needed.
  729. ///
  730. /// 2. The cache is not automatically updated if new symbols are introduced
  731. /// between calls to splitBlock. Any newly introduced symbols may be
  732. /// added to the cache manually (descending offset order must be
  733. /// preserved), or the cache can be set to None and rebuilt by
  734. /// splitBlock on the next call.
  735. Block &splitBlock(Block &B, size_t SplitIndex,
  736. SplitBlockCache *Cache = nullptr);
  737. /// Add an external symbol.
  738. /// Some formats (e.g. ELF) allow Symbols to have sizes. For Symbols whose
  739. /// size is not known, you should substitute '0'.
  740. /// For external symbols Linkage determines whether the symbol must be
  741. /// present during lookup: Externals with strong linkage must be found or
  742. /// an error will be emitted. Externals with weak linkage are permitted to
  743. /// be undefined, in which case they are assigned a value of 0.
  744. Symbol &addExternalSymbol(StringRef Name, uint64_t Size, Linkage L) {
  745. auto &Sym =
  746. Symbol::constructExternal(Allocator.Allocate<Symbol>(),
  747. createAddressable(0, false), Name, Size, L);
  748. ExternalSymbols.insert(&Sym);
  749. return Sym;
  750. }
  751. /// Add an absolute symbol.
  752. Symbol &addAbsoluteSymbol(StringRef Name, JITTargetAddress Address,
  753. uint64_t Size, Linkage L, Scope S, bool IsLive) {
  754. auto &Sym = Symbol::constructAbsolute(Allocator.Allocate<Symbol>(),
  755. createAddressable(Address), Name,
  756. Size, L, S, IsLive);
  757. AbsoluteSymbols.insert(&Sym);
  758. return Sym;
  759. }
  760. /// Convenience method for adding a weak zero-fill symbol.
  761. Symbol &addCommonSymbol(StringRef Name, Scope S, Section &Section,
  762. JITTargetAddress Address, uint64_t Size,
  763. uint64_t Alignment, bool IsLive) {
  764. auto &Sym = Symbol::constructCommon(
  765. Allocator.Allocate<Symbol>(),
  766. createBlock(Section, Size, Address, Alignment, 0), Name, Size, S,
  767. IsLive);
  768. Section.addSymbol(Sym);
  769. return Sym;
  770. }
  771. /// Add an anonymous symbol.
  772. Symbol &addAnonymousSymbol(Block &Content, JITTargetAddress Offset,
  773. JITTargetAddress Size, bool IsCallable,
  774. bool IsLive) {
  775. auto &Sym = Symbol::constructAnonDef(Allocator.Allocate<Symbol>(), Content,
  776. Offset, Size, IsCallable, IsLive);
  777. Content.getSection().addSymbol(Sym);
  778. return Sym;
  779. }
  780. /// Add a named symbol.
  781. Symbol &addDefinedSymbol(Block &Content, JITTargetAddress Offset,
  782. StringRef Name, JITTargetAddress Size, Linkage L,
  783. Scope S, bool IsCallable, bool IsLive) {
  784. auto &Sym =
  785. Symbol::constructNamedDef(Allocator.Allocate<Symbol>(), Content, Offset,
  786. Name, Size, L, S, IsLive, IsCallable);
  787. Content.getSection().addSymbol(Sym);
  788. return Sym;
  789. }
  790. iterator_range<section_iterator> sections() {
  791. return make_range(section_iterator(Sections.begin()),
  792. section_iterator(Sections.end()));
  793. }
  794. /// Returns the section with the given name if it exists, otherwise returns
  795. /// null.
  796. Section *findSectionByName(StringRef Name) {
  797. for (auto &S : sections())
  798. if (S.getName() == Name)
  799. return &S;
  800. return nullptr;
  801. }
  802. iterator_range<block_iterator> blocks() {
  803. return make_range(block_iterator(Sections.begin(), Sections.end()),
  804. block_iterator(Sections.end(), Sections.end()));
  805. }
  806. iterator_range<const_block_iterator> blocks() const {
  807. return make_range(const_block_iterator(Sections.begin(), Sections.end()),
  808. const_block_iterator(Sections.end(), Sections.end()));
  809. }
  810. iterator_range<external_symbol_iterator> external_symbols() {
  811. return make_range(ExternalSymbols.begin(), ExternalSymbols.end());
  812. }
  813. iterator_range<external_symbol_iterator> absolute_symbols() {
  814. return make_range(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
  815. }
  816. iterator_range<defined_symbol_iterator> defined_symbols() {
  817. return make_range(defined_symbol_iterator(Sections.begin(), Sections.end()),
  818. defined_symbol_iterator(Sections.end(), Sections.end()));
  819. }
  820. iterator_range<const_defined_symbol_iterator> defined_symbols() const {
  821. return make_range(
  822. const_defined_symbol_iterator(Sections.begin(), Sections.end()),
  823. const_defined_symbol_iterator(Sections.end(), Sections.end()));
  824. }
  825. /// Turn a defined symbol into an external one.
  826. void makeExternal(Symbol &Sym) {
  827. if (Sym.getAddressable().isAbsolute()) {
  828. assert(AbsoluteSymbols.count(&Sym) &&
  829. "Sym is not in the absolute symbols set");
  830. AbsoluteSymbols.erase(&Sym);
  831. } else {
  832. assert(Sym.isDefined() && "Sym is not a defined symbol");
  833. Section &Sec = Sym.getBlock().getSection();
  834. Sec.removeSymbol(Sym);
  835. }
  836. Sym.makeExternal(createAddressable(0, false));
  837. ExternalSymbols.insert(&Sym);
  838. }
  839. /// Removes an external symbol. Also removes the underlying Addressable.
  840. void removeExternalSymbol(Symbol &Sym) {
  841. assert(!Sym.isDefined() && !Sym.isAbsolute() &&
  842. "Sym is not an external symbol");
  843. assert(ExternalSymbols.count(&Sym) && "Symbol is not in the externals set");
  844. ExternalSymbols.erase(&Sym);
  845. Addressable &Base = *Sym.Base;
  846. destroySymbol(Sym);
  847. destroyAddressable(Base);
  848. }
  849. /// Remove an absolute symbol. Also removes the underlying Addressable.
  850. void removeAbsoluteSymbol(Symbol &Sym) {
  851. assert(!Sym.isDefined() && Sym.isAbsolute() &&
  852. "Sym is not an absolute symbol");
  853. assert(AbsoluteSymbols.count(&Sym) &&
  854. "Symbol is not in the absolute symbols set");
  855. AbsoluteSymbols.erase(&Sym);
  856. Addressable &Base = *Sym.Base;
  857. destroySymbol(Sym);
  858. destroyAddressable(Base);
  859. }
  860. /// Removes defined symbols. Does not remove the underlying block.
  861. void removeDefinedSymbol(Symbol &Sym) {
  862. assert(Sym.isDefined() && "Sym is not a defined symbol");
  863. Sym.getBlock().getSection().removeSymbol(Sym);
  864. destroySymbol(Sym);
  865. }
  866. /// Remove a block.
  867. void removeBlock(Block &B) {
  868. assert(llvm::none_of(B.getSection().symbols(),
  869. [&](const Symbol *Sym) {
  870. return &Sym->getBlock() == &B;
  871. }) &&
  872. "Block still has symbols attached");
  873. B.getSection().removeBlock(B);
  874. destroyBlock(B);
  875. }
  876. /// Dump the graph.
  877. ///
  878. /// If supplied, the EdgeKindToName function will be used to name edge
  879. /// kinds in the debug output. Otherwise raw edge kind numbers will be
  880. /// displayed.
  881. void dump(raw_ostream &OS,
  882. std::function<StringRef(Edge::Kind)> EdegKindToName =
  883. std::function<StringRef(Edge::Kind)>());
  884. private:
  885. // Put the BumpPtrAllocator first so that we don't free any of the underlying
  886. // memory until the Symbol/Addressable destructors have been run.
  887. BumpPtrAllocator Allocator;
  888. std::string Name;
  889. Triple TT;
  890. unsigned PointerSize;
  891. support::endianness Endianness;
  892. SectionList Sections;
  893. ExternalSymbolSet ExternalSymbols;
  894. ExternalSymbolSet AbsoluteSymbols;
  895. };
  896. /// Enables easy lookup of blocks by addresses.
  897. class BlockAddressMap {
  898. public:
  899. using AddrToBlockMap = std::map<JITTargetAddress, Block *>;
  900. using const_iterator = AddrToBlockMap::const_iterator;
  901. /// A block predicate that always adds all blocks.
  902. static bool includeAllBlocks(const Block &B) { return true; }
  903. /// A block predicate that always includes blocks with non-null addresses.
  904. static bool includeNonNull(const Block &B) { return B.getAddress(); }
  905. BlockAddressMap() = default;
  906. /// Add a block to the map. Returns an error if the block overlaps with any
  907. /// existing block.
  908. template <typename PredFn = decltype(includeAllBlocks)>
  909. Error addBlock(Block &B, PredFn Pred = includeAllBlocks) {
  910. if (!Pred(B))
  911. return Error::success();
  912. auto I = AddrToBlock.upper_bound(B.getAddress());
  913. // If we're not at the end of the map, check for overlap with the next
  914. // element.
  915. if (I != AddrToBlock.end()) {
  916. if (B.getAddress() + B.getSize() > I->second->getAddress())
  917. return overlapError(B, *I->second);
  918. }
  919. // If we're not at the start of the map, check for overlap with the previous
  920. // element.
  921. if (I != AddrToBlock.begin()) {
  922. auto &PrevBlock = *std::prev(I)->second;
  923. if (PrevBlock.getAddress() + PrevBlock.getSize() > B.getAddress())
  924. return overlapError(B, PrevBlock);
  925. }
  926. AddrToBlock.insert(I, std::make_pair(B.getAddress(), &B));
  927. return Error::success();
  928. }
  929. /// Add a block to the map without checking for overlap with existing blocks.
  930. /// The client is responsible for ensuring that the block added does not
  931. /// overlap with any existing block.
  932. void addBlockWithoutChecking(Block &B) { AddrToBlock[B.getAddress()] = &B; }
  933. /// Add a range of blocks to the map. Returns an error if any block in the
  934. /// range overlaps with any other block in the range, or with any existing
  935. /// block in the map.
  936. template <typename BlockPtrRange,
  937. typename PredFn = decltype(includeAllBlocks)>
  938. Error addBlocks(BlockPtrRange &&Blocks, PredFn Pred = includeAllBlocks) {
  939. for (auto *B : Blocks)
  940. if (auto Err = addBlock(*B, Pred))
  941. return Err;
  942. return Error::success();
  943. }
  944. /// Add a range of blocks to the map without checking for overlap with
  945. /// existing blocks. The client is responsible for ensuring that the block
  946. /// added does not overlap with any existing block.
  947. template <typename BlockPtrRange>
  948. void addBlocksWithoutChecking(BlockPtrRange &&Blocks) {
  949. for (auto *B : Blocks)
  950. addBlockWithoutChecking(*B);
  951. }
  952. /// Iterates over (Address, Block*) pairs in ascending order of address.
  953. const_iterator begin() const { return AddrToBlock.begin(); }
  954. const_iterator end() const { return AddrToBlock.end(); }
  955. /// Returns the block starting at the given address, or nullptr if no such
  956. /// block exists.
  957. Block *getBlockAt(JITTargetAddress Addr) const {
  958. auto I = AddrToBlock.find(Addr);
  959. if (I == AddrToBlock.end())
  960. return nullptr;
  961. return I->second;
  962. }
  963. /// Returns the block covering the given address, or nullptr if no such block
  964. /// exists.
  965. Block *getBlockCovering(JITTargetAddress Addr) const {
  966. auto I = AddrToBlock.upper_bound(Addr);
  967. if (I == AddrToBlock.begin())
  968. return nullptr;
  969. auto *B = std::prev(I)->second;
  970. if (Addr < B->getAddress() + B->getSize())
  971. return B;
  972. return nullptr;
  973. }
  974. private:
  975. Error overlapError(Block &NewBlock, Block &ExistingBlock) {
  976. auto NewBlockEnd = NewBlock.getAddress() + NewBlock.getSize();
  977. auto ExistingBlockEnd =
  978. ExistingBlock.getAddress() + ExistingBlock.getSize();
  979. return make_error<JITLinkError>(
  980. "Block at " +
  981. formatv("{0:x16} -- {1:x16}", NewBlock.getAddress(), NewBlockEnd) +
  982. " overlaps " +
  983. formatv("{0:x16} -- {1:x16}", ExistingBlock.getAddress(),
  984. ExistingBlockEnd));
  985. }
  986. AddrToBlockMap AddrToBlock;
  987. };
  988. /// A map of addresses to Symbols.
  989. class SymbolAddressMap {
  990. public:
  991. using SymbolVector = SmallVector<Symbol *, 1>;
  992. /// Add a symbol to the SymbolAddressMap.
  993. void addSymbol(Symbol &Sym) {
  994. AddrToSymbols[Sym.getAddress()].push_back(&Sym);
  995. }
  996. /// Add all symbols in a given range to the SymbolAddressMap.
  997. template <typename SymbolPtrCollection>
  998. void addSymbols(SymbolPtrCollection &&Symbols) {
  999. for (auto *Sym : Symbols)
  1000. addSymbol(*Sym);
  1001. }
  1002. /// Returns the list of symbols that start at the given address, or nullptr if
  1003. /// no such symbols exist.
  1004. const SymbolVector *getSymbolsAt(JITTargetAddress Addr) const {
  1005. auto I = AddrToSymbols.find(Addr);
  1006. if (I == AddrToSymbols.end())
  1007. return nullptr;
  1008. return &I->second;
  1009. }
  1010. private:
  1011. std::map<JITTargetAddress, SymbolVector> AddrToSymbols;
  1012. };
  1013. /// A function for mutating LinkGraphs.
  1014. using LinkGraphPassFunction = std::function<Error(LinkGraph &)>;
  1015. /// A list of LinkGraph passes.
  1016. using LinkGraphPassList = std::vector<LinkGraphPassFunction>;
  1017. /// An LinkGraph pass configuration, consisting of a list of pre-prune,
  1018. /// post-prune, and post-fixup passes.
  1019. struct PassConfiguration {
  1020. /// Pre-prune passes.
  1021. ///
  1022. /// These passes are called on the graph after it is built, and before any
  1023. /// symbols have been pruned. Graph nodes still have their original vmaddrs.
  1024. ///
  1025. /// Notable use cases: Marking symbols live or should-discard.
  1026. LinkGraphPassList PrePrunePasses;
  1027. /// Post-prune passes.
  1028. ///
  1029. /// These passes are called on the graph after dead stripping, but before
  1030. /// memory is allocated or nodes assigned their final addresses.
  1031. ///
  1032. /// Notable use cases: Building GOT, stub, and TLV symbols.
  1033. LinkGraphPassList PostPrunePasses;
  1034. /// Post-allocation passes.
  1035. ///
  1036. /// These passes are called on the graph after memory has been allocated and
  1037. /// defined nodes have been assigned their final addresses, but before the
  1038. /// context has been notified of these addresses. At this point externals
  1039. /// have not been resolved, and symbol content has not yet been copied into
  1040. /// working memory.
  1041. ///
  1042. /// Notable use cases: Setting up data structures associated with addresses
  1043. /// of defined symbols (e.g. a mapping of __dso_handle to JITDylib* for the
  1044. /// JIT runtime) -- using a PostAllocationPass for this ensures that the
  1045. /// data structures are in-place before any query for resolved symbols
  1046. /// can complete.
  1047. LinkGraphPassList PostAllocationPasses;
  1048. /// Pre-fixup passes.
  1049. ///
  1050. /// These passes are called on the graph after memory has been allocated,
  1051. /// content copied into working memory, and all nodes (including externals)
  1052. /// have been assigned their final addresses, but before any fixups have been
  1053. /// applied.
  1054. ///
  1055. /// Notable use cases: Late link-time optimizations like GOT and stub
  1056. /// elimination.
  1057. LinkGraphPassList PreFixupPasses;
  1058. /// Post-fixup passes.
  1059. ///
  1060. /// These passes are called on the graph after block contents has been copied
  1061. /// to working memory, and fixups applied. Graph nodes have been updated to
  1062. /// their final target vmaddrs.
  1063. ///
  1064. /// Notable use cases: Testing and validation.
  1065. LinkGraphPassList PostFixupPasses;
  1066. };
  1067. /// Flags for symbol lookup.
  1068. ///
  1069. /// FIXME: These basically duplicate orc::SymbolLookupFlags -- We should merge
  1070. /// the two types once we have an OrcSupport library.
  1071. enum class SymbolLookupFlags { RequiredSymbol, WeaklyReferencedSymbol };
  1072. raw_ostream &operator<<(raw_ostream &OS, const SymbolLookupFlags &LF);
  1073. /// A map of symbol names to resolved addresses.
  1074. using AsyncLookupResult = DenseMap<StringRef, JITEvaluatedSymbol>;
  1075. /// A function object to call with a resolved symbol map (See AsyncLookupResult)
  1076. /// or an error if resolution failed.
  1077. class JITLinkAsyncLookupContinuation {
  1078. public:
  1079. virtual ~JITLinkAsyncLookupContinuation() {}
  1080. virtual void run(Expected<AsyncLookupResult> LR) = 0;
  1081. private:
  1082. virtual void anchor();
  1083. };
  1084. /// Create a lookup continuation from a function object.
  1085. template <typename Continuation>
  1086. std::unique_ptr<JITLinkAsyncLookupContinuation>
  1087. createLookupContinuation(Continuation Cont) {
  1088. class Impl final : public JITLinkAsyncLookupContinuation {
  1089. public:
  1090. Impl(Continuation C) : C(std::move(C)) {}
  1091. void run(Expected<AsyncLookupResult> LR) override { C(std::move(LR)); }
  1092. private:
  1093. Continuation C;
  1094. };
  1095. return std::make_unique<Impl>(std::move(Cont));
  1096. }
  1097. /// Holds context for a single jitLink invocation.
  1098. class JITLinkContext {
  1099. public:
  1100. using LookupMap = DenseMap<StringRef, SymbolLookupFlags>;
  1101. /// Create a JITLinkContext.
  1102. JITLinkContext(const JITLinkDylib *JD) : JD(JD) {}
  1103. /// Destroy a JITLinkContext.
  1104. virtual ~JITLinkContext();
  1105. /// Return the JITLinkDylib that this link is targeting, if any.
  1106. const JITLinkDylib *getJITLinkDylib() const { return JD; }
  1107. /// Return the MemoryManager to be used for this link.
  1108. virtual JITLinkMemoryManager &getMemoryManager() = 0;
  1109. /// Notify this context that linking failed.
  1110. /// Called by JITLink if linking cannot be completed.
  1111. virtual void notifyFailed(Error Err) = 0;
  1112. /// Called by JITLink to resolve external symbols. This method is passed a
  1113. /// lookup continutation which it must call with a result to continue the
  1114. /// linking process.
  1115. virtual void lookup(const LookupMap &Symbols,
  1116. std::unique_ptr<JITLinkAsyncLookupContinuation> LC) = 0;
  1117. /// Called by JITLink once all defined symbols in the graph have been assigned
  1118. /// their final memory locations in the target process. At this point the
  1119. /// LinkGraph can be inspected to build a symbol table, however the block
  1120. /// content will not generally have been copied to the target location yet.
  1121. ///
  1122. /// If the client detects an error in the LinkGraph state (e.g. unexpected or
  1123. /// missing symbols) they may return an error here. The error will be
  1124. /// propagated to notifyFailed and the linker will bail out.
  1125. virtual Error notifyResolved(LinkGraph &G) = 0;
  1126. /// Called by JITLink to notify the context that the object has been
  1127. /// finalized (i.e. emitted to memory and memory permissions set). If all of
  1128. /// this objects dependencies have also been finalized then the code is ready
  1129. /// to run.
  1130. virtual void
  1131. notifyFinalized(std::unique_ptr<JITLinkMemoryManager::Allocation> A) = 0;
  1132. /// Called by JITLink prior to linking to determine whether default passes for
  1133. /// the target should be added. The default implementation returns true.
  1134. /// If subclasses override this method to return false for any target then
  1135. /// they are required to fully configure the pass pipeline for that target.
  1136. virtual bool shouldAddDefaultTargetPasses(const Triple &TT) const;
  1137. /// Returns the mark-live pass to be used for this link. If no pass is
  1138. /// returned (the default) then the target-specific linker implementation will
  1139. /// choose a conservative default (usually marking all symbols live).
  1140. /// This function is only called if shouldAddDefaultTargetPasses returns true,
  1141. /// otherwise the JITContext is responsible for adding a mark-live pass in
  1142. /// modifyPassConfig.
  1143. virtual LinkGraphPassFunction getMarkLivePass(const Triple &TT) const;
  1144. /// Called by JITLink to modify the pass pipeline prior to linking.
  1145. /// The default version performs no modification.
  1146. virtual Error modifyPassConfig(const Triple &TT, PassConfiguration &Config);
  1147. private:
  1148. const JITLinkDylib *JD = nullptr;
  1149. };
  1150. /// Marks all symbols in a graph live. This can be used as a default,
  1151. /// conservative mark-live implementation.
  1152. Error markAllSymbolsLive(LinkGraph &G);
  1153. /// Create a LinkGraph from the given object buffer.
  1154. ///
  1155. /// Note: The graph does not take ownership of the underlying buffer, nor copy
  1156. /// its contents. The caller is responsible for ensuring that the object buffer
  1157. /// outlives the graph.
  1158. Expected<std::unique_ptr<LinkGraph>>
  1159. createLinkGraphFromObject(MemoryBufferRef ObjectBuffer);
  1160. /// Link the given graph.
  1161. void link(std::unique_ptr<LinkGraph> G, std::unique_ptr<JITLinkContext> Ctx);
  1162. } // end namespace jitlink
  1163. } // end namespace llvm
  1164. #endif // LLVM_EXECUTIONENGINE_JITLINK_JITLINK_H
  1165. #ifdef __GNUC__
  1166. #pragma GCC diagnostic pop
  1167. #endif