LLVM 17.0.0git
ELF_riscv.cpp
Go to the documentation of this file.
1//===------- ELF_riscv.cpp -JIT linker implementation for ELF/riscv -------===//
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// ELF/riscv jit-link implementation.
10//
11//===----------------------------------------------------------------------===//
12
14#include "ELFLinkGraphBuilder.h"
15#include "JITLinkGeneric.h"
20#include "llvm/Object/ELF.h"
22#include "llvm/Support/Endian.h"
23
24#define DEBUG_TYPE "jitlink"
25using namespace llvm;
26using namespace llvm::jitlink;
27using namespace llvm::jitlink::riscv;
28
29namespace {
30
31class PerGraphGOTAndPLTStubsBuilder_ELF_riscv
33 PerGraphGOTAndPLTStubsBuilder_ELF_riscv> {
34public:
35 static constexpr size_t StubEntrySize = 16;
36 static const uint8_t NullGOTEntryContent[8];
37 static const uint8_t RV64StubContent[StubEntrySize];
38 static const uint8_t RV32StubContent[StubEntrySize];
39
41 PerGraphGOTAndPLTStubsBuilder_ELF_riscv>::PerGraphGOTAndPLTStubsBuilder;
42
43 bool isRV64() const { return G.getPointerSize() == 8; }
44
45 bool isGOTEdgeToFix(Edge &E) const { return E.getKind() == R_RISCV_GOT_HI20; }
46
47 Symbol &createGOTEntry(Symbol &Target) {
48 Block &GOTBlock =
49 G.createContentBlock(getGOTSection(), getGOTEntryBlockContent(),
50 orc::ExecutorAddr(), G.getPointerSize(), 0);
51 GOTBlock.addEdge(isRV64() ? R_RISCV_64 : R_RISCV_32, 0, Target, 0);
52 return G.addAnonymousSymbol(GOTBlock, 0, G.getPointerSize(), false, false);
53 }
54
55 Symbol &createPLTStub(Symbol &Target) {
56 Block &StubContentBlock = G.createContentBlock(
57 getStubsSection(), getStubBlockContent(), orc::ExecutorAddr(), 4, 0);
58 auto &GOTEntrySymbol = getGOTEntry(Target);
59 StubContentBlock.addEdge(R_RISCV_CALL, 0, GOTEntrySymbol, 0);
60 return G.addAnonymousSymbol(StubContentBlock, 0, StubEntrySize, true,
61 false);
62 }
63
64 void fixGOTEdge(Edge &E, Symbol &GOTEntry) {
65 // Replace the relocation pair (R_RISCV_GOT_HI20, R_RISCV_PCREL_LO12)
66 // with (R_RISCV_PCREL_HI20, R_RISCV_PCREL_LO12)
67 // Therefore, here just change the R_RISCV_GOT_HI20 to R_RISCV_PCREL_HI20
68 E.setKind(R_RISCV_PCREL_HI20);
69 E.setTarget(GOTEntry);
70 }
71
72 void fixPLTEdge(Edge &E, Symbol &PLTStubs) {
73 assert((E.getKind() == R_RISCV_CALL || E.getKind() == R_RISCV_CALL_PLT ||
74 E.getKind() == CallRelaxable) &&
75 "Not a PLT edge?");
76 E.setKind(R_RISCV_CALL);
77 E.setTarget(PLTStubs);
78 }
79
80 bool isExternalBranchEdge(Edge &E) const {
81 return (E.getKind() == R_RISCV_CALL || E.getKind() == R_RISCV_CALL_PLT ||
82 E.getKind() == CallRelaxable) &&
83 !E.getTarget().isDefined();
84 }
85
86private:
87 Section &getGOTSection() const {
88 if (!GOTSection)
89 GOTSection = &G.createSection("$__GOT", orc::MemProt::Read);
90 return *GOTSection;
91 }
92
93 Section &getStubsSection() const {
94 if (!StubsSection)
95 StubsSection =
96 &G.createSection("$__STUBS", orc::MemProt::Read | orc::MemProt::Exec);
97 return *StubsSection;
98 }
99
100 ArrayRef<char> getGOTEntryBlockContent() {
101 return {reinterpret_cast<const char *>(NullGOTEntryContent),
102 G.getPointerSize()};
103 }
104
105 ArrayRef<char> getStubBlockContent() {
106 auto StubContent = isRV64() ? RV64StubContent : RV32StubContent;
107 return {reinterpret_cast<const char *>(StubContent), StubEntrySize};
108 }
109
110 mutable Section *GOTSection = nullptr;
111 mutable Section *StubsSection = nullptr;
112};
113
114const uint8_t PerGraphGOTAndPLTStubsBuilder_ELF_riscv::NullGOTEntryContent[8] =
115 {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
116
117const uint8_t
118 PerGraphGOTAndPLTStubsBuilder_ELF_riscv::RV64StubContent[StubEntrySize] = {
119 0x17, 0x0e, 0x00, 0x00, // auipc t3, literal
120 0x03, 0x3e, 0x0e, 0x00, // ld t3, literal(t3)
121 0x67, 0x00, 0x0e, 0x00, // jr t3
122 0x13, 0x00, 0x00, 0x00}; // nop
123
124const uint8_t
125 PerGraphGOTAndPLTStubsBuilder_ELF_riscv::RV32StubContent[StubEntrySize] = {
126 0x17, 0x0e, 0x00, 0x00, // auipc t3, literal
127 0x03, 0x2e, 0x0e, 0x00, // lw t3, literal(t3)
128 0x67, 0x00, 0x0e, 0x00, // jr t3
129 0x13, 0x00, 0x00, 0x00}; // nop
130} // namespace
131namespace llvm {
132namespace jitlink {
133
135 using namespace riscv;
136 assert((E.getKind() == R_RISCV_PCREL_LO12_I ||
137 E.getKind() == R_RISCV_PCREL_LO12_S) &&
138 "Can only have high relocation for R_RISCV_PCREL_LO12_I or "
139 "R_RISCV_PCREL_LO12_S");
140
141 const Symbol &Sym = E.getTarget();
142 const Block &B = Sym.getBlock();
144
145 struct Comp {
146 bool operator()(const Edge &Lhs, orc::ExecutorAddrDiff Offset) {
147 return Lhs.getOffset() < Offset;
148 }
149 bool operator()(orc::ExecutorAddrDiff Offset, const Edge &Rhs) {
150 return Offset < Rhs.getOffset();
151 }
152 };
153
154 auto Bound =
155 std::equal_range(B.edges().begin(), B.edges().end(), Offset, Comp{});
156
157 for (auto It = Bound.first; It != Bound.second; ++It) {
158 if (It->getKind() == R_RISCV_PCREL_HI20)
159 return *It;
160 }
161
162 return make_error<JITLinkError>(
163 "No HI20 PCREL relocation type be found for LO12 PCREL relocation type");
164}
165
166static uint32_t extractBits(uint32_t Num, unsigned Low, unsigned Size) {
167 return (Num & (((1ULL << Size) - 1) << Low)) >> Low;
168}
169
170static inline bool isAlignmentCorrect(uint64_t Value, int N) {
171 return (Value & (N - 1)) ? false : true;
172}
173
174// Requires 0 < N <= 64.
175static inline bool isInRangeForImm(int64_t Value, int N) {
176 return Value == llvm::SignExtend64(Value, N);
177}
178
179class ELFJITLinker_riscv : public JITLinker<ELFJITLinker_riscv> {
180 friend class JITLinker<ELFJITLinker_riscv>;
181
182public:
183 ELFJITLinker_riscv(std::unique_ptr<JITLinkContext> Ctx,
184 std::unique_ptr<LinkGraph> G, PassConfiguration PassConfig)
185 : JITLinker(std::move(Ctx), std::move(G), std::move(PassConfig)) {}
186
187private:
188 Error applyFixup(LinkGraph &G, Block &B, const Edge &E) const {
189 using namespace riscv;
190 using namespace llvm::support;
191
192 char *BlockWorkingMem = B.getAlreadyMutableContent().data();
193 char *FixupPtr = BlockWorkingMem + E.getOffset();
194 orc::ExecutorAddr FixupAddress = B.getAddress() + E.getOffset();
195 switch (E.getKind()) {
196 case R_RISCV_32: {
197 int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
198 *(little32_t *)FixupPtr = static_cast<uint32_t>(Value);
199 break;
200 }
201 case R_RISCV_64: {
202 int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
203 *(little64_t *)FixupPtr = static_cast<uint64_t>(Value);
204 break;
205 }
206 case R_RISCV_BRANCH: {
207 int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
208 if (LLVM_UNLIKELY(!isInRangeForImm(Value >> 1, 12)))
209 return makeTargetOutOfRangeError(G, B, E);
211 return makeAlignmentError(FixupAddress, Value, 2, E);
212 uint32_t Imm12 = extractBits(Value, 12, 1) << 31;
213 uint32_t Imm10_5 = extractBits(Value, 5, 6) << 25;
214 uint32_t Imm4_1 = extractBits(Value, 1, 4) << 8;
215 uint32_t Imm11 = extractBits(Value, 11, 1) << 7;
216 uint32_t RawInstr = *(little32_t *)FixupPtr;
217 *(little32_t *)FixupPtr =
218 (RawInstr & 0x1FFF07F) | Imm12 | Imm10_5 | Imm4_1 | Imm11;
219 break;
220 }
221 case R_RISCV_JAL: {
222 int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
223 if (LLVM_UNLIKELY(!isInRangeForImm(Value >> 1, 20)))
224 return makeTargetOutOfRangeError(G, B, E);
226 return makeAlignmentError(FixupAddress, Value, 2, E);
227 uint32_t Imm20 = extractBits(Value, 20, 1) << 31;
228 uint32_t Imm10_1 = extractBits(Value, 1, 10) << 21;
229 uint32_t Imm11 = extractBits(Value, 11, 1) << 20;
230 uint32_t Imm19_12 = extractBits(Value, 12, 8) << 12;
231 uint32_t RawInstr = *(little32_t *)FixupPtr;
232 *(little32_t *)FixupPtr =
233 (RawInstr & 0xFFF) | Imm20 | Imm10_1 | Imm11 | Imm19_12;
234 break;
235 }
236 case R_RISCV_CALL_PLT:
237 case R_RISCV_CALL: {
238 int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
239 int64_t Hi = Value + 0x800;
241 return makeTargetOutOfRangeError(G, B, E);
242 int32_t Lo = Value & 0xFFF;
243 uint32_t RawInstrAuipc = *(little32_t *)FixupPtr;
244 uint32_t RawInstrJalr = *(little32_t *)(FixupPtr + 4);
245 *(little32_t *)FixupPtr =
246 RawInstrAuipc | (static_cast<uint32_t>(Hi & 0xFFFFF000));
247 *(little32_t *)(FixupPtr + 4) =
248 RawInstrJalr | (static_cast<uint32_t>(Lo) << 20);
249 break;
250 }
251 // The relocations R_RISCV_CALL_PLT and R_RISCV_GOT_HI20 are handled by
252 // PerGraphGOTAndPLTStubsBuilder_ELF_riscv and are transformed into
253 // R_RISCV_CALL and R_RISCV_PCREL_HI20.
254 case R_RISCV_PCREL_HI20: {
255 int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
256 int64_t Hi = Value + 0x800;
258 return makeTargetOutOfRangeError(G, B, E);
259 uint32_t RawInstr = *(little32_t *)FixupPtr;
260 *(little32_t *)FixupPtr =
261 (RawInstr & 0xFFF) | (static_cast<uint32_t>(Hi & 0xFFFFF000));
262 break;
263 }
265 // FIXME: We assume that R_RISCV_PCREL_HI20 is present in object code and
266 // pairs with current relocation R_RISCV_PCREL_LO12_I. So here may need a
267 // check.
268 auto RelHI20 = getRISCVPCRelHi20(E);
269 if (!RelHI20)
270 return RelHI20.takeError();
271 int64_t Value = RelHI20->getTarget().getAddress() +
272 RelHI20->getAddend() - E.getTarget().getAddress();
273 int64_t Lo = Value & 0xFFF;
274 uint32_t RawInstr = *(little32_t *)FixupPtr;
275 *(little32_t *)FixupPtr =
276 (RawInstr & 0xFFFFF) | (static_cast<uint32_t>(Lo & 0xFFF) << 20);
277 break;
278 }
280 // FIXME: We assume that R_RISCV_PCREL_HI20 is present in object code and
281 // pairs with current relocation R_RISCV_PCREL_LO12_S. So here may need a
282 // check.
283 auto RelHI20 = getRISCVPCRelHi20(E);
284 if (!RelHI20)
285 return RelHI20.takeError();
286 int64_t Value = RelHI20->getTarget().getAddress() +
287 RelHI20->getAddend() - E.getTarget().getAddress();
288 int64_t Lo = Value & 0xFFF;
289 uint32_t Imm11_5 = extractBits(Lo, 5, 7) << 25;
290 uint32_t Imm4_0 = extractBits(Lo, 0, 5) << 7;
291 uint32_t RawInstr = *(little32_t *)FixupPtr;
292
293 *(little32_t *)FixupPtr = (RawInstr & 0x1FFF07F) | Imm11_5 | Imm4_0;
294 break;
295 }
296 case R_RISCV_HI20: {
297 int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
298 int64_t Hi = Value + 0x800;
300 return makeTargetOutOfRangeError(G, B, E);
301 uint32_t RawInstr = *(little32_t *)FixupPtr;
302 *(little32_t *)FixupPtr =
303 (RawInstr & 0xFFF) | (static_cast<uint32_t>(Hi & 0xFFFFF000));
304 break;
305 }
306 case R_RISCV_LO12_I: {
307 // FIXME: We assume that R_RISCV_HI20 is present in object code and pairs
308 // with current relocation R_RISCV_LO12_I. So here may need a check.
309 int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
310 int32_t Lo = Value & 0xFFF;
311 uint32_t RawInstr = *(little32_t *)FixupPtr;
312 *(little32_t *)FixupPtr =
313 (RawInstr & 0xFFFFF) | (static_cast<uint32_t>(Lo & 0xFFF) << 20);
314 break;
315 }
316 case R_RISCV_LO12_S: {
317 // FIXME: We assume that R_RISCV_HI20 is present in object code and pairs
318 // with current relocation R_RISCV_LO12_S. So here may need a check.
319 int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
320 int64_t Lo = Value & 0xFFF;
321 uint32_t Imm11_5 = extractBits(Lo, 5, 7) << 25;
322 uint32_t Imm4_0 = extractBits(Lo, 0, 5) << 7;
323 uint32_t RawInstr = *(little32_t *)FixupPtr;
324 *(little32_t *)FixupPtr = (RawInstr & 0x1FFF07F) | Imm11_5 | Imm4_0;
325 break;
326 }
327 case R_RISCV_ADD8: {
328 int64_t Value =
329 (E.getTarget().getAddress() +
330 *(reinterpret_cast<const uint8_t *>(FixupPtr)) + E.getAddend())
331 .getValue();
332 *FixupPtr = static_cast<uint8_t>(Value);
333 break;
334 }
335 case R_RISCV_ADD16: {
336 int64_t Value = (E.getTarget().getAddress() +
337 support::endian::read16le(FixupPtr) + E.getAddend())
338 .getValue();
339 *(little16_t *)FixupPtr = static_cast<uint16_t>(Value);
340 break;
341 }
342 case R_RISCV_ADD32: {
343 int64_t Value = (E.getTarget().getAddress() +
344 support::endian::read32le(FixupPtr) + E.getAddend())
345 .getValue();
346 *(little32_t *)FixupPtr = static_cast<uint32_t>(Value);
347 break;
348 }
349 case R_RISCV_ADD64: {
350 int64_t Value = (E.getTarget().getAddress() +
351 support::endian::read64le(FixupPtr) + E.getAddend())
352 .getValue();
353 *(little64_t *)FixupPtr = static_cast<uint64_t>(Value);
354 break;
355 }
356 case R_RISCV_SUB8: {
357 int64_t Value = *(reinterpret_cast<const uint8_t *>(FixupPtr)) -
358 E.getTarget().getAddress().getValue() - E.getAddend();
359 *FixupPtr = static_cast<uint8_t>(Value);
360 break;
361 }
362 case R_RISCV_SUB16: {
363 int64_t Value = support::endian::read16le(FixupPtr) -
364 E.getTarget().getAddress().getValue() - E.getAddend();
365 *(little16_t *)FixupPtr = static_cast<uint32_t>(Value);
366 break;
367 }
368 case R_RISCV_SUB32: {
369 int64_t Value = support::endian::read32le(FixupPtr) -
370 E.getTarget().getAddress().getValue() - E.getAddend();
371 *(little32_t *)FixupPtr = static_cast<uint32_t>(Value);
372 break;
373 }
374 case R_RISCV_SUB64: {
375 int64_t Value = support::endian::read64le(FixupPtr) -
376 E.getTarget().getAddress().getValue() - E.getAddend();
377 *(little64_t *)FixupPtr = static_cast<uint64_t>(Value);
378 break;
379 }
380 case R_RISCV_RVC_BRANCH: {
381 int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
382 if (LLVM_UNLIKELY(!isInRangeForImm(Value >> 1, 8)))
383 return makeTargetOutOfRangeError(G, B, E);
385 return makeAlignmentError(FixupAddress, Value, 2, E);
386 uint16_t Imm8 = extractBits(Value, 8, 1) << 12;
387 uint16_t Imm4_3 = extractBits(Value, 3, 2) << 10;
388 uint16_t Imm7_6 = extractBits(Value, 6, 2) << 5;
389 uint16_t Imm2_1 = extractBits(Value, 1, 2) << 3;
390 uint16_t Imm5 = extractBits(Value, 5, 1) << 2;
391 uint16_t RawInstr = *(little16_t *)FixupPtr;
392 *(little16_t *)FixupPtr =
393 (RawInstr & 0xE383) | Imm8 | Imm4_3 | Imm7_6 | Imm2_1 | Imm5;
394 break;
395 }
396 case R_RISCV_RVC_JUMP: {
397 int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
398 if (LLVM_UNLIKELY(!isInRangeForImm(Value >> 1, 11)))
399 return makeTargetOutOfRangeError(G, B, E);
401 return makeAlignmentError(FixupAddress, Value, 2, E);
402 uint16_t Imm11 = extractBits(Value, 11, 1) << 12;
403 uint16_t Imm4 = extractBits(Value, 4, 1) << 11;
404 uint16_t Imm9_8 = extractBits(Value, 8, 2) << 9;
405 uint16_t Imm10 = extractBits(Value, 10, 1) << 8;
406 uint16_t Imm6 = extractBits(Value, 6, 1) << 7;
407 uint16_t Imm7 = extractBits(Value, 7, 1) << 6;
408 uint16_t Imm3_1 = extractBits(Value, 1, 3) << 3;
409 uint16_t Imm5 = extractBits(Value, 5, 1) << 2;
410 uint16_t RawInstr = *(little16_t *)FixupPtr;
411 *(little16_t *)FixupPtr = (RawInstr & 0xE003) | Imm11 | Imm4 | Imm9_8 |
412 Imm10 | Imm6 | Imm7 | Imm3_1 | Imm5;
413 break;
414 }
415 case R_RISCV_SUB6: {
416 int64_t Value = *(reinterpret_cast<const uint8_t *>(FixupPtr)) & 0x3f;
417 Value -= E.getTarget().getAddress().getValue() - E.getAddend();
418 *FixupPtr = (*FixupPtr & 0xc0) | (static_cast<uint8_t>(Value) & 0x3f);
419 break;
420 }
421 case R_RISCV_SET6: {
422 int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
423 uint32_t RawData = *(little32_t *)FixupPtr;
424 int64_t Word6 = Value & 0x3f;
425 *(little32_t *)FixupPtr = (RawData & 0xffffffc0) | Word6;
426 break;
427 }
428 case R_RISCV_SET8: {
429 int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
430 uint32_t RawData = *(little32_t *)FixupPtr;
431 int64_t Word8 = Value & 0xff;
432 *(little32_t *)FixupPtr = (RawData & 0xffffff00) | Word8;
433 break;
434 }
435 case R_RISCV_SET16: {
436 int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
437 uint32_t RawData = *(little32_t *)FixupPtr;
438 int64_t Word16 = Value & 0xffff;
439 *(little32_t *)FixupPtr = (RawData & 0xffff0000) | Word16;
440 break;
441 }
442 case R_RISCV_SET32: {
443 int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
444 int64_t Word32 = Value & 0xffffffff;
445 *(little32_t *)FixupPtr = Word32;
446 break;
447 }
448 case R_RISCV_32_PCREL: {
449 int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
450 int64_t Word32 = Value & 0xffffffff;
451 *(little32_t *)FixupPtr = Word32;
452 break;
453 }
454 }
455 return Error::success();
456 }
457};
458
459namespace {
460
461struct SymbolAnchor {
464 bool End; // true for the anchor of getOffset() + getSize()
465};
466
467struct BlockRelaxAux {
468 // This records symbol start and end offsets which will be adjusted according
469 // to the nearest RelocDeltas element.
471 // All edges that either 1) are R_RISCV_ALIGN or 2) have a R_RISCV_RELAX edge
472 // at the same offset.
474 // For RelaxEdges[I], the actual offset is RelaxEdges[I]->getOffset() - (I ?
475 // RelocDeltas[I - 1] : 0).
477 // For RelaxEdges[I], the actual type is EdgeKinds[I].
479 // List of rewritten instructions. Contains one raw encoded instruction per
480 // element in EdgeKinds that isn't Invalid or R_RISCV_ALIGN.
482};
483
484struct RelaxConfig {
485 bool IsRV32;
486 bool HasRVC;
487};
488
489struct RelaxAux {
490 RelaxConfig Config;
492};
493
494} // namespace
495
496static bool shouldRelax(const Section &S) {
498}
499
500static bool isRelaxable(const Edge &E) {
501 switch (E.getKind()) {
502 default:
503 return false;
504 case CallRelaxable:
505 case AlignRelaxable:
506 return true;
507 }
508}
509
510static RelaxAux initRelaxAux(LinkGraph &G) {
511 RelaxAux Aux;
512 Aux.Config.IsRV32 = G.getTargetTriple().isRISCV32();
513 const auto &Features = G.getFeatures();
514 Aux.Config.HasRVC =
515 std::find(Features.begin(), Features.end(), "+c") != Features.end();
516
517 for (auto &S : G.sections()) {
518 if (!shouldRelax(S))
519 continue;
520 for (auto *B : S.blocks()) {
521 auto BlockEmplaceResult = Aux.Blocks.try_emplace(B);
522 assert(BlockEmplaceResult.second && "Block encountered twice");
523 auto &BlockAux = BlockEmplaceResult.first->second;
524
525 for (auto &E : B->edges())
526 if (isRelaxable(E))
527 BlockAux.RelaxEdges.push_back(&E);
528
529 if (BlockAux.RelaxEdges.empty()) {
530 Aux.Blocks.erase(BlockEmplaceResult.first);
531 continue;
532 }
533
534 const auto NumEdges = BlockAux.RelaxEdges.size();
535 BlockAux.RelocDeltas.resize(NumEdges, 0);
536 BlockAux.EdgeKinds.resize_for_overwrite(NumEdges);
537
538 // Store anchors (offset and offset+size) for symbols.
539 for (auto *Sym : S.symbols()) {
540 if (!Sym->isDefined() || &Sym->getBlock() != B)
541 continue;
542
543 BlockAux.Anchors.push_back({Sym->getOffset(), Sym, false});
544 BlockAux.Anchors.push_back(
545 {Sym->getOffset() + Sym->getSize(), Sym, true});
546 }
547 }
548 }
549
550 // Sort anchors by offset so that we can find the closest relocation
551 // efficiently. For a zero size symbol, ensure that its start anchor precedes
552 // its end anchor. For two symbols with anchors at the same offset, their
553 // order does not matter.
554 for (auto &BlockAuxIter : Aux.Blocks) {
555 llvm::sort(BlockAuxIter.second.Anchors, [](auto &A, auto &B) {
556 return std::make_pair(A.Offset, A.End) < std::make_pair(B.Offset, B.End);
557 });
558 }
559
560 return Aux;
561}
562
563static void relaxAlign(orc::ExecutorAddr Loc, const Edge &E, uint32_t &Remove,
564 Edge::Kind &NewEdgeKind) {
565 // E points to the start of the padding bytes.
566 // E + Addend points to the instruction to be aligned by removing padding.
567 // Alignment is the smallest power of 2 strictly greater than Addend.
568 const auto Align = NextPowerOf2(E.getAddend());
569 const auto DestLoc = alignTo(Loc.getValue(), Align);
570 const auto SrcLoc = Loc.getValue() + E.getAddend();
571 Remove = SrcLoc - DestLoc;
572 assert(static_cast<int32_t>(Remove) >= 0 &&
573 "R_RISCV_ALIGN needs expanding the content");
574 NewEdgeKind = AlignRelaxable;
575}
576
577static void relaxCall(const Block &B, BlockRelaxAux &Aux,
578 const RelaxConfig &Config, orc::ExecutorAddr Loc,
579 const Edge &E, uint32_t &Remove,
580 Edge::Kind &NewEdgeKind) {
581 const auto JALR =
582 support::endian::read32le(B.getContent().data() + E.getOffset() + 4);
583 const auto RD = extractBits(JALR, 7, 5);
584 const auto Dest = E.getTarget().getAddress() + E.getAddend();
585 const auto Displace = Dest - Loc;
586
587 if (Config.HasRVC && isInt<12>(Displace) && RD == 0) {
588 NewEdgeKind = R_RISCV_RVC_JUMP;
589 Aux.Writes.push_back(0xa001); // c.j
590 Remove = 6;
591 } else if (Config.HasRVC && Config.IsRV32 && isInt<12>(Displace) && RD == 1) {
592 NewEdgeKind = R_RISCV_RVC_JUMP;
593 Aux.Writes.push_back(0x2001); // c.jal
594 Remove = 6;
595 } else if (isInt<21>(Displace)) {
596 NewEdgeKind = R_RISCV_JAL;
597 Aux.Writes.push_back(0x6f | RD << 7); // jal
598 Remove = 4;
599 } else {
600 // Not relaxable
601 NewEdgeKind = R_RISCV_CALL_PLT;
602 Remove = 0;
603 }
604}
605
606static bool relaxBlock(LinkGraph &G, Block &Block, BlockRelaxAux &Aux,
607 const RelaxConfig &Config) {
608 const auto BlockAddr = Block.getAddress();
609 bool Changed = false;
610 ArrayRef<SymbolAnchor> SA = ArrayRef(Aux.Anchors);
611 uint32_t Delta = 0;
612
613 Aux.EdgeKinds.assign(Aux.EdgeKinds.size(), Edge::Invalid);
614 Aux.Writes.clear();
615
616 for (auto [I, E] : llvm::enumerate(Aux.RelaxEdges)) {
617 const auto Loc = BlockAddr + E->getOffset() - Delta;
618 auto &Cur = Aux.RelocDeltas[I];
619 uint32_t Remove = 0;
620 switch (E->getKind()) {
621 case AlignRelaxable:
622 relaxAlign(Loc, *E, Remove, Aux.EdgeKinds[I]);
623 break;
624 case CallRelaxable:
625 relaxCall(Block, Aux, Config, Loc, *E, Remove, Aux.EdgeKinds[I]);
626 break;
627 default:
628 llvm_unreachable("Unexpected relaxable edge kind");
629 }
630
631 // For all anchors whose offsets are <= E->getOffset(), they are preceded by
632 // the previous relocation whose RelocDeltas value equals Delta.
633 // Decrease their offset and update their size.
634 for (; SA.size() && SA[0].Offset <= E->getOffset(); SA = SA.slice(1)) {
635 if (SA[0].End)
636 SA[0].Sym->setSize(SA[0].Offset - Delta - SA[0].Sym->getOffset());
637 else
638 SA[0].Sym->setOffset(SA[0].Offset - Delta);
639 }
640
641 Delta += Remove;
642 if (Delta != Cur) {
643 Cur = Delta;
644 Changed = true;
645 }
646 }
647
648 for (const SymbolAnchor &A : SA) {
649 if (A.End)
650 A.Sym->setSize(A.Offset - Delta - A.Sym->getOffset());
651 else
652 A.Sym->setOffset(A.Offset - Delta);
653 }
654
655 return Changed;
656}
657
658static bool relaxOnce(LinkGraph &G, RelaxAux &Aux) {
659 bool Changed = false;
660
661 for (auto &[B, BlockAux] : Aux.Blocks)
662 Changed |= relaxBlock(G, *B, BlockAux, Aux.Config);
663
664 return Changed;
665}
666
667static void finalizeBlockRelax(LinkGraph &G, Block &Block, BlockRelaxAux &Aux) {
668 auto Contents = Block.getAlreadyMutableContent();
669 auto *Dest = Contents.data();
670 auto NextWrite = Aux.Writes.begin();
671 uint32_t Offset = 0;
672 uint32_t Delta = 0;
673
674 // Update section content: remove NOPs for R_RISCV_ALIGN and rewrite
675 // instructions for relaxed relocations.
676 for (auto [I, E] : llvm::enumerate(Aux.RelaxEdges)) {
677 uint32_t Remove = Aux.RelocDeltas[I] - Delta;
678 Delta = Aux.RelocDeltas[I];
679 if (Remove == 0 && Aux.EdgeKinds[I] == Edge::Invalid)
680 continue;
681
682 // Copy from last location to the current relocated location.
683 const auto Size = E->getOffset() - Offset;
684 std::memmove(Dest, Contents.data() + Offset, Size);
685 Dest += Size;
686
687 uint32_t Skip = 0;
688 switch (Aux.EdgeKinds[I]) {
689 case Edge::Invalid:
690 break;
691 case AlignRelaxable:
692 // For R_RISCV_ALIGN, we will place Offset in a location (among NOPs) to
693 // satisfy the alignment requirement. If both Remove and E->getAddend()
694 // are multiples of 4, it is as if we have skipped some NOPs. Otherwise we
695 // are in the middle of a 4-byte NOP, and we need to rewrite the NOP
696 // sequence.
697 if (Remove % 4 || E->getAddend() % 4) {
698 Skip = E->getAddend() - Remove;
699 uint32_t J = 0;
700 for (; J + 4 <= Skip; J += 4)
701 support::endian::write32le(Dest + J, 0x00000013); // nop
702 if (J != Skip) {
703 assert(J + 2 == Skip);
704 support::endian::write16le(Dest + J, 0x0001); // c.nop
705 }
706 }
707 break;
708 case R_RISCV_RVC_JUMP:
709 Skip = 2;
710 support::endian::write16le(Dest, *NextWrite++);
711 break;
712 case R_RISCV_JAL:
713 Skip = 4;
714 support::endian::write32le(Dest, *NextWrite++);
715 break;
716 }
717
718 Dest += Skip;
719 Offset = E->getOffset() + Skip + Remove;
720 }
721
722 std::memmove(Dest, Contents.data() + Offset, Contents.size() - Offset);
723
724 // Fixup edge offsets and kinds.
725 Delta = 0;
726 for (auto [I, E] : llvm::enumerate(Aux.RelaxEdges)) {
727 E->setOffset(E->getOffset() - Delta);
728
729 if (Aux.EdgeKinds[I] != Edge::Invalid)
730 E->setKind(Aux.EdgeKinds[I]);
731
732 Delta = Aux.RelocDeltas[I];
733 }
734
735 // Remove AlignRelaxable edges: all other relaxable edges got modified and
736 // will be used later while linking. Alignment is entirely handled here so we
737 // don't need these edges anymore.
738 for (auto *B : G.blocks()) {
739 for (auto IE = B->edges().begin(); IE != B->edges().end();) {
740 if (IE->getKind() == AlignRelaxable)
741 IE = B->removeEdge(IE);
742 else
743 ++IE;
744 }
745 }
746}
747
748static void finalizeRelax(LinkGraph &G, RelaxAux &Aux) {
749 for (auto &[B, BlockAux] : Aux.Blocks)
750 finalizeBlockRelax(G, *B, BlockAux);
751}
752
754 auto Aux = initRelaxAux(G);
755 while (relaxOnce(G, Aux)) {
756 }
757 finalizeRelax(G, Aux);
758 return Error::success();
759}
760
761template <typename ELFT>
763private:
765 getRelocationKind(const uint32_t Type) {
766 using namespace riscv;
767 switch (Type) {
768 case ELF::R_RISCV_32:
769 return EdgeKind_riscv::R_RISCV_32;
770 case ELF::R_RISCV_64:
771 return EdgeKind_riscv::R_RISCV_64;
772 case ELF::R_RISCV_BRANCH:
773 return EdgeKind_riscv::R_RISCV_BRANCH;
774 case ELF::R_RISCV_JAL:
775 return EdgeKind_riscv::R_RISCV_JAL;
776 case ELF::R_RISCV_CALL:
777 return EdgeKind_riscv::R_RISCV_CALL;
778 case ELF::R_RISCV_CALL_PLT:
779 return EdgeKind_riscv::R_RISCV_CALL_PLT;
780 case ELF::R_RISCV_GOT_HI20:
781 return EdgeKind_riscv::R_RISCV_GOT_HI20;
782 case ELF::R_RISCV_PCREL_HI20:
783 return EdgeKind_riscv::R_RISCV_PCREL_HI20;
784 case ELF::R_RISCV_PCREL_LO12_I:
785 return EdgeKind_riscv::R_RISCV_PCREL_LO12_I;
786 case ELF::R_RISCV_PCREL_LO12_S:
787 return EdgeKind_riscv::R_RISCV_PCREL_LO12_S;
788 case ELF::R_RISCV_HI20:
789 return EdgeKind_riscv::R_RISCV_HI20;
790 case ELF::R_RISCV_LO12_I:
791 return EdgeKind_riscv::R_RISCV_LO12_I;
792 case ELF::R_RISCV_LO12_S:
793 return EdgeKind_riscv::R_RISCV_LO12_S;
794 case ELF::R_RISCV_ADD8:
795 return EdgeKind_riscv::R_RISCV_ADD8;
796 case ELF::R_RISCV_ADD16:
797 return EdgeKind_riscv::R_RISCV_ADD16;
798 case ELF::R_RISCV_ADD32:
799 return EdgeKind_riscv::R_RISCV_ADD32;
800 case ELF::R_RISCV_ADD64:
801 return EdgeKind_riscv::R_RISCV_ADD64;
802 case ELF::R_RISCV_SUB8:
803 return EdgeKind_riscv::R_RISCV_SUB8;
804 case ELF::R_RISCV_SUB16:
805 return EdgeKind_riscv::R_RISCV_SUB16;
806 case ELF::R_RISCV_SUB32:
807 return EdgeKind_riscv::R_RISCV_SUB32;
808 case ELF::R_RISCV_SUB64:
809 return EdgeKind_riscv::R_RISCV_SUB64;
810 case ELF::R_RISCV_RVC_BRANCH:
811 return EdgeKind_riscv::R_RISCV_RVC_BRANCH;
812 case ELF::R_RISCV_RVC_JUMP:
813 return EdgeKind_riscv::R_RISCV_RVC_JUMP;
814 case ELF::R_RISCV_SUB6:
815 return EdgeKind_riscv::R_RISCV_SUB6;
816 case ELF::R_RISCV_SET6:
817 return EdgeKind_riscv::R_RISCV_SET6;
818 case ELF::R_RISCV_SET8:
819 return EdgeKind_riscv::R_RISCV_SET8;
820 case ELF::R_RISCV_SET16:
821 return EdgeKind_riscv::R_RISCV_SET16;
822 case ELF::R_RISCV_SET32:
823 return EdgeKind_riscv::R_RISCV_SET32;
824 case ELF::R_RISCV_32_PCREL:
825 return EdgeKind_riscv::R_RISCV_32_PCREL;
826 case ELF::R_RISCV_ALIGN:
827 return EdgeKind_riscv::AlignRelaxable;
828 }
829
830 return make_error<JITLinkError>(
831 "Unsupported riscv relocation:" + formatv("{0:d}: ", Type) +
833 }
834
835 EdgeKind_riscv getRelaxableRelocationKind(EdgeKind_riscv Kind) {
836 switch (Kind) {
837 default:
838 // Just ignore unsupported relaxations
839 return Kind;
840 case R_RISCV_CALL:
841 case R_RISCV_CALL_PLT:
842 return CallRelaxable;
843 }
844 }
845
846 Error addRelocations() override {
847 LLVM_DEBUG(dbgs() << "Processing relocations:\n");
848
851 for (const auto &RelSect : Base::Sections)
852 if (Error Err = Base::forEachRelaRelocation(RelSect, this,
853 &Self::addSingleRelocation))
854 return Err;
855
856 return Error::success();
857 }
858
859 Error addSingleRelocation(const typename ELFT::Rela &Rel,
860 const typename ELFT::Shdr &FixupSect,
861 Block &BlockToFix) {
863
864 uint32_t Type = Rel.getType(false);
865 int64_t Addend = Rel.r_addend;
866
867 if (Type == ELF::R_RISCV_RELAX) {
868 if (BlockToFix.edges_empty())
869 return make_error<StringError>(
870 "R_RISCV_RELAX without preceding relocation",
872
873 auto &PrevEdge = *std::prev(BlockToFix.edges().end());
874 auto Kind = static_cast<EdgeKind_riscv>(PrevEdge.getKind());
875 PrevEdge.setKind(getRelaxableRelocationKind(Kind));
876 return Error::success();
877 }
878
879 Expected<riscv::EdgeKind_riscv> Kind = getRelocationKind(Type);
880 if (!Kind)
881 return Kind.takeError();
882
883 uint32_t SymbolIndex = Rel.getSymbol(false);
884 auto ObjSymbol = Base::Obj.getRelocationSymbol(Rel, Base::SymTabSec);
885 if (!ObjSymbol)
886 return ObjSymbol.takeError();
887
888 Symbol *GraphSymbol = Base::getGraphSymbol(SymbolIndex);
889 if (!GraphSymbol)
890 return make_error<StringError>(
891 formatv("Could not find symbol at given index, did you add it to "
892 "JITSymbolTable? index: {0}, shndx: {1} Size of table: {2}",
893 SymbolIndex, (*ObjSymbol)->st_shndx,
894 Base::GraphSymbols.size()),
896
897 auto FixupAddress = orc::ExecutorAddr(FixupSect.sh_addr) + Rel.r_offset;
898 Edge::OffsetT Offset = FixupAddress - BlockToFix.getAddress();
899 Edge GE(*Kind, Offset, *GraphSymbol, Addend);
900 LLVM_DEBUG({
901 dbgs() << " ";
902 printEdge(dbgs(), BlockToFix, GE, riscv::getEdgeKindName(*Kind));
903 dbgs() << "\n";
904 });
905
906 BlockToFix.addEdge(std::move(GE));
907 return Error::success();
908 }
909
910public:
914 : ELFLinkGraphBuilder<ELFT>(Obj, std::move(TT), std::move(Features),
915 FileName, riscv::getEdgeKindName) {}
916};
917
920 LLVM_DEBUG({
921 dbgs() << "Building jitlink graph for new input "
922 << ObjectBuffer.getBufferIdentifier() << "...\n";
923 });
924
925 auto ELFObj = object::ObjectFile::createELFObjectFile(ObjectBuffer);
926 if (!ELFObj)
927 return ELFObj.takeError();
928
929 auto Features = (*ELFObj)->getFeatures();
930 if (!Features)
931 return Features.takeError();
932
933 if ((*ELFObj)->getArch() == Triple::riscv64) {
934 auto &ELFObjFile = cast<object::ELFObjectFile<object::ELF64LE>>(**ELFObj);
936 (*ELFObj)->getFileName(), ELFObjFile.getELFFile(),
937 (*ELFObj)->makeTriple(), Features->getFeatures())
938 .buildGraph();
939 } else {
940 assert((*ELFObj)->getArch() == Triple::riscv32 &&
941 "Invalid triple for RISCV ELF object file");
942 auto &ELFObjFile = cast<object::ELFObjectFile<object::ELF32LE>>(**ELFObj);
944 (*ELFObj)->getFileName(), ELFObjFile.getELFFile(),
945 (*ELFObj)->makeTriple(), Features->getFeatures())
946 .buildGraph();
947 }
948}
949
950void link_ELF_riscv(std::unique_ptr<LinkGraph> G,
951 std::unique_ptr<JITLinkContext> Ctx) {
953 const Triple &TT = G->getTargetTriple();
954 if (Ctx->shouldAddDefaultTargetPasses(TT)) {
955 if (auto MarkLive = Ctx->getMarkLivePass(TT))
956 Config.PrePrunePasses.push_back(std::move(MarkLive));
957 else
958 Config.PrePrunePasses.push_back(markAllSymbolsLive);
959 Config.PostPrunePasses.push_back(
960 PerGraphGOTAndPLTStubsBuilder_ELF_riscv::asPass);
961 Config.PreFixupPasses.push_back(relax);
962 }
963 if (auto Err = Ctx->modifyPassConfig(*G, Config))
964 return Ctx->notifyFailed(std::move(Err));
965
966 ELFJITLinker_riscv::link(std::move(Ctx), std::move(G), std::move(Config));
967}
968
969} // namespace jitlink
970} // namespace llvm
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition: Compiler.h:210
#define LLVM_DEBUG(X)
Definition: Debug.h:101
uint64_t Size
bool End
Definition: ELF_riscv.cpp:464
RelaxConfig Config
Definition: ELF_riscv.cpp:490
DenseMap< Block *, BlockRelaxAux > Blocks
Definition: ELF_riscv.cpp:491
SmallVector< uint32_t, 0 > Writes
Definition: ELF_riscv.cpp:481
SmallVector< uint32_t, 0 > RelocDeltas
Definition: ELF_riscv.cpp:476
SmallVector< Edge *, 0 > RelaxEdges
Definition: ELF_riscv.cpp:473
Symbol * Sym
Definition: ELF_riscv.cpp:463
SmallVector< Edge::Kind, 0 > EdgeKinds
Definition: ELF_riscv.cpp:478
SmallVector< SymbolAnchor, 0 > Anchors
Definition: ELF_riscv.cpp:470
bool HasRVC
Definition: ELF_riscv.cpp:486
bool IsRV32
Definition: ELF_riscv.cpp:485
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:163
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition: ArrayRef.h:193
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
static ErrorSuccess success()
Create a success value.
Definition: Error.h:330
Tagged union holding either a T or a Error.
Definition: Error.h:470
StringRef getBufferIdentifier() const
T * data() const
Definition: ArrayRef.h:352
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
static Expected< std::unique_ptr< ObjectFile > > createELFObjectFile(MemoryBufferRef Object, bool InitContent=true)
Represents an address in the executor process.
uint64_t getValue() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ EM_RISCV
Definition: ELF.h:317
StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type)
Definition: ELF.cpp:22
uint64_t read64le(const void *P)
Definition: Endian.h:382
uint16_t read16le(const void *P)
Definition: Endian.h:380
void write32le(void *P, uint32_t V)
Definition: Endian.h:416
void write16le(void *P, uint16_t V)
Definition: Endian.h:415
uint32_t read32le(const void *P)
Definition: Endian.h:381
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
@ Offset
Definition: DWP.cpp:440
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are are tuples (A,...
Definition: STLExtras.h:2430
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:79
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1744
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1946
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition: MathExtras.h:518
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition: MathExtras.h:418
Definition: BitVector.h:858
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39