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>, unsigned shard);
42 void scanSection(InputSectionBase &sec, unsigned shard) override {
43 if (ctx.arg.is64)
44 elf::scanSection1<LoongArch, ELF64LE>(target&: *this, sec, shard);
45 else
46 elf::scanSection1<LoongArch, ELF32LE>(target&: *this, sec, shard);
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 unsigned shard) {
484 RelocScan rs(ctx, &sec, shard);
485 sec.relocations.reserve(N: rels.size());
486 for (auto it = rels.begin(); it != rels.end(); ++it) {
487 RelType type = it->getType(false);
488 uint32_t symIndex = it->getSymbol(false);
489 Symbol &sym = sec.getFile<ELFT>()->getSymbol(symIndex);
490 uint64_t offset = it->r_offset;
491 if (sym.isUndefined() && symIndex != 0 &&
492 rs.maybeReportUndefined(sym&: cast<Undefined>(Val&: sym), offset))
493 continue;
494 int64_t addend = rs.getAddend<ELFT>(*it, type);
495 RelExpr expr;
496 // Relocation types that only need a RelExpr set `expr` and break out of
497 // the switch to reach rs.process(). Types that need special handling
498 // (fast-path helpers, TLS) call a handler and use `continue`.
499 switch (type) {
500 case R_LARCH_NONE:
501 case R_LARCH_MARK_LA:
502 case R_LARCH_MARK_PCREL:
503 continue;
504
505 // Absolute relocations:
506 case R_LARCH_32:
507 case R_LARCH_64:
508 case R_LARCH_ABS_HI20:
509 case R_LARCH_ABS_LO12:
510 case R_LARCH_ABS64_LO20:
511 case R_LARCH_ABS64_HI12:
512 expr = R_ABS;
513 break;
514
515 case R_LARCH_PCALA_LO12:
516 // R_LARCH_PCALA_LO12 on JIRL is used for function calls (glibc 2.37).
517 expr = isJirl(insn: read32le(P: sec.content().data() + offset)) ? R_PLT : R_ABS;
518 break;
519
520 // PC-indirect relocations (lo12 paired with a preceding hi20 pcadd):
521 case R_LARCH_PCADD_LO12:
522 case R_LARCH_GOT_PCADD_LO12:
523 case R_LARCH_TLS_IE_PCADD_LO12:
524 case R_LARCH_TLS_LD_PCADD_LO12:
525 case R_LARCH_TLS_GD_PCADD_LO12:
526 case R_LARCH_TLS_DESC_PCADD_LO12:
527 expr = RE_LOONGARCH_PC_INDIRECT;
528 break;
529
530 // PC-relative relocations:
531 case R_LARCH_32_PCREL:
532 case R_LARCH_64_PCREL:
533 case R_LARCH_PCREL20_S2:
534 case R_LARCH_PCADD_HI20:
535 rs.processR_PC(type, offset, addend, sym);
536 continue;
537
538 // PLT-generating relocations:
539 case R_LARCH_B16:
540 case R_LARCH_B21:
541 case R_LARCH_B26:
542 case R_LARCH_CALL30:
543 case R_LARCH_CALL36:
544 rs.processR_PLT_PC(type, offset, addend, sym);
545 continue;
546
547 // Page-PC relocations:
548 case R_LARCH_PCALA_HI20:
549 // Why not RE_LOONGARCH_PAGE_PC, majority of references don't go through
550 // PLT anyway so why waste time checking only to get everything relaxed
551 // back to it?
552 //
553 // This is again due to the R_LARCH_PCALA_LO12 on JIRL case, where we want
554 // both the HI20 and LO12 to potentially refer to the PLT. But in reality
555 // the HI20 reloc appears earlier, and the relocs don't contain enough
556 // information to let us properly resolve semantics per symbol.
557 // Unlike RISCV, our LO12 relocs *do not* point to their corresponding
558 // HI20 relocs, hence it is nearly impossible to 100% accurately determine
559 // each HI20's "flavor" without taking big performance hits, in the
560 // presence of edge cases (e.g. HI20 without pairing LO12; paired LO12
561 // placed so far apart that relationship is not certain anymore), and
562 // programmer mistakes (e.g. as outlined in
563 // https://github.com/loongson/la-abi-specs/pull/3).
564 //
565 // Ideally we would scan in an extra pass for all LO12s on JIRL, then mark
566 // every HI20 reloc referring to the same symbol differently; this is not
567 // feasible with the current function signature of getRelExpr that doesn't
568 // allow for such inter-pass state.
569 //
570 // So, unfortunately we have to again workaround this quirk the same way
571 // as BFD: assuming every R_LARCH_PCALA_HI20 is potentially PLT-needing,
572 // only relaxing back to RE_LOONGARCH_PAGE_PC if it's known not so at a
573 // later stage.
574 expr = RE_LOONGARCH_PLT_PAGE_PC;
575 break;
576 case R_LARCH_PCALA64_LO20:
577 case R_LARCH_PCALA64_HI12:
578 expr = RE_LOONGARCH_PAGE_PC;
579 break;
580
581 // GOT-generating relocations:
582 case R_LARCH_GOT_PC_HI20:
583 case R_LARCH_GOT64_PC_LO20:
584 case R_LARCH_GOT64_PC_HI12:
585 expr = RE_LOONGARCH_GOT_PAGE_PC;
586 break;
587 case R_LARCH_GOT_PCADD_HI20:
588 expr = R_GOT_PC;
589 break;
590 case R_LARCH_GOT_PC_LO12:
591 expr = RE_LOONGARCH_GOT;
592 break;
593 case R_LARCH_GOT_HI20:
594 case R_LARCH_GOT_LO12:
595 case R_LARCH_GOT64_LO20:
596 case R_LARCH_GOT64_HI12:
597 expr = R_GOT;
598 break;
599
600 // DTPREL relocations:
601 case R_LARCH_TLS_DTPREL32:
602 case R_LARCH_TLS_DTPREL64:
603 expr = R_DTPREL;
604 break;
605
606 // TLS LE relocations:
607 case R_LARCH_TLS_TPREL32:
608 case R_LARCH_TLS_TPREL64:
609 case R_LARCH_TLS_LE_HI20:
610 case R_LARCH_TLS_LE_HI20_R:
611 case R_LARCH_TLS_LE_LO12:
612 case R_LARCH_TLS_LE_LO12_R:
613 case R_LARCH_TLS_LE64_LO20:
614 case R_LARCH_TLS_LE64_HI12:
615 if (rs.checkTlsLe(offset, sym, type))
616 continue;
617 expr = R_TPREL;
618 break;
619 // TLS IE relocations (optimizable to LE in non-extreme code model):
620 case R_LARCH_TLS_IE_PC_HI20:
621 rs.handleTlsIe(ieExpr: RE_LOONGARCH_GOT_PAGE_PC, type, offset, addend, sym);
622 continue;
623 case R_LARCH_TLS_IE_PC_LO12:
624 rs.handleTlsIe(ieExpr: RE_LOONGARCH_GOT, type, offset, addend, sym);
625 continue;
626 // TLS IE relocations (extreme code model, no IE->LE optimization):
627 case R_LARCH_TLS_IE64_PC_LO20:
628 case R_LARCH_TLS_IE64_PC_HI12:
629 rs.handleTlsIe<false>(ieExpr: RE_LOONGARCH_GOT_PAGE_PC, type, offset, addend,
630 sym);
631 continue;
632 // TLS IE relocations (pcadd/absolute, no IE->LE optimization):
633 case R_LARCH_TLS_IE_PCADD_HI20:
634 rs.handleTlsIe<false>(ieExpr: R_GOT_PC, type, offset, addend, sym);
635 continue;
636 case R_LARCH_TLS_IE_HI20:
637 case R_LARCH_TLS_IE_LO12:
638 case R_LARCH_TLS_IE64_LO20:
639 case R_LARCH_TLS_IE64_HI12:
640 rs.handleTlsIe<false>(ieExpr: R_GOT, type, offset, addend, sym);
641 continue;
642 // TLS GD/LD relocations (no GD/LD->IE/LE optimization):
643 case R_LARCH_TLS_LD_PC_HI20:
644 case R_LARCH_TLS_GD_PC_HI20:
645 sym.setFlags(NEEDS_TLSGD);
646 sec.addReloc(r: {.expr: RE_LOONGARCH_TLSGD_PAGE_PC, .type: type, .offset: offset, .addend: addend, .sym: &sym});
647 continue;
648 case R_LARCH_TLS_LD_HI20:
649 ctx.needsTlsLd.store(i: true, m: std::memory_order_relaxed);
650 sec.addReloc(r: {.expr: R_TLSLD_GOT, .type: type, .offset: offset, .addend: addend, .sym: &sym});
651 continue;
652 case R_LARCH_TLS_GD_HI20:
653 sym.setFlags(NEEDS_TLSGD);
654 sec.addReloc(r: {.expr: R_TLSGD_GOT, .type: type, .offset: offset, .addend: addend, .sym: &sym});
655 continue;
656 case R_LARCH_TLS_LD_PCREL20_S2:
657 case R_LARCH_TLS_LD_PCADD_HI20:
658 ctx.needsTlsLd.store(i: true, m: std::memory_order_relaxed);
659 sec.addReloc(r: {.expr: R_TLSLD_PC, .type: type, .offset: offset, .addend: addend, .sym: &sym});
660 continue;
661 case R_LARCH_TLS_GD_PCREL20_S2:
662 case R_LARCH_TLS_GD_PCADD_HI20:
663 sym.setFlags(NEEDS_TLSGD);
664 sec.addReloc(r: {.expr: R_TLSGD_PC, .type: type, .offset: offset, .addend: addend, .sym: &sym});
665 continue;
666
667 // TLSDESC relocations (optimizable to IE/LE in non-extreme code model):
668 case R_LARCH_TLS_DESC_PC_HI20:
669 rs.handleTlsDesc(sharedExpr: RE_LOONGARCH_TLSDESC_PAGE_PC, ieExpr: RE_LOONGARCH_GOT_PAGE_PC,
670 type, offset, addend, sym);
671 continue;
672 case R_LARCH_TLS_DESC_PC_LO12:
673 case R_LARCH_TLS_DESC_LD:
674 rs.handleTlsDesc(sharedExpr: R_TLSDESC, ieExpr: RE_LOONGARCH_GOT_PAGE_PC, type, offset,
675 addend, sym);
676 continue;
677 case R_LARCH_TLS_DESC_PCREL20_S2:
678 rs.handleTlsDesc(sharedExpr: R_TLSDESC_PC, ieExpr: RE_LOONGARCH_GOT_PAGE_PC, type, offset,
679 addend, sym);
680 continue;
681 case R_LARCH_TLS_DESC_CALL:
682 if (!ctx.arg.shared)
683 sec.addReloc(
684 r: {.expr: sym.isPreemptible ? R_GOT : R_TPREL, .type: type, .offset: offset, .addend: addend, .sym: &sym});
685 continue;
686 // TLSDESC relocations (extreme code model, no optimization):
687 case R_LARCH_TLS_DESC64_PC_LO20:
688 case R_LARCH_TLS_DESC64_PC_HI12:
689 sym.setFlags(NEEDS_TLSDESC);
690 sec.addReloc(r: {.expr: RE_LOONGARCH_TLSDESC_PAGE_PC, .type: type, .offset: offset, .addend: addend, .sym: &sym});
691 continue;
692 // TLSDESC relocations (absolute/pcadd, no optimization):
693 case R_LARCH_TLS_DESC_HI20:
694 case R_LARCH_TLS_DESC_LO12:
695 case R_LARCH_TLS_DESC64_LO20:
696 case R_LARCH_TLS_DESC64_HI12:
697 case R_LARCH_TLS_DESC_PCADD_HI20:
698 sym.setFlags(NEEDS_TLSDESC);
699 sec.addReloc(r: {.expr: R_TLSDESC, .type: type, .offset: offset, .addend: addend, .sym: &sym});
700 continue;
701
702 // Relaxation hints:
703 case R_LARCH_TLS_LE_ADD_R:
704 case R_LARCH_RELAX:
705 if (ctx.arg.relax)
706 sec.addReloc(r: {.expr: R_RELAX_HINT, .type: type, .offset: offset, .addend: addend, .sym: &sym});
707 continue;
708 case R_LARCH_ALIGN:
709 sec.addReloc(r: {.expr: R_RELAX_HINT, .type: type, .offset: offset, .addend: addend, .sym: &sym});
710 continue;
711
712 // Misc relocations:
713 case R_LARCH_ADD6:
714 case R_LARCH_ADD8:
715 case R_LARCH_ADD16:
716 case R_LARCH_ADD32:
717 case R_LARCH_ADD64:
718 case R_LARCH_ADD_ULEB128:
719 case R_LARCH_SUB6:
720 case R_LARCH_SUB8:
721 case R_LARCH_SUB16:
722 case R_LARCH_SUB32:
723 case R_LARCH_SUB64:
724 case R_LARCH_SUB_ULEB128:
725 expr = RE_RISCV_ADD;
726 break;
727
728 default:
729 Err(ctx) << getErrorLoc(ctx, loc: sec.content().data() + offset)
730 << "unknown relocation (" << type.v << ") against symbol "
731 << &sym;
732 continue;
733 }
734 rs.process(expr, type, offset, sym, addend);
735 }
736
737 llvm::stable_sort(sec.relocs(),
738 [](const Relocation &lhs, const Relocation &rhs) {
739 return lhs.offset < rhs.offset;
740 });
741}
742
743void LoongArch::relocate(uint8_t *loc, const Relocation &rel,
744 uint64_t val) const {
745 switch (rel.type) {
746 case R_LARCH_32_PCREL:
747 checkInt(ctx, loc, v: val, n: 32, rel);
748 [[fallthrough]];
749 case R_LARCH_32:
750 case R_LARCH_TLS_DTPREL32:
751 write32le(P: loc, V: val);
752 return;
753 case R_LARCH_64:
754 case R_LARCH_TLS_DTPREL64:
755 case R_LARCH_64_PCREL:
756 write64le(P: loc, V: val);
757 return;
758
759 // Relocs intended for `pcaddi`.
760 case R_LARCH_PCREL20_S2:
761 case R_LARCH_TLS_LD_PCREL20_S2:
762 case R_LARCH_TLS_GD_PCREL20_S2:
763 case R_LARCH_TLS_DESC_PCREL20_S2:
764 checkInt(ctx, loc, v: val, n: 22, rel);
765 checkAlignment(ctx, loc, v: val, n: 4, rel);
766 write32le(P: loc, V: setJ20(insn: read32le(P: loc), imm: val >> 2));
767 return;
768
769 case R_LARCH_B16:
770 checkInt(ctx, loc, v: val, n: 18, rel);
771 checkAlignment(ctx, loc, v: val, n: 4, rel);
772 write32le(P: loc, V: setK16(insn: read32le(P: loc), imm: val >> 2));
773 return;
774
775 case R_LARCH_B21:
776 checkInt(ctx, loc, v: val, n: 23, rel);
777 checkAlignment(ctx, loc, v: val, n: 4, rel);
778 write32le(P: loc, V: setD5k16(insn: read32le(P: loc), imm: val >> 2));
779 return;
780
781 case R_LARCH_B26:
782 checkInt(ctx, loc, v: val, n: 28, rel);
783 checkAlignment(ctx, loc, v: val, n: 4, rel);
784 write32le(P: loc, V: setD10k16(insn: read32le(P: loc), imm: val >> 2));
785 return;
786
787 case R_LARCH_CALL30: {
788 // This relocation is designed for adjacent pcaddu12i+jirl pairs that
789 // are patched in one time.
790 // The relocation range is [-2G, +2G) (of course must be 4-byte aligned).
791 checkInt(ctx, loc, v: val, n: 32, rel);
792 checkAlignment(ctx, loc, v: val, n: 4, rel);
793 // Although jirl adds the immediate as a signed value, it is always positive
794 // in this case, so no adjustment is needed, unlike CALL36.
795 uint32_t hi20 = extractBits(v: val, begin: 31, end: 12);
796 // Despite the name, the lower part is actually 12 bits with 4-byte aligned.
797 uint32_t lo10 = extractBits(v: val, begin: 11, end: 2);
798 write32le(P: loc, V: setJ20(insn: read32le(P: loc), imm: hi20));
799 write32le(P: loc + 4, V: setK16(insn: read32le(P: loc + 4), imm: lo10));
800 return;
801 }
802
803 case R_LARCH_CALL36: {
804 // This relocation is designed for adjacent pcaddu18i+jirl pairs that
805 // are patched in one time. Because of sign extension of these insns'
806 // immediate fields, the relocation range is [-128G - 0x20000, +128G -
807 // 0x20000) (of course must be 4-byte aligned).
808 if (((int64_t)val + 0x20000) != llvm::SignExtend64(X: val + 0x20000, B: 38))
809 reportRangeError(ctx, loc, rel, v: Twine(val), min: llvm::minIntN(N: 38) - 0x20000,
810 max: llvm::maxIntN(N: 38) - 0x20000);
811 checkAlignment(ctx, loc, v: val, n: 4, rel);
812 // Since jirl performs sign extension on the offset immediate, adds (1<<17)
813 // to original val to get the correct hi20.
814 uint32_t hi20 = extractBits(v: val + (1 << 17), begin: 37, end: 18);
815 // Despite the name, the lower part is actually 18 bits with 4-byte aligned.
816 uint32_t lo16 = extractBits(v: val, begin: 17, end: 2);
817 write32le(P: loc, V: setJ20(insn: read32le(P: loc), imm: hi20));
818 write32le(P: loc + 4, V: setK16(insn: read32le(P: loc + 4), imm: lo16));
819 return;
820 }
821
822 // Relocs intended for `addi`, `ld` or `st`.
823 case R_LARCH_PCALA_LO12:
824 // We have to again inspect the insn word to handle the R_LARCH_PCALA_LO12
825 // on JIRL case: firstly JIRL wants its immediate's 2 lowest zeroes
826 // removed by us (in contrast to regular R_LARCH_PCALA_LO12), secondly
827 // its immediate slot width is different too (16, not 12).
828 // In this case, process like an R_LARCH_B16, but without overflow checking
829 // and only taking the value's lowest 12 bits.
830 if (isJirl(insn: read32le(P: loc))) {
831 checkAlignment(ctx, loc, v: val, n: 4, rel);
832 val = SignExtend64<12>(x: val);
833 write32le(P: loc, V: setK16(insn: read32le(P: loc), imm: val >> 2));
834 return;
835 }
836 [[fallthrough]];
837 case R_LARCH_ABS_LO12:
838 case R_LARCH_GOT_PC_LO12:
839 case R_LARCH_GOT_LO12:
840 case R_LARCH_TLS_LE_LO12:
841 case R_LARCH_TLS_IE_PC_LO12:
842 case R_LARCH_TLS_IE_LO12:
843 case R_LARCH_TLS_LE_LO12_R:
844 case R_LARCH_TLS_DESC_PC_LO12:
845 case R_LARCH_TLS_DESC_LO12:
846 case R_LARCH_PCADD_LO12:
847 case R_LARCH_GOT_PCADD_LO12:
848 case R_LARCH_TLS_IE_PCADD_LO12:
849 case R_LARCH_TLS_LD_PCADD_LO12:
850 case R_LARCH_TLS_GD_PCADD_LO12:
851 case R_LARCH_TLS_DESC_PCADD_LO12:
852 write32le(P: loc, V: setK12(insn: read32le(P: loc), imm: extractBits(v: val, begin: 11, end: 0)));
853 return;
854
855 // Relocs intended for `lu12i.w` or `pcalau12i`.
856 case R_LARCH_ABS_HI20:
857 case R_LARCH_PCALA_HI20:
858 case R_LARCH_GOT_PC_HI20:
859 case R_LARCH_GOT_HI20:
860 case R_LARCH_TLS_LE_HI20:
861 case R_LARCH_TLS_IE_PC_HI20:
862 case R_LARCH_TLS_IE_HI20:
863 case R_LARCH_TLS_LD_PC_HI20:
864 case R_LARCH_TLS_LD_HI20:
865 case R_LARCH_TLS_GD_PC_HI20:
866 case R_LARCH_TLS_GD_HI20:
867 case R_LARCH_TLS_DESC_PC_HI20:
868 case R_LARCH_TLS_DESC_HI20:
869 write32le(P: loc, V: setJ20(insn: read32le(P: loc), imm: extractBits(v: val, begin: 31, end: 12)));
870 return;
871 case R_LARCH_PCADD_HI20:
872 case R_LARCH_GOT_PCADD_HI20:
873 case R_LARCH_TLS_IE_PCADD_HI20:
874 case R_LARCH_TLS_LD_PCADD_HI20:
875 case R_LARCH_TLS_GD_PCADD_HI20:
876 case R_LARCH_TLS_DESC_PCADD_HI20: {
877 uint64_t hi = val + 0x800;
878 checkInt(ctx, loc, v: SignExtend64(X: hi, B: ctx.arg.wordsize * 8) >> 12, n: 20, rel);
879 write32le(P: loc, V: setJ20(insn: read32le(P: loc), imm: extractBits(v: hi, begin: 31, end: 12)));
880 return;
881 }
882 case R_LARCH_TLS_LE_HI20_R:
883 write32le(P: loc, V: setJ20(insn: read32le(P: loc), imm: extractBits(v: val + 0x800, begin: 31, end: 12)));
884 return;
885
886 // Relocs intended for `lu32i.d`.
887 case R_LARCH_ABS64_LO20:
888 case R_LARCH_PCALA64_LO20:
889 case R_LARCH_GOT64_PC_LO20:
890 case R_LARCH_GOT64_LO20:
891 case R_LARCH_TLS_LE64_LO20:
892 case R_LARCH_TLS_IE64_PC_LO20:
893 case R_LARCH_TLS_IE64_LO20:
894 case R_LARCH_TLS_DESC64_PC_LO20:
895 case R_LARCH_TLS_DESC64_LO20:
896 write32le(P: loc, V: setJ20(insn: read32le(P: loc), imm: extractBits(v: val, begin: 51, end: 32)));
897 return;
898
899 // Relocs intended for `lu52i.d`.
900 case R_LARCH_ABS64_HI12:
901 case R_LARCH_PCALA64_HI12:
902 case R_LARCH_GOT64_PC_HI12:
903 case R_LARCH_GOT64_HI12:
904 case R_LARCH_TLS_LE64_HI12:
905 case R_LARCH_TLS_IE64_PC_HI12:
906 case R_LARCH_TLS_IE64_HI12:
907 case R_LARCH_TLS_DESC64_PC_HI12:
908 case R_LARCH_TLS_DESC64_HI12:
909 write32le(P: loc, V: setK12(insn: read32le(P: loc), imm: extractBits(v: val, begin: 63, end: 52)));
910 return;
911
912 case R_LARCH_ADD6:
913 *loc = (*loc & 0xc0) | ((*loc + val) & 0x3f);
914 return;
915 case R_LARCH_ADD8:
916 *loc += val;
917 return;
918 case R_LARCH_ADD16:
919 write16le(P: loc, V: read16le(P: loc) + val);
920 return;
921 case R_LARCH_ADD32:
922 write32le(P: loc, V: read32le(P: loc) + val);
923 return;
924 case R_LARCH_ADD64:
925 write64le(P: loc, V: read64le(P: loc) + val);
926 return;
927 case R_LARCH_ADD_ULEB128:
928 handleUleb128(ctx, loc, val);
929 return;
930 case R_LARCH_SUB6:
931 *loc = (*loc & 0xc0) | ((*loc - val) & 0x3f);
932 return;
933 case R_LARCH_SUB8:
934 *loc -= val;
935 return;
936 case R_LARCH_SUB16:
937 write16le(P: loc, V: read16le(P: loc) - val);
938 return;
939 case R_LARCH_SUB32:
940 write32le(P: loc, V: read32le(P: loc) - val);
941 return;
942 case R_LARCH_SUB64:
943 write64le(P: loc, V: read64le(P: loc) - val);
944 return;
945 case R_LARCH_SUB_ULEB128:
946 handleUleb128(ctx, loc, val: -val);
947 return;
948
949 case R_LARCH_MARK_LA:
950 case R_LARCH_MARK_PCREL:
951 // no-op
952 return;
953
954 case R_LARCH_TLS_LE_ADD_R:
955 case R_LARCH_RELAX:
956 return; // Ignored (for now)
957
958 case R_LARCH_TLS_DESC_LD:
959 return; // nothing to do.
960 case R_LARCH_TLS_DESC32:
961 write32le(P: loc + 4, V: val);
962 return;
963 case R_LARCH_TLS_DESC64:
964 write64le(P: loc + 8, V: val);
965 return;
966
967 default:
968 llvm_unreachable("unknown relocation");
969 }
970}
971
972// If the section alignment is > 4, advance `dot` to insert NOPs and synthesize
973// an ALIGN relocation. Otherwise, return false to use default handling.
974template <class ELFT, class RelTy>
975bool LoongArch::synthesizeAlignForInput(uint64_t &dot, InputSection *sec,
976 Relocs<RelTy> rels) {
977 if (!baseSec) {
978 // Record the first input section with RELAX relocations. We will synthesize
979 // ALIGN relocations here.
980 for (auto rel : rels) {
981 if (rel.getType(false) == R_LARCH_RELAX) {
982 baseSec = sec;
983 break;
984 }
985 }
986 } else if (sec->addralign > 4) {
987 // If the alignment is > 4, synthesize an ALIGN unless an ALIGN relocation
988 // at offset 0 already guarantees `addralign`. Note: A weaker ALIGN at
989 // offset 0 from older assemblers do not suppress synthesis (e.g.
990 // `.p2align 2; .option norelax; nop; .p2align 3` does not suppress
991 // synthesized `.p2align 3`).
992 bool covered = llvm::any_of(rels, [&](const RelTy &rel) {
993 if (rel.r_offset != 0 || rel.getType(false) != R_LARCH_ALIGN)
994 return false;
995 if constexpr (RelTy::HasAddend)
996 return uint64_t(rel.r_addend) >= sec->addralign - 4;
997 return false;
998 });
999 if (!covered) {
1000 synthesizedAligns.emplace_back(Args: dot - baseSec->getVA(),
1001 Args: sec->addralign - 4);
1002 dot += sec->addralign - 4;
1003 return true;
1004 }
1005 }
1006 return false;
1007}
1008
1009// Finalize the relocation section by appending synthesized ALIGN relocations
1010// after processing all input sections.
1011template <class ELFT, class RelTy>
1012void LoongArch::finalizeSynthesizeAligns(uint64_t &dot, InputSection *sec,
1013 Relocs<RelTy> rels) {
1014 auto *f = cast<ObjFile<ELFT>>(baseSec->file);
1015 auto shdr = f->template getELFShdrs<ELFT>()[baseSec->relSecIdx];
1016 // Create a copy of InputSection.
1017 sec = make<InputSection>(*f, shdr, baseSec->name);
1018 auto *baseRelSec = cast<InputSection>(f->getSections()[baseSec->relSecIdx]);
1019 *sec = *baseRelSec;
1020 baseSec = nullptr;
1021
1022 // Allocate buffer for original and synthesized relocations in RELA format.
1023 // If CREL is used, OutputSection::finalizeNonAllocCrel will convert RELA to
1024 // CREL.
1025 auto newSize = rels.size() + synthesizedAligns.size();
1026 auto *relas = makeThreadLocalN<typename ELFT::Rela>(newSize);
1027 sec->size = newSize * sizeof(typename ELFT::Rela);
1028 sec->content_ = reinterpret_cast<uint8_t *>(relas);
1029 sec->type = SHT_RELA;
1030 // Copy original relocations to the new buffer, potentially converting CREL to
1031 // RELA.
1032 for (auto [i, r] : llvm::enumerate(rels)) {
1033 relas[i].r_offset = r.r_offset;
1034 relas[i].setSymbolAndType(r.getSymbol(0), r.getType(0), false);
1035 if constexpr (RelTy::HasAddend)
1036 relas[i].r_addend = r.r_addend;
1037 }
1038 // Append synthesized ALIGN relocations to the buffer.
1039 for (auto [i, r] : llvm::enumerate(First&: synthesizedAligns)) {
1040 auto &rela = relas[rels.size() + i];
1041 rela.r_offset = r.first;
1042 rela.setSymbolAndType(0, R_LARCH_ALIGN, false);
1043 rela.r_addend = r.second;
1044 }
1045 synthesizedAligns.clear();
1046 // Replace the old relocation section with the new one in the output section.
1047 // addOrphanSections ensures that the output relocation section is processed
1048 // after osec.
1049 for (SectionCommand *cmd : sec->getParent()->commands) {
1050 auto *isd = dyn_cast<InputSectionDescription>(Val: cmd);
1051 if (!isd)
1052 continue;
1053 for (auto *&isec : isd->sections)
1054 if (isec == baseRelSec)
1055 isec = sec;
1056 }
1057}
1058
1059template <class ELFT>
1060bool LoongArch::synthesizeAlignAux(uint64_t &dot, InputSection *sec) {
1061 bool ret = false;
1062 if (sec) {
1063 invokeOnRelocs(*sec, ret = synthesizeAlignForInput<ELFT>, dot, sec);
1064 } else if (baseSec) {
1065 invokeOnRelocs(*baseSec, finalizeSynthesizeAligns<ELFT>, dot, sec);
1066 }
1067 return ret;
1068}
1069
1070// Without linker relaxation enabled for a particular relocatable file or
1071// section, the assembler will not generate R_LARCH_ALIGN relocations for
1072// alignment directives. This becomes problematic in a two-stage linking
1073// process: ld -r a.o b.o -o ab.o; ld ab.o -o ab. This function synthesizes an
1074// R_LARCH_ALIGN relocation at section start when needed.
1075//
1076// When called with an input section (`sec` is not null): If the section
1077// alignment is > 4, advance `dot` to insert NOPs and synthesize an ALIGN
1078// relocation.
1079//
1080// When called after all input sections are processed (`sec` is null): The
1081// output relocation section is updated with all the newly synthesized ALIGN
1082// relocations.
1083bool LoongArch::synthesizeAlign(uint64_t &dot, InputSection *sec) {
1084 assert(ctx.arg.relocatable);
1085 if (ctx.arg.is64)
1086 return synthesizeAlignAux<ELF64LE>(dot, sec);
1087 return synthesizeAlignAux<ELF32LE>(dot, sec);
1088}
1089
1090static bool relaxable(ArrayRef<Relocation> relocs, size_t i) {
1091 return i + 1 < relocs.size() && relocs[i + 1].type == R_LARCH_RELAX;
1092}
1093
1094static bool isPairRelaxable(ArrayRef<Relocation> relocs, size_t i) {
1095 return relaxable(relocs, i) && relaxable(relocs, i: i + 2) &&
1096 relocs[i].offset + 4 == relocs[i + 2].offset;
1097}
1098
1099// Relax code sequence.
1100// From:
1101// pcalau12i $a0, %pc_hi20(sym) | %ld_pc_hi20(sym) | %gd_pc_hi20(sym)
1102// | %desc_pc_hi20(sym)
1103// addi.w/d $a0, $a0, %pc_lo12(sym) | %got_pc_lo12(sym) | %got_pc_lo12(sym)
1104// | %desc_pc_lo12(sym)
1105// To:
1106// pcaddi $a0, %pc_lo12(sym) | %got_pc_lo12(sym) | %got_pc_lo12(sym)
1107// | %desc_pcrel_20(sym)
1108//
1109// From:
1110// pcalau12i $a0, %got_pc_hi20(sym_got)
1111// ld.w/d $a0, $a0, %got_pc_lo12(sym_got)
1112// To:
1113// pcaddi $a0, %got_pc_hi20(sym_got)
1114static void relaxPCHi20Lo12(Ctx &ctx, const InputSection &sec, size_t i,
1115 uint64_t loc, Relocation &rHi20, Relocation &rLo12,
1116 uint32_t &remove) {
1117 // check if the relocations are relaxable sequences.
1118 if (!((rHi20.type == R_LARCH_PCALA_HI20 &&
1119 rLo12.type == R_LARCH_PCALA_LO12) ||
1120 (rHi20.type == R_LARCH_GOT_PC_HI20 &&
1121 rLo12.type == R_LARCH_GOT_PC_LO12) ||
1122 (rHi20.type == R_LARCH_TLS_GD_PC_HI20 &&
1123 rLo12.type == R_LARCH_GOT_PC_LO12) ||
1124 (rHi20.type == R_LARCH_TLS_LD_PC_HI20 &&
1125 rLo12.type == R_LARCH_GOT_PC_LO12) ||
1126 (rHi20.type == R_LARCH_TLS_DESC_PC_HI20 &&
1127 rLo12.type == R_LARCH_TLS_DESC_PC_LO12)))
1128 return;
1129
1130 // GOT references to absolute symbols can't be relaxed to use pcaddi in
1131 // position-independent code, because these instructions produce a relative
1132 // address.
1133 // Meanwhile skip undefined, preemptible and STT_GNU_IFUNC symbols, because
1134 // these symbols may be resolve in runtime.
1135 // Moreover, relaxation can only occur if the addends of both relocations are
1136 // zero for GOT references.
1137 if (rHi20.type == R_LARCH_GOT_PC_HI20 &&
1138 (!rHi20.sym || rHi20.sym != rLo12.sym || !rHi20.sym->isDefined() ||
1139 rHi20.sym->isPreemptible || rHi20.sym->isGnuIFunc() ||
1140 (ctx.arg.isPic && !cast<Defined>(Val&: *rHi20.sym).section) ||
1141 rHi20.addend != 0 || rLo12.addend != 0))
1142 return;
1143
1144 uint64_t dest = 0;
1145 if (rHi20.expr == RE_LOONGARCH_PLT_PAGE_PC)
1146 dest = rHi20.sym->getPltVA(ctx);
1147 else if (rHi20.expr == RE_LOONGARCH_PAGE_PC ||
1148 rHi20.expr == RE_LOONGARCH_GOT_PAGE_PC)
1149 dest = rHi20.sym->getVA(ctx);
1150 else if (rHi20.expr == RE_LOONGARCH_TLSGD_PAGE_PC)
1151 dest = ctx.in.got->getGlobalDynAddr(b: *rHi20.sym);
1152 else if (rHi20.expr == RE_LOONGARCH_TLSDESC_PAGE_PC)
1153 dest = ctx.in.got->getTlsDescAddr(sym: *rHi20.sym);
1154 else {
1155 Err(ctx) << getErrorLoc(ctx, loc: (const uint8_t *)loc) << "unknown expr ("
1156 << rHi20.expr << ") against symbol " << rHi20.sym
1157 << "in relaxPCHi20Lo12";
1158 return;
1159 }
1160 dest += rHi20.addend;
1161
1162 const int64_t displace = dest - loc;
1163 // Check if the displace aligns 4 bytes or exceeds the range of pcaddi.
1164 if ((displace & 0x3) != 0 || !isInt<22>(x: displace))
1165 return;
1166
1167 // Note: If we can ensure that the .o files generated by LLVM only contain
1168 // relaxable instruction sequences with R_LARCH_RELAX, then we do not need to
1169 // decode instructions. The relaxable instruction sequences imply the
1170 // following constraints:
1171 // * For relocation pairs related to got_pc, the opcodes of instructions
1172 // must be pcalau12i + ld.w/d. In other cases, the opcodes must be pcalau12i +
1173 // addi.w/d.
1174 // * The destination register of pcalau12i is guaranteed to be used only by
1175 // the immediately following instruction.
1176 const uint32_t currInsn = read32le(P: sec.content().data() + rHi20.offset);
1177 const uint32_t nextInsn = read32le(P: sec.content().data() + rLo12.offset);
1178 // Check if use the same register.
1179 if (getD5(v: currInsn) != getJ5(v: nextInsn) || getJ5(v: nextInsn) != getD5(v: nextInsn))
1180 return;
1181
1182 sec.relaxAux->relocTypes[i] = R_LARCH_RELAX;
1183 if (rHi20.type == R_LARCH_TLS_GD_PC_HI20)
1184 sec.relaxAux->relocTypes[i + 2] = R_LARCH_TLS_GD_PCREL20_S2;
1185 else if (rHi20.type == R_LARCH_TLS_LD_PC_HI20)
1186 sec.relaxAux->relocTypes[i + 2] = R_LARCH_TLS_LD_PCREL20_S2;
1187 else if (rHi20.type == R_LARCH_TLS_DESC_PC_HI20)
1188 sec.relaxAux->relocTypes[i + 2] = R_LARCH_TLS_DESC_PCREL20_S2;
1189 else
1190 sec.relaxAux->relocTypes[i + 2] = R_LARCH_PCREL20_S2;
1191 sec.relaxAux->writes.push_back(Elt: insn(op: PCADDI, d: getD5(v: nextInsn), j: 0, k: 0));
1192 remove = 4;
1193}
1194
1195// Relax code sequence.
1196// From:
1197// la32r:
1198// pcaddu12i $ra, %call30(foo)
1199// jirl $ra, $ra, 0
1200// la32s/la64:
1201// pcaddu18i $ra, %call36(foo)
1202// jirl $ra, $ra, 0
1203// To:
1204// b/bl foo
1205static void relaxMediumCall(Ctx &ctx, const InputSection &sec, size_t i,
1206 uint64_t loc, Relocation &r, uint32_t &remove) {
1207 const uint64_t dest =
1208 (r.expr == R_PLT_PC ? r.sym->getPltVA(ctx) : r.sym->getVA(ctx)) +
1209 r.addend;
1210
1211 const int64_t displace = dest - loc;
1212 // Check if the displace aligns 4 bytes or exceeds the range of b[l].
1213 if ((displace & 0x3) != 0 || !isInt<28>(x: displace))
1214 return;
1215
1216 const uint32_t nextInsn = read32le(P: sec.content().data() + r.offset + 4);
1217 if (getD5(v: nextInsn) == R_RA) {
1218 // convert jirl to bl
1219 sec.relaxAux->relocTypes[i] = R_LARCH_B26;
1220 sec.relaxAux->writes.push_back(Elt: insn(op: BL, d: 0, j: 0, k: 0));
1221 remove = 4;
1222 } else if (getD5(v: nextInsn) == R_ZERO) {
1223 // convert jirl to b
1224 sec.relaxAux->relocTypes[i] = R_LARCH_B26;
1225 sec.relaxAux->writes.push_back(Elt: insn(op: B, d: 0, j: 0, k: 0));
1226 remove = 4;
1227 }
1228}
1229
1230// Relax code sequence.
1231// From:
1232// lu12i.w $rd, %le_hi20_r(sym)
1233// add.w/d $rd, $rd, $tp, %le_add_r(sym)
1234// addi/ld/st.w/d $rd, $rd, %le_lo12_r(sym)
1235// To:
1236// addi/ld/st.w/d $rd, $tp, %le_lo12_r(sym)
1237static void relaxTlsLe(Ctx &ctx, const InputSection &sec, size_t i,
1238 uint64_t loc, Relocation &r, uint32_t &remove) {
1239 uint64_t val = r.sym->getVA(ctx, addend: r.addend);
1240 // Check if the val exceeds the range of addi/ld/st.
1241 if (!isInt<12>(x: val))
1242 return;
1243 uint32_t currInsn = read32le(P: sec.content().data() + r.offset);
1244 switch (r.type) {
1245 case R_LARCH_TLS_LE_HI20_R:
1246 case R_LARCH_TLS_LE_ADD_R:
1247 sec.relaxAux->relocTypes[i] = R_LARCH_RELAX;
1248 remove = 4;
1249 break;
1250 case R_LARCH_TLS_LE_LO12_R:
1251 sec.relaxAux->writes.push_back(Elt: setJ5(insn: currInsn, imm: R_TP));
1252 sec.relaxAux->relocTypes[i] = R_LARCH_TLS_LE_LO12_R;
1253 break;
1254 }
1255}
1256
1257static bool relax(Ctx &ctx, InputSection &sec) {
1258 const uint64_t secAddr = sec.getVA();
1259 const MutableArrayRef<Relocation> relocs = sec.relocs();
1260 auto &aux = *sec.relaxAux;
1261 bool changed = false;
1262 ArrayRef<SymbolAnchor> sa = ArrayRef(aux.anchors);
1263 uint64_t delta = 0;
1264
1265 std::fill_n(first: aux.relocTypes.get(), n: relocs.size(), value: R_LARCH_NONE);
1266 aux.writes.clear();
1267 for (auto [i, r] : llvm::enumerate(First: relocs)) {
1268 const uint64_t loc = secAddr + r.offset - delta;
1269 uint32_t &cur = aux.relocDeltas[i], remove = 0;
1270 switch (r.type) {
1271 case R_LARCH_ALIGN: {
1272 const uint64_t addend =
1273 r.sym->isUndefined() ? Log2_64(Value: r.addend) + 1 : r.addend;
1274 const uint64_t allBytes = (1ULL << (addend & 0xff)) - 4;
1275 const uint64_t align = 1ULL << (addend & 0xff);
1276 const uint64_t maxBytes = addend >> 8;
1277 const uint64_t off = loc & (align - 1);
1278 const uint64_t curBytes = off == 0 ? 0 : align - off;
1279 // All bytes beyond the alignment boundary should be removed.
1280 // If emit bytes more than max bytes to emit, remove all.
1281 if (maxBytes != 0 && curBytes > maxBytes)
1282 remove = allBytes;
1283 else
1284 remove = allBytes - curBytes;
1285 // If we can't satisfy this alignment, we've found a bad input.
1286 if (LLVM_UNLIKELY(static_cast<int32_t>(remove) < 0)) {
1287 Err(ctx) << getErrorLoc(ctx, loc: (const uint8_t *)loc)
1288 << "insufficient padding bytes for " << r.type << ": "
1289 << allBytes << " bytes available for "
1290 << "requested alignment of " << align << " bytes";
1291 remove = 0;
1292 }
1293 break;
1294 }
1295 case R_LARCH_PCALA_HI20:
1296 case R_LARCH_GOT_PC_HI20:
1297 case R_LARCH_TLS_GD_PC_HI20:
1298 case R_LARCH_TLS_LD_PC_HI20:
1299 // The overflow check for i+2 will be carried out in isPairRelaxable.
1300 if (isPairRelaxable(relocs, i))
1301 relaxPCHi20Lo12(ctx, sec, i, loc, rHi20&: r, rLo12&: relocs[i + 2], remove);
1302 break;
1303 case R_LARCH_TLS_DESC_PC_HI20:
1304 if (r.expr == RE_LOONGARCH_GOT_PAGE_PC || r.expr == R_TPREL) {
1305 if (relaxable(relocs, i))
1306 remove = 4;
1307 } else if (isPairRelaxable(relocs, i))
1308 relaxPCHi20Lo12(ctx, sec, i, loc, rHi20&: r, rLo12&: relocs[i + 2], remove);
1309 break;
1310 case R_LARCH_CALL30:
1311 case R_LARCH_CALL36:
1312 if (relaxable(relocs, i))
1313 relaxMediumCall(ctx, sec, i, loc, r, remove);
1314 break;
1315 case R_LARCH_TLS_LE_HI20_R:
1316 case R_LARCH_TLS_LE_ADD_R:
1317 case R_LARCH_TLS_LE_LO12_R:
1318 if (relaxable(relocs, i))
1319 relaxTlsLe(ctx, sec, i, loc, r, remove);
1320 break;
1321 case R_LARCH_TLS_IE_PC_HI20:
1322 if (relaxable(relocs, i) && r.expr == R_TPREL &&
1323 isUInt<12>(x: r.sym->getVA(ctx, addend: r.addend)))
1324 remove = 4;
1325 break;
1326 case R_LARCH_TLS_DESC_PC_LO12:
1327 if (relaxable(relocs, i) &&
1328 (r.expr == RE_LOONGARCH_GOT_PAGE_PC || r.expr == R_TPREL))
1329 remove = 4;
1330 break;
1331 case R_LARCH_TLS_DESC_LD:
1332 if (relaxable(relocs, i) && r.expr == R_TPREL &&
1333 isUInt<12>(x: r.sym->getVA(ctx, addend: r.addend)))
1334 remove = 4;
1335 break;
1336 }
1337
1338 // For all anchors whose offsets are <= r.offset, they are preceded by
1339 // the previous relocation whose `relocDeltas` value equals `delta`.
1340 // Decrease their st_value and update their st_size.
1341 for (; sa.size() && sa[0].offset <= r.offset; sa = sa.slice(N: 1)) {
1342 if (sa[0].end)
1343 sa[0].d->size = sa[0].offset - delta - sa[0].d->value;
1344 else
1345 sa[0].d->value = sa[0].offset - delta;
1346 }
1347 delta += remove;
1348 if (delta != cur) {
1349 cur = delta;
1350 changed = true;
1351 }
1352 }
1353
1354 for (const SymbolAnchor &a : sa) {
1355 if (a.end)
1356 a.d->size = a.offset - delta - a.d->value;
1357 else
1358 a.d->value = a.offset - delta;
1359 }
1360 // Inform assignAddresses that the size has changed.
1361 if (!isUInt<32>(x: delta))
1362 Fatal(ctx) << "section size decrease is too large: " << delta;
1363 sec.bytesDropped = delta;
1364 return changed;
1365}
1366
1367// Convert TLS IE to LE in the normal or medium code model.
1368// Original code sequence:
1369// * pcalau12i $a0, %ie_pc_hi20(sym)
1370// * ld.d $a0, $a0, %ie_pc_lo12(sym)
1371//
1372// The code sequence converted is as follows:
1373// * lu12i.w $a0, %le_hi20(sym) # le_hi20 != 0, otherwise NOP
1374// * ori $a0, src, %le_lo12(sym) # le_hi20 != 0, src = $a0,
1375// # otherwise, src = $zero
1376//
1377// When relaxation enables, redundant NOPs can be removed.
1378static void tlsIeToLe(uint8_t *loc, const Relocation &rel, uint64_t val) {
1379 assert(isInt<32>(val) &&
1380 "val exceeds the range of medium code model in tlsIeToLe");
1381
1382 bool isUInt12 = isUInt<12>(x: val);
1383 const uint32_t currInsn = read32le(P: loc);
1384 switch (rel.type) {
1385 case R_LARCH_TLS_IE_PC_HI20:
1386 if (isUInt12)
1387 write32le(P: loc, V: insn(op: ANDI, d: R_ZERO, j: R_ZERO, k: 0)); // nop
1388 else
1389 write32le(P: loc, V: insn(op: LU12I_W, d: getD5(v: currInsn), j: extractBits(v: val, begin: 31, end: 12),
1390 k: 0)); // lu12i.w $a0, %le_hi20
1391 break;
1392 case R_LARCH_TLS_IE_PC_LO12:
1393 if (isUInt12)
1394 write32le(P: loc, V: insn(op: ORI, d: getD5(v: currInsn), j: R_ZERO,
1395 k: val)); // ori $a0, $zero, %le_lo12
1396 else
1397 write32le(P: loc, V: insn(op: ORI, d: getD5(v: currInsn), j: getJ5(v: currInsn),
1398 k: lo12(val))); // ori $a0, $a0, %le_lo12
1399 break;
1400 }
1401}
1402
1403// Convert TLSDESC GD/LD to IE.
1404// In normal or medium code model, there are two forms of code sequences:
1405// * pcalau12i $a0, %desc_pc_hi20(sym_desc)
1406// * addi.d $a0, $a0, %desc_pc_lo12(sym_desc)
1407// * ld.d $ra, $a0, %desc_ld(sym_desc)
1408// * jirl $ra, $ra, %desc_call(sym_desc)
1409// ------
1410// * pcaddi $a0, %desc_pcrel_20(a)
1411// * load $ra, $a0, %desc_ld(a)
1412// * jirl $ra, $ra, %desc_call(a)
1413//
1414// The code sequence obtained is as follows:
1415// * pcalau12i $a0, %ie_pc_hi20(sym_ie)
1416// * ld.[wd] $a0, $a0, %ie_pc_lo12(sym_ie)
1417//
1418// Simplicity, whether tlsdescToIe or tlsdescToLe, we always tend to convert the
1419// preceding instructions to NOPs, due to both forms of code sequence
1420// (corresponding to relocation combinations:
1421// R_LARCH_TLS_DESC_PC_HI20+R_LARCH_TLS_DESC_PC_LO12 and
1422// R_LARCH_TLS_DESC_PCREL20_S2) have same process.
1423//
1424// When relaxation enables, redundant NOPs can be removed.
1425void LoongArch::tlsdescToIe(uint8_t *loc, const Relocation &rel,
1426 uint64_t val) const {
1427 switch (rel.type) {
1428 case R_LARCH_TLS_DESC_PC_HI20:
1429 case R_LARCH_TLS_DESC_PC_LO12:
1430 case R_LARCH_TLS_DESC_PCREL20_S2:
1431 write32le(P: loc, V: insn(op: ANDI, d: R_ZERO, j: R_ZERO, k: 0)); // nop
1432 break;
1433 case R_LARCH_TLS_DESC_LD:
1434 write32le(P: loc, V: insn(op: PCALAU12I, d: R_A0, j: 0, k: 0)); // pcalau12i $a0, %ie_pc_hi20
1435 relocateNoSym(loc, type: R_LARCH_TLS_IE_PC_HI20, val);
1436 break;
1437 case R_LARCH_TLS_DESC_CALL:
1438 write32le(P: loc, V: insn(op: ctx.arg.is64 ? LD_D : LD_W, d: R_A0, j: R_A0,
1439 k: 0)); // ld.[wd] $a0, $a0, %ie_pc_lo12
1440 relocateNoSym(loc, type: R_LARCH_TLS_IE_PC_LO12, val);
1441 break;
1442 default:
1443 llvm_unreachable("unsupported relocation for TLSDESC to IE");
1444 }
1445}
1446
1447// Convert TLSDESC GD/LD to LE.
1448// The code sequence obtained in the normal or medium code model is as follows:
1449// * lu12i.w $a0, %le_hi20(sym) # le_hi20 != 0, otherwise NOP
1450// * ori $a0, src, %le_lo12(sym) # le_hi20 != 0, src = $a0,
1451// # otherwise, src = $zero
1452// See the comment in tlsdescToIe for detailed information.
1453void LoongArch::tlsdescToLe(uint8_t *loc, const Relocation &rel,
1454 uint64_t val) const {
1455 assert(isInt<32>(val) &&
1456 "val exceeds the range of medium code model in tlsdescToLe");
1457
1458 bool isUInt12 = isUInt<12>(x: val);
1459 switch (rel.type) {
1460 case R_LARCH_TLS_DESC_PC_HI20:
1461 case R_LARCH_TLS_DESC_PC_LO12:
1462 case R_LARCH_TLS_DESC_PCREL20_S2:
1463 write32le(P: loc, V: insn(op: ANDI, d: R_ZERO, j: R_ZERO, k: 0)); // nop
1464 break;
1465 case R_LARCH_TLS_DESC_LD:
1466 if (isUInt12)
1467 write32le(P: loc, V: insn(op: ANDI, d: R_ZERO, j: R_ZERO, k: 0)); // nop
1468 else
1469 write32le(P: loc, V: insn(op: LU12I_W, d: R_A0, j: extractBits(v: val, begin: 31, end: 12),
1470 k: 0)); // lu12i.w $a0, %le_hi20
1471 break;
1472 case R_LARCH_TLS_DESC_CALL:
1473 if (isUInt12)
1474 write32le(P: loc, V: insn(op: ORI, d: R_A0, j: R_ZERO, k: val)); // ori $a0, $zero, %le_lo12
1475 else
1476 write32le(P: loc,
1477 V: insn(op: ORI, d: R_A0, j: R_A0, k: lo12(val))); // ori $a0, $a0, %le_lo12
1478 break;
1479 default:
1480 llvm_unreachable("unsupported relocation for TLSDESC to LE");
1481 }
1482}
1483
1484// Try GOT indirection to PC relative optimization.
1485// From:
1486// * pcalau12i $a0, %got_pc_hi20(sym_got)
1487// * ld.w/d $a0, $a0, %got_pc_lo12(sym_got)
1488// To:
1489// * pcalau12i $a0, %pc_hi20(sym)
1490// * addi.w/d $a0, $a0, %pc_lo12(sym)
1491//
1492// Note: Althouth the optimization has been performed, the GOT entries still
1493// exists, similarly to AArch64. Eliminating the entries will increase code
1494// complexity.
1495bool LoongArch::tryGotToPCRel(uint8_t *loc, const Relocation &rHi20,
1496 const Relocation &rLo12, uint64_t secAddr) const {
1497 // Check if the relocations apply to consecutive instructions.
1498 if (rHi20.offset + 4 != rLo12.offset)
1499 return false;
1500
1501 // Check if the relocations reference the same symbol and skip undefined,
1502 // preemptible and STT_GNU_IFUNC symbols.
1503 if (!rHi20.sym || rHi20.sym != rLo12.sym || !rHi20.sym->isDefined() ||
1504 rHi20.sym->isPreemptible || rHi20.sym->isGnuIFunc())
1505 return false;
1506
1507 // GOT references to absolute symbols can't be relaxed to use PCALAU12I/ADDI
1508 // in position-independent code because these instructions produce a relative
1509 // address.
1510 if ((ctx.arg.isPic && !cast<Defined>(Val&: *rHi20.sym).section))
1511 return false;
1512
1513 // Check if the addends of the both relocations are zero.
1514 if (rHi20.addend != 0 || rLo12.addend != 0)
1515 return false;
1516
1517 const uint32_t currInsn = read32le(P: loc);
1518 const uint32_t nextInsn = read32le(P: loc + 4);
1519 const uint32_t ldOpcode = ctx.arg.is64 ? LD_D : LD_W;
1520 // Check if the first instruction is PCALAU12I and the second instruction is
1521 // LD.
1522 if ((currInsn & 0xfe000000) != PCALAU12I ||
1523 (nextInsn & 0xffc00000) != ldOpcode)
1524 return false;
1525
1526 // Check if use the same register.
1527 if (getD5(v: currInsn) != getJ5(v: nextInsn) || getJ5(v: nextInsn) != getD5(v: nextInsn))
1528 return false;
1529
1530 Symbol &sym = *rHi20.sym;
1531 uint64_t symLocal = sym.getVA(ctx);
1532 const int64_t displace = symLocal - getLoongArchPage(p: secAddr + rHi20.offset);
1533 // Check if the symbol address is in
1534 // [(PC & ~0xfff) - 2GiB - 0x800, (PC & ~0xfff) + 2GiB - 0x800).
1535 const int64_t underflow = -0x80000000LL - 0x800;
1536 const int64_t overflow = 0x80000000LL - 0x800;
1537 if (!(displace >= underflow && displace < overflow))
1538 return false;
1539
1540 Relocation newRHi20 = {.expr: RE_LOONGARCH_PAGE_PC, .type: R_LARCH_PCALA_HI20, .offset: rHi20.offset,
1541 .addend: rHi20.addend, .sym: &sym};
1542 Relocation newRLo12 = {.expr: R_ABS, .type: R_LARCH_PCALA_LO12, .offset: rLo12.offset, .addend: rLo12.addend,
1543 .sym: &sym};
1544 uint64_t pageDelta =
1545 getLoongArchPageDelta(dest: symLocal, pc: secAddr + rHi20.offset, type: rHi20.type);
1546 // pcalau12i $a0, %pc_hi20
1547 write32le(P: loc, V: insn(op: PCALAU12I, d: getD5(v: currInsn), j: 0, k: 0));
1548 relocate(loc, rel: newRHi20, val: pageDelta);
1549 // addi.w/d $a0, $a0, %pc_lo12
1550 write32le(P: loc + 4, V: insn(op: ctx.arg.is64 ? ADDI_D : ADDI_W, d: getD5(v: nextInsn),
1551 j: getJ5(v: nextInsn), k: 0));
1552 relocate(loc: loc + 4, rel: newRLo12, val: SignExtend64(X: symLocal, B: 64));
1553 return true;
1554}
1555
1556// During TLSDESC to IE, the converted code sequence always includes an
1557// instruction related to the Lo12 relocation (ld.[wd]). To obtain correct val
1558// in `getRelocTargetVA`, expr of this instruction should be adjusted to R_GOT,
1559// while expr of other instructions related to the Hi20 relocation (pcalau12i)
1560// should be adjusted to RE_LOONGARCH_GOT_PAGE_PC. Specifically, in the normal
1561// or medium code model, the instruction with relocation R_LARCH_TLS_DESC_CALL
1562// is the candidate of Lo12 relocation.
1563
1564static bool pairForGotRels(ArrayRef<Relocation> relocs) {
1565 // Check if R_LARCH_GOT_PC_HI20 and R_LARCH_GOT_PC_LO12 always appear in
1566 // pairs.
1567 size_t i = 0;
1568 const size_t size = relocs.size();
1569 for (; i != size; ++i) {
1570 if (relocs[i].type == R_LARCH_GOT_PC_HI20) {
1571 if (i + 1 < size && relocs[i + 1].type == R_LARCH_GOT_PC_LO12) {
1572 ++i;
1573 continue;
1574 }
1575 if (relaxable(relocs, i) && i + 2 < size &&
1576 relocs[i + 2].type == R_LARCH_GOT_PC_LO12) {
1577 i += 2;
1578 continue;
1579 }
1580 break;
1581 } else if (relocs[i].type == R_LARCH_GOT_PC_LO12) {
1582 break;
1583 }
1584 }
1585 return i == size;
1586}
1587
1588void LoongArch::relocateAlloc(InputSection &sec, uint8_t *buf) const {
1589 const unsigned bits = ctx.arg.is64 ? 64 : 32;
1590 uint64_t secAddr = sec.getOutputSection()->addr + sec.outSecOff;
1591 bool isExtreme = false;
1592 const MutableArrayRef<Relocation> relocs = sec.relocs();
1593 const bool isPairForGotRels = pairForGotRels(relocs);
1594 for (size_t i = 0, size = relocs.size(); i != size; ++i) {
1595 Relocation &rel = relocs[i];
1596 if (rel.expr == R_RELAX_HINT)
1597 continue;
1598 uint8_t *loc = buf + rel.offset;
1599 uint64_t val = SignExtend64(
1600 X: sec.getRelocTargetVA(ctx, r: rel, p: secAddr + rel.offset), B: bits);
1601 switch (rel.type) {
1602 case R_LARCH_TLS_IE_PC_HI20:
1603 case R_LARCH_TLS_IE_PC_LO12:
1604 // IE to LE. Not supported in extreme code model.
1605 if (rel.expr != R_TPREL)
1606 break;
1607 if (rel.type == R_LARCH_TLS_IE_PC_HI20)
1608 isExtreme =
1609 i + 2 < size && relocs[i + 2].type == R_LARCH_TLS_IE64_PC_LO20;
1610 if (isExtreme) {
1611 rel.expr = getRelExpr(type: rel.type, s: *rel.sym, loc);
1612 val = SignExtend64(X: sec.getRelocTargetVA(ctx, r: rel, p: secAddr + rel.offset),
1613 B: bits);
1614 break;
1615 }
1616 if (relaxable(relocs, i) && rel.type == R_LARCH_TLS_IE_PC_HI20 &&
1617 isUInt<12>(x: val))
1618 continue;
1619 tlsIeToLe(loc, rel, val);
1620 continue;
1621
1622 case R_LARCH_TLS_DESC_PC_HI20:
1623 case R_LARCH_TLS_DESC_PC_LO12:
1624 case R_LARCH_TLS_DESC_LD:
1625 case R_LARCH_TLS_DESC_PCREL20_S2:
1626 // TLSDESC to LE/IE. Not supported in extreme code model.
1627 if (rel.expr != R_TPREL && rel.expr != RE_LOONGARCH_GOT_PAGE_PC)
1628 break;
1629 if (rel.type == R_LARCH_TLS_DESC_PC_HI20)
1630 isExtreme =
1631 i + 2 < size && relocs[i + 2].type == R_LARCH_TLS_DESC64_PC_LO20;
1632 if (isExtreme) {
1633 rel.expr = getRelExpr(type: rel.type, s: *rel.sym, loc);
1634 val = SignExtend64(X: sec.getRelocTargetVA(ctx, r: rel, p: secAddr + rel.offset),
1635 B: bits);
1636 break;
1637 }
1638 if (relaxable(relocs, i) && (rel.type == R_LARCH_TLS_DESC_PC_HI20 ||
1639 rel.type == R_LARCH_TLS_DESC_PC_LO12))
1640 continue;
1641 if (rel.expr == R_TPREL) {
1642 if (relaxable(relocs, i) && rel.type == R_LARCH_TLS_DESC_LD &&
1643 isUInt<12>(x: val))
1644 continue;
1645 tlsdescToLe(loc, rel, val);
1646 } else {
1647 tlsdescToIe(loc, rel, val);
1648 }
1649 continue;
1650
1651 case R_LARCH_TLS_DESC_CALL:
1652 if (isExtreme)
1653 continue;
1654 if (rel.expr == R_TPREL)
1655 tlsdescToLe(loc, rel, val);
1656 else
1657 tlsdescToIe(loc, rel, val);
1658 continue;
1659
1660 case R_LARCH_GOT_PC_HI20:
1661 // GOT indirection to PC relative optimization in normal or medium code
1662 // model, whether or not with R_LARCH_RELAX. If the code sequence can be
1663 // relaxed to a single pcaddi, the first instruction will be removed and
1664 // it will not reach here.
1665 if (isPairForGotRels) {
1666 bool isRelax = relaxable(relocs, i);
1667 const Relocation lo12Rel = isRelax ? relocs[i + 2] : relocs[i + 1];
1668 if (lo12Rel.type == R_LARCH_GOT_PC_LO12 &&
1669 tryGotToPCRel(loc, rHi20: rel, rLo12: lo12Rel, secAddr)) {
1670 i += isRelax ? 2 : 1;
1671 continue;
1672 }
1673 }
1674 break;
1675
1676 default:
1677 break;
1678 }
1679 relocate(loc, rel, val);
1680 }
1681}
1682
1683// When relaxing just R_LARCH_ALIGN, relocDeltas is usually changed only once in
1684// the absence of a linker script. For call and load/store R_LARCH_RELAX, code
1685// shrinkage may reduce displacement and make more relocations eligible for
1686// relaxation. Code shrinkage may increase displacement to a call/load/store
1687// target at a higher fixed address, invalidating an earlier relaxation. Any
1688// change in section sizes can have cascading effect and require another
1689// relaxation pass.
1690bool LoongArch::relaxOnce(int pass) const {
1691 if (pass == 0)
1692 initSymbolAnchors(ctx);
1693
1694 SmallVector<InputSection *, 0> storage;
1695 bool changed = false;
1696 for (OutputSection *osec : ctx.outputSections) {
1697 if (!(osec->flags & SHF_EXECINSTR))
1698 continue;
1699 for (InputSection *sec : getInputSections(os: *osec, storage))
1700 if (sec->relaxAux)
1701 changed |= relax(ctx, sec&: *sec);
1702 }
1703 return changed;
1704}
1705
1706void LoongArch::finalizeRelax(int passes) const {
1707 Log(ctx) << "relaxation passes: " << passes;
1708 SmallVector<InputSection *, 0> storage;
1709 for (OutputSection *osec : ctx.outputSections) {
1710 if (!(osec->flags & SHF_EXECINSTR))
1711 continue;
1712 for (InputSection *sec : getInputSections(os: *osec, storage)) {
1713 if (!sec->relaxAux)
1714 continue;
1715 RelaxAux &aux = *sec->relaxAux;
1716 if (!aux.relocDeltas)
1717 continue;
1718
1719 MutableArrayRef<Relocation> rels = sec->relocs();
1720 ArrayRef<uint8_t> old = sec->content();
1721 size_t newSize = old.size() - aux.relocDeltas[rels.size() - 1];
1722 size_t writesIdx = 0;
1723 uint8_t *p = ctx.bAlloc.Allocate<uint8_t>(Num: newSize);
1724 uint64_t offset = 0;
1725 int64_t delta = 0;
1726 sec->content_ = p;
1727 sec->size = newSize;
1728 sec->bytesDropped = 0;
1729
1730 // Update section content: remove NOPs for R_LARCH_ALIGN and rewrite
1731 // instructions for relaxed relocations.
1732 for (size_t i = 0, e = rels.size(); i != e; ++i) {
1733 uint32_t remove = aux.relocDeltas[i] - delta;
1734 delta = aux.relocDeltas[i];
1735 if (remove == 0 && aux.relocTypes[i] == R_LARCH_NONE)
1736 continue;
1737
1738 // Copy from last location to the current relocated location.
1739 Relocation &r = rels[i];
1740 uint64_t size = r.offset - offset;
1741 memcpy(dest: p, src: old.data() + offset, n: size);
1742 p += size;
1743
1744 int64_t skip = 0;
1745 if (RelType newType = aux.relocTypes[i]) {
1746 switch (newType) {
1747 case R_LARCH_RELAX:
1748 break;
1749 case R_LARCH_PCREL20_S2:
1750 skip = 4;
1751 write32le(P: p, V: aux.writes[writesIdx++]);
1752 // RelExpr is needed for relocating.
1753 r.expr = r.sym->hasFlag(bit: NEEDS_PLT) ? R_PLT_PC : R_PC;
1754 break;
1755 case R_LARCH_B26:
1756 case R_LARCH_TLS_LE_LO12_R:
1757 skip = 4;
1758 write32le(P: p, V: aux.writes[writesIdx++]);
1759 break;
1760 case R_LARCH_TLS_GD_PCREL20_S2:
1761 // Note: R_LARCH_TLS_LD_PCREL20_S2 must also use R_TLSGD_PC instead
1762 // of R_TLSLD_PC due to historical reasons. In fact, right now TLSLD
1763 // behaves exactly like TLSGD on LoongArch.
1764 //
1765 // This reason has also been mentioned in mold commit:
1766 // https://github.com/rui314/mold/commit/5dfa1cf07c03bd57cb3d493b652ef22441bcd71c
1767 case R_LARCH_TLS_LD_PCREL20_S2:
1768 skip = 4;
1769 write32le(P: p, V: aux.writes[writesIdx++]);
1770 r.expr = R_TLSGD_PC;
1771 break;
1772 case R_LARCH_TLS_DESC_PCREL20_S2:
1773 skip = 4;
1774 write32le(P: p, V: aux.writes[writesIdx++]);
1775 r.expr = R_TLSDESC_PC;
1776 break;
1777 default:
1778 llvm_unreachable("unsupported type");
1779 }
1780 }
1781
1782 p += skip;
1783 offset = r.offset + skip + remove;
1784 }
1785 memcpy(dest: p, src: old.data() + offset, n: old.size() - offset);
1786
1787 // Subtract the previous relocDeltas value from the relocation offset.
1788 // For a pair of R_LARCH_XXX/R_LARCH_RELAX with the same offset, decrease
1789 // their r_offset by the same delta.
1790 delta = 0;
1791 for (size_t i = 0, e = rels.size(); i != e;) {
1792 uint64_t cur = rels[i].offset;
1793 do {
1794 rels[i].offset -= delta;
1795 if (aux.relocTypes[i] != R_LARCH_NONE)
1796 rels[i].type = aux.relocTypes[i];
1797 } while (++i != e && rels[i].offset == cur);
1798 delta = aux.relocDeltas[i - 1];
1799 }
1800 }
1801 }
1802}
1803
1804void elf::setLoongArchTargetInfo(Ctx &ctx) {
1805 ctx.target.reset(p: new LoongArch(ctx));
1806}
1807