Path: blob/main/contrib/llvm-project/lld/ELF/Arch/RISCV.cpp
34878 views
//===- RISCV.cpp ----------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "InputFiles.h"9#include "OutputSections.h"10#include "Symbols.h"11#include "SyntheticSections.h"12#include "Target.h"13#include "llvm/Support/ELFAttributes.h"14#include "llvm/Support/LEB128.h"15#include "llvm/Support/RISCVAttributeParser.h"16#include "llvm/Support/RISCVAttributes.h"17#include "llvm/Support/TimeProfiler.h"18#include "llvm/TargetParser/RISCVISAInfo.h"1920using namespace llvm;21using namespace llvm::object;22using namespace llvm::support::endian;23using namespace llvm::ELF;24using namespace lld;25using namespace lld::elf;2627namespace {2829class RISCV final : public TargetInfo {30public:31RISCV();32uint32_t calcEFlags() const override;33int64_t getImplicitAddend(const uint8_t *buf, RelType type) const override;34void writeGotHeader(uint8_t *buf) const override;35void writeGotPlt(uint8_t *buf, const Symbol &s) const override;36void writeIgotPlt(uint8_t *buf, const Symbol &s) const override;37void writePltHeader(uint8_t *buf) const override;38void writePlt(uint8_t *buf, const Symbol &sym,39uint64_t pltEntryAddr) const override;40RelType getDynRel(RelType type) const override;41RelExpr getRelExpr(RelType type, const Symbol &s,42const uint8_t *loc) const override;43void relocate(uint8_t *loc, const Relocation &rel,44uint64_t val) const override;45void relocateAlloc(InputSectionBase &sec, uint8_t *buf) const override;46bool relaxOnce(int pass) const override;47void finalizeRelax(int passes) const override;48};4950} // end anonymous namespace5152// These are internal relocation numbers for GP relaxation. They aren't part53// of the psABI spec.54#define INTERNAL_R_RISCV_GPREL_I 25655#define INTERNAL_R_RISCV_GPREL_S 2575657const uint64_t dtpOffset = 0x800;5859namespace {60enum Op {61ADDI = 0x13,62AUIPC = 0x17,63JALR = 0x67,64LD = 0x3003,65LUI = 0x37,66LW = 0x2003,67SRLI = 0x5013,68SUB = 0x40000033,69};7071enum Reg {72X_RA = 1,73X_GP = 3,74X_TP = 4,75X_T0 = 5,76X_T1 = 6,77X_T2 = 7,78X_A0 = 10,79X_T3 = 28,80};81} // namespace8283static uint32_t hi20(uint32_t val) { return (val + 0x800) >> 12; }84static uint32_t lo12(uint32_t val) { return val & 4095; }8586static uint32_t itype(uint32_t op, uint32_t rd, uint32_t rs1, uint32_t imm) {87return op | (rd << 7) | (rs1 << 15) | (imm << 20);88}89static uint32_t rtype(uint32_t op, uint32_t rd, uint32_t rs1, uint32_t rs2) {90return op | (rd << 7) | (rs1 << 15) | (rs2 << 20);91}92static uint32_t utype(uint32_t op, uint32_t rd, uint32_t imm) {93return op | (rd << 7) | (imm << 12);94}9596// Extract bits v[begin:end], where range is inclusive, and begin must be < 63.97static uint32_t extractBits(uint64_t v, uint32_t begin, uint32_t end) {98return (v & ((1ULL << (begin + 1)) - 1)) >> end;99}100101static uint32_t setLO12_I(uint32_t insn, uint32_t imm) {102return (insn & 0xfffff) | (imm << 20);103}104static uint32_t setLO12_S(uint32_t insn, uint32_t imm) {105return (insn & 0x1fff07f) | (extractBits(imm, 11, 5) << 25) |106(extractBits(imm, 4, 0) << 7);107}108109RISCV::RISCV() {110copyRel = R_RISCV_COPY;111pltRel = R_RISCV_JUMP_SLOT;112relativeRel = R_RISCV_RELATIVE;113iRelativeRel = R_RISCV_IRELATIVE;114if (config->is64) {115symbolicRel = R_RISCV_64;116tlsModuleIndexRel = R_RISCV_TLS_DTPMOD64;117tlsOffsetRel = R_RISCV_TLS_DTPREL64;118tlsGotRel = R_RISCV_TLS_TPREL64;119} else {120symbolicRel = R_RISCV_32;121tlsModuleIndexRel = R_RISCV_TLS_DTPMOD32;122tlsOffsetRel = R_RISCV_TLS_DTPREL32;123tlsGotRel = R_RISCV_TLS_TPREL32;124}125gotRel = symbolicRel;126tlsDescRel = R_RISCV_TLSDESC;127128// .got[0] = _DYNAMIC129gotHeaderEntriesNum = 1;130131// .got.plt[0] = _dl_runtime_resolve, .got.plt[1] = link_map132gotPltHeaderEntriesNum = 2;133134pltHeaderSize = 32;135pltEntrySize = 16;136ipltEntrySize = 16;137}138139static uint32_t getEFlags(InputFile *f) {140if (config->is64)141return cast<ObjFile<ELF64LE>>(f)->getObj().getHeader().e_flags;142return cast<ObjFile<ELF32LE>>(f)->getObj().getHeader().e_flags;143}144145uint32_t RISCV::calcEFlags() const {146// If there are only binary input files (from -b binary), use a147// value of 0 for the ELF header flags.148if (ctx.objectFiles.empty())149return 0;150151uint32_t target = getEFlags(ctx.objectFiles.front());152153for (InputFile *f : ctx.objectFiles) {154uint32_t eflags = getEFlags(f);155if (eflags & EF_RISCV_RVC)156target |= EF_RISCV_RVC;157158if ((eflags & EF_RISCV_FLOAT_ABI) != (target & EF_RISCV_FLOAT_ABI))159error(160toString(f) +161": cannot link object files with different floating-point ABI from " +162toString(ctx.objectFiles[0]));163164if ((eflags & EF_RISCV_RVE) != (target & EF_RISCV_RVE))165error(toString(f) +166": cannot link object files with different EF_RISCV_RVE");167}168169return target;170}171172int64_t RISCV::getImplicitAddend(const uint8_t *buf, RelType type) const {173switch (type) {174default:175internalLinkerError(getErrorLocation(buf),176"cannot read addend for relocation " + toString(type));177return 0;178case R_RISCV_32:179case R_RISCV_TLS_DTPMOD32:180case R_RISCV_TLS_DTPREL32:181case R_RISCV_TLS_TPREL32:182return SignExtend64<32>(read32le(buf));183case R_RISCV_64:184case R_RISCV_TLS_DTPMOD64:185case R_RISCV_TLS_DTPREL64:186case R_RISCV_TLS_TPREL64:187return read64le(buf);188case R_RISCV_RELATIVE:189case R_RISCV_IRELATIVE:190return config->is64 ? read64le(buf) : read32le(buf);191case R_RISCV_NONE:192case R_RISCV_JUMP_SLOT:193// These relocations are defined as not having an implicit addend.194return 0;195case R_RISCV_TLSDESC:196return config->is64 ? read64le(buf + 8) : read32le(buf + 4);197}198}199200void RISCV::writeGotHeader(uint8_t *buf) const {201if (config->is64)202write64le(buf, mainPart->dynamic->getVA());203else204write32le(buf, mainPart->dynamic->getVA());205}206207void RISCV::writeGotPlt(uint8_t *buf, const Symbol &s) const {208if (config->is64)209write64le(buf, in.plt->getVA());210else211write32le(buf, in.plt->getVA());212}213214void RISCV::writeIgotPlt(uint8_t *buf, const Symbol &s) const {215if (config->writeAddends) {216if (config->is64)217write64le(buf, s.getVA());218else219write32le(buf, s.getVA());220}221}222223void RISCV::writePltHeader(uint8_t *buf) const {224// 1: auipc t2, %pcrel_hi(.got.plt)225// sub t1, t1, t3226// l[wd] t3, %pcrel_lo(1b)(t2); t3 = _dl_runtime_resolve227// addi t1, t1, -pltHeaderSize-12; t1 = &.plt[i] - &.plt[0]228// addi t0, t2, %pcrel_lo(1b)229// srli t1, t1, (rv64?1:2); t1 = &.got.plt[i] - &.got.plt[0]230// l[wd] t0, Wordsize(t0); t0 = link_map231// jr t3232uint32_t offset = in.gotPlt->getVA() - in.plt->getVA();233uint32_t load = config->is64 ? LD : LW;234write32le(buf + 0, utype(AUIPC, X_T2, hi20(offset)));235write32le(buf + 4, rtype(SUB, X_T1, X_T1, X_T3));236write32le(buf + 8, itype(load, X_T3, X_T2, lo12(offset)));237write32le(buf + 12, itype(ADDI, X_T1, X_T1, -target->pltHeaderSize - 12));238write32le(buf + 16, itype(ADDI, X_T0, X_T2, lo12(offset)));239write32le(buf + 20, itype(SRLI, X_T1, X_T1, config->is64 ? 1 : 2));240write32le(buf + 24, itype(load, X_T0, X_T0, config->wordsize));241write32le(buf + 28, itype(JALR, 0, X_T3, 0));242}243244void RISCV::writePlt(uint8_t *buf, const Symbol &sym,245uint64_t pltEntryAddr) const {246// 1: auipc t3, %pcrel_hi([email protected])247// l[wd] t3, %pcrel_lo(1b)(t3)248// jalr t1, t3249// nop250uint32_t offset = sym.getGotPltVA() - pltEntryAddr;251write32le(buf + 0, utype(AUIPC, X_T3, hi20(offset)));252write32le(buf + 4, itype(config->is64 ? LD : LW, X_T3, X_T3, lo12(offset)));253write32le(buf + 8, itype(JALR, X_T1, X_T3, 0));254write32le(buf + 12, itype(ADDI, 0, 0, 0));255}256257RelType RISCV::getDynRel(RelType type) const {258return type == target->symbolicRel ? type259: static_cast<RelType>(R_RISCV_NONE);260}261262RelExpr RISCV::getRelExpr(const RelType type, const Symbol &s,263const uint8_t *loc) const {264switch (type) {265case R_RISCV_NONE:266return R_NONE;267case R_RISCV_32:268case R_RISCV_64:269case R_RISCV_HI20:270case R_RISCV_LO12_I:271case R_RISCV_LO12_S:272case R_RISCV_RVC_LUI:273return R_ABS;274case R_RISCV_ADD8:275case R_RISCV_ADD16:276case R_RISCV_ADD32:277case R_RISCV_ADD64:278case R_RISCV_SET6:279case R_RISCV_SET8:280case R_RISCV_SET16:281case R_RISCV_SET32:282case R_RISCV_SUB6:283case R_RISCV_SUB8:284case R_RISCV_SUB16:285case R_RISCV_SUB32:286case R_RISCV_SUB64:287return R_RISCV_ADD;288case R_RISCV_JAL:289case R_RISCV_BRANCH:290case R_RISCV_PCREL_HI20:291case R_RISCV_RVC_BRANCH:292case R_RISCV_RVC_JUMP:293case R_RISCV_32_PCREL:294return R_PC;295case R_RISCV_CALL:296case R_RISCV_CALL_PLT:297case R_RISCV_PLT32:298return R_PLT_PC;299case R_RISCV_GOT_HI20:300case R_RISCV_GOT32_PCREL:301return R_GOT_PC;302case R_RISCV_PCREL_LO12_I:303case R_RISCV_PCREL_LO12_S:304return R_RISCV_PC_INDIRECT;305case R_RISCV_TLSDESC_HI20:306case R_RISCV_TLSDESC_LOAD_LO12:307case R_RISCV_TLSDESC_ADD_LO12:308return R_TLSDESC_PC;309case R_RISCV_TLSDESC_CALL:310return R_TLSDESC_CALL;311case R_RISCV_TLS_GD_HI20:312return R_TLSGD_PC;313case R_RISCV_TLS_GOT_HI20:314return R_GOT_PC;315case R_RISCV_TPREL_HI20:316case R_RISCV_TPREL_LO12_I:317case R_RISCV_TPREL_LO12_S:318return R_TPREL;319case R_RISCV_ALIGN:320return R_RELAX_HINT;321case R_RISCV_TPREL_ADD:322case R_RISCV_RELAX:323return config->relax ? R_RELAX_HINT : R_NONE;324case R_RISCV_SET_ULEB128:325case R_RISCV_SUB_ULEB128:326return R_RISCV_LEB128;327default:328error(getErrorLocation(loc) + "unknown relocation (" + Twine(type) +329") against symbol " + toString(s));330return R_NONE;331}332}333334void RISCV::relocate(uint8_t *loc, const Relocation &rel, uint64_t val) const {335const unsigned bits = config->wordsize * 8;336337switch (rel.type) {338case R_RISCV_32:339write32le(loc, val);340return;341case R_RISCV_64:342write64le(loc, val);343return;344345case R_RISCV_RVC_BRANCH: {346checkInt(loc, val, 9, rel);347checkAlignment(loc, val, 2, rel);348uint16_t insn = read16le(loc) & 0xE383;349uint16_t imm8 = extractBits(val, 8, 8) << 12;350uint16_t imm4_3 = extractBits(val, 4, 3) << 10;351uint16_t imm7_6 = extractBits(val, 7, 6) << 5;352uint16_t imm2_1 = extractBits(val, 2, 1) << 3;353uint16_t imm5 = extractBits(val, 5, 5) << 2;354insn |= imm8 | imm4_3 | imm7_6 | imm2_1 | imm5;355356write16le(loc, insn);357return;358}359360case R_RISCV_RVC_JUMP: {361checkInt(loc, val, 12, rel);362checkAlignment(loc, val, 2, rel);363uint16_t insn = read16le(loc) & 0xE003;364uint16_t imm11 = extractBits(val, 11, 11) << 12;365uint16_t imm4 = extractBits(val, 4, 4) << 11;366uint16_t imm9_8 = extractBits(val, 9, 8) << 9;367uint16_t imm10 = extractBits(val, 10, 10) << 8;368uint16_t imm6 = extractBits(val, 6, 6) << 7;369uint16_t imm7 = extractBits(val, 7, 7) << 6;370uint16_t imm3_1 = extractBits(val, 3, 1) << 3;371uint16_t imm5 = extractBits(val, 5, 5) << 2;372insn |= imm11 | imm4 | imm9_8 | imm10 | imm6 | imm7 | imm3_1 | imm5;373374write16le(loc, insn);375return;376}377378case R_RISCV_RVC_LUI: {379int64_t imm = SignExtend64(val + 0x800, bits) >> 12;380checkInt(loc, imm, 6, rel);381if (imm == 0) { // `c.lui rd, 0` is illegal, convert to `c.li rd, 0`382write16le(loc, (read16le(loc) & 0x0F83) | 0x4000);383} else {384uint16_t imm17 = extractBits(val + 0x800, 17, 17) << 12;385uint16_t imm16_12 = extractBits(val + 0x800, 16, 12) << 2;386write16le(loc, (read16le(loc) & 0xEF83) | imm17 | imm16_12);387}388return;389}390391case R_RISCV_JAL: {392checkInt(loc, val, 21, rel);393checkAlignment(loc, val, 2, rel);394395uint32_t insn = read32le(loc) & 0xFFF;396uint32_t imm20 = extractBits(val, 20, 20) << 31;397uint32_t imm10_1 = extractBits(val, 10, 1) << 21;398uint32_t imm11 = extractBits(val, 11, 11) << 20;399uint32_t imm19_12 = extractBits(val, 19, 12) << 12;400insn |= imm20 | imm10_1 | imm11 | imm19_12;401402write32le(loc, insn);403return;404}405406case R_RISCV_BRANCH: {407checkInt(loc, val, 13, rel);408checkAlignment(loc, val, 2, rel);409410uint32_t insn = read32le(loc) & 0x1FFF07F;411uint32_t imm12 = extractBits(val, 12, 12) << 31;412uint32_t imm10_5 = extractBits(val, 10, 5) << 25;413uint32_t imm4_1 = extractBits(val, 4, 1) << 8;414uint32_t imm11 = extractBits(val, 11, 11) << 7;415insn |= imm12 | imm10_5 | imm4_1 | imm11;416417write32le(loc, insn);418return;419}420421// auipc + jalr pair422case R_RISCV_CALL:423case R_RISCV_CALL_PLT: {424int64_t hi = SignExtend64(val + 0x800, bits) >> 12;425checkInt(loc, hi, 20, rel);426if (isInt<20>(hi)) {427relocateNoSym(loc, R_RISCV_PCREL_HI20, val);428relocateNoSym(loc + 4, R_RISCV_PCREL_LO12_I, val);429}430return;431}432433case R_RISCV_GOT_HI20:434case R_RISCV_PCREL_HI20:435case R_RISCV_TLSDESC_HI20:436case R_RISCV_TLS_GD_HI20:437case R_RISCV_TLS_GOT_HI20:438case R_RISCV_TPREL_HI20:439case R_RISCV_HI20: {440uint64_t hi = val + 0x800;441checkInt(loc, SignExtend64(hi, bits) >> 12, 20, rel);442write32le(loc, (read32le(loc) & 0xFFF) | (hi & 0xFFFFF000));443return;444}445446case R_RISCV_PCREL_LO12_I:447case R_RISCV_TLSDESC_LOAD_LO12:448case R_RISCV_TLSDESC_ADD_LO12:449case R_RISCV_TPREL_LO12_I:450case R_RISCV_LO12_I: {451uint64_t hi = (val + 0x800) >> 12;452uint64_t lo = val - (hi << 12);453write32le(loc, setLO12_I(read32le(loc), lo & 0xfff));454return;455}456457case R_RISCV_PCREL_LO12_S:458case R_RISCV_TPREL_LO12_S:459case R_RISCV_LO12_S: {460uint64_t hi = (val + 0x800) >> 12;461uint64_t lo = val - (hi << 12);462write32le(loc, setLO12_S(read32le(loc), lo));463return;464}465466case INTERNAL_R_RISCV_GPREL_I:467case INTERNAL_R_RISCV_GPREL_S: {468Defined *gp = ElfSym::riscvGlobalPointer;469int64_t displace = SignExtend64(val - gp->getVA(), bits);470checkInt(loc, displace, 12, rel);471uint32_t insn = (read32le(loc) & ~(31 << 15)) | (X_GP << 15);472if (rel.type == INTERNAL_R_RISCV_GPREL_I)473insn = setLO12_I(insn, displace);474else475insn = setLO12_S(insn, displace);476write32le(loc, insn);477return;478}479480case R_RISCV_ADD8:481*loc += val;482return;483case R_RISCV_ADD16:484write16le(loc, read16le(loc) + val);485return;486case R_RISCV_ADD32:487write32le(loc, read32le(loc) + val);488return;489case R_RISCV_ADD64:490write64le(loc, read64le(loc) + val);491return;492case R_RISCV_SUB6:493*loc = (*loc & 0xc0) | (((*loc & 0x3f) - val) & 0x3f);494return;495case R_RISCV_SUB8:496*loc -= val;497return;498case R_RISCV_SUB16:499write16le(loc, read16le(loc) - val);500return;501case R_RISCV_SUB32:502write32le(loc, read32le(loc) - val);503return;504case R_RISCV_SUB64:505write64le(loc, read64le(loc) - val);506return;507case R_RISCV_SET6:508*loc = (*loc & 0xc0) | (val & 0x3f);509return;510case R_RISCV_SET8:511*loc = val;512return;513case R_RISCV_SET16:514write16le(loc, val);515return;516case R_RISCV_SET32:517case R_RISCV_32_PCREL:518case R_RISCV_PLT32:519case R_RISCV_GOT32_PCREL:520checkInt(loc, val, 32, rel);521write32le(loc, val);522return;523524case R_RISCV_TLS_DTPREL32:525write32le(loc, val - dtpOffset);526break;527case R_RISCV_TLS_DTPREL64:528write64le(loc, val - dtpOffset);529break;530531case R_RISCV_RELAX:532return;533case R_RISCV_TLSDESC:534// The addend is stored in the second word.535if (config->is64)536write64le(loc + 8, val);537else538write32le(loc + 4, val);539break;540default:541llvm_unreachable("unknown relocation");542}543}544545static bool relaxable(ArrayRef<Relocation> relocs, size_t i) {546return i + 1 != relocs.size() && relocs[i + 1].type == R_RISCV_RELAX;547}548549static void tlsdescToIe(uint8_t *loc, const Relocation &rel, uint64_t val) {550switch (rel.type) {551case R_RISCV_TLSDESC_HI20:552case R_RISCV_TLSDESC_LOAD_LO12:553write32le(loc, 0x00000013); // nop554break;555case R_RISCV_TLSDESC_ADD_LO12:556write32le(loc, utype(AUIPC, X_A0, hi20(val))); // auipc a0,<hi20>557break;558case R_RISCV_TLSDESC_CALL:559if (config->is64)560write32le(loc, itype(LD, X_A0, X_A0, lo12(val))); // ld a0,<lo12>(a0)561else562write32le(loc, itype(LW, X_A0, X_A0, lo12(val))); // lw a0,<lo12>(a0)563break;564default:565llvm_unreachable("unsupported relocation for TLSDESC to IE");566}567}568569static void tlsdescToLe(uint8_t *loc, const Relocation &rel, uint64_t val) {570switch (rel.type) {571case R_RISCV_TLSDESC_HI20:572case R_RISCV_TLSDESC_LOAD_LO12:573write32le(loc, 0x00000013); // nop574return;575case R_RISCV_TLSDESC_ADD_LO12:576if (isInt<12>(val))577write32le(loc, 0x00000013); // nop578else579write32le(loc, utype(LUI, X_A0, hi20(val))); // lui a0,<hi20>580return;581case R_RISCV_TLSDESC_CALL:582if (isInt<12>(val))583write32le(loc, itype(ADDI, X_A0, 0, val)); // addi a0,zero,<lo12>584else585write32le(loc, itype(ADDI, X_A0, X_A0, lo12(val))); // addi a0,a0,<lo12>586return;587default:588llvm_unreachable("unsupported relocation for TLSDESC to LE");589}590}591592void RISCV::relocateAlloc(InputSectionBase &sec, uint8_t *buf) const {593uint64_t secAddr = sec.getOutputSection()->addr;594if (auto *s = dyn_cast<InputSection>(&sec))595secAddr += s->outSecOff;596else if (auto *ehIn = dyn_cast<EhInputSection>(&sec))597secAddr += ehIn->getParent()->outSecOff;598uint64_t tlsdescVal = 0;599bool tlsdescRelax = false, isToLe = false;600const ArrayRef<Relocation> relocs = sec.relocs();601for (size_t i = 0, size = relocs.size(); i != size; ++i) {602const Relocation &rel = relocs[i];603uint8_t *loc = buf + rel.offset;604uint64_t val =605sec.getRelocTargetVA(sec.file, rel.type, rel.addend,606secAddr + rel.offset, *rel.sym, rel.expr);607608switch (rel.expr) {609case R_RELAX_HINT:610continue;611case R_TLSDESC_PC:612// For R_RISCV_TLSDESC_HI20, store &got(sym)-PC to be used by the613// following two instructions L[DW] and ADDI.614if (rel.type == R_RISCV_TLSDESC_HI20)615tlsdescVal = val;616else617val = tlsdescVal;618break;619case R_RELAX_TLS_GD_TO_IE:620// Only R_RISCV_TLSDESC_HI20 reaches here. tlsdescVal will be finalized621// after we see R_RISCV_TLSDESC_ADD_LO12 in the R_RELAX_TLS_GD_TO_LE case.622// The net effect is that tlsdescVal will be smaller than `val` to take623// into account of NOP instructions (in the absence of R_RISCV_RELAX)624// before AUIPC.625tlsdescVal = val + rel.offset;626isToLe = false;627tlsdescRelax = relaxable(relocs, i);628if (!tlsdescRelax)629tlsdescToIe(loc, rel, val);630continue;631case R_RELAX_TLS_GD_TO_LE:632// See the comment in handleTlsRelocation. For TLSDESC=>IE,633// R_RISCV_TLSDESC_{LOAD_LO12,ADD_LO12,CALL} also reach here. If isToLe is634// false, this is actually TLSDESC=>IE optimization.635if (rel.type == R_RISCV_TLSDESC_HI20) {636tlsdescVal = val;637isToLe = true;638tlsdescRelax = relaxable(relocs, i);639} else {640if (!isToLe && rel.type == R_RISCV_TLSDESC_ADD_LO12)641tlsdescVal -= rel.offset;642val = tlsdescVal;643}644// When NOP conversion is eligible and relaxation applies, don't write a645// NOP in case an unrelated instruction follows the current instruction.646if (tlsdescRelax &&647(rel.type == R_RISCV_TLSDESC_HI20 ||648rel.type == R_RISCV_TLSDESC_LOAD_LO12 ||649(rel.type == R_RISCV_TLSDESC_ADD_LO12 && isToLe && !hi20(val))))650continue;651if (isToLe)652tlsdescToLe(loc, rel, val);653else654tlsdescToIe(loc, rel, val);655continue;656case R_RISCV_LEB128:657if (i + 1 < size) {658const Relocation &rel1 = relocs[i + 1];659if (rel.type == R_RISCV_SET_ULEB128 &&660rel1.type == R_RISCV_SUB_ULEB128 && rel.offset == rel1.offset) {661auto val = rel.sym->getVA(rel.addend) - rel1.sym->getVA(rel1.addend);662if (overwriteULEB128(loc, val) >= 0x80)663errorOrWarn(sec.getLocation(rel.offset) + ": ULEB128 value " +664Twine(val) + " exceeds available space; references '" +665lld::toString(*rel.sym) + "'");666++i;667continue;668}669}670errorOrWarn(sec.getLocation(rel.offset) +671": R_RISCV_SET_ULEB128 not paired with R_RISCV_SUB_SET128");672return;673default:674break;675}676relocate(loc, rel, val);677}678}679680void elf::initSymbolAnchors() {681SmallVector<InputSection *, 0> storage;682for (OutputSection *osec : outputSections) {683if (!(osec->flags & SHF_EXECINSTR))684continue;685for (InputSection *sec : getInputSections(*osec, storage)) {686sec->relaxAux = make<RelaxAux>();687if (sec->relocs().size()) {688sec->relaxAux->relocDeltas =689std::make_unique<uint32_t[]>(sec->relocs().size());690sec->relaxAux->relocTypes =691std::make_unique<RelType[]>(sec->relocs().size());692}693}694}695// Store anchors (st_value and st_value+st_size) for symbols relative to text696// sections.697//698// For a defined symbol foo, we may have `d->file != file` with --wrap=foo.699// We should process foo, as the defining object file's symbol table may not700// contain foo after redirectSymbols changed the foo entry to __wrap_foo. To701// avoid adding a Defined that is undefined in one object file, use702// `!d->scriptDefined` to exclude symbols that are definitely not wrapped.703//704// `relaxAux->anchors` may contain duplicate symbols, but that is fine.705for (InputFile *file : ctx.objectFiles)706for (Symbol *sym : file->getSymbols()) {707auto *d = dyn_cast<Defined>(sym);708if (!d || (d->file != file && !d->scriptDefined))709continue;710if (auto *sec = dyn_cast_or_null<InputSection>(d->section))711if (sec->flags & SHF_EXECINSTR && sec->relaxAux) {712// If sec is discarded, relaxAux will be nullptr.713sec->relaxAux->anchors.push_back({d->value, d, false});714sec->relaxAux->anchors.push_back({d->value + d->size, d, true});715}716}717// Sort anchors by offset so that we can find the closest relocation718// efficiently. For a zero size symbol, ensure that its start anchor precedes719// its end anchor. For two symbols with anchors at the same offset, their720// order does not matter.721for (OutputSection *osec : outputSections) {722if (!(osec->flags & SHF_EXECINSTR))723continue;724for (InputSection *sec : getInputSections(*osec, storage)) {725llvm::sort(sec->relaxAux->anchors, [](auto &a, auto &b) {726return std::make_pair(a.offset, a.end) <727std::make_pair(b.offset, b.end);728});729}730}731}732733// Relax R_RISCV_CALL/R_RISCV_CALL_PLT auipc+jalr to c.j, c.jal, or jal.734static void relaxCall(const InputSection &sec, size_t i, uint64_t loc,735Relocation &r, uint32_t &remove) {736const bool rvc = getEFlags(sec.file) & EF_RISCV_RVC;737const Symbol &sym = *r.sym;738const uint64_t insnPair = read64le(sec.content().data() + r.offset);739const uint32_t rd = extractBits(insnPair, 32 + 11, 32 + 7);740const uint64_t dest =741(r.expr == R_PLT_PC ? sym.getPltVA() : sym.getVA()) + r.addend;742const int64_t displace = dest - loc;743744if (rvc && isInt<12>(displace) && rd == 0) {745sec.relaxAux->relocTypes[i] = R_RISCV_RVC_JUMP;746sec.relaxAux->writes.push_back(0xa001); // c.j747remove = 6;748} else if (rvc && isInt<12>(displace) && rd == X_RA &&749!config->is64) { // RV32C only750sec.relaxAux->relocTypes[i] = R_RISCV_RVC_JUMP;751sec.relaxAux->writes.push_back(0x2001); // c.jal752remove = 6;753} else if (isInt<21>(displace)) {754sec.relaxAux->relocTypes[i] = R_RISCV_JAL;755sec.relaxAux->writes.push_back(0x6f | rd << 7); // jal756remove = 4;757}758}759760// Relax local-exec TLS when hi20 is zero.761static void relaxTlsLe(const InputSection &sec, size_t i, uint64_t loc,762Relocation &r, uint32_t &remove) {763uint64_t val = r.sym->getVA(r.addend);764if (hi20(val) != 0)765return;766uint32_t insn = read32le(sec.content().data() + r.offset);767switch (r.type) {768case R_RISCV_TPREL_HI20:769case R_RISCV_TPREL_ADD:770// Remove lui rd, %tprel_hi(x) and add rd, rd, tp, %tprel_add(x).771sec.relaxAux->relocTypes[i] = R_RISCV_RELAX;772remove = 4;773break;774case R_RISCV_TPREL_LO12_I:775// addi rd, rd, %tprel_lo(x) => addi rd, tp, st_value(x)776sec.relaxAux->relocTypes[i] = R_RISCV_32;777insn = (insn & ~(31 << 15)) | (X_TP << 15);778sec.relaxAux->writes.push_back(setLO12_I(insn, val));779break;780case R_RISCV_TPREL_LO12_S:781// sw rs, %tprel_lo(x)(rd) => sw rs, st_value(x)(rd)782sec.relaxAux->relocTypes[i] = R_RISCV_32;783insn = (insn & ~(31 << 15)) | (X_TP << 15);784sec.relaxAux->writes.push_back(setLO12_S(insn, val));785break;786}787}788789static void relaxHi20Lo12(const InputSection &sec, size_t i, uint64_t loc,790Relocation &r, uint32_t &remove) {791const Defined *gp = ElfSym::riscvGlobalPointer;792if (!gp)793return;794795if (!isInt<12>(r.sym->getVA(r.addend) - gp->getVA()))796return;797798switch (r.type) {799case R_RISCV_HI20:800// Remove lui rd, %hi20(x).801sec.relaxAux->relocTypes[i] = R_RISCV_RELAX;802remove = 4;803break;804case R_RISCV_LO12_I:805sec.relaxAux->relocTypes[i] = INTERNAL_R_RISCV_GPREL_I;806break;807case R_RISCV_LO12_S:808sec.relaxAux->relocTypes[i] = INTERNAL_R_RISCV_GPREL_S;809break;810}811}812813static bool relax(InputSection &sec) {814const uint64_t secAddr = sec.getVA();815const MutableArrayRef<Relocation> relocs = sec.relocs();816auto &aux = *sec.relaxAux;817bool changed = false;818ArrayRef<SymbolAnchor> sa = ArrayRef(aux.anchors);819uint64_t delta = 0;820bool tlsdescRelax = false, toLeShortForm = false;821822std::fill_n(aux.relocTypes.get(), relocs.size(), R_RISCV_NONE);823aux.writes.clear();824for (auto [i, r] : llvm::enumerate(relocs)) {825const uint64_t loc = secAddr + r.offset - delta;826uint32_t &cur = aux.relocDeltas[i], remove = 0;827switch (r.type) {828case R_RISCV_ALIGN: {829const uint64_t nextLoc = loc + r.addend;830const uint64_t align = PowerOf2Ceil(r.addend + 2);831// All bytes beyond the alignment boundary should be removed.832remove = nextLoc - ((loc + align - 1) & -align);833// If we can't satisfy this alignment, we've found a bad input.834if (LLVM_UNLIKELY(static_cast<int32_t>(remove) < 0)) {835errorOrWarn(getErrorLocation((const uint8_t*)loc) +836"insufficient padding bytes for " + lld::toString(r.type) +837": " + Twine(r.addend) + " bytes available "838"for requested alignment of " + Twine(align) + " bytes");839remove = 0;840}841break;842}843case R_RISCV_CALL:844case R_RISCV_CALL_PLT:845if (relaxable(relocs, i))846relaxCall(sec, i, loc, r, remove);847break;848case R_RISCV_TPREL_HI20:849case R_RISCV_TPREL_ADD:850case R_RISCV_TPREL_LO12_I:851case R_RISCV_TPREL_LO12_S:852if (relaxable(relocs, i))853relaxTlsLe(sec, i, loc, r, remove);854break;855case R_RISCV_HI20:856case R_RISCV_LO12_I:857case R_RISCV_LO12_S:858if (relaxable(relocs, i))859relaxHi20Lo12(sec, i, loc, r, remove);860break;861case R_RISCV_TLSDESC_HI20:862// For TLSDESC=>LE, we can use the short form if hi20 is zero.863tlsdescRelax = relaxable(relocs, i);864toLeShortForm = tlsdescRelax && r.expr == R_RELAX_TLS_GD_TO_LE &&865!hi20(r.sym->getVA(r.addend));866[[fallthrough]];867case R_RISCV_TLSDESC_LOAD_LO12:868// For TLSDESC=>LE/IE, AUIPC and L[DW] are removed if relaxable.869if (tlsdescRelax && r.expr != R_TLSDESC_PC)870remove = 4;871break;872case R_RISCV_TLSDESC_ADD_LO12:873if (toLeShortForm)874remove = 4;875break;876}877878// For all anchors whose offsets are <= r.offset, they are preceded by879// the previous relocation whose `relocDeltas` value equals `delta`.880// Decrease their st_value and update their st_size.881for (; sa.size() && sa[0].offset <= r.offset; sa = sa.slice(1)) {882if (sa[0].end)883sa[0].d->size = sa[0].offset - delta - sa[0].d->value;884else885sa[0].d->value = sa[0].offset - delta;886}887delta += remove;888if (delta != cur) {889cur = delta;890changed = true;891}892}893894for (const SymbolAnchor &a : sa) {895if (a.end)896a.d->size = a.offset - delta - a.d->value;897else898a.d->value = a.offset - delta;899}900// Inform assignAddresses that the size has changed.901if (!isUInt<32>(delta))902fatal("section size decrease is too large: " + Twine(delta));903sec.bytesDropped = delta;904return changed;905}906907// When relaxing just R_RISCV_ALIGN, relocDeltas is usually changed only once in908// the absence of a linker script. For call and load/store R_RISCV_RELAX, code909// shrinkage may reduce displacement and make more relocations eligible for910// relaxation. Code shrinkage may increase displacement to a call/load/store911// target at a higher fixed address, invalidating an earlier relaxation. Any912// change in section sizes can have cascading effect and require another913// relaxation pass.914bool RISCV::relaxOnce(int pass) const {915llvm::TimeTraceScope timeScope("RISC-V relaxOnce");916if (config->relocatable)917return false;918919if (pass == 0)920initSymbolAnchors();921922SmallVector<InputSection *, 0> storage;923bool changed = false;924for (OutputSection *osec : outputSections) {925if (!(osec->flags & SHF_EXECINSTR))926continue;927for (InputSection *sec : getInputSections(*osec, storage))928changed |= relax(*sec);929}930return changed;931}932933void RISCV::finalizeRelax(int passes) const {934llvm::TimeTraceScope timeScope("Finalize RISC-V relaxation");935log("relaxation passes: " + Twine(passes));936SmallVector<InputSection *, 0> storage;937for (OutputSection *osec : outputSections) {938if (!(osec->flags & SHF_EXECINSTR))939continue;940for (InputSection *sec : getInputSections(*osec, storage)) {941RelaxAux &aux = *sec->relaxAux;942if (!aux.relocDeltas)943continue;944945MutableArrayRef<Relocation> rels = sec->relocs();946ArrayRef<uint8_t> old = sec->content();947size_t newSize = old.size() - aux.relocDeltas[rels.size() - 1];948size_t writesIdx = 0;949uint8_t *p = context().bAlloc.Allocate<uint8_t>(newSize);950uint64_t offset = 0;951int64_t delta = 0;952sec->content_ = p;953sec->size = newSize;954sec->bytesDropped = 0;955956// Update section content: remove NOPs for R_RISCV_ALIGN and rewrite957// instructions for relaxed relocations.958for (size_t i = 0, e = rels.size(); i != e; ++i) {959uint32_t remove = aux.relocDeltas[i] - delta;960delta = aux.relocDeltas[i];961if (remove == 0 && aux.relocTypes[i] == R_RISCV_NONE)962continue;963964// Copy from last location to the current relocated location.965const Relocation &r = rels[i];966uint64_t size = r.offset - offset;967memcpy(p, old.data() + offset, size);968p += size;969970// For R_RISCV_ALIGN, we will place `offset` in a location (among NOPs)971// to satisfy the alignment requirement. If both `remove` and r.addend972// are multiples of 4, it is as if we have skipped some NOPs. Otherwise973// we are in the middle of a 4-byte NOP, and we need to rewrite the NOP974// sequence.975int64_t skip = 0;976if (r.type == R_RISCV_ALIGN) {977if (remove % 4 || r.addend % 4) {978skip = r.addend - remove;979int64_t j = 0;980for (; j + 4 <= skip; j += 4)981write32le(p + j, 0x00000013); // nop982if (j != skip) {983assert(j + 2 == skip);984write16le(p + j, 0x0001); // c.nop985}986}987} else if (RelType newType = aux.relocTypes[i]) {988switch (newType) {989case INTERNAL_R_RISCV_GPREL_I:990case INTERNAL_R_RISCV_GPREL_S:991break;992case R_RISCV_RELAX:993// Used by relaxTlsLe to indicate the relocation is ignored.994break;995case R_RISCV_RVC_JUMP:996skip = 2;997write16le(p, aux.writes[writesIdx++]);998break;999case R_RISCV_JAL:1000skip = 4;1001write32le(p, aux.writes[writesIdx++]);1002break;1003case R_RISCV_32:1004// Used by relaxTlsLe to write a uint32_t then suppress the handling1005// in relocateAlloc.1006skip = 4;1007write32le(p, aux.writes[writesIdx++]);1008aux.relocTypes[i] = R_RISCV_NONE;1009break;1010default:1011llvm_unreachable("unsupported type");1012}1013}10141015p += skip;1016offset = r.offset + skip + remove;1017}1018memcpy(p, old.data() + offset, old.size() - offset);10191020// Subtract the previous relocDeltas value from the relocation offset.1021// For a pair of R_RISCV_CALL/R_RISCV_RELAX with the same offset, decrease1022// their r_offset by the same delta.1023delta = 0;1024for (size_t i = 0, e = rels.size(); i != e;) {1025uint64_t cur = rels[i].offset;1026do {1027rels[i].offset -= delta;1028if (aux.relocTypes[i] != R_RISCV_NONE)1029rels[i].type = aux.relocTypes[i];1030} while (++i != e && rels[i].offset == cur);1031delta = aux.relocDeltas[i - 1];1032}1033}1034}1035}10361037namespace {1038// Representation of the merged .riscv.attributes input sections. The psABI1039// specifies merge policy for attributes. E.g. if we link an object without an1040// extension with an object with the extension, the output Tag_RISCV_arch shall1041// contain the extension. Some tools like objdump parse .riscv.attributes and1042// disabling some instructions if the first Tag_RISCV_arch does not contain an1043// extension.1044class RISCVAttributesSection final : public SyntheticSection {1045public:1046RISCVAttributesSection()1047: SyntheticSection(0, SHT_RISCV_ATTRIBUTES, 1, ".riscv.attributes") {}10481049size_t getSize() const override { return size; }1050void writeTo(uint8_t *buf) override;10511052static constexpr StringRef vendor = "riscv";1053DenseMap<unsigned, unsigned> intAttr;1054DenseMap<unsigned, StringRef> strAttr;1055size_t size = 0;1056};1057} // namespace10581059static void mergeArch(RISCVISAUtils::OrderedExtensionMap &mergedExts,1060unsigned &mergedXlen, const InputSectionBase *sec,1061StringRef s) {1062auto maybeInfo = RISCVISAInfo::parseNormalizedArchString(s);1063if (!maybeInfo) {1064errorOrWarn(toString(sec) + ": " + s + ": " +1065llvm::toString(maybeInfo.takeError()));1066return;1067}10681069// Merge extensions.1070RISCVISAInfo &info = **maybeInfo;1071if (mergedExts.empty()) {1072mergedExts = info.getExtensions();1073mergedXlen = info.getXLen();1074} else {1075for (const auto &ext : info.getExtensions()) {1076auto p = mergedExts.insert(ext);1077if (!p.second) {1078if (std::tie(p.first->second.Major, p.first->second.Minor) <1079std::tie(ext.second.Major, ext.second.Minor))1080p.first->second = ext.second;1081}1082}1083}1084}10851086static void mergeAtomic(DenseMap<unsigned, unsigned>::iterator it,1087const InputSectionBase *oldSection,1088const InputSectionBase *newSection,1089RISCVAttrs::RISCVAtomicAbiTag oldTag,1090RISCVAttrs::RISCVAtomicAbiTag newTag) {1091using RISCVAttrs::RISCVAtomicAbiTag;1092// Same tags stay the same, and UNKNOWN is compatible with anything1093if (oldTag == newTag || newTag == RISCVAtomicAbiTag::UNKNOWN)1094return;10951096auto reportAbiError = [&]() {1097errorOrWarn("atomic abi mismatch for " + oldSection->name + "\n>>> " +1098toString(oldSection) +1099": atomic_abi=" + Twine(static_cast<unsigned>(oldTag)) +1100"\n>>> " + toString(newSection) +1101": atomic_abi=" + Twine(static_cast<unsigned>(newTag)));1102};11031104auto reportUnknownAbiError = [](const InputSectionBase *section,1105RISCVAtomicAbiTag tag) {1106switch (tag) {1107case RISCVAtomicAbiTag::UNKNOWN:1108case RISCVAtomicAbiTag::A6C:1109case RISCVAtomicAbiTag::A6S:1110case RISCVAtomicAbiTag::A7:1111return;1112};1113errorOrWarn("unknown atomic abi for " + section->name + "\n>>> " +1114toString(section) +1115": atomic_abi=" + Twine(static_cast<unsigned>(tag)));1116};1117switch (oldTag) {1118case RISCVAtomicAbiTag::UNKNOWN:1119it->getSecond() = static_cast<unsigned>(newTag);1120return;1121case RISCVAtomicAbiTag::A6C:1122switch (newTag) {1123case RISCVAtomicAbiTag::A6S:1124it->getSecond() = static_cast<unsigned>(RISCVAtomicAbiTag::A6C);1125return;1126case RISCVAtomicAbiTag::A7:1127reportAbiError();1128return;1129case RISCVAttrs::RISCVAtomicAbiTag::UNKNOWN:1130case RISCVAttrs::RISCVAtomicAbiTag::A6C:1131return;1132};1133break;11341135case RISCVAtomicAbiTag::A6S:1136switch (newTag) {1137case RISCVAtomicAbiTag::A6C:1138it->getSecond() = static_cast<unsigned>(RISCVAtomicAbiTag::A6C);1139return;1140case RISCVAtomicAbiTag::A7:1141it->getSecond() = static_cast<unsigned>(RISCVAtomicAbiTag::A7);1142return;1143case RISCVAttrs::RISCVAtomicAbiTag::UNKNOWN:1144case RISCVAttrs::RISCVAtomicAbiTag::A6S:1145return;1146};1147break;11481149case RISCVAtomicAbiTag::A7:1150switch (newTag) {1151case RISCVAtomicAbiTag::A6S:1152it->getSecond() = static_cast<unsigned>(RISCVAtomicAbiTag::A7);1153return;1154case RISCVAtomicAbiTag::A6C:1155reportAbiError();1156return;1157case RISCVAttrs::RISCVAtomicAbiTag::UNKNOWN:1158case RISCVAttrs::RISCVAtomicAbiTag::A7:1159return;1160};1161break;1162};11631164// If we get here, then we have an invalid tag, so report it.1165// Putting these checks at the end allows us to only do these checks when we1166// need to, since this is expected to be a rare occurrence.1167reportUnknownAbiError(oldSection, oldTag);1168reportUnknownAbiError(newSection, newTag);1169}11701171static RISCVAttributesSection *1172mergeAttributesSection(const SmallVector<InputSectionBase *, 0> §ions) {1173using RISCVAttrs::RISCVAtomicAbiTag;1174RISCVISAUtils::OrderedExtensionMap exts;1175const InputSectionBase *firstStackAlign = nullptr;1176const InputSectionBase *firstAtomicAbi = nullptr;1177unsigned firstStackAlignValue = 0, xlen = 0;1178bool hasArch = false;11791180in.riscvAttributes = std::make_unique<RISCVAttributesSection>();1181auto &merged = static_cast<RISCVAttributesSection &>(*in.riscvAttributes);11821183// Collect all tags values from attributes section.1184const auto &attributesTags = RISCVAttrs::getRISCVAttributeTags();1185for (const InputSectionBase *sec : sections) {1186RISCVAttributeParser parser;1187if (Error e = parser.parse(sec->content(), llvm::endianness::little))1188warn(toString(sec) + ": " + llvm::toString(std::move(e)));1189for (const auto &tag : attributesTags) {1190switch (RISCVAttrs::AttrType(tag.attr)) {1191// Integer attributes.1192case RISCVAttrs::STACK_ALIGN:1193if (auto i = parser.getAttributeValue(tag.attr)) {1194auto r = merged.intAttr.try_emplace(tag.attr, *i);1195if (r.second) {1196firstStackAlign = sec;1197firstStackAlignValue = *i;1198} else if (r.first->second != *i) {1199errorOrWarn(toString(sec) + " has stack_align=" + Twine(*i) +1200" but " + toString(firstStackAlign) +1201" has stack_align=" + Twine(firstStackAlignValue));1202}1203}1204continue;1205case RISCVAttrs::UNALIGNED_ACCESS:1206if (auto i = parser.getAttributeValue(tag.attr))1207merged.intAttr[tag.attr] |= *i;1208continue;12091210// String attributes.1211case RISCVAttrs::ARCH:1212if (auto s = parser.getAttributeString(tag.attr)) {1213hasArch = true;1214mergeArch(exts, xlen, sec, *s);1215}1216continue;12171218// Attributes which use the default handling.1219case RISCVAttrs::PRIV_SPEC:1220case RISCVAttrs::PRIV_SPEC_MINOR:1221case RISCVAttrs::PRIV_SPEC_REVISION:1222break;12231224case RISCVAttrs::AttrType::ATOMIC_ABI:1225if (auto i = parser.getAttributeValue(tag.attr)) {1226auto r = merged.intAttr.try_emplace(tag.attr, *i);1227if (r.second)1228firstAtomicAbi = sec;1229else1230mergeAtomic(r.first, firstAtomicAbi, sec,1231static_cast<RISCVAtomicAbiTag>(r.first->getSecond()),1232static_cast<RISCVAtomicAbiTag>(*i));1233}1234continue;1235}12361237// Fallback for deprecated priv_spec* and other unknown attributes: retain1238// the attribute if all input sections agree on the value. GNU ld uses 01239// and empty strings as default values which are not dumped to the output.1240// TODO Adjust after resolution to1241// https://github.com/riscv-non-isa/riscv-elf-psabi-doc/issues/3521242if (tag.attr % 2 == 0) {1243if (auto i = parser.getAttributeValue(tag.attr)) {1244auto r = merged.intAttr.try_emplace(tag.attr, *i);1245if (!r.second && r.first->second != *i)1246r.first->second = 0;1247}1248} else if (auto s = parser.getAttributeString(tag.attr)) {1249auto r = merged.strAttr.try_emplace(tag.attr, *s);1250if (!r.second && r.first->second != *s)1251r.first->second = {};1252}1253}1254}12551256if (hasArch && xlen != 0) {1257if (auto result = RISCVISAInfo::createFromExtMap(xlen, exts)) {1258merged.strAttr.try_emplace(RISCVAttrs::ARCH,1259saver().save((*result)->toString()));1260} else {1261errorOrWarn(llvm::toString(result.takeError()));1262}1263}12641265// The total size of headers: format-version [ <section-length> "vendor-name"1266// [ <file-tag> <size>.1267size_t size = 5 + merged.vendor.size() + 1 + 5;1268for (auto &attr : merged.intAttr)1269if (attr.second != 0)1270size += getULEB128Size(attr.first) + getULEB128Size(attr.second);1271for (auto &attr : merged.strAttr)1272if (!attr.second.empty())1273size += getULEB128Size(attr.first) + attr.second.size() + 1;1274merged.size = size;1275return &merged;1276}12771278void RISCVAttributesSection::writeTo(uint8_t *buf) {1279const size_t size = getSize();1280uint8_t *const end = buf + size;1281*buf = ELFAttrs::Format_Version;1282write32(buf + 1, size - 1);1283buf += 5;12841285memcpy(buf, vendor.data(), vendor.size());1286buf += vendor.size() + 1;12871288*buf = ELFAttrs::File;1289write32(buf + 1, end - buf);1290buf += 5;12911292for (auto &attr : intAttr) {1293if (attr.second == 0)1294continue;1295buf += encodeULEB128(attr.first, buf);1296buf += encodeULEB128(attr.second, buf);1297}1298for (auto &attr : strAttr) {1299if (attr.second.empty())1300continue;1301buf += encodeULEB128(attr.first, buf);1302memcpy(buf, attr.second.data(), attr.second.size());1303buf += attr.second.size() + 1;1304}1305}13061307void elf::mergeRISCVAttributesSections() {1308// Find the first input SHT_RISCV_ATTRIBUTES; return if not found.1309size_t place =1310llvm::find_if(ctx.inputSections,1311[](auto *s) { return s->type == SHT_RISCV_ATTRIBUTES; }) -1312ctx.inputSections.begin();1313if (place == ctx.inputSections.size())1314return;13151316// Extract all SHT_RISCV_ATTRIBUTES sections into `sections`.1317SmallVector<InputSectionBase *, 0> sections;1318llvm::erase_if(ctx.inputSections, [&](InputSectionBase *s) {1319if (s->type != SHT_RISCV_ATTRIBUTES)1320return false;1321sections.push_back(s);1322return true;1323});13241325// Add the merged section.1326ctx.inputSections.insert(ctx.inputSections.begin() + place,1327mergeAttributesSection(sections));1328}13291330TargetInfo *elf::getRISCVTargetInfo() {1331static RISCV target;1332return ⌖1333}133413351336