xref: /freebsd/contrib/llvm-project/lld/ELF/Arch/RISCV.cpp (revision 5f757f3ff9144b609b3c433dfd370cc6bdc191ad)
10b57cec5SDimitry Andric //===- RISCV.cpp ----------------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "InputFiles.h"
10753f127fSDimitry Andric #include "OutputSections.h"
11480093f4SDimitry Andric #include "Symbols.h"
120b57cec5SDimitry Andric #include "SyntheticSections.h"
130b57cec5SDimitry Andric #include "Target.h"
14bdd1243dSDimitry Andric #include "llvm/Support/ELFAttributes.h"
15bdd1243dSDimitry Andric #include "llvm/Support/LEB128.h"
16bdd1243dSDimitry Andric #include "llvm/Support/RISCVAttributeParser.h"
17bdd1243dSDimitry Andric #include "llvm/Support/RISCVAttributes.h"
18bdd1243dSDimitry Andric #include "llvm/Support/RISCVISAInfo.h"
19753f127fSDimitry Andric #include "llvm/Support/TimeProfiler.h"
200b57cec5SDimitry Andric 
210b57cec5SDimitry Andric using namespace llvm;
220b57cec5SDimitry Andric using namespace llvm::object;
230b57cec5SDimitry Andric using namespace llvm::support::endian;
240b57cec5SDimitry Andric using namespace llvm::ELF;
255ffd83dbSDimitry Andric using namespace lld;
265ffd83dbSDimitry Andric using namespace lld::elf;
270b57cec5SDimitry Andric 
280b57cec5SDimitry Andric namespace {
290b57cec5SDimitry Andric 
300b57cec5SDimitry Andric class RISCV final : public TargetInfo {
310b57cec5SDimitry Andric public:
320b57cec5SDimitry Andric   RISCV();
330b57cec5SDimitry Andric   uint32_t calcEFlags() const override;
34fe6060f1SDimitry Andric   int64_t getImplicitAddend(const uint8_t *buf, RelType type) const override;
350b57cec5SDimitry Andric   void writeGotHeader(uint8_t *buf) const override;
360b57cec5SDimitry Andric   void writeGotPlt(uint8_t *buf, const Symbol &s) const override;
37fe6060f1SDimitry Andric   void writeIgotPlt(uint8_t *buf, const Symbol &s) const override;
380b57cec5SDimitry Andric   void writePltHeader(uint8_t *buf) const override;
39480093f4SDimitry Andric   void writePlt(uint8_t *buf, const Symbol &sym,
40480093f4SDimitry Andric                 uint64_t pltEntryAddr) const override;
410b57cec5SDimitry Andric   RelType getDynRel(RelType type) const override;
420b57cec5SDimitry Andric   RelExpr getRelExpr(RelType type, const Symbol &s,
430b57cec5SDimitry Andric                      const uint8_t *loc) const override;
445ffd83dbSDimitry Andric   void relocate(uint8_t *loc, const Relocation &rel,
455ffd83dbSDimitry Andric                 uint64_t val) const override;
46753f127fSDimitry Andric   bool relaxOnce(int pass) const override;
470b57cec5SDimitry Andric };
480b57cec5SDimitry Andric 
490b57cec5SDimitry Andric } // end anonymous namespace
500b57cec5SDimitry Andric 
5106c3fb27SDimitry Andric // These are internal relocation numbers for GP relaxation. They aren't part
5206c3fb27SDimitry Andric // of the psABI spec.
5306c3fb27SDimitry Andric #define INTERNAL_R_RISCV_GPREL_I 256
5406c3fb27SDimitry Andric #define INTERNAL_R_RISCV_GPREL_S 257
5506c3fb27SDimitry Andric 
560b57cec5SDimitry Andric const uint64_t dtpOffset = 0x800;
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric enum Op {
590b57cec5SDimitry Andric   ADDI = 0x13,
600b57cec5SDimitry Andric   AUIPC = 0x17,
610b57cec5SDimitry Andric   JALR = 0x67,
620b57cec5SDimitry Andric   LD = 0x3003,
630b57cec5SDimitry Andric   LW = 0x2003,
640b57cec5SDimitry Andric   SRLI = 0x5013,
650b57cec5SDimitry Andric   SUB = 0x40000033,
660b57cec5SDimitry Andric };
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric enum Reg {
690b57cec5SDimitry Andric   X_RA = 1,
7006c3fb27SDimitry Andric   X_GP = 3,
71fcaf7f86SDimitry Andric   X_TP = 4,
720b57cec5SDimitry Andric   X_T0 = 5,
730b57cec5SDimitry Andric   X_T1 = 6,
740b57cec5SDimitry Andric   X_T2 = 7,
750b57cec5SDimitry Andric   X_T3 = 28,
760b57cec5SDimitry Andric };
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric static uint32_t hi20(uint32_t val) { return (val + 0x800) >> 12; }
790b57cec5SDimitry Andric static uint32_t lo12(uint32_t val) { return val & 4095; }
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric static uint32_t itype(uint32_t op, uint32_t rd, uint32_t rs1, uint32_t imm) {
820b57cec5SDimitry Andric   return op | (rd << 7) | (rs1 << 15) | (imm << 20);
830b57cec5SDimitry Andric }
840b57cec5SDimitry Andric static uint32_t rtype(uint32_t op, uint32_t rd, uint32_t rs1, uint32_t rs2) {
850b57cec5SDimitry Andric   return op | (rd << 7) | (rs1 << 15) | (rs2 << 20);
860b57cec5SDimitry Andric }
870b57cec5SDimitry Andric static uint32_t utype(uint32_t op, uint32_t rd, uint32_t imm) {
880b57cec5SDimitry Andric   return op | (rd << 7) | (imm << 12);
890b57cec5SDimitry Andric }
900b57cec5SDimitry Andric 
91fcaf7f86SDimitry Andric // Extract bits v[begin:end], where range is inclusive, and begin must be < 63.
92fcaf7f86SDimitry Andric static uint32_t extractBits(uint64_t v, uint32_t begin, uint32_t end) {
93fcaf7f86SDimitry Andric   return (v & ((1ULL << (begin + 1)) - 1)) >> end;
94fcaf7f86SDimitry Andric }
95fcaf7f86SDimitry Andric 
96fcaf7f86SDimitry Andric static uint32_t setLO12_I(uint32_t insn, uint32_t imm) {
97fcaf7f86SDimitry Andric   return (insn & 0xfffff) | (imm << 20);
98fcaf7f86SDimitry Andric }
99fcaf7f86SDimitry Andric static uint32_t setLO12_S(uint32_t insn, uint32_t imm) {
100fcaf7f86SDimitry Andric   return (insn & 0x1fff07f) | (extractBits(imm, 11, 5) << 25) |
101fcaf7f86SDimitry Andric          (extractBits(imm, 4, 0) << 7);
102fcaf7f86SDimitry Andric }
103fcaf7f86SDimitry Andric 
1040b57cec5SDimitry Andric RISCV::RISCV() {
1050b57cec5SDimitry Andric   copyRel = R_RISCV_COPY;
1060b57cec5SDimitry Andric   pltRel = R_RISCV_JUMP_SLOT;
1070b57cec5SDimitry Andric   relativeRel = R_RISCV_RELATIVE;
1085ffd83dbSDimitry Andric   iRelativeRel = R_RISCV_IRELATIVE;
1090b57cec5SDimitry Andric   if (config->is64) {
1100b57cec5SDimitry Andric     symbolicRel = R_RISCV_64;
1110b57cec5SDimitry Andric     tlsModuleIndexRel = R_RISCV_TLS_DTPMOD64;
1120b57cec5SDimitry Andric     tlsOffsetRel = R_RISCV_TLS_DTPREL64;
1130b57cec5SDimitry Andric     tlsGotRel = R_RISCV_TLS_TPREL64;
1140b57cec5SDimitry Andric   } else {
1150b57cec5SDimitry Andric     symbolicRel = R_RISCV_32;
1160b57cec5SDimitry Andric     tlsModuleIndexRel = R_RISCV_TLS_DTPMOD32;
1170b57cec5SDimitry Andric     tlsOffsetRel = R_RISCV_TLS_DTPREL32;
1180b57cec5SDimitry Andric     tlsGotRel = R_RISCV_TLS_TPREL32;
1190b57cec5SDimitry Andric   }
1200b57cec5SDimitry Andric   gotRel = symbolicRel;
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric   // .got[0] = _DYNAMIC
1230b57cec5SDimitry Andric   gotHeaderEntriesNum = 1;
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   // .got.plt[0] = _dl_runtime_resolve, .got.plt[1] = link_map
1260b57cec5SDimitry Andric   gotPltHeaderEntriesNum = 2;
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric   pltHeaderSize = 32;
129480093f4SDimitry Andric   pltEntrySize = 16;
130480093f4SDimitry Andric   ipltEntrySize = 16;
1310b57cec5SDimitry Andric }
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric static uint32_t getEFlags(InputFile *f) {
1340b57cec5SDimitry Andric   if (config->is64)
135e8d8bef9SDimitry Andric     return cast<ObjFile<ELF64LE>>(f)->getObj().getHeader().e_flags;
136e8d8bef9SDimitry Andric   return cast<ObjFile<ELF32LE>>(f)->getObj().getHeader().e_flags;
1370b57cec5SDimitry Andric }
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric uint32_t RISCV::calcEFlags() const {
140a1517e11SDimitry Andric   // If there are only binary input files (from -b binary), use a
141a1517e11SDimitry Andric   // value of 0 for the ELF header flags.
142bdd1243dSDimitry Andric   if (ctx.objectFiles.empty())
143a1517e11SDimitry Andric     return 0;
1440b57cec5SDimitry Andric 
145bdd1243dSDimitry Andric   uint32_t target = getEFlags(ctx.objectFiles.front());
1460b57cec5SDimitry Andric 
147bdd1243dSDimitry Andric   for (InputFile *f : ctx.objectFiles) {
1480b57cec5SDimitry Andric     uint32_t eflags = getEFlags(f);
1490b57cec5SDimitry Andric     if (eflags & EF_RISCV_RVC)
1500b57cec5SDimitry Andric       target |= EF_RISCV_RVC;
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric     if ((eflags & EF_RISCV_FLOAT_ABI) != (target & EF_RISCV_FLOAT_ABI))
153bdd1243dSDimitry Andric       error(
154bdd1243dSDimitry Andric           toString(f) +
155bdd1243dSDimitry Andric           ": cannot link object files with different floating-point ABI from " +
156bdd1243dSDimitry Andric           toString(ctx.objectFiles[0]));
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric     if ((eflags & EF_RISCV_RVE) != (target & EF_RISCV_RVE))
1590b57cec5SDimitry Andric       error(toString(f) +
1600b57cec5SDimitry Andric             ": cannot link object files with different EF_RISCV_RVE");
1610b57cec5SDimitry Andric   }
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric   return target;
1640b57cec5SDimitry Andric }
1650b57cec5SDimitry Andric 
166fe6060f1SDimitry Andric int64_t RISCV::getImplicitAddend(const uint8_t *buf, RelType type) const {
167fe6060f1SDimitry Andric   switch (type) {
168fe6060f1SDimitry Andric   default:
169fe6060f1SDimitry Andric     internalLinkerError(getErrorLocation(buf),
170fe6060f1SDimitry Andric                         "cannot read addend for relocation " + toString(type));
171fe6060f1SDimitry Andric     return 0;
172fe6060f1SDimitry Andric   case R_RISCV_32:
173fe6060f1SDimitry Andric   case R_RISCV_TLS_DTPMOD32:
174fe6060f1SDimitry Andric   case R_RISCV_TLS_DTPREL32:
175bdd1243dSDimitry Andric   case R_RISCV_TLS_TPREL32:
176fe6060f1SDimitry Andric     return SignExtend64<32>(read32le(buf));
177fe6060f1SDimitry Andric   case R_RISCV_64:
178bdd1243dSDimitry Andric   case R_RISCV_TLS_DTPMOD64:
179bdd1243dSDimitry Andric   case R_RISCV_TLS_DTPREL64:
180bdd1243dSDimitry Andric   case R_RISCV_TLS_TPREL64:
181fe6060f1SDimitry Andric     return read64le(buf);
182fe6060f1SDimitry Andric   case R_RISCV_RELATIVE:
183fe6060f1SDimitry Andric   case R_RISCV_IRELATIVE:
184fe6060f1SDimitry Andric     return config->is64 ? read64le(buf) : read32le(buf);
185fe6060f1SDimitry Andric   case R_RISCV_NONE:
186fe6060f1SDimitry Andric   case R_RISCV_JUMP_SLOT:
187fe6060f1SDimitry Andric     // These relocations are defined as not having an implicit addend.
188fe6060f1SDimitry Andric     return 0;
189fe6060f1SDimitry Andric   }
190fe6060f1SDimitry Andric }
191fe6060f1SDimitry Andric 
1920b57cec5SDimitry Andric void RISCV::writeGotHeader(uint8_t *buf) const {
1930b57cec5SDimitry Andric   if (config->is64)
1940b57cec5SDimitry Andric     write64le(buf, mainPart->dynamic->getVA());
1950b57cec5SDimitry Andric   else
1960b57cec5SDimitry Andric     write32le(buf, mainPart->dynamic->getVA());
1970b57cec5SDimitry Andric }
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric void RISCV::writeGotPlt(uint8_t *buf, const Symbol &s) const {
2000b57cec5SDimitry Andric   if (config->is64)
2010b57cec5SDimitry Andric     write64le(buf, in.plt->getVA());
2020b57cec5SDimitry Andric   else
2030b57cec5SDimitry Andric     write32le(buf, in.plt->getVA());
2040b57cec5SDimitry Andric }
2050b57cec5SDimitry Andric 
206fe6060f1SDimitry Andric void RISCV::writeIgotPlt(uint8_t *buf, const Symbol &s) const {
207fe6060f1SDimitry Andric   if (config->writeAddends) {
208fe6060f1SDimitry Andric     if (config->is64)
209fe6060f1SDimitry Andric       write64le(buf, s.getVA());
210fe6060f1SDimitry Andric     else
211fe6060f1SDimitry Andric       write32le(buf, s.getVA());
212fe6060f1SDimitry Andric   }
213fe6060f1SDimitry Andric }
214fe6060f1SDimitry Andric 
2150b57cec5SDimitry Andric void RISCV::writePltHeader(uint8_t *buf) const {
2160b57cec5SDimitry Andric   // 1: auipc t2, %pcrel_hi(.got.plt)
2170b57cec5SDimitry Andric   // sub t1, t1, t3
2180b57cec5SDimitry Andric   // l[wd] t3, %pcrel_lo(1b)(t2); t3 = _dl_runtime_resolve
2190b57cec5SDimitry Andric   // addi t1, t1, -pltHeaderSize-12; t1 = &.plt[i] - &.plt[0]
2200b57cec5SDimitry Andric   // addi t0, t2, %pcrel_lo(1b)
2210b57cec5SDimitry Andric   // srli t1, t1, (rv64?1:2); t1 = &.got.plt[i] - &.got.plt[0]
2220b57cec5SDimitry Andric   // l[wd] t0, Wordsize(t0); t0 = link_map
2230b57cec5SDimitry Andric   // jr t3
2240b57cec5SDimitry Andric   uint32_t offset = in.gotPlt->getVA() - in.plt->getVA();
2250b57cec5SDimitry Andric   uint32_t load = config->is64 ? LD : LW;
2260b57cec5SDimitry Andric   write32le(buf + 0, utype(AUIPC, X_T2, hi20(offset)));
2270b57cec5SDimitry Andric   write32le(buf + 4, rtype(SUB, X_T1, X_T1, X_T3));
2280b57cec5SDimitry Andric   write32le(buf + 8, itype(load, X_T3, X_T2, lo12(offset)));
2290b57cec5SDimitry Andric   write32le(buf + 12, itype(ADDI, X_T1, X_T1, -target->pltHeaderSize - 12));
2300b57cec5SDimitry Andric   write32le(buf + 16, itype(ADDI, X_T0, X_T2, lo12(offset)));
2310b57cec5SDimitry Andric   write32le(buf + 20, itype(SRLI, X_T1, X_T1, config->is64 ? 1 : 2));
2320b57cec5SDimitry Andric   write32le(buf + 24, itype(load, X_T0, X_T0, config->wordsize));
2330b57cec5SDimitry Andric   write32le(buf + 28, itype(JALR, 0, X_T3, 0));
2340b57cec5SDimitry Andric }
2350b57cec5SDimitry Andric 
236480093f4SDimitry Andric void RISCV::writePlt(uint8_t *buf, const Symbol &sym,
237480093f4SDimitry Andric                      uint64_t pltEntryAddr) const {
2380b57cec5SDimitry Andric   // 1: auipc t3, %pcrel_hi(f@.got.plt)
2390b57cec5SDimitry Andric   // l[wd] t3, %pcrel_lo(1b)(t3)
2400b57cec5SDimitry Andric   // jalr t1, t3
2410b57cec5SDimitry Andric   // nop
242480093f4SDimitry Andric   uint32_t offset = sym.getGotPltVA() - pltEntryAddr;
2430b57cec5SDimitry Andric   write32le(buf + 0, utype(AUIPC, X_T3, hi20(offset)));
2440b57cec5SDimitry Andric   write32le(buf + 4, itype(config->is64 ? LD : LW, X_T3, X_T3, lo12(offset)));
2450b57cec5SDimitry Andric   write32le(buf + 8, itype(JALR, X_T1, X_T3, 0));
2460b57cec5SDimitry Andric   write32le(buf + 12, itype(ADDI, 0, 0, 0));
2470b57cec5SDimitry Andric }
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric RelType RISCV::getDynRel(RelType type) const {
2500b57cec5SDimitry Andric   return type == target->symbolicRel ? type
2510b57cec5SDimitry Andric                                      : static_cast<RelType>(R_RISCV_NONE);
2520b57cec5SDimitry Andric }
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric RelExpr RISCV::getRelExpr(const RelType type, const Symbol &s,
2550b57cec5SDimitry Andric                           const uint8_t *loc) const {
2560b57cec5SDimitry Andric   switch (type) {
257480093f4SDimitry Andric   case R_RISCV_NONE:
258480093f4SDimitry Andric     return R_NONE;
259480093f4SDimitry Andric   case R_RISCV_32:
260480093f4SDimitry Andric   case R_RISCV_64:
261480093f4SDimitry Andric   case R_RISCV_HI20:
262480093f4SDimitry Andric   case R_RISCV_LO12_I:
263480093f4SDimitry Andric   case R_RISCV_LO12_S:
264480093f4SDimitry Andric   case R_RISCV_RVC_LUI:
265480093f4SDimitry Andric     return R_ABS;
2660b57cec5SDimitry Andric   case R_RISCV_ADD8:
2670b57cec5SDimitry Andric   case R_RISCV_ADD16:
2680b57cec5SDimitry Andric   case R_RISCV_ADD32:
2690b57cec5SDimitry Andric   case R_RISCV_ADD64:
2700b57cec5SDimitry Andric   case R_RISCV_SET6:
2710b57cec5SDimitry Andric   case R_RISCV_SET8:
2720b57cec5SDimitry Andric   case R_RISCV_SET16:
2730b57cec5SDimitry Andric   case R_RISCV_SET32:
2740b57cec5SDimitry Andric   case R_RISCV_SUB6:
2750b57cec5SDimitry Andric   case R_RISCV_SUB8:
2760b57cec5SDimitry Andric   case R_RISCV_SUB16:
2770b57cec5SDimitry Andric   case R_RISCV_SUB32:
2780b57cec5SDimitry Andric   case R_RISCV_SUB64:
2790b57cec5SDimitry Andric     return R_RISCV_ADD;
2800b57cec5SDimitry Andric   case R_RISCV_JAL:
2810b57cec5SDimitry Andric   case R_RISCV_BRANCH:
2820b57cec5SDimitry Andric   case R_RISCV_PCREL_HI20:
2830b57cec5SDimitry Andric   case R_RISCV_RVC_BRANCH:
2840b57cec5SDimitry Andric   case R_RISCV_RVC_JUMP:
2850b57cec5SDimitry Andric   case R_RISCV_32_PCREL:
2860b57cec5SDimitry Andric     return R_PC;
2870b57cec5SDimitry Andric   case R_RISCV_CALL:
2880b57cec5SDimitry Andric   case R_RISCV_CALL_PLT:
28906c3fb27SDimitry Andric   case R_RISCV_PLT32:
2900b57cec5SDimitry Andric     return R_PLT_PC;
2910b57cec5SDimitry Andric   case R_RISCV_GOT_HI20:
2920b57cec5SDimitry Andric     return R_GOT_PC;
2930b57cec5SDimitry Andric   case R_RISCV_PCREL_LO12_I:
2940b57cec5SDimitry Andric   case R_RISCV_PCREL_LO12_S:
2950b57cec5SDimitry Andric     return R_RISCV_PC_INDIRECT;
2960b57cec5SDimitry Andric   case R_RISCV_TLS_GD_HI20:
2970b57cec5SDimitry Andric     return R_TLSGD_PC;
2980b57cec5SDimitry Andric   case R_RISCV_TLS_GOT_HI20:
2990b57cec5SDimitry Andric     return R_GOT_PC;
3000b57cec5SDimitry Andric   case R_RISCV_TPREL_HI20:
3010b57cec5SDimitry Andric   case R_RISCV_TPREL_LO12_I:
3020b57cec5SDimitry Andric   case R_RISCV_TPREL_LO12_S:
303e8d8bef9SDimitry Andric     return R_TPREL;
30455e4f9d5SDimitry Andric   case R_RISCV_ALIGN:
305753f127fSDimitry Andric     return R_RELAX_HINT;
306fcaf7f86SDimitry Andric   case R_RISCV_TPREL_ADD:
307753f127fSDimitry Andric   case R_RISCV_RELAX:
308753f127fSDimitry Andric     return config->relax ? R_RELAX_HINT : R_NONE;
309*5f757f3fSDimitry Andric   case R_RISCV_SET_ULEB128:
310*5f757f3fSDimitry Andric     return R_RISCV_LEB128;
3110b57cec5SDimitry Andric   default:
312480093f4SDimitry Andric     error(getErrorLocation(loc) + "unknown relocation (" + Twine(type) +
313480093f4SDimitry Andric           ") against symbol " + toString(s));
314480093f4SDimitry Andric     return R_NONE;
3150b57cec5SDimitry Andric   }
3160b57cec5SDimitry Andric }
3170b57cec5SDimitry Andric 
3185ffd83dbSDimitry Andric void RISCV::relocate(uint8_t *loc, const Relocation &rel, uint64_t val) const {
3190b57cec5SDimitry Andric   const unsigned bits = config->wordsize * 8;
3200b57cec5SDimitry Andric 
3215ffd83dbSDimitry Andric   switch (rel.type) {
3220b57cec5SDimitry Andric   case R_RISCV_32:
3230b57cec5SDimitry Andric     write32le(loc, val);
3240b57cec5SDimitry Andric     return;
3250b57cec5SDimitry Andric   case R_RISCV_64:
3260b57cec5SDimitry Andric     write64le(loc, val);
3270b57cec5SDimitry Andric     return;
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric   case R_RISCV_RVC_BRANCH: {
330753f127fSDimitry Andric     checkInt(loc, val, 9, rel);
3315ffd83dbSDimitry Andric     checkAlignment(loc, val, 2, rel);
3320b57cec5SDimitry Andric     uint16_t insn = read16le(loc) & 0xE383;
3330b57cec5SDimitry Andric     uint16_t imm8 = extractBits(val, 8, 8) << 12;
3340b57cec5SDimitry Andric     uint16_t imm4_3 = extractBits(val, 4, 3) << 10;
3350b57cec5SDimitry Andric     uint16_t imm7_6 = extractBits(val, 7, 6) << 5;
3360b57cec5SDimitry Andric     uint16_t imm2_1 = extractBits(val, 2, 1) << 3;
3370b57cec5SDimitry Andric     uint16_t imm5 = extractBits(val, 5, 5) << 2;
3380b57cec5SDimitry Andric     insn |= imm8 | imm4_3 | imm7_6 | imm2_1 | imm5;
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric     write16le(loc, insn);
3410b57cec5SDimitry Andric     return;
3420b57cec5SDimitry Andric   }
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric   case R_RISCV_RVC_JUMP: {
345753f127fSDimitry Andric     checkInt(loc, val, 12, rel);
3465ffd83dbSDimitry Andric     checkAlignment(loc, val, 2, rel);
3470b57cec5SDimitry Andric     uint16_t insn = read16le(loc) & 0xE003;
3480b57cec5SDimitry Andric     uint16_t imm11 = extractBits(val, 11, 11) << 12;
3490b57cec5SDimitry Andric     uint16_t imm4 = extractBits(val, 4, 4) << 11;
3500b57cec5SDimitry Andric     uint16_t imm9_8 = extractBits(val, 9, 8) << 9;
3510b57cec5SDimitry Andric     uint16_t imm10 = extractBits(val, 10, 10) << 8;
3520b57cec5SDimitry Andric     uint16_t imm6 = extractBits(val, 6, 6) << 7;
3530b57cec5SDimitry Andric     uint16_t imm7 = extractBits(val, 7, 7) << 6;
3540b57cec5SDimitry Andric     uint16_t imm3_1 = extractBits(val, 3, 1) << 3;
3550b57cec5SDimitry Andric     uint16_t imm5 = extractBits(val, 5, 5) << 2;
3560b57cec5SDimitry Andric     insn |= imm11 | imm4 | imm9_8 | imm10 | imm6 | imm7 | imm3_1 | imm5;
3570b57cec5SDimitry Andric 
3580b57cec5SDimitry Andric     write16le(loc, insn);
3590b57cec5SDimitry Andric     return;
3600b57cec5SDimitry Andric   }
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric   case R_RISCV_RVC_LUI: {
3630b57cec5SDimitry Andric     int64_t imm = SignExtend64(val + 0x800, bits) >> 12;
3645ffd83dbSDimitry Andric     checkInt(loc, imm, 6, rel);
3650b57cec5SDimitry Andric     if (imm == 0) { // `c.lui rd, 0` is illegal, convert to `c.li rd, 0`
3660b57cec5SDimitry Andric       write16le(loc, (read16le(loc) & 0x0F83) | 0x4000);
3670b57cec5SDimitry Andric     } else {
3680b57cec5SDimitry Andric       uint16_t imm17 = extractBits(val + 0x800, 17, 17) << 12;
3690b57cec5SDimitry Andric       uint16_t imm16_12 = extractBits(val + 0x800, 16, 12) << 2;
3700b57cec5SDimitry Andric       write16le(loc, (read16le(loc) & 0xEF83) | imm17 | imm16_12);
3710b57cec5SDimitry Andric     }
3720b57cec5SDimitry Andric     return;
3730b57cec5SDimitry Andric   }
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric   case R_RISCV_JAL: {
376753f127fSDimitry Andric     checkInt(loc, val, 21, rel);
3775ffd83dbSDimitry Andric     checkAlignment(loc, val, 2, rel);
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric     uint32_t insn = read32le(loc) & 0xFFF;
3800b57cec5SDimitry Andric     uint32_t imm20 = extractBits(val, 20, 20) << 31;
3810b57cec5SDimitry Andric     uint32_t imm10_1 = extractBits(val, 10, 1) << 21;
3820b57cec5SDimitry Andric     uint32_t imm11 = extractBits(val, 11, 11) << 20;
3830b57cec5SDimitry Andric     uint32_t imm19_12 = extractBits(val, 19, 12) << 12;
3840b57cec5SDimitry Andric     insn |= imm20 | imm10_1 | imm11 | imm19_12;
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric     write32le(loc, insn);
3870b57cec5SDimitry Andric     return;
3880b57cec5SDimitry Andric   }
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric   case R_RISCV_BRANCH: {
391753f127fSDimitry Andric     checkInt(loc, val, 13, rel);
3925ffd83dbSDimitry Andric     checkAlignment(loc, val, 2, rel);
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric     uint32_t insn = read32le(loc) & 0x1FFF07F;
3950b57cec5SDimitry Andric     uint32_t imm12 = extractBits(val, 12, 12) << 31;
3960b57cec5SDimitry Andric     uint32_t imm10_5 = extractBits(val, 10, 5) << 25;
3970b57cec5SDimitry Andric     uint32_t imm4_1 = extractBits(val, 4, 1) << 8;
3980b57cec5SDimitry Andric     uint32_t imm11 = extractBits(val, 11, 11) << 7;
3990b57cec5SDimitry Andric     insn |= imm12 | imm10_5 | imm4_1 | imm11;
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric     write32le(loc, insn);
4020b57cec5SDimitry Andric     return;
4030b57cec5SDimitry Andric   }
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric   // auipc + jalr pair
4060b57cec5SDimitry Andric   case R_RISCV_CALL:
4070b57cec5SDimitry Andric   case R_RISCV_CALL_PLT: {
4080b57cec5SDimitry Andric     int64_t hi = SignExtend64(val + 0x800, bits) >> 12;
4095ffd83dbSDimitry Andric     checkInt(loc, hi, 20, rel);
4100b57cec5SDimitry Andric     if (isInt<20>(hi)) {
4115ffd83dbSDimitry Andric       relocateNoSym(loc, R_RISCV_PCREL_HI20, val);
4125ffd83dbSDimitry Andric       relocateNoSym(loc + 4, R_RISCV_PCREL_LO12_I, val);
4130b57cec5SDimitry Andric     }
4140b57cec5SDimitry Andric     return;
4150b57cec5SDimitry Andric   }
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric   case R_RISCV_GOT_HI20:
4180b57cec5SDimitry Andric   case R_RISCV_PCREL_HI20:
4190b57cec5SDimitry Andric   case R_RISCV_TLS_GD_HI20:
4200b57cec5SDimitry Andric   case R_RISCV_TLS_GOT_HI20:
4210b57cec5SDimitry Andric   case R_RISCV_TPREL_HI20:
4220b57cec5SDimitry Andric   case R_RISCV_HI20: {
4230b57cec5SDimitry Andric     uint64_t hi = val + 0x800;
4245ffd83dbSDimitry Andric     checkInt(loc, SignExtend64(hi, bits) >> 12, 20, rel);
4250b57cec5SDimitry Andric     write32le(loc, (read32le(loc) & 0xFFF) | (hi & 0xFFFFF000));
4260b57cec5SDimitry Andric     return;
4270b57cec5SDimitry Andric   }
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric   case R_RISCV_PCREL_LO12_I:
4300b57cec5SDimitry Andric   case R_RISCV_TPREL_LO12_I:
4310b57cec5SDimitry Andric   case R_RISCV_LO12_I: {
4320b57cec5SDimitry Andric     uint64_t hi = (val + 0x800) >> 12;
4330b57cec5SDimitry Andric     uint64_t lo = val - (hi << 12);
434fcaf7f86SDimitry Andric     write32le(loc, setLO12_I(read32le(loc), lo & 0xfff));
4350b57cec5SDimitry Andric     return;
4360b57cec5SDimitry Andric   }
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric   case R_RISCV_PCREL_LO12_S:
4390b57cec5SDimitry Andric   case R_RISCV_TPREL_LO12_S:
4400b57cec5SDimitry Andric   case R_RISCV_LO12_S: {
4410b57cec5SDimitry Andric     uint64_t hi = (val + 0x800) >> 12;
4420b57cec5SDimitry Andric     uint64_t lo = val - (hi << 12);
443fcaf7f86SDimitry Andric     write32le(loc, setLO12_S(read32le(loc), lo));
4440b57cec5SDimitry Andric     return;
4450b57cec5SDimitry Andric   }
4460b57cec5SDimitry Andric 
44706c3fb27SDimitry Andric   case INTERNAL_R_RISCV_GPREL_I:
44806c3fb27SDimitry Andric   case INTERNAL_R_RISCV_GPREL_S: {
44906c3fb27SDimitry Andric     Defined *gp = ElfSym::riscvGlobalPointer;
45006c3fb27SDimitry Andric     int64_t displace = SignExtend64(val - gp->getVA(), bits);
45106c3fb27SDimitry Andric     checkInt(loc, displace, 12, rel);
45206c3fb27SDimitry Andric     uint32_t insn = (read32le(loc) & ~(31 << 15)) | (X_GP << 15);
45306c3fb27SDimitry Andric     if (rel.type == INTERNAL_R_RISCV_GPREL_I)
45406c3fb27SDimitry Andric       insn = setLO12_I(insn, displace);
45506c3fb27SDimitry Andric     else
45606c3fb27SDimitry Andric       insn = setLO12_S(insn, displace);
45706c3fb27SDimitry Andric     write32le(loc, insn);
45806c3fb27SDimitry Andric     return;
45906c3fb27SDimitry Andric   }
46006c3fb27SDimitry Andric 
4610b57cec5SDimitry Andric   case R_RISCV_ADD8:
4620b57cec5SDimitry Andric     *loc += val;
4630b57cec5SDimitry Andric     return;
4640b57cec5SDimitry Andric   case R_RISCV_ADD16:
4650b57cec5SDimitry Andric     write16le(loc, read16le(loc) + val);
4660b57cec5SDimitry Andric     return;
4670b57cec5SDimitry Andric   case R_RISCV_ADD32:
4680b57cec5SDimitry Andric     write32le(loc, read32le(loc) + val);
4690b57cec5SDimitry Andric     return;
4700b57cec5SDimitry Andric   case R_RISCV_ADD64:
4710b57cec5SDimitry Andric     write64le(loc, read64le(loc) + val);
4720b57cec5SDimitry Andric     return;
4730b57cec5SDimitry Andric   case R_RISCV_SUB6:
4740b57cec5SDimitry Andric     *loc = (*loc & 0xc0) | (((*loc & 0x3f) - val) & 0x3f);
4750b57cec5SDimitry Andric     return;
4760b57cec5SDimitry Andric   case R_RISCV_SUB8:
4770b57cec5SDimitry Andric     *loc -= val;
4780b57cec5SDimitry Andric     return;
4790b57cec5SDimitry Andric   case R_RISCV_SUB16:
4800b57cec5SDimitry Andric     write16le(loc, read16le(loc) - val);
4810b57cec5SDimitry Andric     return;
4820b57cec5SDimitry Andric   case R_RISCV_SUB32:
4830b57cec5SDimitry Andric     write32le(loc, read32le(loc) - val);
4840b57cec5SDimitry Andric     return;
4850b57cec5SDimitry Andric   case R_RISCV_SUB64:
4860b57cec5SDimitry Andric     write64le(loc, read64le(loc) - val);
4870b57cec5SDimitry Andric     return;
4880b57cec5SDimitry Andric   case R_RISCV_SET6:
4890b57cec5SDimitry Andric     *loc = (*loc & 0xc0) | (val & 0x3f);
4900b57cec5SDimitry Andric     return;
4910b57cec5SDimitry Andric   case R_RISCV_SET8:
4920b57cec5SDimitry Andric     *loc = val;
4930b57cec5SDimitry Andric     return;
4940b57cec5SDimitry Andric   case R_RISCV_SET16:
4950b57cec5SDimitry Andric     write16le(loc, val);
4960b57cec5SDimitry Andric     return;
4970b57cec5SDimitry Andric   case R_RISCV_SET32:
4980b57cec5SDimitry Andric   case R_RISCV_32_PCREL:
49906c3fb27SDimitry Andric   case R_RISCV_PLT32:
5000b57cec5SDimitry Andric     write32le(loc, val);
5010b57cec5SDimitry Andric     return;
5020b57cec5SDimitry Andric 
5030b57cec5SDimitry Andric   case R_RISCV_TLS_DTPREL32:
5040b57cec5SDimitry Andric     write32le(loc, val - dtpOffset);
5050b57cec5SDimitry Andric     break;
5060b57cec5SDimitry Andric   case R_RISCV_TLS_DTPREL64:
5070b57cec5SDimitry Andric     write64le(loc, val - dtpOffset);
5080b57cec5SDimitry Andric     break;
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric   case R_RISCV_RELAX:
5110b57cec5SDimitry Andric     return; // Ignored (for now)
5120b57cec5SDimitry Andric 
5130b57cec5SDimitry Andric   default:
514480093f4SDimitry Andric     llvm_unreachable("unknown relocation");
5150b57cec5SDimitry Andric   }
5160b57cec5SDimitry Andric }
5170b57cec5SDimitry Andric 
518753f127fSDimitry Andric namespace {
519753f127fSDimitry Andric struct SymbolAnchor {
520753f127fSDimitry Andric   uint64_t offset;
521753f127fSDimitry Andric   Defined *d;
522753f127fSDimitry Andric   bool end; // true for the anchor of st_value+st_size
523753f127fSDimitry Andric };
524753f127fSDimitry Andric } // namespace
525753f127fSDimitry Andric 
526753f127fSDimitry Andric struct elf::RISCVRelaxAux {
527753f127fSDimitry Andric   // This records symbol start and end offsets which will be adjusted according
528753f127fSDimitry Andric   // to the nearest relocDeltas element.
529753f127fSDimitry Andric   SmallVector<SymbolAnchor, 0> anchors;
530753f127fSDimitry Andric   // For relocations[i], the actual offset is r_offset - (i ? relocDeltas[i-1] :
531753f127fSDimitry Andric   // 0).
532753f127fSDimitry Andric   std::unique_ptr<uint32_t[]> relocDeltas;
533753f127fSDimitry Andric   // For relocations[i], the actual type is relocTypes[i].
534753f127fSDimitry Andric   std::unique_ptr<RelType[]> relocTypes;
535753f127fSDimitry Andric   SmallVector<uint32_t, 0> writes;
536753f127fSDimitry Andric };
537753f127fSDimitry Andric 
538753f127fSDimitry Andric static void initSymbolAnchors() {
539753f127fSDimitry Andric   SmallVector<InputSection *, 0> storage;
540753f127fSDimitry Andric   for (OutputSection *osec : outputSections) {
541753f127fSDimitry Andric     if (!(osec->flags & SHF_EXECINSTR))
542753f127fSDimitry Andric       continue;
543753f127fSDimitry Andric     for (InputSection *sec : getInputSections(*osec, storage)) {
544753f127fSDimitry Andric       sec->relaxAux = make<RISCVRelaxAux>();
545bdd1243dSDimitry Andric       if (sec->relocs().size()) {
546753f127fSDimitry Andric         sec->relaxAux->relocDeltas =
547bdd1243dSDimitry Andric             std::make_unique<uint32_t[]>(sec->relocs().size());
548753f127fSDimitry Andric         sec->relaxAux->relocTypes =
549bdd1243dSDimitry Andric             std::make_unique<RelType[]>(sec->relocs().size());
550753f127fSDimitry Andric       }
551753f127fSDimitry Andric     }
552753f127fSDimitry Andric   }
553753f127fSDimitry Andric   // Store anchors (st_value and st_value+st_size) for symbols relative to text
554753f127fSDimitry Andric   // sections.
55506c3fb27SDimitry Andric   //
55606c3fb27SDimitry Andric   // For a defined symbol foo, we may have `d->file != file` with --wrap=foo.
55706c3fb27SDimitry Andric   // We should process foo, as the defining object file's symbol table may not
55806c3fb27SDimitry Andric   // contain foo after redirectSymbols changed the foo entry to __wrap_foo. To
55906c3fb27SDimitry Andric   // avoid adding a Defined that is undefined in one object file, use
56006c3fb27SDimitry Andric   // `!d->scriptDefined` to exclude symbols that are definitely not wrapped.
56106c3fb27SDimitry Andric   //
56206c3fb27SDimitry Andric   // `relaxAux->anchors` may contain duplicate symbols, but that is fine.
563bdd1243dSDimitry Andric   for (InputFile *file : ctx.objectFiles)
564753f127fSDimitry Andric     for (Symbol *sym : file->getSymbols()) {
565753f127fSDimitry Andric       auto *d = dyn_cast<Defined>(sym);
56606c3fb27SDimitry Andric       if (!d || (d->file != file && !d->scriptDefined))
567753f127fSDimitry Andric         continue;
568753f127fSDimitry Andric       if (auto *sec = dyn_cast_or_null<InputSection>(d->section))
569753f127fSDimitry Andric         if (sec->flags & SHF_EXECINSTR && sec->relaxAux) {
570753f127fSDimitry Andric           // If sec is discarded, relaxAux will be nullptr.
571753f127fSDimitry Andric           sec->relaxAux->anchors.push_back({d->value, d, false});
572753f127fSDimitry Andric           sec->relaxAux->anchors.push_back({d->value + d->size, d, true});
573753f127fSDimitry Andric         }
574753f127fSDimitry Andric     }
575753f127fSDimitry Andric   // Sort anchors by offset so that we can find the closest relocation
576753f127fSDimitry Andric   // efficiently. For a zero size symbol, ensure that its start anchor precedes
577753f127fSDimitry Andric   // its end anchor. For two symbols with anchors at the same offset, their
578753f127fSDimitry Andric   // order does not matter.
579753f127fSDimitry Andric   for (OutputSection *osec : outputSections) {
580753f127fSDimitry Andric     if (!(osec->flags & SHF_EXECINSTR))
581753f127fSDimitry Andric       continue;
582753f127fSDimitry Andric     for (InputSection *sec : getInputSections(*osec, storage)) {
583753f127fSDimitry Andric       llvm::sort(sec->relaxAux->anchors, [](auto &a, auto &b) {
584753f127fSDimitry Andric         return std::make_pair(a.offset, a.end) <
585753f127fSDimitry Andric                std::make_pair(b.offset, b.end);
586753f127fSDimitry Andric       });
587753f127fSDimitry Andric     }
588753f127fSDimitry Andric   }
589753f127fSDimitry Andric }
590753f127fSDimitry Andric 
591753f127fSDimitry Andric // Relax R_RISCV_CALL/R_RISCV_CALL_PLT auipc+jalr to c.j, c.jal, or jal.
592753f127fSDimitry Andric static void relaxCall(const InputSection &sec, size_t i, uint64_t loc,
593753f127fSDimitry Andric                       Relocation &r, uint32_t &remove) {
594*5f757f3fSDimitry Andric   const bool rvc = getEFlags(sec.file) & EF_RISCV_RVC;
595753f127fSDimitry Andric   const Symbol &sym = *r.sym;
596bdd1243dSDimitry Andric   const uint64_t insnPair = read64le(sec.content().data() + r.offset);
597753f127fSDimitry Andric   const uint32_t rd = extractBits(insnPair, 32 + 11, 32 + 7);
598753f127fSDimitry Andric   const uint64_t dest =
599753f127fSDimitry Andric       (r.expr == R_PLT_PC ? sym.getPltVA() : sym.getVA()) + r.addend;
600753f127fSDimitry Andric   const int64_t displace = dest - loc;
601753f127fSDimitry Andric 
602753f127fSDimitry Andric   if (rvc && isInt<12>(displace) && rd == 0) {
603753f127fSDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_RVC_JUMP;
604753f127fSDimitry Andric     sec.relaxAux->writes.push_back(0xa001); // c.j
605753f127fSDimitry Andric     remove = 6;
606753f127fSDimitry Andric   } else if (rvc && isInt<12>(displace) && rd == X_RA &&
607753f127fSDimitry Andric              !config->is64) { // RV32C only
608753f127fSDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_RVC_JUMP;
609753f127fSDimitry Andric     sec.relaxAux->writes.push_back(0x2001); // c.jal
610753f127fSDimitry Andric     remove = 6;
611753f127fSDimitry Andric   } else if (isInt<21>(displace)) {
612753f127fSDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_JAL;
613753f127fSDimitry Andric     sec.relaxAux->writes.push_back(0x6f | rd << 7); // jal
614753f127fSDimitry Andric     remove = 4;
615753f127fSDimitry Andric   }
616753f127fSDimitry Andric }
617753f127fSDimitry Andric 
618fcaf7f86SDimitry Andric // Relax local-exec TLS when hi20 is zero.
619fcaf7f86SDimitry Andric static void relaxTlsLe(const InputSection &sec, size_t i, uint64_t loc,
620fcaf7f86SDimitry Andric                        Relocation &r, uint32_t &remove) {
621fcaf7f86SDimitry Andric   uint64_t val = r.sym->getVA(r.addend);
622fcaf7f86SDimitry Andric   if (hi20(val) != 0)
623fcaf7f86SDimitry Andric     return;
624bdd1243dSDimitry Andric   uint32_t insn = read32le(sec.content().data() + r.offset);
625fcaf7f86SDimitry Andric   switch (r.type) {
626fcaf7f86SDimitry Andric   case R_RISCV_TPREL_HI20:
627fcaf7f86SDimitry Andric   case R_RISCV_TPREL_ADD:
628fcaf7f86SDimitry Andric     // Remove lui rd, %tprel_hi(x) and add rd, rd, tp, %tprel_add(x).
629fcaf7f86SDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_RELAX;
630fcaf7f86SDimitry Andric     remove = 4;
631fcaf7f86SDimitry Andric     break;
632fcaf7f86SDimitry Andric   case R_RISCV_TPREL_LO12_I:
633fcaf7f86SDimitry Andric     // addi rd, rd, %tprel_lo(x) => addi rd, tp, st_value(x)
634fcaf7f86SDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_32;
635fcaf7f86SDimitry Andric     insn = (insn & ~(31 << 15)) | (X_TP << 15);
636fcaf7f86SDimitry Andric     sec.relaxAux->writes.push_back(setLO12_I(insn, val));
637fcaf7f86SDimitry Andric     break;
638fcaf7f86SDimitry Andric   case R_RISCV_TPREL_LO12_S:
639fcaf7f86SDimitry Andric     // sw rs, %tprel_lo(x)(rd) => sw rs, st_value(x)(rd)
640fcaf7f86SDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_32;
641fcaf7f86SDimitry Andric     insn = (insn & ~(31 << 15)) | (X_TP << 15);
642fcaf7f86SDimitry Andric     sec.relaxAux->writes.push_back(setLO12_S(insn, val));
643fcaf7f86SDimitry Andric     break;
644fcaf7f86SDimitry Andric   }
645fcaf7f86SDimitry Andric }
646fcaf7f86SDimitry Andric 
64706c3fb27SDimitry Andric static void relaxHi20Lo12(const InputSection &sec, size_t i, uint64_t loc,
64806c3fb27SDimitry Andric                           Relocation &r, uint32_t &remove) {
64906c3fb27SDimitry Andric   const Defined *gp = ElfSym::riscvGlobalPointer;
65006c3fb27SDimitry Andric   if (!gp)
65106c3fb27SDimitry Andric     return;
65206c3fb27SDimitry Andric 
65306c3fb27SDimitry Andric   if (!isInt<12>(r.sym->getVA(r.addend) - gp->getVA()))
65406c3fb27SDimitry Andric     return;
65506c3fb27SDimitry Andric 
65606c3fb27SDimitry Andric   switch (r.type) {
65706c3fb27SDimitry Andric   case R_RISCV_HI20:
65806c3fb27SDimitry Andric     // Remove lui rd, %hi20(x).
65906c3fb27SDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_RELAX;
66006c3fb27SDimitry Andric     remove = 4;
66106c3fb27SDimitry Andric     break;
66206c3fb27SDimitry Andric   case R_RISCV_LO12_I:
66306c3fb27SDimitry Andric     sec.relaxAux->relocTypes[i] = INTERNAL_R_RISCV_GPREL_I;
66406c3fb27SDimitry Andric     break;
66506c3fb27SDimitry Andric   case R_RISCV_LO12_S:
66606c3fb27SDimitry Andric     sec.relaxAux->relocTypes[i] = INTERNAL_R_RISCV_GPREL_S;
66706c3fb27SDimitry Andric     break;
66806c3fb27SDimitry Andric   }
66906c3fb27SDimitry Andric }
67006c3fb27SDimitry Andric 
671753f127fSDimitry Andric static bool relax(InputSection &sec) {
672753f127fSDimitry Andric   const uint64_t secAddr = sec.getVA();
673753f127fSDimitry Andric   auto &aux = *sec.relaxAux;
674753f127fSDimitry Andric   bool changed = false;
675bdd1243dSDimitry Andric   ArrayRef<SymbolAnchor> sa = ArrayRef(aux.anchors);
67606c3fb27SDimitry Andric   uint64_t delta = 0;
677753f127fSDimitry Andric 
678bdd1243dSDimitry Andric   std::fill_n(aux.relocTypes.get(), sec.relocs().size(), R_RISCV_NONE);
679753f127fSDimitry Andric   aux.writes.clear();
680bdd1243dSDimitry Andric   for (auto [i, r] : llvm::enumerate(sec.relocs())) {
681753f127fSDimitry Andric     const uint64_t loc = secAddr + r.offset - delta;
682753f127fSDimitry Andric     uint32_t &cur = aux.relocDeltas[i], remove = 0;
683753f127fSDimitry Andric     switch (r.type) {
684753f127fSDimitry Andric     case R_RISCV_ALIGN: {
685753f127fSDimitry Andric       const uint64_t nextLoc = loc + r.addend;
686753f127fSDimitry Andric       const uint64_t align = PowerOf2Ceil(r.addend + 2);
687753f127fSDimitry Andric       // All bytes beyond the alignment boundary should be removed.
688753f127fSDimitry Andric       remove = nextLoc - ((loc + align - 1) & -align);
689753f127fSDimitry Andric       assert(static_cast<int32_t>(remove) >= 0 &&
690753f127fSDimitry Andric              "R_RISCV_ALIGN needs expanding the content");
691753f127fSDimitry Andric       break;
692753f127fSDimitry Andric     }
693753f127fSDimitry Andric     case R_RISCV_CALL:
694753f127fSDimitry Andric     case R_RISCV_CALL_PLT:
695bdd1243dSDimitry Andric       if (i + 1 != sec.relocs().size() &&
696bdd1243dSDimitry Andric           sec.relocs()[i + 1].type == R_RISCV_RELAX)
697753f127fSDimitry Andric         relaxCall(sec, i, loc, r, remove);
698753f127fSDimitry Andric       break;
699fcaf7f86SDimitry Andric     case R_RISCV_TPREL_HI20:
700fcaf7f86SDimitry Andric     case R_RISCV_TPREL_ADD:
701fcaf7f86SDimitry Andric     case R_RISCV_TPREL_LO12_I:
702fcaf7f86SDimitry Andric     case R_RISCV_TPREL_LO12_S:
703bdd1243dSDimitry Andric       if (i + 1 != sec.relocs().size() &&
704bdd1243dSDimitry Andric           sec.relocs()[i + 1].type == R_RISCV_RELAX)
705fcaf7f86SDimitry Andric         relaxTlsLe(sec, i, loc, r, remove);
706fcaf7f86SDimitry Andric       break;
70706c3fb27SDimitry Andric     case R_RISCV_HI20:
70806c3fb27SDimitry Andric     case R_RISCV_LO12_I:
70906c3fb27SDimitry Andric     case R_RISCV_LO12_S:
71006c3fb27SDimitry Andric       if (i + 1 != sec.relocs().size() &&
71106c3fb27SDimitry Andric           sec.relocs()[i + 1].type == R_RISCV_RELAX)
71206c3fb27SDimitry Andric         relaxHi20Lo12(sec, i, loc, r, remove);
71306c3fb27SDimitry Andric       break;
714753f127fSDimitry Andric     }
715753f127fSDimitry Andric 
716753f127fSDimitry Andric     // For all anchors whose offsets are <= r.offset, they are preceded by
717753f127fSDimitry Andric     // the previous relocation whose `relocDeltas` value equals `delta`.
718753f127fSDimitry Andric     // Decrease their st_value and update their st_size.
719753f127fSDimitry Andric     for (; sa.size() && sa[0].offset <= r.offset; sa = sa.slice(1)) {
720753f127fSDimitry Andric       if (sa[0].end)
721753f127fSDimitry Andric         sa[0].d->size = sa[0].offset - delta - sa[0].d->value;
722753f127fSDimitry Andric       else
72306c3fb27SDimitry Andric         sa[0].d->value = sa[0].offset - delta;
724753f127fSDimitry Andric     }
725753f127fSDimitry Andric     delta += remove;
726753f127fSDimitry Andric     if (delta != cur) {
727753f127fSDimitry Andric       cur = delta;
728753f127fSDimitry Andric       changed = true;
729753f127fSDimitry Andric     }
730753f127fSDimitry Andric   }
731753f127fSDimitry Andric 
732753f127fSDimitry Andric   for (const SymbolAnchor &a : sa) {
733753f127fSDimitry Andric     if (a.end)
734753f127fSDimitry Andric       a.d->size = a.offset - delta - a.d->value;
735753f127fSDimitry Andric     else
73606c3fb27SDimitry Andric       a.d->value = a.offset - delta;
737753f127fSDimitry Andric   }
738753f127fSDimitry Andric   // Inform assignAddresses that the size has changed.
73906c3fb27SDimitry Andric   if (!isUInt<32>(delta))
74006c3fb27SDimitry Andric     fatal("section size decrease is too large: " + Twine(delta));
741753f127fSDimitry Andric   sec.bytesDropped = delta;
742753f127fSDimitry Andric   return changed;
743753f127fSDimitry Andric }
744753f127fSDimitry Andric 
745753f127fSDimitry Andric // When relaxing just R_RISCV_ALIGN, relocDeltas is usually changed only once in
746753f127fSDimitry Andric // the absence of a linker script. For call and load/store R_RISCV_RELAX, code
747753f127fSDimitry Andric // shrinkage may reduce displacement and make more relocations eligible for
748753f127fSDimitry Andric // relaxation. Code shrinkage may increase displacement to a call/load/store
749753f127fSDimitry Andric // target at a higher fixed address, invalidating an earlier relaxation. Any
750753f127fSDimitry Andric // change in section sizes can have cascading effect and require another
751753f127fSDimitry Andric // relaxation pass.
752753f127fSDimitry Andric bool RISCV::relaxOnce(int pass) const {
753753f127fSDimitry Andric   llvm::TimeTraceScope timeScope("RISC-V relaxOnce");
754753f127fSDimitry Andric   if (config->relocatable)
755753f127fSDimitry Andric     return false;
756753f127fSDimitry Andric 
757753f127fSDimitry Andric   if (pass == 0)
758753f127fSDimitry Andric     initSymbolAnchors();
759753f127fSDimitry Andric 
760753f127fSDimitry Andric   SmallVector<InputSection *, 0> storage;
761753f127fSDimitry Andric   bool changed = false;
762753f127fSDimitry Andric   for (OutputSection *osec : outputSections) {
763753f127fSDimitry Andric     if (!(osec->flags & SHF_EXECINSTR))
764753f127fSDimitry Andric       continue;
765753f127fSDimitry Andric     for (InputSection *sec : getInputSections(*osec, storage))
766753f127fSDimitry Andric       changed |= relax(*sec);
767753f127fSDimitry Andric   }
768753f127fSDimitry Andric   return changed;
769753f127fSDimitry Andric }
770753f127fSDimitry Andric 
771753f127fSDimitry Andric void elf::riscvFinalizeRelax(int passes) {
772753f127fSDimitry Andric   llvm::TimeTraceScope timeScope("Finalize RISC-V relaxation");
773753f127fSDimitry Andric   log("relaxation passes: " + Twine(passes));
774753f127fSDimitry Andric   SmallVector<InputSection *, 0> storage;
775753f127fSDimitry Andric   for (OutputSection *osec : outputSections) {
776753f127fSDimitry Andric     if (!(osec->flags & SHF_EXECINSTR))
777753f127fSDimitry Andric       continue;
778753f127fSDimitry Andric     for (InputSection *sec : getInputSections(*osec, storage)) {
779753f127fSDimitry Andric       RISCVRelaxAux &aux = *sec->relaxAux;
780753f127fSDimitry Andric       if (!aux.relocDeltas)
781753f127fSDimitry Andric         continue;
782753f127fSDimitry Andric 
783bdd1243dSDimitry Andric       MutableArrayRef<Relocation> rels = sec->relocs();
784bdd1243dSDimitry Andric       ArrayRef<uint8_t> old = sec->content();
785bdd1243dSDimitry Andric       size_t newSize = old.size() - aux.relocDeltas[rels.size() - 1];
786753f127fSDimitry Andric       size_t writesIdx = 0;
787753f127fSDimitry Andric       uint8_t *p = context().bAlloc.Allocate<uint8_t>(newSize);
788753f127fSDimitry Andric       uint64_t offset = 0;
789753f127fSDimitry Andric       int64_t delta = 0;
790bdd1243dSDimitry Andric       sec->content_ = p;
791bdd1243dSDimitry Andric       sec->size = newSize;
792753f127fSDimitry Andric       sec->bytesDropped = 0;
793753f127fSDimitry Andric 
794753f127fSDimitry Andric       // Update section content: remove NOPs for R_RISCV_ALIGN and rewrite
795753f127fSDimitry Andric       // instructions for relaxed relocations.
796753f127fSDimitry Andric       for (size_t i = 0, e = rels.size(); i != e; ++i) {
797753f127fSDimitry Andric         uint32_t remove = aux.relocDeltas[i] - delta;
798753f127fSDimitry Andric         delta = aux.relocDeltas[i];
799fcaf7f86SDimitry Andric         if (remove == 0 && aux.relocTypes[i] == R_RISCV_NONE)
800753f127fSDimitry Andric           continue;
801753f127fSDimitry Andric 
802753f127fSDimitry Andric         // Copy from last location to the current relocated location.
803753f127fSDimitry Andric         const Relocation &r = rels[i];
804753f127fSDimitry Andric         uint64_t size = r.offset - offset;
805753f127fSDimitry Andric         memcpy(p, old.data() + offset, size);
806753f127fSDimitry Andric         p += size;
807753f127fSDimitry Andric 
808753f127fSDimitry Andric         // For R_RISCV_ALIGN, we will place `offset` in a location (among NOPs)
8096246ae0bSDimitry Andric         // to satisfy the alignment requirement. If both `remove` and r.addend
8106246ae0bSDimitry Andric         // are multiples of 4, it is as if we have skipped some NOPs. Otherwise
8116246ae0bSDimitry Andric         // we are in the middle of a 4-byte NOP, and we need to rewrite the NOP
8126246ae0bSDimitry Andric         // sequence.
813753f127fSDimitry Andric         int64_t skip = 0;
814753f127fSDimitry Andric         if (r.type == R_RISCV_ALIGN) {
8156246ae0bSDimitry Andric           if (remove % 4 || r.addend % 4) {
816753f127fSDimitry Andric             skip = r.addend - remove;
817753f127fSDimitry Andric             int64_t j = 0;
818753f127fSDimitry Andric             for (; j + 4 <= skip; j += 4)
819753f127fSDimitry Andric               write32le(p + j, 0x00000013); // nop
820753f127fSDimitry Andric             if (j != skip) {
821753f127fSDimitry Andric               assert(j + 2 == skip);
822753f127fSDimitry Andric               write16le(p + j, 0x0001); // c.nop
823753f127fSDimitry Andric             }
824753f127fSDimitry Andric           }
825753f127fSDimitry Andric         } else if (RelType newType = aux.relocTypes[i]) {
826753f127fSDimitry Andric           switch (newType) {
82706c3fb27SDimitry Andric           case INTERNAL_R_RISCV_GPREL_I:
82806c3fb27SDimitry Andric           case INTERNAL_R_RISCV_GPREL_S:
82906c3fb27SDimitry Andric             break;
830fcaf7f86SDimitry Andric           case R_RISCV_RELAX:
831fcaf7f86SDimitry Andric             // Used by relaxTlsLe to indicate the relocation is ignored.
832fcaf7f86SDimitry Andric             break;
833753f127fSDimitry Andric           case R_RISCV_RVC_JUMP:
834753f127fSDimitry Andric             skip = 2;
835fcaf7f86SDimitry Andric             write16le(p, aux.writes[writesIdx++]);
836753f127fSDimitry Andric             break;
837753f127fSDimitry Andric           case R_RISCV_JAL:
838753f127fSDimitry Andric             skip = 4;
839fcaf7f86SDimitry Andric             write32le(p, aux.writes[writesIdx++]);
840fcaf7f86SDimitry Andric             break;
841fcaf7f86SDimitry Andric           case R_RISCV_32:
842fcaf7f86SDimitry Andric             // Used by relaxTlsLe to write a uint32_t then suppress the handling
843fcaf7f86SDimitry Andric             // in relocateAlloc.
844fcaf7f86SDimitry Andric             skip = 4;
845fcaf7f86SDimitry Andric             write32le(p, aux.writes[writesIdx++]);
846fcaf7f86SDimitry Andric             aux.relocTypes[i] = R_RISCV_NONE;
847753f127fSDimitry Andric             break;
848753f127fSDimitry Andric           default:
849753f127fSDimitry Andric             llvm_unreachable("unsupported type");
850753f127fSDimitry Andric           }
851753f127fSDimitry Andric         }
852753f127fSDimitry Andric 
853753f127fSDimitry Andric         p += skip;
854753f127fSDimitry Andric         offset = r.offset + skip + remove;
855753f127fSDimitry Andric       }
856753f127fSDimitry Andric       memcpy(p, old.data() + offset, old.size() - offset);
857753f127fSDimitry Andric 
858753f127fSDimitry Andric       // Subtract the previous relocDeltas value from the relocation offset.
859753f127fSDimitry Andric       // For a pair of R_RISCV_CALL/R_RISCV_RELAX with the same offset, decrease
860753f127fSDimitry Andric       // their r_offset by the same delta.
861753f127fSDimitry Andric       delta = 0;
862753f127fSDimitry Andric       for (size_t i = 0, e = rels.size(); i != e;) {
863753f127fSDimitry Andric         uint64_t cur = rels[i].offset;
864753f127fSDimitry Andric         do {
865753f127fSDimitry Andric           rels[i].offset -= delta;
866753f127fSDimitry Andric           if (aux.relocTypes[i] != R_RISCV_NONE)
867753f127fSDimitry Andric             rels[i].type = aux.relocTypes[i];
868753f127fSDimitry Andric         } while (++i != e && rels[i].offset == cur);
869753f127fSDimitry Andric         delta = aux.relocDeltas[i - 1];
870753f127fSDimitry Andric       }
871753f127fSDimitry Andric     }
872753f127fSDimitry Andric   }
873753f127fSDimitry Andric }
874753f127fSDimitry Andric 
875bdd1243dSDimitry Andric namespace {
876bdd1243dSDimitry Andric // Representation of the merged .riscv.attributes input sections. The psABI
877bdd1243dSDimitry Andric // specifies merge policy for attributes. E.g. if we link an object without an
878bdd1243dSDimitry Andric // extension with an object with the extension, the output Tag_RISCV_arch shall
879bdd1243dSDimitry Andric // contain the extension. Some tools like objdump parse .riscv.attributes and
880bdd1243dSDimitry Andric // disabling some instructions if the first Tag_RISCV_arch does not contain an
881bdd1243dSDimitry Andric // extension.
882bdd1243dSDimitry Andric class RISCVAttributesSection final : public SyntheticSection {
883bdd1243dSDimitry Andric public:
884bdd1243dSDimitry Andric   RISCVAttributesSection()
885bdd1243dSDimitry Andric       : SyntheticSection(0, SHT_RISCV_ATTRIBUTES, 1, ".riscv.attributes") {}
886bdd1243dSDimitry Andric 
887bdd1243dSDimitry Andric   size_t getSize() const override { return size; }
888bdd1243dSDimitry Andric   void writeTo(uint8_t *buf) override;
889bdd1243dSDimitry Andric 
890bdd1243dSDimitry Andric   static constexpr StringRef vendor = "riscv";
891bdd1243dSDimitry Andric   DenseMap<unsigned, unsigned> intAttr;
892bdd1243dSDimitry Andric   DenseMap<unsigned, StringRef> strAttr;
893bdd1243dSDimitry Andric   size_t size = 0;
894bdd1243dSDimitry Andric };
895bdd1243dSDimitry Andric } // namespace
896bdd1243dSDimitry Andric 
897bdd1243dSDimitry Andric static void mergeArch(RISCVISAInfo::OrderedExtensionMap &mergedExts,
898bdd1243dSDimitry Andric                       unsigned &mergedXlen, const InputSectionBase *sec,
899bdd1243dSDimitry Andric                       StringRef s) {
9001ac55f4cSDimitry Andric   auto maybeInfo = RISCVISAInfo::parseNormalizedArchString(s);
901bdd1243dSDimitry Andric   if (!maybeInfo) {
902bdd1243dSDimitry Andric     errorOrWarn(toString(sec) + ": " + s + ": " +
903bdd1243dSDimitry Andric                 llvm::toString(maybeInfo.takeError()));
904bdd1243dSDimitry Andric     return;
905bdd1243dSDimitry Andric   }
906bdd1243dSDimitry Andric 
907bdd1243dSDimitry Andric   // Merge extensions.
908bdd1243dSDimitry Andric   RISCVISAInfo &info = **maybeInfo;
909bdd1243dSDimitry Andric   if (mergedExts.empty()) {
910bdd1243dSDimitry Andric     mergedExts = info.getExtensions();
911bdd1243dSDimitry Andric     mergedXlen = info.getXLen();
912bdd1243dSDimitry Andric   } else {
913bdd1243dSDimitry Andric     for (const auto &ext : info.getExtensions()) {
914bdd1243dSDimitry Andric       if (auto it = mergedExts.find(ext.first); it != mergedExts.end()) {
915bdd1243dSDimitry Andric         if (std::tie(it->second.MajorVersion, it->second.MinorVersion) >=
916bdd1243dSDimitry Andric             std::tie(ext.second.MajorVersion, ext.second.MinorVersion))
917bdd1243dSDimitry Andric           continue;
918bdd1243dSDimitry Andric       }
919bdd1243dSDimitry Andric       mergedExts[ext.first] = ext.second;
920bdd1243dSDimitry Andric     }
921bdd1243dSDimitry Andric   }
922bdd1243dSDimitry Andric }
923bdd1243dSDimitry Andric 
924bdd1243dSDimitry Andric static RISCVAttributesSection *
925bdd1243dSDimitry Andric mergeAttributesSection(const SmallVector<InputSectionBase *, 0> &sections) {
926bdd1243dSDimitry Andric   RISCVISAInfo::OrderedExtensionMap exts;
927bdd1243dSDimitry Andric   const InputSectionBase *firstStackAlign = nullptr;
928bdd1243dSDimitry Andric   unsigned firstStackAlignValue = 0, xlen = 0;
929bdd1243dSDimitry Andric   bool hasArch = false;
930bdd1243dSDimitry Andric 
931bdd1243dSDimitry Andric   in.riscvAttributes = std::make_unique<RISCVAttributesSection>();
932bdd1243dSDimitry Andric   auto &merged = static_cast<RISCVAttributesSection &>(*in.riscvAttributes);
933bdd1243dSDimitry Andric 
934bdd1243dSDimitry Andric   // Collect all tags values from attributes section.
935bdd1243dSDimitry Andric   const auto &attributesTags = RISCVAttrs::getRISCVAttributeTags();
936bdd1243dSDimitry Andric   for (const InputSectionBase *sec : sections) {
937bdd1243dSDimitry Andric     RISCVAttributeParser parser;
938*5f757f3fSDimitry Andric     if (Error e = parser.parse(sec->content(), llvm::endianness::little))
939bdd1243dSDimitry Andric       warn(toString(sec) + ": " + llvm::toString(std::move(e)));
940bdd1243dSDimitry Andric     for (const auto &tag : attributesTags) {
941bdd1243dSDimitry Andric       switch (RISCVAttrs::AttrType(tag.attr)) {
942bdd1243dSDimitry Andric         // Integer attributes.
943bdd1243dSDimitry Andric       case RISCVAttrs::STACK_ALIGN:
944bdd1243dSDimitry Andric         if (auto i = parser.getAttributeValue(tag.attr)) {
945bdd1243dSDimitry Andric           auto r = merged.intAttr.try_emplace(tag.attr, *i);
946bdd1243dSDimitry Andric           if (r.second) {
947bdd1243dSDimitry Andric             firstStackAlign = sec;
948bdd1243dSDimitry Andric             firstStackAlignValue = *i;
949bdd1243dSDimitry Andric           } else if (r.first->second != *i) {
950bdd1243dSDimitry Andric             errorOrWarn(toString(sec) + " has stack_align=" + Twine(*i) +
951bdd1243dSDimitry Andric                         " but " + toString(firstStackAlign) +
952bdd1243dSDimitry Andric                         " has stack_align=" + Twine(firstStackAlignValue));
953bdd1243dSDimitry Andric           }
954bdd1243dSDimitry Andric         }
955bdd1243dSDimitry Andric         continue;
956bdd1243dSDimitry Andric       case RISCVAttrs::UNALIGNED_ACCESS:
957bdd1243dSDimitry Andric         if (auto i = parser.getAttributeValue(tag.attr))
958bdd1243dSDimitry Andric           merged.intAttr[tag.attr] |= *i;
959bdd1243dSDimitry Andric         continue;
960bdd1243dSDimitry Andric 
961bdd1243dSDimitry Andric         // String attributes.
962bdd1243dSDimitry Andric       case RISCVAttrs::ARCH:
963bdd1243dSDimitry Andric         if (auto s = parser.getAttributeString(tag.attr)) {
964bdd1243dSDimitry Andric           hasArch = true;
965bdd1243dSDimitry Andric           mergeArch(exts, xlen, sec, *s);
966bdd1243dSDimitry Andric         }
967bdd1243dSDimitry Andric         continue;
968bdd1243dSDimitry Andric 
969bdd1243dSDimitry Andric         // Attributes which use the default handling.
970bdd1243dSDimitry Andric       case RISCVAttrs::PRIV_SPEC:
971bdd1243dSDimitry Andric       case RISCVAttrs::PRIV_SPEC_MINOR:
972bdd1243dSDimitry Andric       case RISCVAttrs::PRIV_SPEC_REVISION:
973bdd1243dSDimitry Andric         break;
974bdd1243dSDimitry Andric       }
975bdd1243dSDimitry Andric 
976bdd1243dSDimitry Andric       // Fallback for deprecated priv_spec* and other unknown attributes: retain
977bdd1243dSDimitry Andric       // the attribute if all input sections agree on the value. GNU ld uses 0
978bdd1243dSDimitry Andric       // and empty strings as default values which are not dumped to the output.
979bdd1243dSDimitry Andric       // TODO Adjust after resolution to
980bdd1243dSDimitry Andric       // https://github.com/riscv-non-isa/riscv-elf-psabi-doc/issues/352
981bdd1243dSDimitry Andric       if (tag.attr % 2 == 0) {
982bdd1243dSDimitry Andric         if (auto i = parser.getAttributeValue(tag.attr)) {
983bdd1243dSDimitry Andric           auto r = merged.intAttr.try_emplace(tag.attr, *i);
984bdd1243dSDimitry Andric           if (!r.second && r.first->second != *i)
985bdd1243dSDimitry Andric             r.first->second = 0;
986bdd1243dSDimitry Andric         }
987bdd1243dSDimitry Andric       } else if (auto s = parser.getAttributeString(tag.attr)) {
988bdd1243dSDimitry Andric         auto r = merged.strAttr.try_emplace(tag.attr, *s);
989bdd1243dSDimitry Andric         if (!r.second && r.first->second != *s)
990bdd1243dSDimitry Andric           r.first->second = {};
991bdd1243dSDimitry Andric       }
992bdd1243dSDimitry Andric     }
993bdd1243dSDimitry Andric   }
994bdd1243dSDimitry Andric 
995bdd1243dSDimitry Andric   if (hasArch) {
996bdd1243dSDimitry Andric     if (auto result = RISCVISAInfo::postProcessAndChecking(
997bdd1243dSDimitry Andric             std::make_unique<RISCVISAInfo>(xlen, exts))) {
998bdd1243dSDimitry Andric       merged.strAttr.try_emplace(RISCVAttrs::ARCH,
999bdd1243dSDimitry Andric                                  saver().save((*result)->toString()));
1000bdd1243dSDimitry Andric     } else {
1001bdd1243dSDimitry Andric       errorOrWarn(llvm::toString(result.takeError()));
1002bdd1243dSDimitry Andric     }
1003bdd1243dSDimitry Andric   }
1004bdd1243dSDimitry Andric 
1005bdd1243dSDimitry Andric   // The total size of headers: format-version [ <section-length> "vendor-name"
1006bdd1243dSDimitry Andric   // [ <file-tag> <size>.
1007bdd1243dSDimitry Andric   size_t size = 5 + merged.vendor.size() + 1 + 5;
1008bdd1243dSDimitry Andric   for (auto &attr : merged.intAttr)
1009bdd1243dSDimitry Andric     if (attr.second != 0)
1010bdd1243dSDimitry Andric       size += getULEB128Size(attr.first) + getULEB128Size(attr.second);
1011bdd1243dSDimitry Andric   for (auto &attr : merged.strAttr)
1012bdd1243dSDimitry Andric     if (!attr.second.empty())
1013bdd1243dSDimitry Andric       size += getULEB128Size(attr.first) + attr.second.size() + 1;
1014bdd1243dSDimitry Andric   merged.size = size;
1015bdd1243dSDimitry Andric   return &merged;
1016bdd1243dSDimitry Andric }
1017bdd1243dSDimitry Andric 
1018bdd1243dSDimitry Andric void RISCVAttributesSection::writeTo(uint8_t *buf) {
1019bdd1243dSDimitry Andric   const size_t size = getSize();
1020bdd1243dSDimitry Andric   uint8_t *const end = buf + size;
1021bdd1243dSDimitry Andric   *buf = ELFAttrs::Format_Version;
1022bdd1243dSDimitry Andric   write32(buf + 1, size - 1);
1023bdd1243dSDimitry Andric   buf += 5;
1024bdd1243dSDimitry Andric 
1025bdd1243dSDimitry Andric   memcpy(buf, vendor.data(), vendor.size());
1026bdd1243dSDimitry Andric   buf += vendor.size() + 1;
1027bdd1243dSDimitry Andric 
1028bdd1243dSDimitry Andric   *buf = ELFAttrs::File;
1029bdd1243dSDimitry Andric   write32(buf + 1, end - buf);
1030bdd1243dSDimitry Andric   buf += 5;
1031bdd1243dSDimitry Andric 
1032bdd1243dSDimitry Andric   for (auto &attr : intAttr) {
1033bdd1243dSDimitry Andric     if (attr.second == 0)
1034bdd1243dSDimitry Andric       continue;
1035bdd1243dSDimitry Andric     buf += encodeULEB128(attr.first, buf);
1036bdd1243dSDimitry Andric     buf += encodeULEB128(attr.second, buf);
1037bdd1243dSDimitry Andric   }
1038bdd1243dSDimitry Andric   for (auto &attr : strAttr) {
1039bdd1243dSDimitry Andric     if (attr.second.empty())
1040bdd1243dSDimitry Andric       continue;
1041bdd1243dSDimitry Andric     buf += encodeULEB128(attr.first, buf);
1042bdd1243dSDimitry Andric     memcpy(buf, attr.second.data(), attr.second.size());
1043bdd1243dSDimitry Andric     buf += attr.second.size() + 1;
1044bdd1243dSDimitry Andric   }
1045bdd1243dSDimitry Andric }
1046bdd1243dSDimitry Andric 
1047bdd1243dSDimitry Andric void elf::mergeRISCVAttributesSections() {
1048bdd1243dSDimitry Andric   // Find the first input SHT_RISCV_ATTRIBUTES; return if not found.
1049bdd1243dSDimitry Andric   size_t place =
1050bdd1243dSDimitry Andric       llvm::find_if(ctx.inputSections,
1051bdd1243dSDimitry Andric                     [](auto *s) { return s->type == SHT_RISCV_ATTRIBUTES; }) -
1052bdd1243dSDimitry Andric       ctx.inputSections.begin();
1053bdd1243dSDimitry Andric   if (place == ctx.inputSections.size())
1054bdd1243dSDimitry Andric     return;
1055bdd1243dSDimitry Andric 
1056bdd1243dSDimitry Andric   // Extract all SHT_RISCV_ATTRIBUTES sections into `sections`.
1057bdd1243dSDimitry Andric   SmallVector<InputSectionBase *, 0> sections;
1058bdd1243dSDimitry Andric   llvm::erase_if(ctx.inputSections, [&](InputSectionBase *s) {
1059bdd1243dSDimitry Andric     if (s->type != SHT_RISCV_ATTRIBUTES)
1060bdd1243dSDimitry Andric       return false;
1061bdd1243dSDimitry Andric     sections.push_back(s);
1062bdd1243dSDimitry Andric     return true;
1063bdd1243dSDimitry Andric   });
1064bdd1243dSDimitry Andric 
1065bdd1243dSDimitry Andric   // Add the merged section.
1066bdd1243dSDimitry Andric   ctx.inputSections.insert(ctx.inputSections.begin() + place,
1067bdd1243dSDimitry Andric                            mergeAttributesSection(sections));
1068bdd1243dSDimitry Andric }
1069bdd1243dSDimitry Andric 
10705ffd83dbSDimitry Andric TargetInfo *elf::getRISCVTargetInfo() {
10710b57cec5SDimitry Andric   static RISCV target;
10720b57cec5SDimitry Andric   return &target;
10730b57cec5SDimitry Andric }
1074