1//===- LoongArch.cpp ------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "InputFiles.h"
10#include "OutputSections.h"
11#include "RelocScan.h"
12#include "Symbols.h"
13#include "SyntheticSections.h"
14#include "Target.h"
15#include "llvm/BinaryFormat/ELF.h"
16#include "llvm/Support/LEB128.h"
17
18using namespace llvm;
19using namespace llvm::object;
20using namespace llvm::support::endian;
21using namespace llvm::ELF;
22using namespace lld;
23using namespace lld::elf;
24
25namespace {
26class LoongArch final : public TargetInfo {
27public:
28 LoongArch(Ctx &);
29 uint32_t calcEFlags() const override;
30 int64_t getImplicitAddend(const uint8_t *buf, RelType type) const override;
31 void writeGotPlt(uint8_t *buf, const Symbol &s) const override;
32 void writeIgotPlt(uint8_t *buf, const Symbol &s) const override;
33 void writePltHeader(uint8_t *buf) const override;
34 void writePlt(uint8_t *buf, const Symbol &sym,
35 uint64_t pltEntryAddr) const override;
36 RelType getDynRel(RelType type) const override;
37 RelExpr getRelExpr(RelType type, const Symbol &s,
38 const uint8_t *loc) const override;
39 bool usesOnlyLowPageBits(RelType type) const override;
40 template <class ELFT, class RelTy>
41 void scanSectionImpl(InputSectionBase &, Relocs<RelTy>);
42 void scanSection(InputSectionBase &sec) override {
43 if (ctx.arg.is64)
44 elf::scanSection1<LoongArch, ELF64LE>(target&: *this, sec);
45 else
46 elf::scanSection1<LoongArch, ELF32LE>(target&: *this, sec);
47 }
48 void relocate(uint8_t *loc, const Relocation &rel,
49 uint64_t val) const override;
50 bool relaxOnce(int pass) const override;
51 bool synthesizeAlign(uint64_t &dot, InputSection *sec) override;
52 void relocateAlloc(InputSection &sec, uint8_t *buf) const override;
53 void finalizeRelax(int passes) const override;
54
55private:
56 void tlsdescToIe(uint8_t *loc, const Relocation &rel, uint64_t val) const;
57 void tlsdescToLe(uint8_t *loc, const Relocation &rel, uint64_t val) const;
58 bool tryGotToPCRel(uint8_t *loc, const Relocation &rHi20,
59 const Relocation &rLo12, uint64_t secAddr) const;
60 template <class ELFT, class RelTy>
61 bool synthesizeAlignForInput(uint64_t &dot, InputSection *sec,
62 Relocs<RelTy> rels);
63 template <class ELFT, class RelTy>
64 void finalizeSynthesizeAligns(uint64_t &dot, InputSection *sec,
65 Relocs<RelTy> rels);
66 template <class ELFT>
67 bool synthesizeAlignAux(uint64_t &dot, InputSection *sec);
68
69 // The following two variables are used by synthesized ALIGN relocations.
70 InputSection *baseSec = nullptr;
71 // r_offset and r_addend pairs.
72 SmallVector<std::pair<uint64_t, uint64_t>, 0> synthesizedAligns;
73};
74} // end anonymous namespace
75
76namespace {
77enum Op {
78 SUB_W = 0x00110000,
79 SUB_D = 0x00118000,
80 BREAK = 0x002a0000,
81 SRLI_W = 0x00448000,
82 SRLI_D = 0x00450000,
83 ADDI_W = 0x02800000,
84 ADDI_D = 0x02c00000,
85 ANDI = 0x03400000,
86 ORI = 0x03800000,
87 LU12I_W = 0x14000000,
88 PCADDI = 0x18000000,
89 PCADDU12I = 0x1c000000,
90 PCALAU12I = 0x1a000000,
91 LD_W = 0x28800000,
92 LD_D = 0x28c00000,
93 JIRL = 0x4c000000,
94 B = 0x50000000,
95 BL = 0x54000000,
96};
97
98enum Reg {
99 R_ZERO = 0,
100 R_RA = 1,
101 R_TP = 2,
102 R_A0 = 4,
103 R_T0 = 12,
104 R_T1 = 13,
105 R_T2 = 14,
106 R_T3 = 15,
107};
108} // namespace
109
110// Mask out the input's lowest 12 bits for use with `pcalau12i`, in sequences
111// like `pcalau12i + addi.[wd]` or `pcalau12i + {ld,st}.*` where the `pcalau12i`
112// produces a PC-relative intermediate value with the lowest 12 bits zeroed (the
113// "page") for the next instruction to add in the "page offset". (`pcalau12i`
114// stands for something like "PC ALigned Add Upper that starts from the 12th
115// bit, Immediate".)
116//
117// Here a "page" is in fact just another way to refer to the 12-bit range
118// allowed by the immediate field of the addi/ld/st instructions, and not
119// related to the system or the kernel's actual page size. The semantics happen
120// to match the AArch64 `adrp`, so the concept of "page" is borrowed here.
121static uint64_t getLoongArchPage(uint64_t p) {
122 return p & ~static_cast<uint64_t>(0xfff);
123}
124
125static uint32_t lo12(uint32_t val) { return val & 0xfff; }
126
127// Calculate the adjusted page delta between dest and PC.
128uint64_t elf::getLoongArchPageDelta(uint64_t dest, uint64_t pc, RelType type) {
129 // Note that if the sequence being relocated is `pcalau12i + addi.d + lu32i.d
130 // + lu52i.d`, they must be adjacent so that we can infer the PC of
131 // `pcalau12i` when calculating the page delta for the other two instructions
132 // (lu32i.d and lu52i.d). Compensate all the sign-extensions is a bit
133 // complicated. Just use psABI recommended algorithm.
134 uint64_t pcalau12i_pc;
135 switch (type) {
136 case R_LARCH_PCALA64_LO20:
137 case R_LARCH_GOT64_PC_LO20:
138 case R_LARCH_TLS_IE64_PC_LO20:
139 case R_LARCH_TLS_DESC64_PC_LO20:
140 pcalau12i_pc = pc - 8;
141 break;
142 case R_LARCH_PCALA64_HI12:
143 case R_LARCH_GOT64_PC_HI12:
144 case R_LARCH_TLS_IE64_PC_HI12:
145 case R_LARCH_TLS_DESC64_PC_HI12:
146 pcalau12i_pc = pc - 12;
147 break;
148 default:
149 pcalau12i_pc = pc;
150 break;
151 }
152 uint64_t result = getLoongArchPage(p: dest) - getLoongArchPage(p: pcalau12i_pc);
153 if (dest & 0x800)
154 result += 0x1000 - 0x1'0000'0000;
155 if (result & 0x8000'0000)
156 result += 0x1'0000'0000;
157 return result;
158}
159
160static uint32_t hi20(uint32_t val) { return (val + 0x800) >> 12; }
161
162static uint32_t insn(uint32_t op, uint32_t d, uint32_t j, uint32_t k) {
163 return op | d | (j << 5) | (k << 10);
164}
165
166// Extract bits v[begin:end], where range is inclusive.
167static uint32_t extractBits(uint64_t v, uint32_t begin, uint32_t end) {
168 return begin == 63 ? v >> end : (v & ((1ULL << (begin + 1)) - 1)) >> end;
169}
170
171static uint32_t getD5(uint64_t v) { return extractBits(v, begin: 4, end: 0); }
172
173static uint32_t getJ5(uint64_t v) { return extractBits(v, begin: 9, end: 5); }
174
175static uint32_t setD5k16(uint32_t insn, uint32_t imm) {
176 uint32_t immLo = extractBits(v: imm, begin: 15, end: 0);
177 uint32_t immHi = extractBits(v: imm, begin: 20, end: 16);
178 return (insn & 0xfc0003e0) | (immLo << 10) | immHi;
179}
180
181static uint32_t setD10k16(uint32_t insn, uint32_t imm) {
182 uint32_t immLo = extractBits(v: imm, begin: 15, end: 0);
183 uint32_t immHi = extractBits(v: imm, begin: 25, end: 16);
184 return (insn & 0xfc000000) | (immLo << 10) | immHi;
185}
186
187static uint32_t setJ20(uint32_t insn, uint32_t imm) {
188 return (insn & 0xfe00001f) | (extractBits(v: imm, begin: 19, end: 0) << 5);
189}
190
191static uint32_t setJ5(uint32_t insn, uint32_t imm) {
192 return (insn & 0xfffffc1f) | (extractBits(v: imm, begin: 4, end: 0) << 5);
193}
194
195static uint32_t setK12(uint32_t insn, uint32_t imm) {
196 return (insn & 0xffc003ff) | (extractBits(v: imm, begin: 11, end: 0) << 10);
197}
198
199static uint32_t setK16(uint32_t insn, uint32_t imm) {
200 return (insn & 0xfc0003ff) | (extractBits(v: imm, begin: 15, end: 0) << 10);
201}
202
203static bool isJirl(uint32_t insn) {
204 return (insn & 0xfc000000) == JIRL;
205}
206
207static void handleUleb128(Ctx &ctx, uint8_t *loc, uint64_t val) {
208 const uint32_t maxcount = 1 + 64 / 7;
209 uint32_t count;
210 const char *error = nullptr;
211 uint64_t orig = decodeULEB128(p: loc, n: &count, end: nullptr, error: &error);
212 if (count > maxcount || (count == maxcount && error))
213 Err(ctx) << getErrorLoc(ctx, loc) << "extra space for uleb128";
214 uint64_t mask = count < maxcount ? (1ULL << 7 * count) - 1 : -1ULL;
215 encodeULEB128(Value: (orig + val) & mask, p: loc, PadTo: count);
216}
217
218LoongArch::LoongArch(Ctx &ctx) : TargetInfo(ctx) {
219 // The LoongArch ISA itself does not have a limit on page sizes. According to
220 // the ISA manual, the PS (page size) field in MTLB entries and CSR.STLBPS is
221 // 6 bits wide, meaning the maximum page size is 2^63 which is equivalent to
222 // "unlimited".
223 // However, practically the maximum usable page size is constrained by the
224 // kernel implementation, and 64KiB is the biggest non-huge page size
225 // supported by Linux as of v6.4. The most widespread page size in use,
226 // though, is 16KiB.
227 defaultCommonPageSize = 16384;
228 defaultMaxPageSize = 65536;
229 write32le(P: trapInstr.data(), V: BREAK); // break 0
230
231 copyRel = R_LARCH_COPY;
232 pltRel = R_LARCH_JUMP_SLOT;
233 relativeRel = R_LARCH_RELATIVE;
234 iRelativeRel = R_LARCH_IRELATIVE;
235
236 if (ctx.arg.is64) {
237 symbolicRel = R_LARCH_64;
238 tlsModuleIndexRel = R_LARCH_TLS_DTPMOD64;
239 tlsOffsetRel = R_LARCH_TLS_DTPREL64;
240 tlsGotRel = R_LARCH_TLS_TPREL64;
241 tlsDescRel = R_LARCH_TLS_DESC64;
242 } else {
243 symbolicRel = R_LARCH_32;
244 tlsModuleIndexRel = R_LARCH_TLS_DTPMOD32;
245 tlsOffsetRel = R_LARCH_TLS_DTPREL32;
246 tlsGotRel = R_LARCH_TLS_TPREL32;
247 tlsDescRel = R_LARCH_TLS_DESC32;
248 }
249
250 gotRel = symbolicRel;
251
252 // .got.plt[0] = _dl_runtime_resolve, .got.plt[1] = link_map
253 gotPltHeaderEntriesNum = 2;
254
255 pltHeaderSize = 32;
256 pltEntrySize = 16;
257 ipltEntrySize = 16;
258}
259
260static uint32_t getEFlags(Ctx &ctx, const InputFile *f) {
261 if (ctx.arg.is64)
262 return cast<ObjFile<ELF64LE>>(Val: f)->getObj().getHeader().e_flags;
263 return cast<ObjFile<ELF32LE>>(Val: f)->getObj().getHeader().e_flags;
264}
265
266static bool inputFileHasCode(const InputFile *f) {
267 for (const auto *sec : f->getSections())
268 if (sec && sec->flags & SHF_EXECINSTR)
269 return true;
270
271 return false;
272}
273
274uint32_t LoongArch::calcEFlags() const {
275 // If there are only binary input files (from -b binary), use a
276 // value of 0 for the ELF header flags.
277 if (ctx.objectFiles.empty())
278 return 0;
279
280 uint32_t target = 0;
281 const InputFile *targetFile;
282 for (const InputFile *f : ctx.objectFiles) {
283 // Do not enforce ABI compatibility if the input file does not contain code.
284 // This is useful for allowing linkage with data-only object files produced
285 // with tools like objcopy, that have zero e_flags.
286 if (!inputFileHasCode(f))
287 continue;
288
289 // Take the first non-zero e_flags as the reference.
290 uint32_t flags = getEFlags(ctx, f);
291 if (target == 0 && flags != 0) {
292 target = flags;
293 targetFile = f;
294 }
295
296 if ((flags & EF_LOONGARCH_ABI_MODIFIER_MASK) !=
297 (target & EF_LOONGARCH_ABI_MODIFIER_MASK))
298 ErrAlways(ctx) << f
299 << ": cannot link object files with different ABI from "
300 << targetFile;
301
302 // We cannot process psABI v1.x / object ABI v0 files (containing stack
303 // relocations), unlike ld.bfd.
304 //
305 // Instead of blindly accepting every v0 object and only failing at
306 // relocation processing time, just disallow interlink altogether. We
307 // don't expect significant usage of object ABI v0 in the wild (the old
308 // world may continue using object ABI v0 for a while, but as it's not
309 // binary-compatible with the upstream i.e. new-world ecosystem, it's not
310 // being considered here).
311 //
312 // There are briefly some new-world systems with object ABI v0 binaries too.
313 // It is because these systems were built before the new ABI was finalized.
314 // These are not supported either due to the extremely small number of them,
315 // and the few impacted users are advised to simply rebuild world or
316 // reinstall a recent system.
317 if ((flags & EF_LOONGARCH_OBJABI_MASK) != EF_LOONGARCH_OBJABI_V1)
318 ErrAlways(ctx) << f << ": unsupported object file ABI version";
319 }
320
321 return target;
322}
323
324int64_t LoongArch::getImplicitAddend(const uint8_t *buf, RelType type) const {
325 switch (type) {
326 default:
327 InternalErr(ctx, buf) << "cannot read addend for relocation " << type;
328 return 0;
329 case R_LARCH_32:
330 case R_LARCH_TLS_DTPMOD32:
331 case R_LARCH_TLS_DTPREL32:
332 case R_LARCH_TLS_TPREL32:
333 return SignExtend64<32>(x: read32le(P: buf));
334 case R_LARCH_64:
335 case R_LARCH_TLS_DTPMOD64:
336 case R_LARCH_TLS_DTPREL64:
337 case R_LARCH_TLS_TPREL64:
338 return read64le(P: buf);
339 case R_LARCH_RELATIVE:
340 case R_LARCH_IRELATIVE:
341 return ctx.arg.is64 ? read64le(P: buf) : read32le(P: buf);
342 case R_LARCH_NONE:
343 case R_LARCH_JUMP_SLOT:
344 // These relocations are defined as not having an implicit addend.
345 return 0;
346 case R_LARCH_TLS_DESC32:
347 return read32le(P: buf + 4);
348 case R_LARCH_TLS_DESC64:
349 return read64le(P: buf + 8);
350 }
351}
352
353void LoongArch::writeGotPlt(uint8_t *buf, const Symbol &s) const {
354 if (ctx.arg.is64)
355 write64le(P: buf, V: ctx.in.plt->getVA());
356 else
357 write32le(P: buf, V: ctx.in.plt->getVA());
358}
359
360void LoongArch::writeIgotPlt(uint8_t *buf, const Symbol &s) const {
361 if (ctx.arg.writeAddends) {
362 if (ctx.arg.is64)
363 write64le(P: buf, V: s.getVA(ctx));
364 else
365 write32le(P: buf, V: s.getVA(ctx));
366 }
367}
368
369void LoongArch::writePltHeader(uint8_t *buf) const {
370 // The LoongArch PLT is currently structured just like that of RISCV.
371 // Annoyingly, this means the PLT is still using `pcaddu12i` to perform
372 // PC-relative addressing (because `pcaddu12i` is the same as RISCV `auipc`),
373 // in contrast to the AArch64-like page-offset scheme with `pcalau12i` that
374 // is used everywhere else involving PC-relative operations in the LoongArch
375 // ELF psABI v2.00.
376 //
377 // The `pcrel_{hi20,lo12}` operators are illustrative only and not really
378 // supported by LoongArch assemblers.
379 //
380 // pcaddu12i $t2, %pcrel_hi20(.got.plt)
381 // sub.[wd] $t1, $t1, $t3
382 // ld.[wd] $t3, $t2, %pcrel_lo12(.got.plt) ; t3 = _dl_runtime_resolve
383 // addi.[wd] $t1, $t1, -pltHeaderSize-12 ; t1 = &.plt[i] - &.plt[0]
384 // addi.[wd] $t0, $t2, %pcrel_lo12(.got.plt)
385 // srli.[wd] $t1, $t1, (is64?1:2) ; t1 = &.got.plt[i] - &.got.plt[0]
386 // ld.[wd] $t0, $t0, Wordsize ; t0 = link_map
387 // jr $t3
388 uint32_t offset = ctx.in.gotPlt->getVA() - ctx.in.plt->getVA();
389 uint32_t sub = ctx.arg.is64 ? SUB_D : SUB_W;
390 uint32_t ld = ctx.arg.is64 ? LD_D : LD_W;
391 uint32_t addi = ctx.arg.is64 ? ADDI_D : ADDI_W;
392 uint32_t srli = ctx.arg.is64 ? SRLI_D : SRLI_W;
393 write32le(P: buf + 0, V: insn(op: PCADDU12I, d: R_T2, j: hi20(val: offset), k: 0));
394 write32le(P: buf + 4, V: insn(op: sub, d: R_T1, j: R_T1, k: R_T3));
395 write32le(P: buf + 8, V: insn(op: ld, d: R_T3, j: R_T2, k: lo12(val: offset)));
396 write32le(P: buf + 12,
397 V: insn(op: addi, d: R_T1, j: R_T1, k: lo12(val: -ctx.target->pltHeaderSize - 12)));
398 write32le(P: buf + 16, V: insn(op: addi, d: R_T0, j: R_T2, k: lo12(val: offset)));
399 write32le(P: buf + 20, V: insn(op: srli, d: R_T1, j: R_T1, k: ctx.arg.is64 ? 1 : 2));
400 write32le(P: buf + 24, V: insn(op: ld, d: R_T0, j: R_T0, k: ctx.arg.wordsize));
401 write32le(P: buf + 28, V: insn(op: JIRL, d: R_ZERO, j: R_T3, k: 0));
402}
403
404void LoongArch::writePlt(uint8_t *buf, const Symbol &sym,
405 uint64_t pltEntryAddr) const {
406 // See the comment in writePltHeader for reason why pcaddu12i is used instead
407 // of the pcalau12i that's more commonly seen in the ELF psABI v2.0 days.
408 //
409 // pcaddu12i $t3, %pcrel_hi20(f@.got.plt)
410 // ld.[wd] $t3, $t3, %pcrel_lo12(f@.got.plt)
411 // jirl $t1, $t3, 0
412 // nop
413 uint32_t offset = sym.getGotPltVA(ctx) - pltEntryAddr;
414 write32le(P: buf + 0, V: insn(op: PCADDU12I, d: R_T3, j: hi20(val: offset), k: 0));
415 write32le(P: buf + 4,
416 V: insn(op: ctx.arg.is64 ? LD_D : LD_W, d: R_T3, j: R_T3, k: lo12(val: offset)));
417 write32le(P: buf + 8, V: insn(op: JIRL, d: R_T1, j: R_T3, k: 0));
418 write32le(P: buf + 12, V: insn(op: ANDI, d: R_ZERO, j: R_ZERO, k: 0));
419}
420
421RelType LoongArch::getDynRel(RelType type) const {
422 return type == ctx.target->symbolicRel ? type
423 : static_cast<RelType>(R_LARCH_NONE);
424}
425
426// Used by relocateNonAlloc(), scanEhSection(), and the extreme code model
427// fallback in relocateAlloc(). For alloc sections, scanSectionImpl() is the
428// primary relocation classifier.
429RelExpr LoongArch::getRelExpr(const RelType type, const Symbol &s,
430 const uint8_t *loc) const {
431 switch (type) {
432 case R_LARCH_NONE:
433 return R_NONE;
434 case R_LARCH_32:
435 case R_LARCH_64:
436 return R_ABS;
437 case R_LARCH_ADD6:
438 case R_LARCH_ADD8:
439 case R_LARCH_ADD16:
440 case R_LARCH_ADD32:
441 case R_LARCH_ADD64:
442 case R_LARCH_ADD_ULEB128:
443 case R_LARCH_SUB6:
444 case R_LARCH_SUB8:
445 case R_LARCH_SUB16:
446 case R_LARCH_SUB32:
447 case R_LARCH_SUB64:
448 case R_LARCH_SUB_ULEB128:
449 // The LoongArch add/sub relocs behave like the RISCV counterparts; reuse
450 // the RelExpr to avoid code duplication.
451 return RE_RISCV_ADD;
452 case R_LARCH_32_PCREL:
453 case R_LARCH_64_PCREL:
454 case R_LARCH_PCREL20_S2:
455 case R_LARCH_PCADD_HI20:
456 return R_PC;
457 case R_LARCH_TLS_DTPREL32:
458 case R_LARCH_TLS_DTPREL64:
459 return R_DTPREL;
460 default:
461 Err(ctx) << getErrorLoc(ctx, loc) << "unknown relocation (" << type.v
462 << ") against symbol " << &s;
463 return R_NONE;
464 }
465}
466
467bool LoongArch::usesOnlyLowPageBits(RelType type) const {
468 switch (type) {
469 default:
470 return false;
471 case R_LARCH_PCALA_LO12:
472 case R_LARCH_GOT_LO12:
473 case R_LARCH_GOT_PC_LO12:
474 case R_LARCH_TLS_IE_PC_LO12:
475 case R_LARCH_TLS_DESC_LO12:
476 case R_LARCH_TLS_DESC_PC_LO12:
477 return true;
478 }
479}
480
481template <class ELFT, class RelTy>
482void LoongArch::scanSectionImpl(InputSectionBase &sec, Relocs<RelTy> rels) {
483 RelocScan rs(ctx, &sec);
484 sec.relocations.reserve(N: rels.size());
485 for (auto it = rels.begin(); it != rels.end(); ++it) {
486 RelType type = it->getType(false);
487 uint32_t symIndex = it->getSymbol(false);
488 Symbol &sym = sec.getFile<ELFT>()->getSymbol(symIndex);
489 uint64_t offset = it->r_offset;
490 if (sym.isUndefined() && symIndex != 0 &&
491 rs.maybeReportUndefined(sym&: cast<Undefined>(Val&: sym), offset))
492 continue;
493 int64_t addend = rs.getAddend<ELFT>(*it, type);
494 RelExpr expr;
495 // Relocation types that only need a RelExpr set `expr` and break out of
496 // the switch to reach rs.process(). Types that need special handling
497 // (fast-path helpers, TLS) call a handler and use `continue`.
498 switch (type) {
499 case R_LARCH_NONE:
500 case R_LARCH_MARK_LA:
501 case R_LARCH_MARK_PCREL:
502 continue;
503
504 // Absolute relocations:
505 case R_LARCH_32:
506 case R_LARCH_64:
507 case R_LARCH_ABS_HI20:
508 case R_LARCH_ABS_LO12:
509 case R_LARCH_ABS64_LO20:
510 case R_LARCH_ABS64_HI12:
511 expr = R_ABS;
512 break;
513
514 case R_LARCH_PCALA_LO12:
515 // R_LARCH_PCALA_LO12 on JIRL is used for function calls (glibc 2.37).
516 expr = isJirl(insn: read32le(P: sec.content().data() + offset)) ? R_PLT : R_ABS;
517 break;
518
519 // PC-indirect relocations (lo12 paired with a preceding hi20 pcadd):
520 case R_LARCH_PCADD_LO12:
521 case R_LARCH_GOT_PCADD_LO12:
522 case R_LARCH_TLS_IE_PCADD_LO12:
523 case R_LARCH_TLS_LD_PCADD_LO12:
524 case R_LARCH_TLS_GD_PCADD_LO12:
525 case R_LARCH_TLS_DESC_PCADD_LO12:
526 expr = RE_LOONGARCH_PC_INDIRECT;
527 break;
528
529 // PC-relative relocations:
530 case R_LARCH_32_PCREL:
531 case R_LARCH_64_PCREL:
532 case R_LARCH_PCREL20_S2:
533 case R_LARCH_PCADD_HI20:
534 rs.processR_PC(type, offset, addend, sym);
535 continue;
536
537 // PLT-generating relocations:
538 case R_LARCH_B16:
539 case R_LARCH_B21:
540 case R_LARCH_B26:
541 case R_LARCH_CALL30:
542 case R_LARCH_CALL36:
543 rs.processR_PLT_PC(type, offset, addend, sym);
544 continue;
545
546 // Page-PC relocations:
547 case R_LARCH_PCALA_HI20:
548 // Why not RE_LOONGARCH_PAGE_PC, majority of references don't go through
549 // PLT anyway so why waste time checking only to get everything relaxed
550 // back to it?
551 //
552 // This is again due to the R_LARCH_PCALA_LO12 on JIRL case, where we want
553 // both the HI20 and LO12 to potentially refer to the PLT. But in reality
554 // the HI20 reloc appears earlier, and the relocs don't contain enough
555 // information to let us properly resolve semantics per symbol.
556 // Unlike RISCV, our LO12 relocs *do not* point to their corresponding
557 // HI20 relocs, hence it is nearly impossible to 100% accurately determine
558 // each HI20's "flavor" without taking big performance hits, in the
559 // presence of edge cases (e.g. HI20 without pairing LO12; paired LO12
560 // placed so far apart that relationship is not certain anymore), and
561 // programmer mistakes (e.g. as outlined in
562 // https://github.com/loongson/la-abi-specs/pull/3).
563 //
564 // Ideally we would scan in an extra pass for all LO12s on JIRL, then mark
565 // every HI20 reloc referring to the same symbol differently; this is not
566 // feasible with the current function signature of getRelExpr that doesn't
567 // allow for such inter-pass state.
568 //
569 // So, unfortunately we have to again workaround this quirk the same way
570 // as BFD: assuming every R_LARCH_PCALA_HI20 is potentially PLT-needing,
571 // only relaxing back to RE_LOONGARCH_PAGE_PC if it's known not so at a
572 // later stage.
573 expr = RE_LOONGARCH_PLT_PAGE_PC;
574 break;
575 case R_LARCH_PCALA64_LO20:
576 case R_LARCH_PCALA64_HI12:
577 expr = RE_LOONGARCH_PAGE_PC;
578 break;
579
580 // GOT-generating relocations:
581 case R_LARCH_GOT_PC_HI20:
582 case R_LARCH_GOT64_PC_LO20:
583 case R_LARCH_GOT64_PC_HI12:
584 expr = RE_LOONGARCH_GOT_PAGE_PC;
585 break;
586 case R_LARCH_GOT_PCADD_HI20:
587 expr = R_GOT_PC;
588 break;
589 case R_LARCH_GOT_PC_LO12:
590 expr = RE_LOONGARCH_GOT;
591 break;
592 case R_LARCH_GOT_HI20:
593 case R_LARCH_GOT_LO12:
594 case R_LARCH_GOT64_LO20:
595 case R_LARCH_GOT64_HI12:
596 expr = R_GOT;
597 break;
598
599 // DTPREL relocations:
600 case R_LARCH_TLS_DTPREL32:
601 case R_LARCH_TLS_DTPREL64:
602 expr = R_DTPREL;
603 break;
604
605 // TLS LE relocations:
606 case R_LARCH_TLS_TPREL32:
607 case R_LARCH_TLS_TPREL64:
608 case R_LARCH_TLS_LE_HI20:
609 case R_LARCH_TLS_LE_HI20_R:
610 case R_LARCH_TLS_LE_LO12:
611 case R_LARCH_TLS_LE_LO12_R:
612 case R_LARCH_TLS_LE64_LO20:
613 case R_LARCH_TLS_LE64_HI12:
614 if (rs.checkTlsLe(offset, sym, type))
615 continue;
616 expr = R_TPREL;
617 break;
618 // TLS IE relocations (optimizable to LE in non-extreme code model):
619 case R_LARCH_TLS_IE_PC_HI20:
620 rs.handleTlsIe(ieExpr: RE_LOONGARCH_GOT_PAGE_PC, type, offset, addend, sym);
621 continue;
622 case R_LARCH_TLS_IE_PC_LO12:
623 rs.handleTlsIe(ieExpr: RE_LOONGARCH_GOT, type, offset, addend, sym);
624 continue;
625 // TLS IE relocations (extreme code model, no IE->LE optimization):
626 case R_LARCH_TLS_IE64_PC_LO20:
627 case R_LARCH_TLS_IE64_PC_HI12:
628 rs.handleTlsIe<false>(ieExpr: RE_LOONGARCH_GOT_PAGE_PC, type, offset, addend,
629 sym);
630 continue;
631 // TLS IE relocations (pcadd/absolute, no IE->LE optimization):
632 case R_LARCH_TLS_IE_PCADD_HI20:
633 rs.handleTlsIe<false>(ieExpr: R_GOT_PC, type, offset, addend, sym);
634 continue;
635 case R_LARCH_TLS_IE_HI20:
636 case R_LARCH_TLS_IE_LO12:
637 case R_LARCH_TLS_IE64_LO20:
638 case R_LARCH_TLS_IE64_HI12:
639 rs.handleTlsIe<false>(ieExpr: R_GOT, type, offset, addend, sym);
640 continue;
641 // TLS GD/LD relocations (no GD/LD->IE/LE optimization):
642 case R_LARCH_TLS_LD_PC_HI20:
643 case R_LARCH_TLS_GD_PC_HI20:
644 sym.setFlags(NEEDS_TLSGD);
645 sec.addReloc(r: {.expr: RE_LOONGARCH_TLSGD_PAGE_PC, .type: type, .offset: offset, .addend: addend, .sym: &sym});
646 continue;
647 case R_LARCH_TLS_LD_HI20:
648 ctx.needsTlsLd.store(i: true, m: std::memory_order_relaxed);
649 sec.addReloc(r: {.expr: R_TLSLD_GOT, .type: type, .offset: offset, .addend: addend, .sym: &sym});
650 continue;
651 case R_LARCH_TLS_GD_HI20:
652 sym.setFlags(NEEDS_TLSGD);
653 sec.addReloc(r: {.expr: R_TLSGD_GOT, .type: type, .offset: offset, .addend: addend, .sym: &sym});
654 continue;
655 case R_LARCH_TLS_LD_PCREL20_S2:
656 case R_LARCH_TLS_LD_PCADD_HI20:
657 ctx.needsTlsLd.store(i: true, m: std::memory_order_relaxed);
658 sec.addReloc(r: {.expr: R_TLSLD_PC, .type: type, .offset: offset, .addend: addend, .sym: &sym});
659 continue;
660 case R_LARCH_TLS_GD_PCREL20_S2:
661 case R_LARCH_TLS_GD_PCADD_HI20:
662 sym.setFlags(NEEDS_TLSGD);
663 sec.addReloc(r: {.expr: R_TLSGD_PC, .type: type, .offset: offset, .addend: addend, .sym: &sym});
664 continue;
665
666 // TLSDESC relocations (optimizable to IE/LE in non-extreme code model):
667 case R_LARCH_TLS_DESC_PC_HI20:
668 rs.handleTlsDesc(sharedExpr: RE_LOONGARCH_TLSDESC_PAGE_PC, ieExpr: RE_LOONGARCH_GOT_PAGE_PC,
669 type, offset, addend, sym);
670 continue;
671 case R_LARCH_TLS_DESC_PC_LO12:
672 case R_LARCH_TLS_DESC_LD:
673 rs.handleTlsDesc(sharedExpr: R_TLSDESC, ieExpr: RE_LOONGARCH_GOT_PAGE_PC, type, offset,
674 addend, sym);
675 continue;
676 case R_LARCH_TLS_DESC_PCREL20_S2:
677 rs.handleTlsDesc(sharedExpr: R_TLSDESC_PC, ieExpr: RE_LOONGARCH_GOT_PAGE_PC, type, offset,
678 addend, sym);
679 continue;
680 case R_LARCH_TLS_DESC_CALL:
681 if (!ctx.arg.shared)
682 sec.addReloc(
683 r: {.expr: sym.isPreemptible ? R_GOT : R_TPREL, .type: type, .offset: offset, .addend: addend, .sym: &sym});
684 continue;
685 // TLSDESC relocations (extreme code model, no optimization):
686 case R_LARCH_TLS_DESC64_PC_LO20:
687 case R_LARCH_TLS_DESC64_PC_HI12:
688 sym.setFlags(NEEDS_TLSDESC);
689 sec.addReloc(r: {.expr: RE_LOONGARCH_TLSDESC_PAGE_PC, .type: type, .offset: offset, .addend: addend, .sym: &sym});
690 continue;
691 // TLSDESC relocations (absolute/pcadd, no optimization):
692 case R_LARCH_TLS_DESC_HI20:
693 case R_LARCH_TLS_DESC_LO12:
694 case R_LARCH_TLS_DESC64_LO20:
695 case R_LARCH_TLS_DESC64_HI12:
696 case R_LARCH_TLS_DESC_PCADD_HI20:
697 sym.setFlags(NEEDS_TLSDESC);
698 sec.addReloc(r: {.expr: R_TLSDESC, .type: type, .offset: offset, .addend: addend, .sym: &sym});
699 continue;
700
701 // Relaxation hints:
702 case R_LARCH_TLS_LE_ADD_R:
703 case R_LARCH_RELAX:
704 if (ctx.arg.relax)
705 sec.addReloc(r: {.expr: R_RELAX_HINT, .type: type, .offset: offset, .addend: addend, .sym: &sym});
706 continue;
707 case R_LARCH_ALIGN:
708 sec.addReloc(r: {.expr: R_RELAX_HINT, .type: type, .offset: offset, .addend: addend, .sym: &sym});
709 continue;
710
711 // Misc relocations:
712 case R_LARCH_ADD6:
713 case R_LARCH_ADD8:
714 case R_LARCH_ADD16:
715 case R_LARCH_ADD32:
716 case R_LARCH_ADD64:
717 case R_LARCH_ADD_ULEB128:
718 case R_LARCH_SUB6:
719 case R_LARCH_SUB8:
720 case R_LARCH_SUB16:
721 case R_LARCH_SUB32:
722 case R_LARCH_SUB64:
723 case R_LARCH_SUB_ULEB128:
724 expr = RE_RISCV_ADD;
725 break;
726
727 default:
728 Err(ctx) << getErrorLoc(ctx, loc: sec.content().data() + offset)
729 << "unknown relocation (" << type.v << ") against symbol "
730 << &sym;
731 continue;
732 }
733 rs.process(expr, type, offset, sym, addend);
734 }
735
736 llvm::stable_sort(sec.relocs(),
737 [](const Relocation &lhs, const Relocation &rhs) {
738 return lhs.offset < rhs.offset;
739 });
740}
741
742void LoongArch::relocate(uint8_t *loc, const Relocation &rel,
743 uint64_t val) const {
744 switch (rel.type) {
745 case R_LARCH_32_PCREL:
746 checkInt(ctx, loc, v: val, n: 32, rel);
747 [[fallthrough]];
748 case R_LARCH_32:
749 case R_LARCH_TLS_DTPREL32:
750 write32le(P: loc, V: val);
751 return;
752 case R_LARCH_64:
753 case R_LARCH_TLS_DTPREL64:
754 case R_LARCH_64_PCREL:
755 write64le(P: loc, V: val);
756 return;
757
758 // Relocs intended for `pcaddi`.
759 case R_LARCH_PCREL20_S2:
760 case R_LARCH_TLS_LD_PCREL20_S2:
761 case R_LARCH_TLS_GD_PCREL20_S2:
762 case R_LARCH_TLS_DESC_PCREL20_S2:
763 checkInt(ctx, loc, v: val, n: 22, rel);
764 checkAlignment(ctx, loc, v: val, n: 4, rel);
765 write32le(P: loc, V: setJ20(insn: read32le(P: loc), imm: val >> 2));
766 return;
767
768 case R_LARCH_B16:
769 checkInt(ctx, loc, v: val, n: 18, rel);
770 checkAlignment(ctx, loc, v: val, n: 4, rel);
771 write32le(P: loc, V: setK16(insn: read32le(P: loc), imm: val >> 2));
772 return;
773
774 case R_LARCH_B21:
775 checkInt(ctx, loc, v: val, n: 23, rel);
776 checkAlignment(ctx, loc, v: val, n: 4, rel);
777 write32le(P: loc, V: setD5k16(insn: read32le(P: loc), imm: val >> 2));
778 return;
779
780 case R_LARCH_B26:
781 checkInt(ctx, loc, v: val, n: 28, rel);
782 checkAlignment(ctx, loc, v: val, n: 4, rel);
783 write32le(P: loc, V: setD10k16(insn: read32le(P: loc), imm: val >> 2));
784 return;
785
786 case R_LARCH_CALL30: {
787 // This relocation is designed for adjacent pcaddu12i+jirl pairs that
788 // are patched in one time.
789 // The relocation range is [-2G, +2G) (of course must be 4-byte aligned).
790 checkInt(ctx, loc, v: val, n: 32, rel);
791 checkAlignment(ctx, loc, v: val, n: 4, rel);
792 // Although jirl adds the immediate as a signed value, it is always positive
793 // in this case, so no adjustment is needed, unlike CALL36.
794 uint32_t hi20 = extractBits(v: val, begin: 31, end: 12);
795 // Despite the name, the lower part is actually 12 bits with 4-byte aligned.
796 uint32_t lo10 = extractBits(v: val, begin: 11, end: 2);
797 write32le(P: loc, V: setJ20(insn: read32le(P: loc), imm: hi20));
798 write32le(P: loc + 4, V: setK16(insn: read32le(P: loc + 4), imm: lo10));
799 return;
800 }
801
802 case R_LARCH_CALL36: {
803 // This relocation is designed for adjacent pcaddu18i+jirl pairs that
804 // are patched in one time. Because of sign extension of these insns'
805 // immediate fields, the relocation range is [-128G - 0x20000, +128G -
806 // 0x20000) (of course must be 4-byte aligned).
807 if (((int64_t)val + 0x20000) != llvm::SignExtend64(X: val + 0x20000, B: 38))
808 reportRangeError(ctx, loc, rel, v: Twine(val), min: llvm::minIntN(N: 38) - 0x20000,
809 max: llvm::maxIntN(N: 38) - 0x20000);
810 checkAlignment(ctx, loc, v: val, n: 4, rel);
811 // Since jirl performs sign extension on the offset immediate, adds (1<<17)
812 // to original val to get the correct hi20.
813 uint32_t hi20 = extractBits(v: val + (1 << 17), begin: 37, end: 18);
814 // Despite the name, the lower part is actually 18 bits with 4-byte aligned.
815 uint32_t lo16 = extractBits(v: val, begin: 17, end: 2);
816 write32le(P: loc, V: setJ20(insn: read32le(P: loc), imm: hi20));
817 write32le(P: loc + 4, V: setK16(insn: read32le(P: loc + 4), imm: lo16));
818 return;
819 }
820
821 // Relocs intended for `addi`, `ld` or `st`.
822 case R_LARCH_PCALA_LO12:
823 // We have to again inspect the insn word to handle the R_LARCH_PCALA_LO12
824 // on JIRL case: firstly JIRL wants its immediate's 2 lowest zeroes
825 // removed by us (in contrast to regular R_LARCH_PCALA_LO12), secondly
826 // its immediate slot width is different too (16, not 12).
827 // In this case, process like an R_LARCH_B16, but without overflow checking
828 // and only taking the value's lowest 12 bits.
829 if (isJirl(insn: read32le(P: loc))) {
830 checkAlignment(ctx, loc, v: val, n: 4, rel);
831 val = SignExtend64<12>(x: val);
832 write32le(P: loc, V: setK16(insn: read32le(P: loc), imm: val >> 2));
833 return;
834 }
835 [[fallthrough]];
836 case R_LARCH_ABS_LO12:
837 case R_LARCH_GOT_PC_LO12:
838 case R_LARCH_GOT_LO12:
839 case R_LARCH_TLS_LE_LO12:
840 case R_LARCH_TLS_IE_PC_LO12:
841 case R_LARCH_TLS_IE_LO12:
842 case R_LARCH_TLS_LE_LO12_R:
843 case R_LARCH_TLS_DESC_PC_LO12:
844 case R_LARCH_TLS_DESC_LO12:
845 case R_LARCH_PCADD_LO12:
846 case R_LARCH_GOT_PCADD_LO12:
847 case R_LARCH_TLS_IE_PCADD_LO12:
848 case R_LARCH_TLS_LD_PCADD_LO12:
849 case R_LARCH_TLS_GD_PCADD_LO12:
850 case R_LARCH_TLS_DESC_PCADD_LO12:
851 write32le(P: loc, V: setK12(insn: read32le(P: loc), imm: extractBits(v: val, begin: 11, end: 0)));
852 return;
853
854 // Relocs intended for `lu12i.w` or `pcalau12i`.
855 case R_LARCH_ABS_HI20:
856 case R_LARCH_PCALA_HI20:
857 case R_LARCH_GOT_PC_HI20:
858 case R_LARCH_GOT_HI20:
859 case R_LARCH_TLS_LE_HI20:
860 case R_LARCH_TLS_IE_PC_HI20:
861 case R_LARCH_TLS_IE_HI20:
862 case R_LARCH_TLS_LD_PC_HI20:
863 case R_LARCH_TLS_LD_HI20:
864 case R_LARCH_TLS_GD_PC_HI20:
865 case R_LARCH_TLS_GD_HI20:
866 case R_LARCH_TLS_DESC_PC_HI20:
867 case R_LARCH_TLS_DESC_HI20:
868 write32le(P: loc, V: setJ20(insn: read32le(P: loc), imm: extractBits(v: val, begin: 31, end: 12)));
869 return;
870 case R_LARCH_PCADD_HI20:
871 case R_LARCH_GOT_PCADD_HI20:
872 case R_LARCH_TLS_IE_PCADD_HI20:
873 case R_LARCH_TLS_LD_PCADD_HI20:
874 case R_LARCH_TLS_GD_PCADD_HI20:
875 case R_LARCH_TLS_DESC_PCADD_HI20: {
876 uint64_t hi = val + 0x800;
877 checkInt(ctx, loc, v: SignExtend64(X: hi, B: ctx.arg.wordsize * 8) >> 12, n: 20, rel);
878 write32le(P: loc, V: setJ20(insn: read32le(P: loc), imm: extractBits(v: hi, begin: 31, end: 12)));
879 return;
880 }
881 case R_LARCH_TLS_LE_HI20_R:
882 write32le(P: loc, V: setJ20(insn: read32le(P: loc), imm: extractBits(v: val + 0x800, begin: 31, end: 12)));
883 return;
884
885 // Relocs intended for `lu32i.d`.
886 case R_LARCH_ABS64_LO20:
887 case R_LARCH_PCALA64_LO20:
888 case R_LARCH_GOT64_PC_LO20:
889 case R_LARCH_GOT64_LO20:
890 case R_LARCH_TLS_LE64_LO20:
891 case R_LARCH_TLS_IE64_PC_LO20:
892 case R_LARCH_TLS_IE64_LO20:
893 case R_LARCH_TLS_DESC64_PC_LO20:
894 case R_LARCH_TLS_DESC64_LO20:
895 write32le(P: loc, V: setJ20(insn: read32le(P: loc), imm: extractBits(v: val, begin: 51, end: 32)));
896 return;
897
898 // Relocs intended for `lu52i.d`.
899 case R_LARCH_ABS64_HI12:
900 case R_LARCH_PCALA64_HI12:
901 case R_LARCH_GOT64_PC_HI12:
902 case R_LARCH_GOT64_HI12:
903 case R_LARCH_TLS_LE64_HI12:
904 case R_LARCH_TLS_IE64_PC_HI12:
905 case R_LARCH_TLS_IE64_HI12:
906 case R_LARCH_TLS_DESC64_PC_HI12:
907 case R_LARCH_TLS_DESC64_HI12:
908 write32le(P: loc, V: setK12(insn: read32le(P: loc), imm: extractBits(v: val, begin: 63, end: 52)));
909 return;
910
911 case R_LARCH_ADD6:
912 *loc = (*loc & 0xc0) | ((*loc + val) & 0x3f);
913 return;
914 case R_LARCH_ADD8:
915 *loc += val;
916 return;
917 case R_LARCH_ADD16:
918 write16le(P: loc, V: read16le(P: loc) + val);
919 return;
920 case R_LARCH_ADD32:
921 write32le(P: loc, V: read32le(P: loc) + val);
922 return;
923 case R_LARCH_ADD64:
924 write64le(P: loc, V: read64le(P: loc) + val);
925 return;
926 case R_LARCH_ADD_ULEB128:
927 handleUleb128(ctx, loc, val);
928 return;
929 case R_LARCH_SUB6:
930 *loc = (*loc & 0xc0) | ((*loc - val) & 0x3f);
931 return;
932 case R_LARCH_SUB8:
933 *loc -= val;
934 return;
935 case R_LARCH_SUB16:
936 write16le(P: loc, V: read16le(P: loc) - val);
937 return;
938 case R_LARCH_SUB32:
939 write32le(P: loc, V: read32le(P: loc) - val);
940 return;
941 case R_LARCH_SUB64:
942 write64le(P: loc, V: read64le(P: loc) - val);
943 return;
944 case R_LARCH_SUB_ULEB128:
945 handleUleb128(ctx, loc, val: -val);
946 return;
947
948 case R_LARCH_MARK_LA:
949 case R_LARCH_MARK_PCREL:
950 // no-op
951 return;
952
953 case R_LARCH_TLS_LE_ADD_R:
954 case R_LARCH_RELAX:
955 return; // Ignored (for now)
956
957 case R_LARCH_TLS_DESC_LD:
958 return; // nothing to do.
959 case R_LARCH_TLS_DESC32:
960 write32le(P: loc + 4, V: val);
961 return;
962 case R_LARCH_TLS_DESC64:
963 write64le(P: loc + 8, V: val);
964 return;
965
966 default:
967 llvm_unreachable("unknown relocation");
968 }
969}
970
971// If the section alignment is > 4, advance `dot` to insert NOPs and synthesize
972// an ALIGN relocation. Otherwise, return false to use default handling.
973template <class ELFT, class RelTy>
974bool LoongArch::synthesizeAlignForInput(uint64_t &dot, InputSection *sec,
975 Relocs<RelTy> rels) {
976 if (!baseSec) {
977 // Record the first input section with RELAX relocations. We will synthesize
978 // ALIGN relocations here.
979 for (auto rel : rels) {
980 if (rel.getType(false) == R_LARCH_RELAX) {
981 baseSec = sec;
982 break;
983 }
984 }
985 } else if (sec->addralign > 4) {
986 // If the alignment is > 4, synthesize an ALIGN unless an ALIGN relocation
987 // at offset 0 already guarantees `addralign`. Note: A weaker ALIGN at
988 // offset 0 from older assemblers do not suppress synthesis (e.g.
989 // `.p2align 2; .option norelax; nop; .p2align 3` does not suppress
990 // synthesized `.p2align 3`).
991 bool covered = llvm::any_of(rels, [&](const RelTy &rel) {
992 if (rel.r_offset != 0 || rel.getType(false) != R_LARCH_ALIGN)
993 return false;
994 if constexpr (RelTy::HasAddend)
995 return uint64_t(rel.r_addend) >= sec->addralign - 4;
996 return false;
997 });
998 if (!covered) {
999 synthesizedAligns.emplace_back(Args: dot - baseSec->getVA(),
1000 Args: sec->addralign - 4);
1001 dot += sec->addralign - 4;
1002 return true;
1003 }
1004 }
1005 return false;
1006}
1007
1008// Finalize the relocation section by appending synthesized ALIGN relocations
1009// after processing all input sections.
1010template <class ELFT, class RelTy>
1011void LoongArch::finalizeSynthesizeAligns(uint64_t &dot, InputSection *sec,
1012 Relocs<RelTy> rels) {
1013 auto *f = cast<ObjFile<ELFT>>(baseSec->file);
1014 auto shdr = f->template getELFShdrs<ELFT>()[baseSec->relSecIdx];
1015 // Create a copy of InputSection.
1016 sec = make<InputSection>(*f, shdr, baseSec->name);
1017 auto *baseRelSec = cast<InputSection>(f->getSections()[baseSec->relSecIdx]);
1018 *sec = *baseRelSec;
1019 baseSec = nullptr;
1020
1021 // Allocate buffer for original and synthesized relocations in RELA format.
1022 // If CREL is used, OutputSection::finalizeNonAllocCrel will convert RELA to
1023 // CREL.
1024 auto newSize = rels.size() + synthesizedAligns.size();
1025 auto *relas = makeThreadLocalN<typename ELFT::Rela>(newSize);
1026 sec->size = newSize * sizeof(typename ELFT::Rela);
1027 sec->content_ = reinterpret_cast<uint8_t *>(relas);
1028 sec->type = SHT_RELA;
1029 // Copy original relocations to the new buffer, potentially converting CREL to
1030 // RELA.
1031 for (auto [i, r] : llvm::enumerate(rels)) {
1032 relas[i].r_offset = r.r_offset;
1033 relas[i].setSymbolAndType(r.getSymbol(0), r.getType(0), false);
1034 if constexpr (RelTy::HasAddend)
1035 relas[i].r_addend = r.r_addend;
1036 }
1037 // Append synthesized ALIGN relocations to the buffer.
1038 for (auto [i, r] : llvm::enumerate(First&: synthesizedAligns)) {
1039 auto &rela = relas[rels.size() + i];
1040 rela.r_offset = r.first;
1041 rela.setSymbolAndType(0, R_LARCH_ALIGN, false);
1042 rela.r_addend = r.second;
1043 }
1044 synthesizedAligns.clear();
1045 // Replace the old relocation section with the new one in the output section.
1046 // addOrphanSections ensures that the output relocation section is processed
1047 // after osec.
1048 for (SectionCommand *cmd : sec->getParent()->commands) {
1049 auto *isd = dyn_cast<InputSectionDescription>(Val: cmd);
1050 if (!isd)
1051 continue;
1052 for (auto *&isec : isd->sections)
1053 if (isec == baseRelSec)
1054 isec = sec;
1055 }
1056}
1057
1058template <class ELFT>
1059bool LoongArch::synthesizeAlignAux(uint64_t &dot, InputSection *sec) {
1060 bool ret = false;
1061 if (sec) {
1062 invokeOnRelocs(*sec, ret = synthesizeAlignForInput<ELFT>, dot, sec);
1063 } else if (baseSec) {
1064 invokeOnRelocs(*baseSec, finalizeSynthesizeAligns<ELFT>, dot, sec);
1065 }
1066 return ret;
1067}
1068
1069// Without linker relaxation enabled for a particular relocatable file or
1070// section, the assembler will not generate R_LARCH_ALIGN relocations for
1071// alignment directives. This becomes problematic in a two-stage linking
1072// process: ld -r a.o b.o -o ab.o; ld ab.o -o ab. This function synthesizes an
1073// R_LARCH_ALIGN relocation at section start when needed.
1074//
1075// When called with an input section (`sec` is not null): If the section
1076// alignment is > 4, advance `dot` to insert NOPs and synthesize an ALIGN
1077// relocation.
1078//
1079// When called after all input sections are processed (`sec` is null): The
1080// output relocation section is updated with all the newly synthesized ALIGN
1081// relocations.
1082bool LoongArch::synthesizeAlign(uint64_t &dot, InputSection *sec) {
1083 assert(ctx.arg.relocatable);
1084 if (ctx.arg.is64)
1085 return synthesizeAlignAux<ELF64LE>(dot, sec);
1086 return synthesizeAlignAux<ELF32LE>(dot, sec);
1087}
1088
1089static bool relaxable(ArrayRef<Relocation> relocs, size_t i) {
1090 return i + 1 < relocs.size() && relocs[i + 1].type == R_LARCH_RELAX;
1091}
1092
1093static bool isPairRelaxable(ArrayRef<Relocation> relocs, size_t i) {
1094 return relaxable(relocs, i) && relaxable(relocs, i: i + 2) &&
1095 relocs[i].offset + 4 == relocs[i + 2].offset;
1096}
1097
1098// Relax code sequence.
1099// From:
1100// pcalau12i $a0, %pc_hi20(sym) | %ld_pc_hi20(sym) | %gd_pc_hi20(sym)
1101// | %desc_pc_hi20(sym)
1102// addi.w/d $a0, $a0, %pc_lo12(sym) | %got_pc_lo12(sym) | %got_pc_lo12(sym)
1103// | %desc_pc_lo12(sym)
1104// To:
1105// pcaddi $a0, %pc_lo12(sym) | %got_pc_lo12(sym) | %got_pc_lo12(sym)
1106// | %desc_pcrel_20(sym)
1107//
1108// From:
1109// pcalau12i $a0, %got_pc_hi20(sym_got)
1110// ld.w/d $a0, $a0, %got_pc_lo12(sym_got)
1111// To:
1112// pcaddi $a0, %got_pc_hi20(sym_got)
1113static void relaxPCHi20Lo12(Ctx &ctx, const InputSection &sec, size_t i,
1114 uint64_t loc, Relocation &rHi20, Relocation &rLo12,
1115 uint32_t &remove) {
1116 // check if the relocations are relaxable sequences.
1117 if (!((rHi20.type == R_LARCH_PCALA_HI20 &&
1118 rLo12.type == R_LARCH_PCALA_LO12) ||
1119 (rHi20.type == R_LARCH_GOT_PC_HI20 &&
1120 rLo12.type == R_LARCH_GOT_PC_LO12) ||
1121 (rHi20.type == R_LARCH_TLS_GD_PC_HI20 &&
1122 rLo12.type == R_LARCH_GOT_PC_LO12) ||
1123 (rHi20.type == R_LARCH_TLS_LD_PC_HI20 &&
1124 rLo12.type == R_LARCH_GOT_PC_LO12) ||
1125 (rHi20.type == R_LARCH_TLS_DESC_PC_HI20 &&
1126 rLo12.type == R_LARCH_TLS_DESC_PC_LO12)))
1127 return;
1128
1129 // GOT references to absolute symbols can't be relaxed to use pcaddi in
1130 // position-independent code, because these instructions produce a relative
1131 // address.
1132 // Meanwhile skip undefined, preemptible and STT_GNU_IFUNC symbols, because
1133 // these symbols may be resolve in runtime.
1134 // Moreover, relaxation can only occur if the addends of both relocations are
1135 // zero for GOT references.
1136 if (rHi20.type == R_LARCH_GOT_PC_HI20 &&
1137 (!rHi20.sym || rHi20.sym != rLo12.sym || !rHi20.sym->isDefined() ||
1138 rHi20.sym->isPreemptible || rHi20.sym->isGnuIFunc() ||
1139 (ctx.arg.isPic && !cast<Defined>(Val&: *rHi20.sym).section) ||
1140 rHi20.addend != 0 || rLo12.addend != 0))
1141 return;
1142
1143 uint64_t dest = 0;
1144 if (rHi20.expr == RE_LOONGARCH_PLT_PAGE_PC)
1145 dest = rHi20.sym->getPltVA(ctx);
1146 else if (rHi20.expr == RE_LOONGARCH_PAGE_PC ||
1147 rHi20.expr == RE_LOONGARCH_GOT_PAGE_PC)
1148 dest = rHi20.sym->getVA(ctx);
1149 else if (rHi20.expr == RE_LOONGARCH_TLSGD_PAGE_PC)
1150 dest = ctx.in.got->getGlobalDynAddr(b: *rHi20.sym);
1151 else if (rHi20.expr == RE_LOONGARCH_TLSDESC_PAGE_PC)
1152 dest = ctx.in.got->getTlsDescAddr(sym: *rHi20.sym);
1153 else {
1154 Err(ctx) << getErrorLoc(ctx, loc: (const uint8_t *)loc) << "unknown expr ("
1155 << rHi20.expr << ") against symbol " << rHi20.sym
1156 << "in relaxPCHi20Lo12";
1157 return;
1158 }
1159 dest += rHi20.addend;
1160
1161 const int64_t displace = dest - loc;
1162 // Check if the displace aligns 4 bytes or exceeds the range of pcaddi.
1163 if ((displace & 0x3) != 0 || !isInt<22>(x: displace))
1164 return;
1165
1166 // Note: If we can ensure that the .o files generated by LLVM only contain
1167 // relaxable instruction sequences with R_LARCH_RELAX, then we do not need to
1168 // decode instructions. The relaxable instruction sequences imply the
1169 // following constraints:
1170 // * For relocation pairs related to got_pc, the opcodes of instructions
1171 // must be pcalau12i + ld.w/d. In other cases, the opcodes must be pcalau12i +
1172 // addi.w/d.
1173 // * The destination register of pcalau12i is guaranteed to be used only by
1174 // the immediately following instruction.
1175 const uint32_t currInsn = read32le(P: sec.content().data() + rHi20.offset);
1176 const uint32_t nextInsn = read32le(P: sec.content().data() + rLo12.offset);
1177 // Check if use the same register.
1178 if (getD5(v: currInsn) != getJ5(v: nextInsn) || getJ5(v: nextInsn) != getD5(v: nextInsn))
1179 return;
1180
1181 sec.relaxAux->relocTypes[i] = R_LARCH_RELAX;
1182 if (rHi20.type == R_LARCH_TLS_GD_PC_HI20)
1183 sec.relaxAux->relocTypes[i + 2] = R_LARCH_TLS_GD_PCREL20_S2;
1184 else if (rHi20.type == R_LARCH_TLS_LD_PC_HI20)
1185 sec.relaxAux->relocTypes[i + 2] = R_LARCH_TLS_LD_PCREL20_S2;
1186 else if (rHi20.type == R_LARCH_TLS_DESC_PC_HI20)
1187 sec.relaxAux->relocTypes[i + 2] = R_LARCH_TLS_DESC_PCREL20_S2;
1188 else
1189 sec.relaxAux->relocTypes[i + 2] = R_LARCH_PCREL20_S2;
1190 sec.relaxAux->writes.push_back(Elt: insn(op: PCADDI, d: getD5(v: nextInsn), j: 0, k: 0));
1191 remove = 4;
1192}
1193
1194// Relax code sequence.
1195// From:
1196// la32r:
1197// pcaddu12i $ra, %call30(foo)
1198// jirl $ra, $ra, 0
1199// la32s/la64:
1200// pcaddu18i $ra, %call36(foo)
1201// jirl $ra, $ra, 0
1202// To:
1203// b/bl foo
1204static void relaxMediumCall(Ctx &ctx, const InputSection &sec, size_t i,
1205 uint64_t loc, Relocation &r, uint32_t &remove) {
1206 const uint64_t dest =
1207 (r.expr == R_PLT_PC ? r.sym->getPltVA(ctx) : r.sym->getVA(ctx)) +
1208 r.addend;
1209
1210 const int64_t displace = dest - loc;
1211 // Check if the displace aligns 4 bytes or exceeds the range of b[l].
1212 if ((displace & 0x3) != 0 || !isInt<28>(x: displace))
1213 return;
1214
1215 const uint32_t nextInsn = read32le(P: sec.content().data() + r.offset + 4);
1216 if (getD5(v: nextInsn) == R_RA) {
1217 // convert jirl to bl
1218 sec.relaxAux->relocTypes[i] = R_LARCH_B26;
1219 sec.relaxAux->writes.push_back(Elt: insn(op: BL, d: 0, j: 0, k: 0));
1220 remove = 4;
1221 } else if (getD5(v: nextInsn) == R_ZERO) {
1222 // convert jirl to b
1223 sec.relaxAux->relocTypes[i] = R_LARCH_B26;
1224 sec.relaxAux->writes.push_back(Elt: insn(op: B, d: 0, j: 0, k: 0));
1225 remove = 4;
1226 }
1227}
1228
1229// Relax code sequence.
1230// From:
1231// lu12i.w $rd, %le_hi20_r(sym)
1232// add.w/d $rd, $rd, $tp, %le_add_r(sym)
1233// addi/ld/st.w/d $rd, $rd, %le_lo12_r(sym)
1234// To:
1235// addi/ld/st.w/d $rd, $tp, %le_lo12_r(sym)
1236static void relaxTlsLe(Ctx &ctx, const InputSection &sec, size_t i,
1237 uint64_t loc, Relocation &r, uint32_t &remove) {
1238 uint64_t val = r.sym->getVA(ctx, addend: r.addend);
1239 // Check if the val exceeds the range of addi/ld/st.
1240 if (!isInt<12>(x: val))
1241 return;
1242 uint32_t currInsn = read32le(P: sec.content().data() + r.offset);
1243 switch (r.type) {
1244 case R_LARCH_TLS_LE_HI20_R:
1245 case R_LARCH_TLS_LE_ADD_R:
1246 sec.relaxAux->relocTypes[i] = R_LARCH_RELAX;
1247 remove = 4;
1248 break;
1249 case R_LARCH_TLS_LE_LO12_R:
1250 sec.relaxAux->writes.push_back(Elt: setJ5(insn: currInsn, imm: R_TP));
1251 sec.relaxAux->relocTypes[i] = R_LARCH_TLS_LE_LO12_R;
1252 break;
1253 }
1254}
1255
1256static bool relax(Ctx &ctx, InputSection &sec) {
1257 const uint64_t secAddr = sec.getVA();
1258 const MutableArrayRef<Relocation> relocs = sec.relocs();
1259 auto &aux = *sec.relaxAux;
1260 bool changed = false;
1261 ArrayRef<SymbolAnchor> sa = ArrayRef(aux.anchors);
1262 uint64_t delta = 0;
1263
1264 std::fill_n(first: aux.relocTypes.get(), n: relocs.size(), value: R_LARCH_NONE);
1265 aux.writes.clear();
1266 for (auto [i, r] : llvm::enumerate(First: relocs)) {
1267 const uint64_t loc = secAddr + r.offset - delta;
1268 uint32_t &cur = aux.relocDeltas[i], remove = 0;
1269 switch (r.type) {
1270 case R_LARCH_ALIGN: {
1271 const uint64_t addend =
1272 r.sym->isUndefined() ? Log2_64(Value: r.addend) + 1 : r.addend;
1273 const uint64_t allBytes = (1ULL << (addend & 0xff)) - 4;
1274 const uint64_t align = 1ULL << (addend & 0xff);
1275 const uint64_t maxBytes = addend >> 8;
1276 const uint64_t off = loc & (align - 1);
1277 const uint64_t curBytes = off == 0 ? 0 : align - off;
1278 // All bytes beyond the alignment boundary should be removed.
1279 // If emit bytes more than max bytes to emit, remove all.
1280 if (maxBytes != 0 && curBytes > maxBytes)
1281 remove = allBytes;
1282 else
1283 remove = allBytes - curBytes;
1284 // If we can't satisfy this alignment, we've found a bad input.
1285 if (LLVM_UNLIKELY(static_cast<int32_t>(remove) < 0)) {
1286 Err(ctx) << getErrorLoc(ctx, loc: (const uint8_t *)loc)
1287 << "insufficient padding bytes for " << r.type << ": "
1288 << allBytes << " bytes available for "
1289 << "requested alignment of " << align << " bytes";
1290 remove = 0;
1291 }
1292 break;
1293 }
1294 case R_LARCH_PCALA_HI20:
1295 case R_LARCH_GOT_PC_HI20:
1296 case R_LARCH_TLS_GD_PC_HI20:
1297 case R_LARCH_TLS_LD_PC_HI20:
1298 // The overflow check for i+2 will be carried out in isPairRelaxable.
1299 if (isPairRelaxable(relocs, i))
1300 relaxPCHi20Lo12(ctx, sec, i, loc, rHi20&: r, rLo12&: relocs[i + 2], remove);
1301 break;
1302 case R_LARCH_TLS_DESC_PC_HI20:
1303 if (r.expr == RE_LOONGARCH_GOT_PAGE_PC || r.expr == R_TPREL) {
1304 if (relaxable(relocs, i))
1305 remove = 4;
1306 } else if (isPairRelaxable(relocs, i))
1307 relaxPCHi20Lo12(ctx, sec, i, loc, rHi20&: r, rLo12&: relocs[i + 2], remove);
1308 break;
1309 case R_LARCH_CALL30:
1310 case R_LARCH_CALL36:
1311 if (relaxable(relocs, i))
1312 relaxMediumCall(ctx, sec, i, loc, r, remove);
1313 break;
1314 case R_LARCH_TLS_LE_HI20_R:
1315 case R_LARCH_TLS_LE_ADD_R:
1316 case R_LARCH_TLS_LE_LO12_R:
1317 if (relaxable(relocs, i))
1318 relaxTlsLe(ctx, sec, i, loc, r, remove);
1319 break;
1320 case R_LARCH_TLS_IE_PC_HI20:
1321 if (relaxable(relocs, i) && r.expr == R_TPREL &&
1322 isUInt<12>(x: r.sym->getVA(ctx, addend: r.addend)))
1323 remove = 4;
1324 break;
1325 case R_LARCH_TLS_DESC_PC_LO12:
1326 if (relaxable(relocs, i) &&
1327 (r.expr == RE_LOONGARCH_GOT_PAGE_PC || r.expr == R_TPREL))
1328 remove = 4;
1329 break;
1330 case R_LARCH_TLS_DESC_LD:
1331 if (relaxable(relocs, i) && r.expr == R_TPREL &&
1332 isUInt<12>(x: r.sym->getVA(ctx, addend: r.addend)))
1333 remove = 4;
1334 break;
1335 }
1336
1337 // For all anchors whose offsets are <= r.offset, they are preceded by
1338 // the previous relocation whose `relocDeltas` value equals `delta`.
1339 // Decrease their st_value and update their st_size.
1340 for (; sa.size() && sa[0].offset <= r.offset; sa = sa.slice(N: 1)) {
1341 if (sa[0].end)
1342 sa[0].d->size = sa[0].offset - delta - sa[0].d->value;
1343 else
1344 sa[0].d->value = sa[0].offset - delta;
1345 }
1346 delta += remove;
1347 if (delta != cur) {
1348 cur = delta;
1349 changed = true;
1350 }
1351 }
1352
1353 for (const SymbolAnchor &a : sa) {
1354 if (a.end)
1355 a.d->size = a.offset - delta - a.d->value;
1356 else
1357 a.d->value = a.offset - delta;
1358 }
1359 // Inform assignAddresses that the size has changed.
1360 if (!isUInt<32>(x: delta))
1361 Fatal(ctx) << "section size decrease is too large: " << delta;
1362 sec.bytesDropped = delta;
1363 return changed;
1364}
1365
1366// Convert TLS IE to LE in the normal or medium code model.
1367// Original code sequence:
1368// * pcalau12i $a0, %ie_pc_hi20(sym)
1369// * ld.d $a0, $a0, %ie_pc_lo12(sym)
1370//
1371// The code sequence converted is as follows:
1372// * lu12i.w $a0, %le_hi20(sym) # le_hi20 != 0, otherwise NOP
1373// * ori $a0, src, %le_lo12(sym) # le_hi20 != 0, src = $a0,
1374// # otherwise, src = $zero
1375//
1376// When relaxation enables, redundant NOPs can be removed.
1377static void tlsIeToLe(uint8_t *loc, const Relocation &rel, uint64_t val) {
1378 assert(isInt<32>(val) &&
1379 "val exceeds the range of medium code model in tlsIeToLe");
1380
1381 bool isUInt12 = isUInt<12>(x: val);
1382 const uint32_t currInsn = read32le(P: loc);
1383 switch (rel.type) {
1384 case R_LARCH_TLS_IE_PC_HI20:
1385 if (isUInt12)
1386 write32le(P: loc, V: insn(op: ANDI, d: R_ZERO, j: R_ZERO, k: 0)); // nop
1387 else
1388 write32le(P: loc, V: insn(op: LU12I_W, d: getD5(v: currInsn), j: extractBits(v: val, begin: 31, end: 12),
1389 k: 0)); // lu12i.w $a0, %le_hi20
1390 break;
1391 case R_LARCH_TLS_IE_PC_LO12:
1392 if (isUInt12)
1393 write32le(P: loc, V: insn(op: ORI, d: getD5(v: currInsn), j: R_ZERO,
1394 k: val)); // ori $a0, $zero, %le_lo12
1395 else
1396 write32le(P: loc, V: insn(op: ORI, d: getD5(v: currInsn), j: getJ5(v: currInsn),
1397 k: lo12(val))); // ori $a0, $a0, %le_lo12
1398 break;
1399 }
1400}
1401
1402// Convert TLSDESC GD/LD to IE.
1403// In normal or medium code model, there are two forms of code sequences:
1404// * pcalau12i $a0, %desc_pc_hi20(sym_desc)
1405// * addi.d $a0, $a0, %desc_pc_lo12(sym_desc)
1406// * ld.d $ra, $a0, %desc_ld(sym_desc)
1407// * jirl $ra, $ra, %desc_call(sym_desc)
1408// ------
1409// * pcaddi $a0, %desc_pcrel_20(a)
1410// * load $ra, $a0, %desc_ld(a)
1411// * jirl $ra, $ra, %desc_call(a)
1412//
1413// The code sequence obtained is as follows:
1414// * pcalau12i $a0, %ie_pc_hi20(sym_ie)
1415// * ld.[wd] $a0, $a0, %ie_pc_lo12(sym_ie)
1416//
1417// Simplicity, whether tlsdescToIe or tlsdescToLe, we always tend to convert the
1418// preceding instructions to NOPs, due to both forms of code sequence
1419// (corresponding to relocation combinations:
1420// R_LARCH_TLS_DESC_PC_HI20+R_LARCH_TLS_DESC_PC_LO12 and
1421// R_LARCH_TLS_DESC_PCREL20_S2) have same process.
1422//
1423// When relaxation enables, redundant NOPs can be removed.
1424void LoongArch::tlsdescToIe(uint8_t *loc, const Relocation &rel,
1425 uint64_t val) const {
1426 switch (rel.type) {
1427 case R_LARCH_TLS_DESC_PC_HI20:
1428 case R_LARCH_TLS_DESC_PC_LO12:
1429 case R_LARCH_TLS_DESC_PCREL20_S2:
1430 write32le(P: loc, V: insn(op: ANDI, d: R_ZERO, j: R_ZERO, k: 0)); // nop
1431 break;
1432 case R_LARCH_TLS_DESC_LD:
1433 write32le(P: loc, V: insn(op: PCALAU12I, d: R_A0, j: 0, k: 0)); // pcalau12i $a0, %ie_pc_hi20
1434 relocateNoSym(loc, type: R_LARCH_TLS_IE_PC_HI20, val);
1435 break;
1436 case R_LARCH_TLS_DESC_CALL:
1437 write32le(P: loc, V: insn(op: ctx.arg.is64 ? LD_D : LD_W, d: R_A0, j: R_A0,
1438 k: 0)); // ld.[wd] $a0, $a0, %ie_pc_lo12
1439 relocateNoSym(loc, type: R_LARCH_TLS_IE_PC_LO12, val);
1440 break;
1441 default:
1442 llvm_unreachable("unsupported relocation for TLSDESC to IE");
1443 }
1444}
1445
1446// Convert TLSDESC GD/LD to LE.
1447// The code sequence obtained in the normal or medium code model is as follows:
1448// * lu12i.w $a0, %le_hi20(sym) # le_hi20 != 0, otherwise NOP
1449// * ori $a0, src, %le_lo12(sym) # le_hi20 != 0, src = $a0,
1450// # otherwise, src = $zero
1451// See the comment in tlsdescToIe for detailed information.
1452void LoongArch::tlsdescToLe(uint8_t *loc, const Relocation &rel,
1453 uint64_t val) const {
1454 assert(isInt<32>(val) &&
1455 "val exceeds the range of medium code model in tlsdescToLe");
1456
1457 bool isUInt12 = isUInt<12>(x: val);
1458 switch (rel.type) {
1459 case R_LARCH_TLS_DESC_PC_HI20:
1460 case R_LARCH_TLS_DESC_PC_LO12:
1461 case R_LARCH_TLS_DESC_PCREL20_S2:
1462 write32le(P: loc, V: insn(op: ANDI, d: R_ZERO, j: R_ZERO, k: 0)); // nop
1463 break;
1464 case R_LARCH_TLS_DESC_LD:
1465 if (isUInt12)
1466 write32le(P: loc, V: insn(op: ANDI, d: R_ZERO, j: R_ZERO, k: 0)); // nop
1467 else
1468 write32le(P: loc, V: insn(op: LU12I_W, d: R_A0, j: extractBits(v: val, begin: 31, end: 12),
1469 k: 0)); // lu12i.w $a0, %le_hi20
1470 break;
1471 case R_LARCH_TLS_DESC_CALL:
1472 if (isUInt12)
1473 write32le(P: loc, V: insn(op: ORI, d: R_A0, j: R_ZERO, k: val)); // ori $a0, $zero, %le_lo12
1474 else
1475 write32le(P: loc,
1476 V: insn(op: ORI, d: R_A0, j: R_A0, k: lo12(val))); // ori $a0, $a0, %le_lo12
1477 break;
1478 default:
1479 llvm_unreachable("unsupported relocation for TLSDESC to LE");
1480 }
1481}
1482
1483// Try GOT indirection to PC relative optimization.
1484// From:
1485// * pcalau12i $a0, %got_pc_hi20(sym_got)
1486// * ld.w/d $a0, $a0, %got_pc_lo12(sym_got)
1487// To:
1488// * pcalau12i $a0, %pc_hi20(sym)
1489// * addi.w/d $a0, $a0, %pc_lo12(sym)
1490//
1491// Note: Althouth the optimization has been performed, the GOT entries still
1492// exists, similarly to AArch64. Eliminating the entries will increase code
1493// complexity.
1494bool LoongArch::tryGotToPCRel(uint8_t *loc, const Relocation &rHi20,
1495 const Relocation &rLo12, uint64_t secAddr) const {
1496 // Check if the relocations apply to consecutive instructions.
1497 if (rHi20.offset + 4 != rLo12.offset)
1498 return false;
1499
1500 // Check if the relocations reference the same symbol and skip undefined,
1501 // preemptible and STT_GNU_IFUNC symbols.
1502 if (!rHi20.sym || rHi20.sym != rLo12.sym || !rHi20.sym->isDefined() ||
1503 rHi20.sym->isPreemptible || rHi20.sym->isGnuIFunc())
1504 return false;
1505
1506 // GOT references to absolute symbols can't be relaxed to use PCALAU12I/ADDI
1507 // in position-independent code because these instructions produce a relative
1508 // address.
1509 if ((ctx.arg.isPic && !cast<Defined>(Val&: *rHi20.sym).section))
1510 return false;
1511
1512 // Check if the addends of the both relocations are zero.
1513 if (rHi20.addend != 0 || rLo12.addend != 0)
1514 return false;
1515
1516 const uint32_t currInsn = read32le(P: loc);
1517 const uint32_t nextInsn = read32le(P: loc + 4);
1518 const uint32_t ldOpcode = ctx.arg.is64 ? LD_D : LD_W;
1519 // Check if the first instruction is PCALAU12I and the second instruction is
1520 // LD.
1521 if ((currInsn & 0xfe000000) != PCALAU12I ||
1522 (nextInsn & 0xffc00000) != ldOpcode)
1523 return false;
1524
1525 // Check if use the same register.
1526 if (getD5(v: currInsn) != getJ5(v: nextInsn) || getJ5(v: nextInsn) != getD5(v: nextInsn))
1527 return false;
1528
1529 Symbol &sym = *rHi20.sym;
1530 uint64_t symLocal = sym.getVA(ctx);
1531 const int64_t displace = symLocal - getLoongArchPage(p: secAddr + rHi20.offset);
1532 // Check if the symbol address is in
1533 // [(PC & ~0xfff) - 2GiB - 0x800, (PC & ~0xfff) + 2GiB - 0x800).
1534 const int64_t underflow = -0x80000000LL - 0x800;
1535 const int64_t overflow = 0x80000000LL - 0x800;
1536 if (!(displace >= underflow && displace < overflow))
1537 return false;
1538
1539 Relocation newRHi20 = {.expr: RE_LOONGARCH_PAGE_PC, .type: R_LARCH_PCALA_HI20, .offset: rHi20.offset,
1540 .addend: rHi20.addend, .sym: &sym};
1541 Relocation newRLo12 = {.expr: R_ABS, .type: R_LARCH_PCALA_LO12, .offset: rLo12.offset, .addend: rLo12.addend,
1542 .sym: &sym};
1543 uint64_t pageDelta =
1544 getLoongArchPageDelta(dest: symLocal, pc: secAddr + rHi20.offset, type: rHi20.type);
1545 // pcalau12i $a0, %pc_hi20
1546 write32le(P: loc, V: insn(op: PCALAU12I, d: getD5(v: currInsn), j: 0, k: 0));
1547 relocate(loc, rel: newRHi20, val: pageDelta);
1548 // addi.w/d $a0, $a0, %pc_lo12
1549 write32le(P: loc + 4, V: insn(op: ctx.arg.is64 ? ADDI_D : ADDI_W, d: getD5(v: nextInsn),
1550 j: getJ5(v: nextInsn), k: 0));
1551 relocate(loc: loc + 4, rel: newRLo12, val: SignExtend64(X: symLocal, B: 64));
1552 return true;
1553}
1554
1555// During TLSDESC to IE, the converted code sequence always includes an
1556// instruction related to the Lo12 relocation (ld.[wd]). To obtain correct val
1557// in `getRelocTargetVA`, expr of this instruction should be adjusted to R_GOT,
1558// while expr of other instructions related to the Hi20 relocation (pcalau12i)
1559// should be adjusted to RE_LOONGARCH_GOT_PAGE_PC. Specifically, in the normal
1560// or medium code model, the instruction with relocation R_LARCH_TLS_DESC_CALL
1561// is the candidate of Lo12 relocation.
1562
1563static bool pairForGotRels(ArrayRef<Relocation> relocs) {
1564 // Check if R_LARCH_GOT_PC_HI20 and R_LARCH_GOT_PC_LO12 always appear in
1565 // pairs.
1566 size_t i = 0;
1567 const size_t size = relocs.size();
1568 for (; i != size; ++i) {
1569 if (relocs[i].type == R_LARCH_GOT_PC_HI20) {
1570 if (i + 1 < size && relocs[i + 1].type == R_LARCH_GOT_PC_LO12) {
1571 ++i;
1572 continue;
1573 }
1574 if (relaxable(relocs, i) && i + 2 < size &&
1575 relocs[i + 2].type == R_LARCH_GOT_PC_LO12) {
1576 i += 2;
1577 continue;
1578 }
1579 break;
1580 } else if (relocs[i].type == R_LARCH_GOT_PC_LO12) {
1581 break;
1582 }
1583 }
1584 return i == size;
1585}
1586
1587void LoongArch::relocateAlloc(InputSection &sec, uint8_t *buf) const {
1588 const unsigned bits = ctx.arg.is64 ? 64 : 32;
1589 uint64_t secAddr = sec.getOutputSection()->addr + sec.outSecOff;
1590 bool isExtreme = false;
1591 const MutableArrayRef<Relocation> relocs = sec.relocs();
1592 const bool isPairForGotRels = pairForGotRels(relocs);
1593 for (size_t i = 0, size = relocs.size(); i != size; ++i) {
1594 Relocation &rel = relocs[i];
1595 if (rel.expr == R_RELAX_HINT)
1596 continue;
1597 uint8_t *loc = buf + rel.offset;
1598 uint64_t val = SignExtend64(
1599 X: sec.getRelocTargetVA(ctx, r: rel, p: secAddr + rel.offset), B: bits);
1600 switch (rel.type) {
1601 case R_LARCH_TLS_IE_PC_HI20:
1602 case R_LARCH_TLS_IE_PC_LO12:
1603 // IE to LE. Not supported in extreme code model.
1604 if (rel.expr != R_TPREL)
1605 break;
1606 if (rel.type == R_LARCH_TLS_IE_PC_HI20)
1607 isExtreme =
1608 i + 2 < size && relocs[i + 2].type == R_LARCH_TLS_IE64_PC_LO20;
1609 if (isExtreme) {
1610 rel.expr = getRelExpr(type: rel.type, s: *rel.sym, loc);
1611 val = SignExtend64(X: sec.getRelocTargetVA(ctx, r: rel, p: secAddr + rel.offset),
1612 B: bits);
1613 break;
1614 }
1615 if (relaxable(relocs, i) && rel.type == R_LARCH_TLS_IE_PC_HI20 &&
1616 isUInt<12>(x: val))
1617 continue;
1618 tlsIeToLe(loc, rel, val);
1619 continue;
1620
1621 case R_LARCH_TLS_DESC_PC_HI20:
1622 case R_LARCH_TLS_DESC_PC_LO12:
1623 case R_LARCH_TLS_DESC_LD:
1624 case R_LARCH_TLS_DESC_PCREL20_S2:
1625 // TLSDESC to LE/IE. Not supported in extreme code model.
1626 if (rel.expr != R_TPREL && rel.expr != RE_LOONGARCH_GOT_PAGE_PC)
1627 break;
1628 if (rel.type == R_LARCH_TLS_DESC_PC_HI20)
1629 isExtreme =
1630 i + 2 < size && relocs[i + 2].type == R_LARCH_TLS_DESC64_PC_LO20;
1631 if (isExtreme) {
1632 rel.expr = getRelExpr(type: rel.type, s: *rel.sym, loc);
1633 val = SignExtend64(X: sec.getRelocTargetVA(ctx, r: rel, p: secAddr + rel.offset),
1634 B: bits);
1635 break;
1636 }
1637 if (relaxable(relocs, i) && (rel.type == R_LARCH_TLS_DESC_PC_HI20 ||
1638 rel.type == R_LARCH_TLS_DESC_PC_LO12))
1639 continue;
1640 if (rel.expr == R_TPREL) {
1641 if (relaxable(relocs, i) && rel.type == R_LARCH_TLS_DESC_LD &&
1642 isUInt<12>(x: val))
1643 continue;
1644 tlsdescToLe(loc, rel, val);
1645 } else {
1646 tlsdescToIe(loc, rel, val);
1647 }
1648 continue;
1649
1650 case R_LARCH_TLS_DESC_CALL:
1651 if (isExtreme)
1652 continue;
1653 if (rel.expr == R_TPREL)
1654 tlsdescToLe(loc, rel, val);
1655 else
1656 tlsdescToIe(loc, rel, val);
1657 continue;
1658
1659 case R_LARCH_GOT_PC_HI20:
1660 // GOT indirection to PC relative optimization in normal or medium code
1661 // model, whether or not with R_LARCH_RELAX. If the code sequence can be
1662 // relaxed to a single pcaddi, the first instruction will be removed and
1663 // it will not reach here.
1664 if (isPairForGotRels) {
1665 bool isRelax = relaxable(relocs, i);
1666 const Relocation lo12Rel = isRelax ? relocs[i + 2] : relocs[i + 1];
1667 if (lo12Rel.type == R_LARCH_GOT_PC_LO12 &&
1668 tryGotToPCRel(loc, rHi20: rel, rLo12: lo12Rel, secAddr)) {
1669 i += isRelax ? 2 : 1;
1670 continue;
1671 }
1672 }
1673 break;
1674
1675 default:
1676 break;
1677 }
1678 relocate(loc, rel, val);
1679 }
1680}
1681
1682// When relaxing just R_LARCH_ALIGN, relocDeltas is usually changed only once in
1683// the absence of a linker script. For call and load/store R_LARCH_RELAX, code
1684// shrinkage may reduce displacement and make more relocations eligible for
1685// relaxation. Code shrinkage may increase displacement to a call/load/store
1686// target at a higher fixed address, invalidating an earlier relaxation. Any
1687// change in section sizes can have cascading effect and require another
1688// relaxation pass.
1689bool LoongArch::relaxOnce(int pass) const {
1690 if (pass == 0)
1691 initSymbolAnchors(ctx);
1692
1693 SmallVector<InputSection *, 0> storage;
1694 bool changed = false;
1695 for (OutputSection *osec : ctx.outputSections) {
1696 if (!(osec->flags & SHF_EXECINSTR))
1697 continue;
1698 for (InputSection *sec : getInputSections(os: *osec, storage))
1699 if (sec->relaxAux)
1700 changed |= relax(ctx, sec&: *sec);
1701 }
1702 return changed;
1703}
1704
1705void LoongArch::finalizeRelax(int passes) const {
1706 Log(ctx) << "relaxation passes: " << passes;
1707 SmallVector<InputSection *, 0> storage;
1708 for (OutputSection *osec : ctx.outputSections) {
1709 if (!(osec->flags & SHF_EXECINSTR))
1710 continue;
1711 for (InputSection *sec : getInputSections(os: *osec, storage)) {
1712 if (!sec->relaxAux)
1713 continue;
1714 RelaxAux &aux = *sec->relaxAux;
1715 if (!aux.relocDeltas)
1716 continue;
1717
1718 MutableArrayRef<Relocation> rels = sec->relocs();
1719 ArrayRef<uint8_t> old = sec->content();
1720 size_t newSize = old.size() - aux.relocDeltas[rels.size() - 1];
1721 size_t writesIdx = 0;
1722 uint8_t *p = ctx.bAlloc.Allocate<uint8_t>(Num: newSize);
1723 uint64_t offset = 0;
1724 int64_t delta = 0;
1725 sec->content_ = p;
1726 sec->size = newSize;
1727 sec->bytesDropped = 0;
1728
1729 // Update section content: remove NOPs for R_LARCH_ALIGN and rewrite
1730 // instructions for relaxed relocations.
1731 for (size_t i = 0, e = rels.size(); i != e; ++i) {
1732 uint32_t remove = aux.relocDeltas[i] - delta;
1733 delta = aux.relocDeltas[i];
1734 if (remove == 0 && aux.relocTypes[i] == R_LARCH_NONE)
1735 continue;
1736
1737 // Copy from last location to the current relocated location.
1738 Relocation &r = rels[i];
1739 uint64_t size = r.offset - offset;
1740 memcpy(dest: p, src: old.data() + offset, n: size);
1741 p += size;
1742
1743 int64_t skip = 0;
1744 if (RelType newType = aux.relocTypes[i]) {
1745 switch (newType) {
1746 case R_LARCH_RELAX:
1747 break;
1748 case R_LARCH_PCREL20_S2:
1749 skip = 4;
1750 write32le(P: p, V: aux.writes[writesIdx++]);
1751 // RelExpr is needed for relocating.
1752 r.expr = r.sym->hasFlag(bit: NEEDS_PLT) ? R_PLT_PC : R_PC;
1753 break;
1754 case R_LARCH_B26:
1755 case R_LARCH_TLS_LE_LO12_R:
1756 skip = 4;
1757 write32le(P: p, V: aux.writes[writesIdx++]);
1758 break;
1759 case R_LARCH_TLS_GD_PCREL20_S2:
1760 // Note: R_LARCH_TLS_LD_PCREL20_S2 must also use R_TLSGD_PC instead
1761 // of R_TLSLD_PC due to historical reasons. In fact, right now TLSLD
1762 // behaves exactly like TLSGD on LoongArch.
1763 //
1764 // This reason has also been mentioned in mold commit:
1765 // https://github.com/rui314/mold/commit/5dfa1cf07c03bd57cb3d493b652ef22441bcd71c
1766 case R_LARCH_TLS_LD_PCREL20_S2:
1767 skip = 4;
1768 write32le(P: p, V: aux.writes[writesIdx++]);
1769 r.expr = R_TLSGD_PC;
1770 break;
1771 case R_LARCH_TLS_DESC_PCREL20_S2:
1772 skip = 4;
1773 write32le(P: p, V: aux.writes[writesIdx++]);
1774 r.expr = R_TLSDESC_PC;
1775 break;
1776 default:
1777 llvm_unreachable("unsupported type");
1778 }
1779 }
1780
1781 p += skip;
1782 offset = r.offset + skip + remove;
1783 }
1784 memcpy(dest: p, src: old.data() + offset, n: old.size() - offset);
1785
1786 // Subtract the previous relocDeltas value from the relocation offset.
1787 // For a pair of R_LARCH_XXX/R_LARCH_RELAX with the same offset, decrease
1788 // their r_offset by the same delta.
1789 delta = 0;
1790 for (size_t i = 0, e = rels.size(); i != e;) {
1791 uint64_t cur = rels[i].offset;
1792 do {
1793 rels[i].offset -= delta;
1794 if (aux.relocTypes[i] != R_LARCH_NONE)
1795 rels[i].type = aux.relocTypes[i];
1796 } while (++i != e && rels[i].offset == cur);
1797 delta = aux.relocDeltas[i - 1];
1798 }
1799 }
1800 }
1801}
1802
1803void elf::setLoongArchTargetInfo(Ctx &ctx) {
1804 ctx.target.reset(p: new LoongArch(ctx));
1805}
1806