xref: /freebsd-src/contrib/llvm-project/llvm/lib/ExecutionEngine/JITLink/ELF_riscv.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
1fe6060f1SDimitry Andric //===------- ELF_riscv.cpp -JIT linker implementation for ELF/riscv -------===//
2fe6060f1SDimitry Andric //
3fe6060f1SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4fe6060f1SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5fe6060f1SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6fe6060f1SDimitry Andric //
7fe6060f1SDimitry Andric //===----------------------------------------------------------------------===//
8fe6060f1SDimitry Andric //
9fe6060f1SDimitry Andric // ELF/riscv jit-link implementation.
10fe6060f1SDimitry Andric //
11fe6060f1SDimitry Andric //===----------------------------------------------------------------------===//
12fe6060f1SDimitry Andric 
13fe6060f1SDimitry Andric #include "llvm/ExecutionEngine/JITLink/ELF_riscv.h"
14349cc55cSDimitry Andric #include "ELFLinkGraphBuilder.h"
15349cc55cSDimitry Andric #include "JITLinkGeneric.h"
16349cc55cSDimitry Andric #include "PerGraphGOTAndPLTStubsBuilder.h"
17349cc55cSDimitry Andric #include "llvm/BinaryFormat/ELF.h"
18fe6060f1SDimitry Andric #include "llvm/ExecutionEngine/JITLink/JITLink.h"
19fe6060f1SDimitry Andric #include "llvm/ExecutionEngine/JITLink/riscv.h"
20fe6060f1SDimitry Andric #include "llvm/Object/ELF.h"
21fe6060f1SDimitry Andric #include "llvm/Object/ELFObjectFile.h"
2204eeddc0SDimitry Andric #include "llvm/Support/Endian.h"
23fe6060f1SDimitry Andric 
24fe6060f1SDimitry Andric #define DEBUG_TYPE "jitlink"
25fe6060f1SDimitry Andric using namespace llvm;
26349cc55cSDimitry Andric using namespace llvm::jitlink;
27349cc55cSDimitry Andric using namespace llvm::jitlink::riscv;
28fe6060f1SDimitry Andric 
29349cc55cSDimitry Andric namespace {
30349cc55cSDimitry Andric 
31349cc55cSDimitry Andric class PerGraphGOTAndPLTStubsBuilder_ELF_riscv
32349cc55cSDimitry Andric     : public PerGraphGOTAndPLTStubsBuilder<
33349cc55cSDimitry Andric           PerGraphGOTAndPLTStubsBuilder_ELF_riscv> {
34349cc55cSDimitry Andric public:
35349cc55cSDimitry Andric   static constexpr size_t StubEntrySize = 16;
36349cc55cSDimitry Andric   static const uint8_t NullGOTEntryContent[8];
37349cc55cSDimitry Andric   static const uint8_t RV64StubContent[StubEntrySize];
38349cc55cSDimitry Andric   static const uint8_t RV32StubContent[StubEntrySize];
39349cc55cSDimitry Andric 
40349cc55cSDimitry Andric   using PerGraphGOTAndPLTStubsBuilder<
41349cc55cSDimitry Andric       PerGraphGOTAndPLTStubsBuilder_ELF_riscv>::PerGraphGOTAndPLTStubsBuilder;
42349cc55cSDimitry Andric 
43349cc55cSDimitry Andric   bool isRV64() const { return G.getPointerSize() == 8; }
44349cc55cSDimitry Andric 
45349cc55cSDimitry Andric   bool isGOTEdgeToFix(Edge &E) const { return E.getKind() == R_RISCV_GOT_HI20; }
46349cc55cSDimitry Andric 
47349cc55cSDimitry Andric   Symbol &createGOTEntry(Symbol &Target) {
4804eeddc0SDimitry Andric     Block &GOTBlock =
4904eeddc0SDimitry Andric         G.createContentBlock(getGOTSection(), getGOTEntryBlockContent(),
5004eeddc0SDimitry Andric                              orc::ExecutorAddr(), G.getPointerSize(), 0);
51349cc55cSDimitry Andric     GOTBlock.addEdge(isRV64() ? R_RISCV_64 : R_RISCV_32, 0, Target, 0);
52349cc55cSDimitry Andric     return G.addAnonymousSymbol(GOTBlock, 0, G.getPointerSize(), false, false);
53349cc55cSDimitry Andric   }
54349cc55cSDimitry Andric 
55349cc55cSDimitry Andric   Symbol &createPLTStub(Symbol &Target) {
5604eeddc0SDimitry Andric     Block &StubContentBlock = G.createContentBlock(
5704eeddc0SDimitry Andric         getStubsSection(), getStubBlockContent(), orc::ExecutorAddr(), 4, 0);
58349cc55cSDimitry Andric     auto &GOTEntrySymbol = getGOTEntry(Target);
59349cc55cSDimitry Andric     StubContentBlock.addEdge(R_RISCV_CALL, 0, GOTEntrySymbol, 0);
60349cc55cSDimitry Andric     return G.addAnonymousSymbol(StubContentBlock, 0, StubEntrySize, true,
61349cc55cSDimitry Andric                                 false);
62349cc55cSDimitry Andric   }
63349cc55cSDimitry Andric 
64349cc55cSDimitry Andric   void fixGOTEdge(Edge &E, Symbol &GOTEntry) {
65349cc55cSDimitry Andric     // Replace the relocation pair (R_RISCV_GOT_HI20, R_RISCV_PCREL_LO12)
66349cc55cSDimitry Andric     // with (R_RISCV_PCREL_HI20, R_RISCV_PCREL_LO12)
67349cc55cSDimitry Andric     // Therefore, here just change the R_RISCV_GOT_HI20 to R_RISCV_PCREL_HI20
68349cc55cSDimitry Andric     E.setKind(R_RISCV_PCREL_HI20);
69349cc55cSDimitry Andric     E.setTarget(GOTEntry);
70349cc55cSDimitry Andric   }
71349cc55cSDimitry Andric 
72349cc55cSDimitry Andric   void fixPLTEdge(Edge &E, Symbol &PLTStubs) {
73349cc55cSDimitry Andric     assert(E.getKind() == R_RISCV_CALL_PLT && "Not a R_RISCV_CALL_PLT edge?");
74349cc55cSDimitry Andric     E.setKind(R_RISCV_CALL);
75349cc55cSDimitry Andric     E.setTarget(PLTStubs);
76349cc55cSDimitry Andric   }
77349cc55cSDimitry Andric 
78349cc55cSDimitry Andric   bool isExternalBranchEdge(Edge &E) const {
79349cc55cSDimitry Andric     return E.getKind() == R_RISCV_CALL_PLT;
80349cc55cSDimitry Andric   }
81349cc55cSDimitry Andric 
82349cc55cSDimitry Andric private:
83349cc55cSDimitry Andric   Section &getGOTSection() const {
84349cc55cSDimitry Andric     if (!GOTSection)
85349cc55cSDimitry Andric       GOTSection = &G.createSection("$__GOT", MemProt::Read);
86349cc55cSDimitry Andric     return *GOTSection;
87349cc55cSDimitry Andric   }
88349cc55cSDimitry Andric 
89349cc55cSDimitry Andric   Section &getStubsSection() const {
90349cc55cSDimitry Andric     if (!StubsSection)
91349cc55cSDimitry Andric       StubsSection =
92349cc55cSDimitry Andric           &G.createSection("$__STUBS", MemProt::Read | MemProt::Exec);
93349cc55cSDimitry Andric     return *StubsSection;
94349cc55cSDimitry Andric   }
95349cc55cSDimitry Andric 
96349cc55cSDimitry Andric   ArrayRef<char> getGOTEntryBlockContent() {
97349cc55cSDimitry Andric     return {reinterpret_cast<const char *>(NullGOTEntryContent),
98349cc55cSDimitry Andric             G.getPointerSize()};
99349cc55cSDimitry Andric   }
100349cc55cSDimitry Andric 
101349cc55cSDimitry Andric   ArrayRef<char> getStubBlockContent() {
102349cc55cSDimitry Andric     auto StubContent = isRV64() ? RV64StubContent : RV32StubContent;
103349cc55cSDimitry Andric     return {reinterpret_cast<const char *>(StubContent), StubEntrySize};
104349cc55cSDimitry Andric   }
105349cc55cSDimitry Andric 
106349cc55cSDimitry Andric   mutable Section *GOTSection = nullptr;
107349cc55cSDimitry Andric   mutable Section *StubsSection = nullptr;
108349cc55cSDimitry Andric };
109349cc55cSDimitry Andric 
110349cc55cSDimitry Andric const uint8_t PerGraphGOTAndPLTStubsBuilder_ELF_riscv::NullGOTEntryContent[8] =
111349cc55cSDimitry Andric     {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
112349cc55cSDimitry Andric 
113349cc55cSDimitry Andric const uint8_t
114349cc55cSDimitry Andric     PerGraphGOTAndPLTStubsBuilder_ELF_riscv::RV64StubContent[StubEntrySize] = {
115349cc55cSDimitry Andric         0x17, 0x0e, 0x00, 0x00,  // auipc t3, literal
116349cc55cSDimitry Andric         0x03, 0x3e, 0x0e, 0x00,  // ld    t3, literal(t3)
117349cc55cSDimitry Andric         0x67, 0x00, 0x0e, 0x00,  // jr    t3
118349cc55cSDimitry Andric         0x13, 0x00, 0x00, 0x00}; // nop
119349cc55cSDimitry Andric 
120349cc55cSDimitry Andric const uint8_t
121349cc55cSDimitry Andric     PerGraphGOTAndPLTStubsBuilder_ELF_riscv::RV32StubContent[StubEntrySize] = {
122349cc55cSDimitry Andric         0x17, 0x0e, 0x00, 0x00,  // auipc t3, literal
123349cc55cSDimitry Andric         0x03, 0x2e, 0x0e, 0x00,  // lw    t3, literal(t3)
124349cc55cSDimitry Andric         0x67, 0x00, 0x0e, 0x00,  // jr    t3
125349cc55cSDimitry Andric         0x13, 0x00, 0x00, 0x00}; // nop
126349cc55cSDimitry Andric } // namespace
127fe6060f1SDimitry Andric namespace llvm {
128fe6060f1SDimitry Andric namespace jitlink {
129fe6060f1SDimitry Andric 
130fe6060f1SDimitry Andric static Expected<const Edge &> getRISCVPCRelHi20(const Edge &E) {
131fe6060f1SDimitry Andric   using namespace riscv;
132fe6060f1SDimitry Andric   assert((E.getKind() == R_RISCV_PCREL_LO12_I ||
133fe6060f1SDimitry Andric           E.getKind() == R_RISCV_PCREL_LO12_S) &&
134fe6060f1SDimitry Andric          "Can only have high relocation for R_RISCV_PCREL_LO12_I or "
135fe6060f1SDimitry Andric          "R_RISCV_PCREL_LO12_S");
136fe6060f1SDimitry Andric 
137fe6060f1SDimitry Andric   const Symbol &Sym = E.getTarget();
138fe6060f1SDimitry Andric   const Block &B = Sym.getBlock();
13904eeddc0SDimitry Andric   orc::ExecutorAddrDiff Offset = Sym.getOffset();
140fe6060f1SDimitry Andric 
141fe6060f1SDimitry Andric   struct Comp {
14204eeddc0SDimitry Andric     bool operator()(const Edge &Lhs, orc::ExecutorAddrDiff Offset) {
143fe6060f1SDimitry Andric       return Lhs.getOffset() < Offset;
144fe6060f1SDimitry Andric     }
14504eeddc0SDimitry Andric     bool operator()(orc::ExecutorAddrDiff Offset, const Edge &Rhs) {
146fe6060f1SDimitry Andric       return Offset < Rhs.getOffset();
147fe6060f1SDimitry Andric     }
148fe6060f1SDimitry Andric   };
149fe6060f1SDimitry Andric 
150fe6060f1SDimitry Andric   auto Bound =
151fe6060f1SDimitry Andric       std::equal_range(B.edges().begin(), B.edges().end(), Offset, Comp{});
152fe6060f1SDimitry Andric 
153fe6060f1SDimitry Andric   for (auto It = Bound.first; It != Bound.second; ++It) {
154fe6060f1SDimitry Andric     if (It->getKind() == R_RISCV_PCREL_HI20)
155fe6060f1SDimitry Andric       return *It;
156fe6060f1SDimitry Andric   }
157fe6060f1SDimitry Andric 
158fe6060f1SDimitry Andric   return make_error<JITLinkError>(
159fe6060f1SDimitry Andric       "No HI20 PCREL relocation type be found for LO12 PCREL relocation type");
160fe6060f1SDimitry Andric }
161fe6060f1SDimitry Andric 
16204eeddc0SDimitry Andric static uint32_t extractBits(uint32_t Num, unsigned Low, unsigned Size) {
163*81ad6265SDimitry Andric   return (Num & (((1ULL << Size) - 1) << Low)) >> Low;
16404eeddc0SDimitry Andric }
16504eeddc0SDimitry Andric 
166*81ad6265SDimitry Andric static inline bool isAlignmentCorrect(uint64_t Value, int N) {
167*81ad6265SDimitry Andric   return (Value & (N - 1)) ? false : true;
16804eeddc0SDimitry Andric }
16904eeddc0SDimitry Andric 
170*81ad6265SDimitry Andric // Requires 0 < N <= 64.
171*81ad6265SDimitry Andric static inline bool isInRangeForImm(int64_t Value, int N) {
172*81ad6265SDimitry Andric   return Value == llvm::SignExtend64(Value, N);
173fe6060f1SDimitry Andric }
174fe6060f1SDimitry Andric 
175fe6060f1SDimitry Andric class ELFJITLinker_riscv : public JITLinker<ELFJITLinker_riscv> {
176fe6060f1SDimitry Andric   friend class JITLinker<ELFJITLinker_riscv>;
177fe6060f1SDimitry Andric 
178fe6060f1SDimitry Andric public:
179fe6060f1SDimitry Andric   ELFJITLinker_riscv(std::unique_ptr<JITLinkContext> Ctx,
180fe6060f1SDimitry Andric                      std::unique_ptr<LinkGraph> G, PassConfiguration PassConfig)
181fe6060f1SDimitry Andric       : JITLinker(std::move(Ctx), std::move(G), std::move(PassConfig)) {}
182fe6060f1SDimitry Andric 
183fe6060f1SDimitry Andric private:
184fe6060f1SDimitry Andric   Error applyFixup(LinkGraph &G, Block &B, const Edge &E) const {
185fe6060f1SDimitry Andric     using namespace riscv;
186fe6060f1SDimitry Andric     using namespace llvm::support;
187fe6060f1SDimitry Andric 
188fe6060f1SDimitry Andric     char *BlockWorkingMem = B.getAlreadyMutableContent().data();
189fe6060f1SDimitry Andric     char *FixupPtr = BlockWorkingMem + E.getOffset();
19004eeddc0SDimitry Andric     orc::ExecutorAddr FixupAddress = B.getAddress() + E.getOffset();
191fe6060f1SDimitry Andric     switch (E.getKind()) {
192349cc55cSDimitry Andric     case R_RISCV_32: {
19304eeddc0SDimitry Andric       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
194349cc55cSDimitry Andric       *(little32_t *)FixupPtr = static_cast<uint32_t>(Value);
195349cc55cSDimitry Andric       break;
196349cc55cSDimitry Andric     }
197349cc55cSDimitry Andric     case R_RISCV_64: {
19804eeddc0SDimitry Andric       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
199349cc55cSDimitry Andric       *(little64_t *)FixupPtr = static_cast<uint64_t>(Value);
200349cc55cSDimitry Andric       break;
201349cc55cSDimitry Andric     }
20204eeddc0SDimitry Andric     case R_RISCV_BRANCH: {
20304eeddc0SDimitry Andric       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
204*81ad6265SDimitry Andric       if (LLVM_UNLIKELY(!isInRangeForImm(Value >> 1, 12)))
205*81ad6265SDimitry Andric         return makeTargetOutOfRangeError(G, B, E);
206*81ad6265SDimitry Andric       if (LLVM_UNLIKELY(!isAlignmentCorrect(Value, 2)))
207*81ad6265SDimitry Andric         return makeAlignmentError(FixupAddress, Value, 2, E);
208*81ad6265SDimitry Andric       uint32_t Imm31_25 =
209*81ad6265SDimitry Andric           extractBits(Value, 5, 6) << 25 | extractBits(Value, 12, 1) << 31;
210*81ad6265SDimitry Andric       uint32_t Imm11_7 =
211*81ad6265SDimitry Andric           extractBits(Value, 1, 4) << 8 | extractBits(Value, 11, 1) << 7;
212fe6060f1SDimitry Andric       uint32_t RawInstr = *(little32_t *)FixupPtr;
21304eeddc0SDimitry Andric       *(little32_t *)FixupPtr = (RawInstr & 0x1FFF07F) | Imm31_25 | Imm11_7;
21404eeddc0SDimitry Andric       break;
21504eeddc0SDimitry Andric     }
216*81ad6265SDimitry Andric     case R_RISCV_JAL: {
217*81ad6265SDimitry Andric       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
218*81ad6265SDimitry Andric       if (LLVM_UNLIKELY(!isInRangeForImm(Value >> 1, 20)))
219*81ad6265SDimitry Andric         return makeTargetOutOfRangeError(G, B, E);
220*81ad6265SDimitry Andric       if (LLVM_UNLIKELY(!isAlignmentCorrect(Value, 2)))
221*81ad6265SDimitry Andric         return makeAlignmentError(FixupAddress, Value, 2, E);
222*81ad6265SDimitry Andric       uint32_t Imm20 = extractBits(Value, 20, 1) << 31;
223*81ad6265SDimitry Andric       uint32_t Imm10_1 = extractBits(Value, 1, 10) << 21;
224*81ad6265SDimitry Andric       uint32_t Imm11 = extractBits(Value, 11, 1) << 20;
225*81ad6265SDimitry Andric       uint32_t Imm19_12 = extractBits(Value, 12, 8) << 12;
226*81ad6265SDimitry Andric       uint32_t RawInstr = *(little32_t *)FixupPtr;
227*81ad6265SDimitry Andric       *(little32_t *)FixupPtr = RawInstr | Imm20 | Imm10_1 | Imm11 | Imm19_12;
228*81ad6265SDimitry Andric       break;
229*81ad6265SDimitry Andric     }
23004eeddc0SDimitry Andric     case R_RISCV_HI20: {
23104eeddc0SDimitry Andric       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
23204eeddc0SDimitry Andric       int64_t Hi = Value + 0x800;
233*81ad6265SDimitry Andric       if (LLVM_UNLIKELY(!isInRangeForImm(Hi, 32)))
23404eeddc0SDimitry Andric         return makeTargetOutOfRangeError(G, B, E);
23504eeddc0SDimitry Andric       uint32_t RawInstr = *(little32_t *)FixupPtr;
23604eeddc0SDimitry Andric       *(little32_t *)FixupPtr =
23704eeddc0SDimitry Andric           (RawInstr & 0xFFF) | (static_cast<uint32_t>(Hi & 0xFFFFF000));
238fe6060f1SDimitry Andric       break;
239fe6060f1SDimitry Andric     }
240fe6060f1SDimitry Andric     case R_RISCV_LO12_I: {
24104eeddc0SDimitry Andric       // FIXME: We assume that R_RISCV_HI20 is present in object code and pairs
24204eeddc0SDimitry Andric       // with current relocation R_RISCV_LO12_I. So here may need a check.
24304eeddc0SDimitry Andric       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
244fe6060f1SDimitry Andric       int32_t Lo = Value & 0xFFF;
245fe6060f1SDimitry Andric       uint32_t RawInstr = *(little32_t *)FixupPtr;
246fe6060f1SDimitry Andric       *(little32_t *)FixupPtr =
247fe6060f1SDimitry Andric           (RawInstr & 0xFFFFF) | (static_cast<uint32_t>(Lo & 0xFFF) << 20);
248fe6060f1SDimitry Andric       break;
249fe6060f1SDimitry Andric     }
250fe6060f1SDimitry Andric     case R_RISCV_CALL: {
251fe6060f1SDimitry Andric       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
25204eeddc0SDimitry Andric       int64_t Hi = Value + 0x800;
253*81ad6265SDimitry Andric       if (LLVM_UNLIKELY(!isInRangeForImm(Hi, 32)))
25404eeddc0SDimitry Andric         return makeTargetOutOfRangeError(G, B, E);
255fe6060f1SDimitry Andric       int32_t Lo = Value & 0xFFF;
256fe6060f1SDimitry Andric       uint32_t RawInstrAuipc = *(little32_t *)FixupPtr;
257fe6060f1SDimitry Andric       uint32_t RawInstrJalr = *(little32_t *)(FixupPtr + 4);
25804eeddc0SDimitry Andric       *(little32_t *)FixupPtr =
25904eeddc0SDimitry Andric           RawInstrAuipc | (static_cast<uint32_t>(Hi & 0xFFFFF000));
260fe6060f1SDimitry Andric       *(little32_t *)(FixupPtr + 4) =
261fe6060f1SDimitry Andric           RawInstrJalr | (static_cast<uint32_t>(Lo) << 20);
262fe6060f1SDimitry Andric       break;
263fe6060f1SDimitry Andric     }
264fe6060f1SDimitry Andric     case R_RISCV_PCREL_HI20: {
265fe6060f1SDimitry Andric       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
26604eeddc0SDimitry Andric       int64_t Hi = Value + 0x800;
267*81ad6265SDimitry Andric       if (LLVM_UNLIKELY(!isInRangeForImm(Hi, 32)))
26804eeddc0SDimitry Andric         return makeTargetOutOfRangeError(G, B, E);
269fe6060f1SDimitry Andric       uint32_t RawInstr = *(little32_t *)FixupPtr;
27004eeddc0SDimitry Andric       *(little32_t *)FixupPtr =
27104eeddc0SDimitry Andric           (RawInstr & 0xFFF) | (static_cast<uint32_t>(Hi & 0xFFFFF000));
272fe6060f1SDimitry Andric       break;
273fe6060f1SDimitry Andric     }
274fe6060f1SDimitry Andric     case R_RISCV_PCREL_LO12_I: {
27504eeddc0SDimitry Andric       // FIXME: We assume that R_RISCV_PCREL_HI20 is present in object code and
27604eeddc0SDimitry Andric       // pairs with current relocation R_RISCV_PCREL_LO12_I. So here may need a
27704eeddc0SDimitry Andric       // check.
278fe6060f1SDimitry Andric       auto RelHI20 = getRISCVPCRelHi20(E);
279fe6060f1SDimitry Andric       if (!RelHI20)
280fe6060f1SDimitry Andric         return RelHI20.takeError();
281fe6060f1SDimitry Andric       int64_t Value = RelHI20->getTarget().getAddress() +
282fe6060f1SDimitry Andric                       RelHI20->getAddend() - E.getTarget().getAddress();
283fe6060f1SDimitry Andric       int64_t Lo = Value & 0xFFF;
284fe6060f1SDimitry Andric       uint32_t RawInstr = *(little32_t *)FixupPtr;
285fe6060f1SDimitry Andric       *(little32_t *)FixupPtr =
286fe6060f1SDimitry Andric           (RawInstr & 0xFFFFF) | (static_cast<uint32_t>(Lo & 0xFFF) << 20);
287fe6060f1SDimitry Andric       break;
288fe6060f1SDimitry Andric     }
289fe6060f1SDimitry Andric     case R_RISCV_PCREL_LO12_S: {
29004eeddc0SDimitry Andric       // FIXME: We assume that R_RISCV_PCREL_HI20 is present in object code and
29104eeddc0SDimitry Andric       // pairs with current relocation R_RISCV_PCREL_LO12_S. So here may need a
29204eeddc0SDimitry Andric       // check.
293fe6060f1SDimitry Andric       auto RelHI20 = getRISCVPCRelHi20(E);
294fe6060f1SDimitry Andric       int64_t Value = RelHI20->getTarget().getAddress() +
295fe6060f1SDimitry Andric                       RelHI20->getAddend() - E.getTarget().getAddress();
296fe6060f1SDimitry Andric       int64_t Lo = Value & 0xFFF;
29704eeddc0SDimitry Andric       uint32_t Imm31_25 = extractBits(Lo, 5, 7) << 25;
29804eeddc0SDimitry Andric       uint32_t Imm11_7 = extractBits(Lo, 0, 5) << 7;
299fe6060f1SDimitry Andric       uint32_t RawInstr = *(little32_t *)FixupPtr;
300fe6060f1SDimitry Andric 
301fe6060f1SDimitry Andric       *(little32_t *)FixupPtr = (RawInstr & 0x1FFF07F) | Imm31_25 | Imm11_7;
302fe6060f1SDimitry Andric       break;
303fe6060f1SDimitry Andric     }
30404eeddc0SDimitry Andric     case R_RISCV_ADD64: {
30504eeddc0SDimitry Andric       int64_t Value = (E.getTarget().getAddress() +
30604eeddc0SDimitry Andric                        support::endian::read64le(reinterpret_cast<const void *>(
30704eeddc0SDimitry Andric                            FixupAddress.getValue())) +
30804eeddc0SDimitry Andric                        E.getAddend())
30904eeddc0SDimitry Andric                           .getValue();
31004eeddc0SDimitry Andric       *(little64_t *)FixupPtr = static_cast<uint64_t>(Value);
31104eeddc0SDimitry Andric       break;
31204eeddc0SDimitry Andric     }
31304eeddc0SDimitry Andric     case R_RISCV_ADD32: {
31404eeddc0SDimitry Andric       int64_t Value = (E.getTarget().getAddress() +
31504eeddc0SDimitry Andric                        support::endian::read32le(reinterpret_cast<const void *>(
31604eeddc0SDimitry Andric                            FixupAddress.getValue())) +
31704eeddc0SDimitry Andric                        E.getAddend())
31804eeddc0SDimitry Andric                           .getValue();
31904eeddc0SDimitry Andric       *(little32_t *)FixupPtr = static_cast<uint32_t>(Value);
32004eeddc0SDimitry Andric       break;
32104eeddc0SDimitry Andric     }
32204eeddc0SDimitry Andric     case R_RISCV_ADD16: {
32304eeddc0SDimitry Andric       int64_t Value = (E.getTarget().getAddress() +
32404eeddc0SDimitry Andric                        support::endian::read16le(reinterpret_cast<const void *>(
32504eeddc0SDimitry Andric                            FixupAddress.getValue())) +
32604eeddc0SDimitry Andric                        E.getAddend())
32704eeddc0SDimitry Andric                           .getValue();
32804eeddc0SDimitry Andric       *(little16_t *)FixupPtr = static_cast<uint32_t>(Value);
32904eeddc0SDimitry Andric       break;
33004eeddc0SDimitry Andric     }
33104eeddc0SDimitry Andric     case R_RISCV_ADD8: {
33204eeddc0SDimitry Andric       int64_t Value =
33304eeddc0SDimitry Andric           (E.getTarget().getAddress() +
33404eeddc0SDimitry Andric            *(reinterpret_cast<const uint8_t *>(FixupAddress.getValue())) +
33504eeddc0SDimitry Andric            E.getAddend())
33604eeddc0SDimitry Andric               .getValue();
33704eeddc0SDimitry Andric       *FixupPtr = static_cast<uint8_t>(Value);
33804eeddc0SDimitry Andric       break;
33904eeddc0SDimitry Andric     }
34004eeddc0SDimitry Andric     case R_RISCV_SUB64: {
34104eeddc0SDimitry Andric       int64_t Value = support::endian::read64le(reinterpret_cast<const void *>(
34204eeddc0SDimitry Andric                           FixupAddress.getValue())) -
34304eeddc0SDimitry Andric                       E.getTarget().getAddress().getValue() - E.getAddend();
34404eeddc0SDimitry Andric       *(little64_t *)FixupPtr = static_cast<uint64_t>(Value);
34504eeddc0SDimitry Andric       break;
34604eeddc0SDimitry Andric     }
34704eeddc0SDimitry Andric     case R_RISCV_SUB32: {
34804eeddc0SDimitry Andric       int64_t Value = support::endian::read32le(reinterpret_cast<const void *>(
34904eeddc0SDimitry Andric                           FixupAddress.getValue())) -
35004eeddc0SDimitry Andric                       E.getTarget().getAddress().getValue() - E.getAddend();
35104eeddc0SDimitry Andric       *(little32_t *)FixupPtr = static_cast<uint32_t>(Value);
35204eeddc0SDimitry Andric       break;
35304eeddc0SDimitry Andric     }
35404eeddc0SDimitry Andric     case R_RISCV_SUB16: {
35504eeddc0SDimitry Andric       int64_t Value = support::endian::read16le(reinterpret_cast<const void *>(
35604eeddc0SDimitry Andric                           FixupAddress.getValue())) -
35704eeddc0SDimitry Andric                       E.getTarget().getAddress().getValue() - E.getAddend();
35804eeddc0SDimitry Andric       *(little16_t *)FixupPtr = static_cast<uint32_t>(Value);
35904eeddc0SDimitry Andric       break;
36004eeddc0SDimitry Andric     }
36104eeddc0SDimitry Andric     case R_RISCV_SUB8: {
36204eeddc0SDimitry Andric       int64_t Value =
36304eeddc0SDimitry Andric           *(reinterpret_cast<const uint8_t *>(FixupAddress.getValue())) -
36404eeddc0SDimitry Andric           E.getTarget().getAddress().getValue() - E.getAddend();
36504eeddc0SDimitry Andric       *FixupPtr = static_cast<uint8_t>(Value);
36604eeddc0SDimitry Andric       break;
36704eeddc0SDimitry Andric     }
368*81ad6265SDimitry Andric     case R_RISCV_SUB6: {
369*81ad6265SDimitry Andric       int64_t Value =
370*81ad6265SDimitry Andric           *(reinterpret_cast<const uint8_t *>(FixupAddress.getValue())) & 0x3f;
371*81ad6265SDimitry Andric       Value -= E.getTarget().getAddress().getValue() - E.getAddend();
372*81ad6265SDimitry Andric       *FixupPtr = (*FixupPtr & 0xc0) | (static_cast<uint8_t>(Value) & 0x3f);
373*81ad6265SDimitry Andric       break;
374*81ad6265SDimitry Andric     }
37504eeddc0SDimitry Andric     case R_RISCV_SET6: {
37604eeddc0SDimitry Andric       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
37704eeddc0SDimitry Andric       uint32_t RawData = *(little32_t *)FixupPtr;
37804eeddc0SDimitry Andric       int64_t Word6 = Value & 0x3f;
37904eeddc0SDimitry Andric       *(little32_t *)FixupPtr = (RawData & 0xffffffc0) | Word6;
38004eeddc0SDimitry Andric       break;
38104eeddc0SDimitry Andric     }
38204eeddc0SDimitry Andric     case R_RISCV_SET8: {
38304eeddc0SDimitry Andric       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
38404eeddc0SDimitry Andric       uint32_t RawData = *(little32_t *)FixupPtr;
38504eeddc0SDimitry Andric       int64_t Word8 = Value & 0xff;
38604eeddc0SDimitry Andric       *(little32_t *)FixupPtr = (RawData & 0xffffff00) | Word8;
38704eeddc0SDimitry Andric       break;
38804eeddc0SDimitry Andric     }
38904eeddc0SDimitry Andric     case R_RISCV_SET16: {
39004eeddc0SDimitry Andric       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
39104eeddc0SDimitry Andric       uint32_t RawData = *(little32_t *)FixupPtr;
39204eeddc0SDimitry Andric       int64_t Word16 = Value & 0xffff;
39304eeddc0SDimitry Andric       *(little32_t *)FixupPtr = (RawData & 0xffff0000) | Word16;
39404eeddc0SDimitry Andric       break;
39504eeddc0SDimitry Andric     }
39604eeddc0SDimitry Andric     case R_RISCV_SET32: {
39704eeddc0SDimitry Andric       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
39804eeddc0SDimitry Andric       int64_t Word32 = Value & 0xffffffff;
39904eeddc0SDimitry Andric       *(little32_t *)FixupPtr = Word32;
40004eeddc0SDimitry Andric       break;
40104eeddc0SDimitry Andric     }
40204eeddc0SDimitry Andric     case R_RISCV_32_PCREL: {
40304eeddc0SDimitry Andric       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
40404eeddc0SDimitry Andric       int64_t Word32 = Value & 0xffffffff;
40504eeddc0SDimitry Andric       *(little32_t *)FixupPtr = Word32;
40604eeddc0SDimitry Andric       break;
40704eeddc0SDimitry Andric     }
408fe6060f1SDimitry Andric     }
409fe6060f1SDimitry Andric     return Error::success();
410fe6060f1SDimitry Andric   }
411fe6060f1SDimitry Andric };
412fe6060f1SDimitry Andric 
413fe6060f1SDimitry Andric template <typename ELFT>
414fe6060f1SDimitry Andric class ELFLinkGraphBuilder_riscv : public ELFLinkGraphBuilder<ELFT> {
415fe6060f1SDimitry Andric private:
416fe6060f1SDimitry Andric   static Expected<riscv::EdgeKind_riscv>
417fe6060f1SDimitry Andric   getRelocationKind(const uint32_t Type) {
418fe6060f1SDimitry Andric     using namespace riscv;
419fe6060f1SDimitry Andric     switch (Type) {
420fe6060f1SDimitry Andric     case ELF::R_RISCV_32:
421fe6060f1SDimitry Andric       return EdgeKind_riscv::R_RISCV_32;
422fe6060f1SDimitry Andric     case ELF::R_RISCV_64:
423fe6060f1SDimitry Andric       return EdgeKind_riscv::R_RISCV_64;
42404eeddc0SDimitry Andric     case ELF::R_RISCV_BRANCH:
42504eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_BRANCH;
426*81ad6265SDimitry Andric     case ELF::R_RISCV_JAL:
427*81ad6265SDimitry Andric       return EdgeKind_riscv::R_RISCV_JAL;
428fe6060f1SDimitry Andric     case ELF::R_RISCV_HI20:
429fe6060f1SDimitry Andric       return EdgeKind_riscv::R_RISCV_HI20;
430fe6060f1SDimitry Andric     case ELF::R_RISCV_LO12_I:
431fe6060f1SDimitry Andric       return EdgeKind_riscv::R_RISCV_LO12_I;
432fe6060f1SDimitry Andric     case ELF::R_RISCV_CALL:
433fe6060f1SDimitry Andric       return EdgeKind_riscv::R_RISCV_CALL;
434fe6060f1SDimitry Andric     case ELF::R_RISCV_PCREL_HI20:
435fe6060f1SDimitry Andric       return EdgeKind_riscv::R_RISCV_PCREL_HI20;
436fe6060f1SDimitry Andric     case ELF::R_RISCV_PCREL_LO12_I:
437fe6060f1SDimitry Andric       return EdgeKind_riscv::R_RISCV_PCREL_LO12_I;
438fe6060f1SDimitry Andric     case ELF::R_RISCV_PCREL_LO12_S:
439fe6060f1SDimitry Andric       return EdgeKind_riscv::R_RISCV_PCREL_LO12_S;
440349cc55cSDimitry Andric     case ELF::R_RISCV_GOT_HI20:
441349cc55cSDimitry Andric       return EdgeKind_riscv::R_RISCV_GOT_HI20;
442349cc55cSDimitry Andric     case ELF::R_RISCV_CALL_PLT:
443349cc55cSDimitry Andric       return EdgeKind_riscv::R_RISCV_CALL_PLT;
44404eeddc0SDimitry Andric     case ELF::R_RISCV_ADD64:
44504eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_ADD64;
44604eeddc0SDimitry Andric     case ELF::R_RISCV_ADD32:
44704eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_ADD32;
44804eeddc0SDimitry Andric     case ELF::R_RISCV_ADD16:
44904eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_ADD16;
45004eeddc0SDimitry Andric     case ELF::R_RISCV_ADD8:
45104eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_ADD8;
45204eeddc0SDimitry Andric     case ELF::R_RISCV_SUB64:
45304eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_SUB64;
45404eeddc0SDimitry Andric     case ELF::R_RISCV_SUB32:
45504eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_SUB32;
45604eeddc0SDimitry Andric     case ELF::R_RISCV_SUB16:
45704eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_SUB16;
45804eeddc0SDimitry Andric     case ELF::R_RISCV_SUB8:
45904eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_SUB8;
460*81ad6265SDimitry Andric     case ELF::R_RISCV_SUB6:
461*81ad6265SDimitry Andric       return EdgeKind_riscv::R_RISCV_SUB6;
46204eeddc0SDimitry Andric     case ELF::R_RISCV_SET6:
46304eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_SET6;
46404eeddc0SDimitry Andric     case ELF::R_RISCV_SET8:
46504eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_SET8;
46604eeddc0SDimitry Andric     case ELF::R_RISCV_SET16:
46704eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_SET16;
46804eeddc0SDimitry Andric     case ELF::R_RISCV_SET32:
46904eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_SET32;
47004eeddc0SDimitry Andric     case ELF::R_RISCV_32_PCREL:
47104eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_32_PCREL;
472fe6060f1SDimitry Andric     }
473fe6060f1SDimitry Andric 
474*81ad6265SDimitry Andric     return make_error<JITLinkError>(
475*81ad6265SDimitry Andric         "Unsupported riscv relocation:" + formatv("{0:d}: ", Type) +
476*81ad6265SDimitry Andric         object::getELFRelocationTypeName(ELF::EM_RISCV, Type));
477fe6060f1SDimitry Andric   }
478fe6060f1SDimitry Andric 
479fe6060f1SDimitry Andric   Error addRelocations() override {
480349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "Processing relocations:\n");
481349cc55cSDimitry Andric 
482fe6060f1SDimitry Andric     using Base = ELFLinkGraphBuilder<ELFT>;
483349cc55cSDimitry Andric     using Self = ELFLinkGraphBuilder_riscv<ELFT>;
484349cc55cSDimitry Andric     for (const auto &RelSect : Base::Sections)
485349cc55cSDimitry Andric       if (Error Err = Base::forEachRelocation(RelSect, this,
486349cc55cSDimitry Andric                                               &Self::addSingleRelocation))
487349cc55cSDimitry Andric         return Err;
488fe6060f1SDimitry Andric 
489349cc55cSDimitry Andric     return Error::success();
490fe6060f1SDimitry Andric   }
491fe6060f1SDimitry Andric 
492349cc55cSDimitry Andric   Error addSingleRelocation(const typename ELFT::Rela &Rel,
493349cc55cSDimitry Andric                             const typename ELFT::Shdr &FixupSect,
49404eeddc0SDimitry Andric                             Block &BlockToFix) {
495349cc55cSDimitry Andric     using Base = ELFLinkGraphBuilder<ELFT>;
496349cc55cSDimitry Andric 
497349cc55cSDimitry Andric     uint32_t SymbolIndex = Rel.getSymbol(false);
498349cc55cSDimitry Andric     auto ObjSymbol = Base::Obj.getRelocationSymbol(Rel, Base::SymTabSec);
499349cc55cSDimitry Andric     if (!ObjSymbol)
500349cc55cSDimitry Andric       return ObjSymbol.takeError();
501349cc55cSDimitry Andric 
502349cc55cSDimitry Andric     Symbol *GraphSymbol = Base::getGraphSymbol(SymbolIndex);
503349cc55cSDimitry Andric     if (!GraphSymbol)
504349cc55cSDimitry Andric       return make_error<StringError>(
505349cc55cSDimitry Andric           formatv("Could not find symbol at given index, did you add it to "
506349cc55cSDimitry Andric                   "JITSymbolTable? index: {0}, shndx: {1} Size of table: {2}",
507349cc55cSDimitry Andric                   SymbolIndex, (*ObjSymbol)->st_shndx,
508349cc55cSDimitry Andric                   Base::GraphSymbols.size()),
509349cc55cSDimitry Andric           inconvertibleErrorCode());
510349cc55cSDimitry Andric 
511349cc55cSDimitry Andric     uint32_t Type = Rel.getType(false);
512349cc55cSDimitry Andric     Expected<riscv::EdgeKind_riscv> Kind = getRelocationKind(Type);
513fe6060f1SDimitry Andric     if (!Kind)
514fe6060f1SDimitry Andric       return Kind.takeError();
515fe6060f1SDimitry Andric 
516349cc55cSDimitry Andric     int64_t Addend = Rel.r_addend;
51704eeddc0SDimitry Andric     auto FixupAddress = orc::ExecutorAddr(FixupSect.sh_addr) + Rel.r_offset;
51804eeddc0SDimitry Andric     Edge::OffsetT Offset = FixupAddress - BlockToFix.getAddress();
519349cc55cSDimitry Andric     Edge GE(*Kind, Offset, *GraphSymbol, Addend);
520349cc55cSDimitry Andric     LLVM_DEBUG({
521349cc55cSDimitry Andric       dbgs() << "    ";
52204eeddc0SDimitry Andric       printEdge(dbgs(), BlockToFix, GE, riscv::getEdgeKindName(*Kind));
523349cc55cSDimitry Andric       dbgs() << "\n";
524349cc55cSDimitry Andric     });
525349cc55cSDimitry Andric 
52604eeddc0SDimitry Andric     BlockToFix.addEdge(std::move(GE));
527fe6060f1SDimitry Andric     return Error::success();
528fe6060f1SDimitry Andric   }
529fe6060f1SDimitry Andric 
530fe6060f1SDimitry Andric public:
531fe6060f1SDimitry Andric   ELFLinkGraphBuilder_riscv(StringRef FileName,
532fe6060f1SDimitry Andric                             const object::ELFFile<ELFT> &Obj, const Triple T)
533fe6060f1SDimitry Andric       : ELFLinkGraphBuilder<ELFT>(Obj, std::move(T), FileName,
534fe6060f1SDimitry Andric                                   riscv::getEdgeKindName) {}
535fe6060f1SDimitry Andric };
536fe6060f1SDimitry Andric 
537fe6060f1SDimitry Andric Expected<std::unique_ptr<LinkGraph>>
538fe6060f1SDimitry Andric createLinkGraphFromELFObject_riscv(MemoryBufferRef ObjectBuffer) {
539fe6060f1SDimitry Andric   LLVM_DEBUG({
540fe6060f1SDimitry Andric     dbgs() << "Building jitlink graph for new input "
541fe6060f1SDimitry Andric            << ObjectBuffer.getBufferIdentifier() << "...\n";
542fe6060f1SDimitry Andric   });
543fe6060f1SDimitry Andric 
544fe6060f1SDimitry Andric   auto ELFObj = object::ObjectFile::createELFObjectFile(ObjectBuffer);
545fe6060f1SDimitry Andric   if (!ELFObj)
546fe6060f1SDimitry Andric     return ELFObj.takeError();
547fe6060f1SDimitry Andric 
548fe6060f1SDimitry Andric   if ((*ELFObj)->getArch() == Triple::riscv64) {
549fe6060f1SDimitry Andric     auto &ELFObjFile = cast<object::ELFObjectFile<object::ELF64LE>>(**ELFObj);
550fe6060f1SDimitry Andric     return ELFLinkGraphBuilder_riscv<object::ELF64LE>(
551fe6060f1SDimitry Andric                (*ELFObj)->getFileName(), ELFObjFile.getELFFile(),
552fe6060f1SDimitry Andric                (*ELFObj)->makeTriple())
553fe6060f1SDimitry Andric         .buildGraph();
554fe6060f1SDimitry Andric   } else {
555fe6060f1SDimitry Andric     assert((*ELFObj)->getArch() == Triple::riscv32 &&
556fe6060f1SDimitry Andric            "Invalid triple for RISCV ELF object file");
557fe6060f1SDimitry Andric     auto &ELFObjFile = cast<object::ELFObjectFile<object::ELF32LE>>(**ELFObj);
558fe6060f1SDimitry Andric     return ELFLinkGraphBuilder_riscv<object::ELF32LE>(
559fe6060f1SDimitry Andric                (*ELFObj)->getFileName(), ELFObjFile.getELFFile(),
560fe6060f1SDimitry Andric                (*ELFObj)->makeTriple())
561fe6060f1SDimitry Andric         .buildGraph();
562fe6060f1SDimitry Andric   }
563fe6060f1SDimitry Andric }
564fe6060f1SDimitry Andric 
565fe6060f1SDimitry Andric void link_ELF_riscv(std::unique_ptr<LinkGraph> G,
566fe6060f1SDimitry Andric                     std::unique_ptr<JITLinkContext> Ctx) {
567fe6060f1SDimitry Andric   PassConfiguration Config;
568fe6060f1SDimitry Andric   const Triple &TT = G->getTargetTriple();
569fe6060f1SDimitry Andric   if (Ctx->shouldAddDefaultTargetPasses(TT)) {
570fe6060f1SDimitry Andric     if (auto MarkLive = Ctx->getMarkLivePass(TT))
571fe6060f1SDimitry Andric       Config.PrePrunePasses.push_back(std::move(MarkLive));
572fe6060f1SDimitry Andric     else
573fe6060f1SDimitry Andric       Config.PrePrunePasses.push_back(markAllSymbolsLive);
574349cc55cSDimitry Andric     Config.PostPrunePasses.push_back(
575349cc55cSDimitry Andric         PerGraphGOTAndPLTStubsBuilder_ELF_riscv::asPass);
576fe6060f1SDimitry Andric   }
577fe6060f1SDimitry Andric   if (auto Err = Ctx->modifyPassConfig(*G, Config))
578fe6060f1SDimitry Andric     return Ctx->notifyFailed(std::move(Err));
579fe6060f1SDimitry Andric 
580fe6060f1SDimitry Andric   ELFJITLinker_riscv::link(std::move(Ctx), std::move(G), std::move(Config));
581fe6060f1SDimitry Andric }
582fe6060f1SDimitry Andric 
583fe6060f1SDimitry Andric } // namespace jitlink
584fe6060f1SDimitry Andric } // namespace llvm
585