LLVM  13.0.0git
JITLink.cpp
Go to the documentation of this file.
1 //===------------- JITLink.cpp - Core Run-time JIT linker APIs ------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
11 
15 #include "llvm/Support/Format.h"
19 
20 using namespace llvm;
21 using namespace llvm::object;
22 
23 #define DEBUG_TYPE "jitlink"
24 
25 namespace {
26 
27 enum JITLinkErrorCode { GenericJITLinkError = 1 };
28 
29 // FIXME: This class is only here to support the transition to llvm::Error. It
30 // will be removed once this transition is complete. Clients should prefer to
31 // deal with the Error value directly, rather than converting to error_code.
32 class JITLinkerErrorCategory : public std::error_category {
33 public:
34  const char *name() const noexcept override { return "runtimedyld"; }
35 
36  std::string message(int Condition) const override {
37  switch (static_cast<JITLinkErrorCode>(Condition)) {
38  case GenericJITLinkError:
39  return "Generic JITLink error";
40  }
41  llvm_unreachable("Unrecognized JITLinkErrorCode");
42  }
43 };
44 
45 static ManagedStatic<JITLinkerErrorCategory> JITLinkerErrorCategory;
46 
47 } // namespace
48 
49 namespace llvm {
50 namespace jitlink {
51 
52 char JITLinkError::ID = 0;
53 
54 void JITLinkError::log(raw_ostream &OS) const { OS << ErrMsg << "\n"; }
55 
56 std::error_code JITLinkError::convertToErrorCode() const {
57  return std::error_code(GenericJITLinkError, *JITLinkerErrorCategory);
58 }
59 
61  switch (K) {
62  case Edge::Invalid:
63  return "INVALID RELOCATION";
64  case Edge::KeepAlive:
65  return "Keep-Alive";
66  default:
67  return "<Unrecognized edge kind>";
68  }
69 }
70 
71 const char *getLinkageName(Linkage L) {
72  switch (L) {
73  case Linkage::Strong:
74  return "strong";
75  case Linkage::Weak:
76  return "weak";
77  }
78  llvm_unreachable("Unrecognized llvm.jitlink.Linkage enum");
79 }
80 
81 const char *getScopeName(Scope S) {
82  switch (S) {
83  case Scope::Default:
84  return "default";
85  case Scope::Hidden:
86  return "hidden";
87  case Scope::Local:
88  return "local";
89  }
90  llvm_unreachable("Unrecognized llvm.jitlink.Scope enum");
91 }
92 
94  return OS << formatv("{0:x16}", B.getAddress()) << " -- "
95  << formatv("{0:x16}", B.getAddress() + B.getSize()) << ": "
96  << "size = " << formatv("{0:x}", B.getSize()) << ", "
97  << (B.isZeroFill() ? "zero-fill" : "content")
98  << ", align = " << B.getAlignment()
99  << ", align-ofs = " << B.getAlignmentOffset()
100  << ", section = " << B.getSection().getName();
101 }
102 
104  OS << "<";
105  if (Sym.getName().empty())
106  OS << "*anon*";
107  else
108  OS << Sym.getName();
109  OS << ": flags = ";
110  switch (Sym.getLinkage()) {
111  case Linkage::Strong:
112  OS << 'S';
113  break;
114  case Linkage::Weak:
115  OS << 'W';
116  break;
117  }
118  switch (Sym.getScope()) {
119  case Scope::Default:
120  OS << 'D';
121  break;
122  case Scope::Hidden:
123  OS << 'H';
124  break;
125  case Scope::Local:
126  OS << 'L';
127  break;
128  }
129  OS << (Sym.isLive() ? '+' : '-')
130  << ", size = " << formatv("{0:x}", Sym.getSize())
131  << ", addr = " << formatv("{0:x16}", Sym.getAddress()) << " ("
132  << formatv("{0:x16}", Sym.getAddressable().getAddress()) << " + "
133  << formatv("{0:x}", Sym.getOffset());
134  if (Sym.isDefined())
135  OS << " " << Sym.getBlock().getSection().getName();
136  OS << ")>";
137  return OS;
138 }
139 
140 void printEdge(raw_ostream &OS, const Block &B, const Edge &E,
141  StringRef EdgeKindName) {
142  OS << "edge@" << formatv("{0:x16}", B.getAddress() + E.getOffset()) << ": "
143  << formatv("{0:x16}", B.getAddress()) << " + "
144  << formatv("{0:x}", E.getOffset()) << " -- " << EdgeKindName << " -> ";
145 
146  auto &TargetSym = E.getTarget();
147  if (TargetSym.hasName())
148  OS << TargetSym.getName();
149  else {
150  auto &TargetBlock = TargetSym.getBlock();
151  auto &TargetSec = TargetBlock.getSection();
152  JITTargetAddress SecAddress = ~JITTargetAddress(0);
153  for (auto *B : TargetSec.blocks())
154  if (B->getAddress() < SecAddress)
155  SecAddress = B->getAddress();
156 
157  JITTargetAddress SecDelta = TargetSym.getAddress() - SecAddress;
158  OS << formatv("{0:x16}", TargetSym.getAddress()) << " (section "
159  << TargetSec.getName();
160  if (SecDelta)
161  OS << " + " << formatv("{0:x}", SecDelta);
162  OS << " / block " << formatv("{0:x16}", TargetBlock.getAddress());
163  if (TargetSym.getOffset())
164  OS << " + " << formatv("{0:x}", TargetSym.getOffset());
165  OS << ")";
166  }
167 
168  if (E.getAddend() != 0)
169  OS << " + " << E.getAddend();
170 }
171 
172 Section::~Section() {
173  for (auto *Sym : Symbols)
174  Sym->~Symbol();
175  for (auto *B : Blocks)
176  B->~Block();
177 }
178 
179 Block &LinkGraph::splitBlock(Block &B, size_t SplitIndex,
180  SplitBlockCache *Cache) {
181 
182  assert(SplitIndex > 0 && "splitBlock can not be called with SplitIndex == 0");
183 
184  // If the split point covers all of B then just return B.
185  if (SplitIndex == B.getSize())
186  return B;
187 
188  assert(SplitIndex < B.getSize() && "SplitIndex out of range");
189 
190  // Create the new block covering [ 0, SplitIndex ).
191  auto &NewBlock =
192  B.isZeroFill()
193  ? createZeroFillBlock(B.getSection(), SplitIndex, B.getAddress(),
194  B.getAlignment(), B.getAlignmentOffset())
195  : createContentBlock(
196  B.getSection(), B.getContent().substr(0, SplitIndex),
197  B.getAddress(), B.getAlignment(), B.getAlignmentOffset());
198 
199  // Modify B to cover [ SplitIndex, B.size() ).
200  B.setAddress(B.getAddress() + SplitIndex);
201  B.setContent(B.getContent().substr(SplitIndex));
202  B.setAlignmentOffset((B.getAlignmentOffset() + SplitIndex) %
203  B.getAlignment());
204 
205  // Handle edge transfer/update.
206  {
207  // Copy edges to NewBlock (recording their iterators so that we can remove
208  // them from B), and update of Edges remaining on B.
209  std::vector<Block::edge_iterator> EdgesToRemove;
210  for (auto I = B.edges().begin(); I != B.edges().end();) {
211  if (I->getOffset() < SplitIndex) {
212  NewBlock.addEdge(*I);
213  I = B.removeEdge(I);
214  } else {
215  I->setOffset(I->getOffset() - SplitIndex);
216  ++I;
217  }
218  }
219  }
220 
221  // Handle symbol transfer/update.
222  {
223  // Initialize the symbols cache if necessary.
224  SplitBlockCache LocalBlockSymbolsCache;
225  if (!Cache)
226  Cache = &LocalBlockSymbolsCache;
227  if (*Cache == None) {
228  *Cache = SplitBlockCache::value_type();
229  for (auto *Sym : B.getSection().symbols())
230  if (&Sym->getBlock() == &B)
231  (*Cache)->push_back(Sym);
232 
233  llvm::sort(**Cache, [](const Symbol *LHS, const Symbol *RHS) {
234  return LHS->getOffset() > RHS->getOffset();
235  });
236  }
237  auto &BlockSymbols = **Cache;
238 
239  // Transfer all symbols with offset less than SplitIndex to NewBlock.
240  while (!BlockSymbols.empty() &&
241  BlockSymbols.back()->getOffset() < SplitIndex) {
242  BlockSymbols.back()->setBlock(NewBlock);
243  BlockSymbols.pop_back();
244  }
245 
246  // Update offsets for all remaining symbols in B.
247  for (auto *Sym : BlockSymbols)
248  Sym->setOffset(Sym->getOffset() - SplitIndex);
249  }
250 
251  return NewBlock;
252 }
253 
255  std::function<StringRef(Edge::Kind)> EdgeKindToName) {
256  if (!EdgeKindToName)
257  EdgeKindToName = [](Edge::Kind K) { return StringRef(); };
258 
259  OS << "Symbols:\n";
260  for (auto *Sym : defined_symbols()) {
261  OS << " " << format("0x%016" PRIx64, Sym->getAddress()) << ": " << *Sym
262  << "\n";
263  if (Sym->isDefined()) {
264  for (auto &E : Sym->getBlock().edges()) {
265  OS << " ";
266  StringRef EdgeName = (E.getKind() < Edge::FirstRelocation
267  ? getGenericEdgeKindName(E.getKind())
268  : EdgeKindToName(E.getKind()));
269 
270  if (!EdgeName.empty())
271  printEdge(OS, Sym->getBlock(), E, EdgeName);
272  else {
273  auto EdgeNumberString = std::to_string(E.getKind());
274  printEdge(OS, Sym->getBlock(), E, EdgeNumberString);
275  }
276  OS << "\n";
277  }
278  }
279  }
280 
281  OS << "Absolute symbols:\n";
282  for (auto *Sym : absolute_symbols())
283  OS << " " << format("0x%016" PRIx64, Sym->getAddress()) << ": " << *Sym
284  << "\n";
285 
286  OS << "External symbols:\n";
287  for (auto *Sym : external_symbols())
288  OS << " " << format("0x%016" PRIx64, Sym->getAddress()) << ": " << *Sym
289  << "\n";
290 }
291 
293  switch (LF) {
294  case SymbolLookupFlags::RequiredSymbol:
295  return OS << "RequiredSymbol";
296  case SymbolLookupFlags::WeaklyReferencedSymbol:
297  return OS << "WeaklyReferencedSymbol";
298  }
299  llvm_unreachable("Unrecognized lookup flags");
300 }
301 
302 void JITLinkAsyncLookupContinuation::anchor() {}
303 
304 JITLinkContext::~JITLinkContext() {}
305 
306 bool JITLinkContext::shouldAddDefaultTargetPasses(const Triple &TT) const {
307  return true;
308 }
309 
310 LinkGraphPassFunction JITLinkContext::getMarkLivePass(const Triple &TT) const {
311  return LinkGraphPassFunction();
312 }
313 
314 Error JITLinkContext::modifyPassConfig(const Triple &TT,
315  PassConfiguration &Config) {
316  return Error::success();
317 }
318 
320  for (auto *Sym : G.defined_symbols())
321  Sym->setLive(true);
322  return Error::success();
323 }
324 
327  auto Magic = identify_magic(ObjectBuffer.getBuffer());
328  switch (Magic) {
330  return createLinkGraphFromMachOObject(ObjectBuffer);
332  return createLinkGraphFromELFObject(ObjectBuffer);
333  default:
334  return make_error<JITLinkError>("Unsupported file format");
335  };
336 }
337 
338 void link(std::unique_ptr<LinkGraph> G, std::unique_ptr<JITLinkContext> Ctx) {
339  switch (G->getTargetTriple().getObjectFormat()) {
340  case Triple::MachO:
341  return link_MachO(std::move(G), std::move(Ctx));
342  case Triple::ELF:
343  return link_ELF(std::move(G), std::move(Ctx));
344  default:
345  Ctx->notifyFailed(make_error<JITLinkError>("Unsupported object format"));
346  };
347 }
348 
349 } // end namespace jitlink
350 } // end namespace llvm
MemoryBuffer.h
llvm::Optional::value_type
T value_type
Definition: Optional.h:243
llvm
This class represents lattice values for constants.
Definition: AllocatorList.h:23
llvm::StringRef::empty
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:156
ManagedStatic.h
llvm::Error::success
static ErrorSuccess success()
Create a success value.
Definition: Error.h:332
llvm::Triple
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:45
llvm::cl::Hidden
@ Hidden
Definition: CommandLine.h:140
llvm::Optional
Definition: APInt.h:33
llvm::dump
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
Definition: SparseBitVector.h:876
llvm::Expected
Tagged union holding either a T or a Error.
Definition: APFloat.h:42
Format.h
llvm::MemoryBufferRef
Definition: MemoryBufferRef.h:22
llvm::formatv
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
Definition: FormatVariadic.h:250
llvm::object
Definition: ObjectFileTransformer.h:18
Magic.h
splitBlock
static void splitBlock(MachineBasicBlock &MBB, MachineInstr &MI, MachineDominatorTree *MDT)
Definition: SIInsertSkips.cpp:180
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::ManagedStatic
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:83
B
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:50
llvm::None
const NoneType None
Definition: None.h:23
llvm::file_magic::elf_relocatable
@ elf_relocatable
ELF Relocatable object file.
Definition: Magic.h:26
llvm::object::operator<<
raw_ostream & operator<<(raw_ostream &OS, const SectionedAddress &Addr)
Definition: ObjectFile.cpp:35
G
const DataFlowGraph & G
Definition: RDFGraph.cpp:202
getLinkageName
static std::string getLinkageName(GlobalValue::LinkageTypes LT)
Definition: AsmWriter.cpp:3147
llvm::Triple::ELF
@ ELF
Definition: Triple.h:233
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
I
#define I(x, y, z)
Definition: MD5.cpp:59
Magic
const char Magic[]
Definition: Archive.cpp:41
message
message(STATUS "Targeting ${t}") add_subdirectory($
Definition: CMakeLists.txt:31
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::MemoryBufferRef::getBuffer
StringRef getBuffer() const
Definition: MemoryBufferRef.h:32
function
print Print MemDeps of function
Definition: MemDepPrinter.cpp:83
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:57
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:136
S
add sub stmia L5 ldr r0 bl L_printf $stub Instead of a and a wouldn t it be better to do three moves *Return an aggregate type is even return S
Definition: README.txt:210
llvm::format
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
name
static const char * name
Definition: SVEIntrinsicOpts.cpp:91
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
llvm::Triple::MachO
@ MachO
Definition: Triple.h:235
llvm::sort
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1439
llvm::TargetStackID::Default
@ Default
Definition: TargetFrameLowering.h:28
llvm::JITTargetAddress
uint64_t JITTargetAddress
Represents an address in the target process's address space.
Definition: JITSymbol.h:42
Invalid
@ Invalid
Definition: AArch64ISelLowering.cpp:7682
llvm::to_string
std::string to_string(const T &Value)
Definition: ScopedPrinter.h:62
raw_ostream.h
llvm::identify_magic
file_magic identify_magic(StringRef magic)
Identify the type of a binary file based on how magical it is.
Definition: Magic.cpp:35
error_category
static ManagedStatic< _object_error_category > error_category
Definition: Error.cpp:76
llvm::file_magic::macho_object
@ macho_object
Mach-O Object file.
Definition: Magic.h:30
llvm::Intrinsic::ID
unsigned ID
Definition: TargetTransformInfo.h:37