xref: /freebsd/contrib/llvm-project/llvm/lib/ExecutionEngine/JITLink/JITLinkGeneric.h (revision 77013d11e6483b970af25e13c9b892075742f7e5)
1 //===------ JITLinkGeneric.h - Generic JIT linker utilities -----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Generic JITLinker utilities. E.g. graph pruning, eh-frame parsing.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LIB_EXECUTIONENGINE_JITLINK_JITLINKGENERIC_H
14 #define LIB_EXECUTIONENGINE_JITLINK_JITLINKGENERIC_H
15 
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ExecutionEngine/JITLink/JITLink.h"
18 
19 #define DEBUG_TYPE "jitlink"
20 
21 namespace llvm {
22 
23 class MemoryBufferRef;
24 
25 namespace jitlink {
26 
27 /// Base class for a JIT linker.
28 ///
29 /// A JITLinkerBase instance links one object file into an ongoing JIT
30 /// session. Symbol resolution and finalization operations are pluggable,
31 /// and called using continuation passing (passing a continuation for the
32 /// remaining linker work) to allow them to be performed asynchronously.
33 class JITLinkerBase {
34 public:
35   JITLinkerBase(std::unique_ptr<JITLinkContext> Ctx,
36                 std::unique_ptr<LinkGraph> G, PassConfiguration Passes)
37       : Ctx(std::move(Ctx)), G(std::move(G)), Passes(std::move(Passes)) {
38     assert(this->Ctx && "Ctx can not be null");
39     assert(this->G && "G can not be null");
40   }
41 
42   virtual ~JITLinkerBase();
43 
44 protected:
45   struct SegmentLayout {
46     using BlocksList = std::vector<Block *>;
47 
48     BlocksList ContentBlocks;
49     BlocksList ZeroFillBlocks;
50   };
51 
52   using SegmentLayoutMap = DenseMap<unsigned, SegmentLayout>;
53 
54   // Phase 1:
55   //   1.1: Run pre-prune passes
56   //   1.2: Prune graph
57   //   1.3: Run post-prune passes
58   //   1.4: Sort blocks into segments
59   //   1.5: Allocate segment memory
60   //   1.6: Identify externals and make an async call to resolve function
61   void linkPhase1(std::unique_ptr<JITLinkerBase> Self);
62 
63   // Phase 2:
64   //   2.1: Apply resolution results
65   //   2.2: Fix up block contents
66   //   2.3: Call OnResolved callback
67   //   2.3: Make an async call to transfer and finalize memory.
68   void linkPhase2(std::unique_ptr<JITLinkerBase> Self,
69                   Expected<AsyncLookupResult> LookupResult,
70                   SegmentLayoutMap Layout);
71 
72   // Phase 3:
73   //   3.1: Call OnFinalized callback, handing off allocation.
74   void linkPhase3(std::unique_ptr<JITLinkerBase> Self, Error Err);
75 
76   // For debug dumping of the link graph.
77   virtual StringRef getEdgeKindName(Edge::Kind K) const = 0;
78 
79   // Align a JITTargetAddress to conform with block alignment requirements.
80   static JITTargetAddress alignToBlock(JITTargetAddress Addr, Block &B) {
81     uint64_t Delta = (B.getAlignmentOffset() - Addr) % B.getAlignment();
82     return Addr + Delta;
83   }
84 
85   // Align a pointer to conform with block alignment requirements.
86   static char *alignToBlock(char *P, Block &B) {
87     uint64_t PAddr = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(P));
88     uint64_t Delta = (B.getAlignmentOffset() - PAddr) % B.getAlignment();
89     return P + Delta;
90   }
91 
92 private:
93   // Run all passes in the given pass list, bailing out immediately if any pass
94   // returns an error.
95   Error runPasses(LinkGraphPassList &Passes);
96 
97   // Copy block contents and apply relocations.
98   // Implemented in JITLinker.
99   virtual Error fixUpBlocks(LinkGraph &G) const = 0;
100 
101   SegmentLayoutMap layOutBlocks();
102   Error allocateSegments(const SegmentLayoutMap &Layout);
103   JITLinkContext::LookupMap getExternalSymbolNames() const;
104   void applyLookupResult(AsyncLookupResult LR);
105   void copyBlockContentToWorkingMemory(const SegmentLayoutMap &Layout,
106                                        JITLinkMemoryManager::Allocation &Alloc);
107   void deallocateAndBailOut(Error Err);
108 
109   void dumpGraph(raw_ostream &OS);
110 
111   std::unique_ptr<JITLinkContext> Ctx;
112   std::unique_ptr<LinkGraph> G;
113   PassConfiguration Passes;
114   std::unique_ptr<JITLinkMemoryManager::Allocation> Alloc;
115 };
116 
117 template <typename LinkerImpl> class JITLinker : public JITLinkerBase {
118 public:
119   using JITLinkerBase::JITLinkerBase;
120 
121   /// Link constructs a LinkerImpl instance and calls linkPhase1.
122   /// Link should be called with the constructor arguments for LinkerImpl, which
123   /// will be forwarded to the constructor.
124   template <typename... ArgTs> static void link(ArgTs &&... Args) {
125     auto L = std::make_unique<LinkerImpl>(std::forward<ArgTs>(Args)...);
126 
127     // Ownership of the linker is passed into the linker's doLink function to
128     // allow it to be passed on to async continuations.
129     //
130     // FIXME: Remove LTmp once we have c++17.
131     // C++17 sequencing rules guarantee that function name expressions are
132     // sequenced before arguments, so L->linkPhase1(std::move(L), ...) will be
133     // well formed.
134     auto &LTmp = *L;
135     LTmp.linkPhase1(std::move(L));
136   }
137 
138 private:
139   const LinkerImpl &impl() const {
140     return static_cast<const LinkerImpl &>(*this);
141   }
142 
143   Error fixUpBlocks(LinkGraph &G) const override {
144     LLVM_DEBUG(dbgs() << "Fixing up blocks:\n");
145 
146     for (auto *B : G.blocks()) {
147       LLVM_DEBUG(dbgs() << "  " << *B << ":\n");
148 
149       // Copy Block data and apply fixups.
150       LLVM_DEBUG(dbgs() << "    Applying fixups.\n");
151       for (auto &E : B->edges()) {
152 
153         // Skip non-relocation edges.
154         if (!E.isRelocation())
155           continue;
156 
157         // Dispatch to LinkerImpl for fixup.
158         auto *BlockData = const_cast<char *>(B->getContent().data());
159         if (auto Err = impl().applyFixup(*B, E, BlockData))
160           return Err;
161       }
162     }
163 
164     return Error::success();
165   }
166 };
167 
168 /// Removes dead symbols/blocks/addressables.
169 ///
170 /// Finds the set of symbols and addressables reachable from any symbol
171 /// initially marked live. All symbols/addressables not marked live at the end
172 /// of this process are removed.
173 void prune(LinkGraph &G);
174 
175 } // end namespace jitlink
176 } // end namespace llvm
177 
178 #undef DEBUG_TYPE // "jitlink"
179 
180 #endif // LLVM_EXECUTIONENGINE_JITLINK_JITLINKGENERIC_H
181