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, uint32_t prevRemove) {
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 // When the caller specifies the old value of `remove`, disallow its
1183 // increment.
1184 if (prevRemove < 4)
1185 return;
1186
1187 sec.relaxAux->relocTypes[i] = R_LARCH_RELAX;
1188 if (rHi20.type == R_LARCH_TLS_GD_PC_HI20)
1189 sec.relaxAux->relocTypes[i + 2] = R_LARCH_TLS_GD_PCREL20_S2;
1190 else if (rHi20.type == R_LARCH_TLS_LD_PC_HI20)
1191 sec.relaxAux->relocTypes[i + 2] = R_LARCH_TLS_LD_PCREL20_S2;
1192 else if (rHi20.type == R_LARCH_TLS_DESC_PC_HI20)
1193 sec.relaxAux->relocTypes[i + 2] = R_LARCH_TLS_DESC_PCREL20_S2;
1194 else
1195 sec.relaxAux->relocTypes[i + 2] = R_LARCH_PCREL20_S2;
1196 sec.relaxAux->writes.push_back(Elt: insn(op: PCADDI, d: getD5(v: nextInsn), j: 0, k: 0));
1197 remove = 4;
1198}
1199
1200// Relax code sequence.
1201// From:
1202// la32r:
1203// pcaddu12i $ra, %call30(foo)
1204// jirl $ra, $ra, 0
1205// la32s/la64:
1206// pcaddu18i $ra, %call36(foo)
1207// jirl $ra, $ra, 0
1208// To:
1209// b/bl foo
1210static void relaxMediumCall(Ctx &ctx, const InputSection &sec, size_t i,
1211 uint64_t loc, Relocation &r, uint32_t &remove,
1212 uint32_t prevRemove) {
1213 const uint64_t dest =
1214 (r.expr == R_PLT_PC ? r.sym->getPltVA(ctx) : r.sym->getVA(ctx)) +
1215 r.addend;
1216
1217 const int64_t displace = dest - loc;
1218 // Check if the displace aligns 4 bytes or exceeds the range of b[l].
1219 if ((displace & 0x3) != 0 || !isInt<28>(x: displace))
1220 return;
1221
1222 // When the caller specifies the old value of `remove`, disallow its
1223 // increment.
1224 if (prevRemove < 4)
1225 return;
1226
1227 const uint32_t nextInsn = read32le(P: sec.content().data() + r.offset + 4);
1228 if (getD5(v: nextInsn) == R_RA) {
1229 // convert jirl to bl
1230 sec.relaxAux->relocTypes[i] = R_LARCH_B26;
1231 sec.relaxAux->writes.push_back(Elt: insn(op: BL, d: 0, j: 0, k: 0));
1232 remove = 4;
1233 } else if (getD5(v: nextInsn) == R_ZERO) {
1234 // convert jirl to b
1235 sec.relaxAux->relocTypes[i] = R_LARCH_B26;
1236 sec.relaxAux->writes.push_back(Elt: insn(op: B, d: 0, j: 0, k: 0));
1237 remove = 4;
1238 }
1239}
1240
1241// Relax code sequence.
1242// From:
1243// lu12i.w $rd, %le_hi20_r(sym)
1244// add.w/d $rd, $rd, $tp, %le_add_r(sym)
1245// addi/ld/st.w/d $rd, $rd, %le_lo12_r(sym)
1246// To:
1247// addi/ld/st.w/d $rd, $tp, %le_lo12_r(sym)
1248static void relaxTlsLe(Ctx &ctx, const InputSection &sec, size_t i,
1249 uint64_t loc, Relocation &r, uint32_t &remove) {
1250 uint64_t val = r.sym->getVA(ctx, addend: r.addend);
1251 // Check if the val exceeds the range of addi/ld/st.
1252 if (!isInt<12>(x: val))
1253 return;
1254 uint32_t currInsn = read32le(P: sec.content().data() + r.offset);
1255 switch (r.type) {
1256 case R_LARCH_TLS_LE_HI20_R:
1257 case R_LARCH_TLS_LE_ADD_R:
1258 sec.relaxAux->relocTypes[i] = R_LARCH_RELAX;
1259 remove = 4;
1260 break;
1261 case R_LARCH_TLS_LE_LO12_R:
1262 sec.relaxAux->writes.push_back(Elt: setJ5(insn: currInsn, imm: R_TP));
1263 sec.relaxAux->relocTypes[i] = R_LARCH_TLS_LE_LO12_R;
1264 break;
1265 }
1266}
1267
1268static bool relax(Ctx &ctx, int pass, InputSection &sec) {
1269 const uint64_t secAddr = sec.getVA();
1270 const MutableArrayRef<Relocation> relocs = sec.relocs();
1271 auto &aux = *sec.relaxAux;
1272 bool changed = false;
1273 ArrayRef<SymbolAnchor> sa = ArrayRef(aux.anchors);
1274 uint64_t delta = 0;
1275
1276 std::fill_n(first: aux.relocTypes.get(), n: relocs.size(), value: R_LARCH_NONE);
1277 aux.writes.clear();
1278 for (auto [i, r] : llvm::enumerate(First: relocs)) {
1279 const uint64_t loc = secAddr + r.offset - delta;
1280 uint32_t &cur = aux.relocDeltas[i], remove = 0;
1281 // Prevent oscillation between states by disallowing the increment of
1282 // `remove` after a few passes. The previous `remove` value is
1283 // `cur-delta`.
1284 uint32_t prevRemove = pass < 4 ? UINT32_MAX : cur - delta;
1285 switch (r.type) {
1286 case R_LARCH_ALIGN: {
1287 const uint64_t addend =
1288 r.sym->isUndefined() ? Log2_64(Value: r.addend) + 1 : r.addend;
1289 const uint64_t allBytes = (1ULL << (addend & 0xff)) - 4;
1290 const uint64_t align = 1ULL << (addend & 0xff);
1291 const uint64_t maxBytes = addend >> 8;
1292 const uint64_t off = loc & (align - 1);
1293 const uint64_t curBytes = off == 0 ? 0 : align - off;
1294 // All bytes beyond the alignment boundary should be removed.
1295 // If emit bytes more than max bytes to emit, remove all.
1296 if (maxBytes != 0 && curBytes > maxBytes)
1297 remove = allBytes;
1298 else
1299 remove = allBytes - curBytes;
1300 // If we can't satisfy this alignment, we've found a bad input.
1301 if (LLVM_UNLIKELY(static_cast<int32_t>(remove) < 0)) {
1302 Err(ctx) << getErrorLoc(ctx, loc: (const uint8_t *)loc)
1303 << "insufficient padding bytes for " << r.type << ": "
1304 << allBytes << " bytes available for "
1305 << "requested alignment of " << align << " bytes";
1306 remove = 0;
1307 }
1308 break;
1309 }
1310 case R_LARCH_PCALA_HI20:
1311 case R_LARCH_GOT_PC_HI20:
1312 case R_LARCH_TLS_GD_PC_HI20:
1313 case R_LARCH_TLS_LD_PC_HI20:
1314 // The overflow check for i+2 will be carried out in isPairRelaxable.
1315 if (isPairRelaxable(relocs, i))
1316 relaxPCHi20Lo12(ctx, sec, i, loc, rHi20&: r, rLo12&: relocs[i + 2], remove, prevRemove);
1317 break;
1318 case R_LARCH_TLS_DESC_PC_HI20:
1319 if (r.expr == RE_LOONGARCH_GOT_PAGE_PC || r.expr == R_TPREL) {
1320 if (relaxable(relocs, i))
1321 remove = 4;
1322 } else if (isPairRelaxable(relocs, i))
1323 relaxPCHi20Lo12(ctx, sec, i, loc, rHi20&: r, rLo12&: relocs[i + 2], remove, prevRemove);
1324 break;
1325 case R_LARCH_CALL30:
1326 case R_LARCH_CALL36:
1327 if (relaxable(relocs, i))
1328 relaxMediumCall(ctx, sec, i, loc, r, remove, prevRemove);
1329 break;
1330 case R_LARCH_TLS_LE_HI20_R:
1331 case R_LARCH_TLS_LE_ADD_R:
1332 case R_LARCH_TLS_LE_LO12_R:
1333 if (relaxable(relocs, i))
1334 relaxTlsLe(ctx, sec, i, loc, r, remove);
1335 break;
1336 case R_LARCH_TLS_IE_PC_HI20:
1337 if (relaxable(relocs, i) && r.expr == R_TPREL &&
1338 isUInt<12>(x: r.sym->getVA(ctx, addend: r.addend)))
1339 remove = 4;
1340 break;
1341 case R_LARCH_TLS_DESC_PC_LO12:
1342 if (relaxable(relocs, i) &&
1343 (r.expr == RE_LOONGARCH_GOT_PAGE_PC || r.expr == R_TPREL))
1344 remove = 4;
1345 break;
1346 case R_LARCH_TLS_DESC_LD:
1347 if (relaxable(relocs, i) && r.expr == R_TPREL &&
1348 isUInt<12>(x: r.sym->getVA(ctx, addend: r.addend)))
1349 remove = 4;
1350 break;
1351 }
1352
1353 // For all anchors whose offsets are <= r.offset, they are preceded by
1354 // the previous relocation whose `relocDeltas` value equals `delta`.
1355 // Decrease their st_value and update their st_size.
1356 for (; sa.size() && sa[0].offset <= r.offset; sa = sa.slice(N: 1)) {
1357 if (sa[0].end)
1358 sa[0].d->size = sa[0].offset - delta - sa[0].d->value;
1359 else
1360 sa[0].d->value = sa[0].offset - delta;
1361 }
1362 delta += remove;
1363 if (delta != cur) {
1364 cur = delta;
1365 changed = true;
1366 }
1367 }
1368
1369 for (const SymbolAnchor &a : sa) {
1370 if (a.end)
1371 a.d->size = a.offset - delta - a.d->value;
1372 else
1373 a.d->value = a.offset - delta;
1374 }
1375 // Inform assignAddresses that the size has changed.
1376 if (!isUInt<32>(x: delta))
1377 Fatal(ctx) << "section size decrease is too large: " << delta;
1378 sec.bytesDropped = delta;
1379 return changed;
1380}
1381
1382// Convert TLS IE to LE in the normal or medium code model.
1383// Original code sequence:
1384// * pcalau12i $a0, %ie_pc_hi20(sym)
1385// * ld.d $a0, $a0, %ie_pc_lo12(sym)
1386//
1387// The code sequence converted is as follows:
1388// * lu12i.w $a0, %le_hi20(sym) # le_hi20 != 0, otherwise NOP
1389// * ori $a0, src, %le_lo12(sym) # le_hi20 != 0, src = $a0,
1390// # otherwise, src = $zero
1391//
1392// When relaxation enables, redundant NOPs can be removed.
1393static void tlsIeToLe(uint8_t *loc, const Relocation &rel, uint64_t val) {
1394 assert(isInt<32>(val) &&
1395 "val exceeds the range of medium code model in tlsIeToLe");
1396
1397 bool isUInt12 = isUInt<12>(x: val);
1398 const uint32_t currInsn = read32le(P: loc);
1399 switch (rel.type) {
1400 case R_LARCH_TLS_IE_PC_HI20:
1401 if (isUInt12)
1402 write32le(P: loc, V: insn(op: ANDI, d: R_ZERO, j: R_ZERO, k: 0)); // nop
1403 else
1404 write32le(P: loc, V: insn(op: LU12I_W, d: getD5(v: currInsn), j: extractBits(v: val, begin: 31, end: 12),
1405 k: 0)); // lu12i.w $a0, %le_hi20
1406 break;
1407 case R_LARCH_TLS_IE_PC_LO12:
1408 if (isUInt12)
1409 write32le(P: loc, V: insn(op: ORI, d: getD5(v: currInsn), j: R_ZERO,
1410 k: val)); // ori $a0, $zero, %le_lo12
1411 else
1412 write32le(P: loc, V: insn(op: ORI, d: getD5(v: currInsn), j: getJ5(v: currInsn),
1413 k: lo12(val))); // ori $a0, $a0, %le_lo12
1414 break;
1415 }
1416}
1417
1418// Convert TLSDESC GD/LD to IE.
1419// In normal or medium code model, there are two forms of code sequences:
1420// * pcalau12i $a0, %desc_pc_hi20(sym_desc)
1421// * addi.d $a0, $a0, %desc_pc_lo12(sym_desc)
1422// * ld.d $ra, $a0, %desc_ld(sym_desc)
1423// * jirl $ra, $ra, %desc_call(sym_desc)
1424// ------
1425// * pcaddi $a0, %desc_pcrel_20(a)
1426// * load $ra, $a0, %desc_ld(a)
1427// * jirl $ra, $ra, %desc_call(a)
1428//
1429// The code sequence obtained is as follows:
1430// * pcalau12i $a0, %ie_pc_hi20(sym_ie)
1431// * ld.[wd] $a0, $a0, %ie_pc_lo12(sym_ie)
1432//
1433// Simplicity, whether tlsdescToIe or tlsdescToLe, we always tend to convert the
1434// preceding instructions to NOPs, due to both forms of code sequence
1435// (corresponding to relocation combinations:
1436// R_LARCH_TLS_DESC_PC_HI20+R_LARCH_TLS_DESC_PC_LO12 and
1437// R_LARCH_TLS_DESC_PCREL20_S2) have same process.
1438//
1439// When relaxation enables, redundant NOPs can be removed.
1440void LoongArch::tlsdescToIe(uint8_t *loc, const Relocation &rel,
1441 uint64_t val) const {
1442 switch (rel.type) {
1443 case R_LARCH_TLS_DESC_PC_HI20:
1444 case R_LARCH_TLS_DESC_PC_LO12:
1445 case R_LARCH_TLS_DESC_PCREL20_S2:
1446 write32le(P: loc, V: insn(op: ANDI, d: R_ZERO, j: R_ZERO, k: 0)); // nop
1447 break;
1448 case R_LARCH_TLS_DESC_LD:
1449 write32le(P: loc, V: insn(op: PCALAU12I, d: R_A0, j: 0, k: 0)); // pcalau12i $a0, %ie_pc_hi20
1450 relocateNoSym(loc, type: R_LARCH_TLS_IE_PC_HI20, val);
1451 break;
1452 case R_LARCH_TLS_DESC_CALL:
1453 write32le(P: loc, V: insn(op: ctx.arg.is64 ? LD_D : LD_W, d: R_A0, j: R_A0,
1454 k: 0)); // ld.[wd] $a0, $a0, %ie_pc_lo12
1455 relocateNoSym(loc, type: R_LARCH_TLS_IE_PC_LO12, val);
1456 break;
1457 default:
1458 llvm_unreachable("unsupported relocation for TLSDESC to IE");
1459 }
1460}
1461
1462// Convert TLSDESC GD/LD to LE.
1463// The code sequence obtained in the normal or medium code model is as follows:
1464// * lu12i.w $a0, %le_hi20(sym) # le_hi20 != 0, otherwise NOP
1465// * ori $a0, src, %le_lo12(sym) # le_hi20 != 0, src = $a0,
1466// # otherwise, src = $zero
1467// See the comment in tlsdescToIe for detailed information.
1468void LoongArch::tlsdescToLe(uint8_t *loc, const Relocation &rel,
1469 uint64_t val) const {
1470 assert(isInt<32>(val) &&
1471 "val exceeds the range of medium code model in tlsdescToLe");
1472
1473 bool isUInt12 = isUInt<12>(x: val);
1474 switch (rel.type) {
1475 case R_LARCH_TLS_DESC_PC_HI20:
1476 case R_LARCH_TLS_DESC_PC_LO12:
1477 case R_LARCH_TLS_DESC_PCREL20_S2:
1478 write32le(P: loc, V: insn(op: ANDI, d: R_ZERO, j: R_ZERO, k: 0)); // nop
1479 break;
1480 case R_LARCH_TLS_DESC_LD:
1481 if (isUInt12)
1482 write32le(P: loc, V: insn(op: ANDI, d: R_ZERO, j: R_ZERO, k: 0)); // nop
1483 else
1484 write32le(P: loc, V: insn(op: LU12I_W, d: R_A0, j: extractBits(v: val, begin: 31, end: 12),
1485 k: 0)); // lu12i.w $a0, %le_hi20
1486 break;
1487 case R_LARCH_TLS_DESC_CALL:
1488 if (isUInt12)
1489 write32le(P: loc, V: insn(op: ORI, d: R_A0, j: R_ZERO, k: val)); // ori $a0, $zero, %le_lo12
1490 else
1491 write32le(P: loc,
1492 V: insn(op: ORI, d: R_A0, j: R_A0, k: lo12(val))); // ori $a0, $a0, %le_lo12
1493 break;
1494 default:
1495 llvm_unreachable("unsupported relocation for TLSDESC to LE");
1496 }
1497}
1498
1499// Try GOT indirection to PC relative optimization.
1500// From:
1501// * pcalau12i $a0, %got_pc_hi20(sym_got)
1502// * ld.w/d $a0, $a0, %got_pc_lo12(sym_got)
1503// To:
1504// * pcalau12i $a0, %pc_hi20(sym)
1505// * addi.w/d $a0, $a0, %pc_lo12(sym)
1506//
1507// Note: Althouth the optimization has been performed, the GOT entries still
1508// exists, similarly to AArch64. Eliminating the entries will increase code
1509// complexity.
1510bool LoongArch::tryGotToPCRel(uint8_t *loc, const Relocation &rHi20,
1511 const Relocation &rLo12, uint64_t secAddr) const {
1512 // Check if the relocations apply to consecutive instructions.
1513 if (rHi20.offset + 4 != rLo12.offset)
1514 return false;
1515
1516 // Check if the relocations reference the same symbol and skip undefined,
1517 // preemptible and STT_GNU_IFUNC symbols.
1518 if (!rHi20.sym || rHi20.sym != rLo12.sym || !rHi20.sym->isDefined() ||
1519 rHi20.sym->isPreemptible || rHi20.sym->isGnuIFunc())
1520 return false;
1521
1522 // GOT references to absolute symbols can't be relaxed to use PCALAU12I/ADDI
1523 // in position-independent code because these instructions produce a relative
1524 // address.
1525 if ((ctx.arg.isPic && !cast<Defined>(Val&: *rHi20.sym).section))
1526 return false;
1527
1528 // Check if the addends of the both relocations are zero.
1529 if (rHi20.addend != 0 || rLo12.addend != 0)
1530 return false;
1531
1532 const uint32_t currInsn = read32le(P: loc);
1533 const uint32_t nextInsn = read32le(P: loc + 4);
1534 const uint32_t ldOpcode = ctx.arg.is64 ? LD_D : LD_W;
1535 // Check if the first instruction is PCALAU12I and the second instruction is
1536 // LD.
1537 if ((currInsn & 0xfe000000) != PCALAU12I ||
1538 (nextInsn & 0xffc00000) != ldOpcode)
1539 return false;
1540
1541 // Check if use the same register.
1542 if (getD5(v: currInsn) != getJ5(v: nextInsn) || getJ5(v: nextInsn) != getD5(v: nextInsn))
1543 return false;
1544
1545 Symbol &sym = *rHi20.sym;
1546 uint64_t symLocal = sym.getVA(ctx);
1547 const int64_t displace = symLocal - getLoongArchPage(p: secAddr + rHi20.offset);
1548 // Check if the symbol address is in
1549 // [(PC & ~0xfff) - 2GiB - 0x800, (PC & ~0xfff) + 2GiB - 0x800).
1550 const int64_t underflow = -0x80000000LL - 0x800;
1551 const int64_t overflow = 0x80000000LL - 0x800;
1552 if (!(displace >= underflow && displace < overflow))
1553 return false;
1554
1555 Relocation newRHi20 = {.expr: RE_LOONGARCH_PAGE_PC, .type: R_LARCH_PCALA_HI20, .offset: rHi20.offset,
1556 .addend: rHi20.addend, .sym: &sym};
1557 Relocation newRLo12 = {.expr: R_ABS, .type: R_LARCH_PCALA_LO12, .offset: rLo12.offset, .addend: rLo12.addend,
1558 .sym: &sym};
1559 uint64_t pageDelta =
1560 getLoongArchPageDelta(dest: symLocal, pc: secAddr + rHi20.offset, type: rHi20.type);
1561 // pcalau12i $a0, %pc_hi20
1562 write32le(P: loc, V: insn(op: PCALAU12I, d: getD5(v: currInsn), j: 0, k: 0));
1563 relocate(loc, rel: newRHi20, val: pageDelta);
1564 // addi.w/d $a0, $a0, %pc_lo12
1565 write32le(P: loc + 4, V: insn(op: ctx.arg.is64 ? ADDI_D : ADDI_W, d: getD5(v: nextInsn),
1566 j: getJ5(v: nextInsn), k: 0));
1567 relocate(loc: loc + 4, rel: newRLo12, val: SignExtend64(X: symLocal, B: 64));
1568 return true;
1569}
1570
1571// During TLSDESC to IE, the converted code sequence always includes an
1572// instruction related to the Lo12 relocation (ld.[wd]). To obtain correct val
1573// in `getRelocTargetVA`, expr of this instruction should be adjusted to R_GOT,
1574// while expr of other instructions related to the Hi20 relocation (pcalau12i)
1575// should be adjusted to RE_LOONGARCH_GOT_PAGE_PC. Specifically, in the normal
1576// or medium code model, the instruction with relocation R_LARCH_TLS_DESC_CALL
1577// is the candidate of Lo12 relocation.
1578
1579static bool pairForGotRels(ArrayRef<Relocation> relocs) {
1580 // Check if R_LARCH_GOT_PC_HI20 and R_LARCH_GOT_PC_LO12 always appear in
1581 // pairs.
1582 size_t i = 0;
1583 const size_t size = relocs.size();
1584 for (; i != size; ++i) {
1585 if (relocs[i].type == R_LARCH_GOT_PC_HI20) {
1586 if (i + 1 < size && relocs[i + 1].type == R_LARCH_GOT_PC_LO12) {
1587 ++i;
1588 continue;
1589 }
1590 if (relaxable(relocs, i) && i + 2 < size &&
1591 relocs[i + 2].type == R_LARCH_GOT_PC_LO12) {
1592 i += 2;
1593 continue;
1594 }
1595 break;
1596 } else if (relocs[i].type == R_LARCH_GOT_PC_LO12) {
1597 break;
1598 }
1599 }
1600 return i == size;
1601}
1602
1603void LoongArch::relocateAlloc(InputSection &sec, uint8_t *buf) const {
1604 const unsigned bits = ctx.arg.is64 ? 64 : 32;
1605 uint64_t secAddr = sec.getOutputSection()->addr + sec.outSecOff;
1606 bool isExtreme = false;
1607 const MutableArrayRef<Relocation> relocs = sec.relocs();
1608 const bool isPairForGotRels = pairForGotRels(relocs);
1609 for (size_t i = 0, size = relocs.size(); i != size; ++i) {
1610 Relocation &rel = relocs[i];
1611 if (rel.expr == R_RELAX_HINT)
1612 continue;
1613 uint8_t *loc = buf + rel.offset;
1614 uint64_t val = SignExtend64(
1615 X: sec.getRelocTargetVA(ctx, r: rel, p: secAddr + rel.offset), B: bits);
1616 switch (rel.type) {
1617 case R_LARCH_TLS_IE_PC_HI20:
1618 case R_LARCH_TLS_IE_PC_LO12:
1619 // IE to LE. Not supported in extreme code model.
1620 if (rel.expr != R_TPREL)
1621 break;
1622 if (rel.type == R_LARCH_TLS_IE_PC_HI20)
1623 isExtreme =
1624 i + 2 < size && relocs[i + 2].type == R_LARCH_TLS_IE64_PC_LO20;
1625 if (isExtreme) {
1626 rel.expr = getRelExpr(type: rel.type, s: *rel.sym, loc);
1627 val = SignExtend64(X: sec.getRelocTargetVA(ctx, r: rel, p: secAddr + rel.offset),
1628 B: bits);
1629 break;
1630 }
1631 if (relaxable(relocs, i) && rel.type == R_LARCH_TLS_IE_PC_HI20 &&
1632 isUInt<12>(x: val))
1633 continue;
1634 tlsIeToLe(loc, rel, val);
1635 continue;
1636
1637 case R_LARCH_TLS_DESC_PC_HI20:
1638 case R_LARCH_TLS_DESC_PC_LO12:
1639 case R_LARCH_TLS_DESC_LD:
1640 case R_LARCH_TLS_DESC_PCREL20_S2:
1641 // TLSDESC to LE/IE. Not supported in extreme code model.
1642 if (rel.expr != R_TPREL && rel.expr != RE_LOONGARCH_GOT_PAGE_PC)
1643 break;
1644 if (rel.type == R_LARCH_TLS_DESC_PC_HI20)
1645 isExtreme =
1646 i + 2 < size && relocs[i + 2].type == R_LARCH_TLS_DESC64_PC_LO20;
1647 if (isExtreme) {
1648 rel.expr = getRelExpr(type: rel.type, s: *rel.sym, loc);
1649 val = SignExtend64(X: sec.getRelocTargetVA(ctx, r: rel, p: secAddr + rel.offset),
1650 B: bits);
1651 break;
1652 }
1653 if (relaxable(relocs, i) && (rel.type == R_LARCH_TLS_DESC_PC_HI20 ||
1654 rel.type == R_LARCH_TLS_DESC_PC_LO12))
1655 continue;
1656 if (rel.expr == R_TPREL) {
1657 if (relaxable(relocs, i) && rel.type == R_LARCH_TLS_DESC_LD &&
1658 isUInt<12>(x: val))
1659 continue;
1660 tlsdescToLe(loc, rel, val);
1661 } else {
1662 tlsdescToIe(loc, rel, val);
1663 }
1664 continue;
1665
1666 case R_LARCH_TLS_DESC_CALL:
1667 if (isExtreme)
1668 continue;
1669 if (rel.expr == R_TPREL)
1670 tlsdescToLe(loc, rel, val);
1671 else
1672 tlsdescToIe(loc, rel, val);
1673 continue;
1674
1675 case R_LARCH_GOT_PC_HI20:
1676 // GOT indirection to PC relative optimization in normal or medium code
1677 // model, whether or not with R_LARCH_RELAX. If the code sequence can be
1678 // relaxed to a single pcaddi, the first instruction will be removed and
1679 // it will not reach here.
1680 if (isPairForGotRels) {
1681 bool isRelax = relaxable(relocs, i);
1682 const Relocation lo12Rel = isRelax ? relocs[i + 2] : relocs[i + 1];
1683 if (lo12Rel.type == R_LARCH_GOT_PC_LO12 &&
1684 tryGotToPCRel(loc, rHi20: rel, rLo12: lo12Rel, secAddr)) {
1685 i += isRelax ? 2 : 1;
1686 continue;
1687 }
1688 }
1689 break;
1690
1691 default:
1692 break;
1693 }
1694 relocate(loc, rel, val);
1695 }
1696}
1697
1698// When relaxing just R_LARCH_ALIGN, relocDeltas is usually changed only once in
1699// the absence of a linker script. For call and load/store R_LARCH_RELAX, code
1700// shrinkage may reduce displacement and make more relocations eligible for
1701// relaxation. Code shrinkage may increase displacement to a call/load/store
1702// target at a higher fixed address, invalidating an earlier relaxation. Any
1703// change in section sizes can have cascading effect and require another
1704// relaxation pass.
1705bool LoongArch::relaxOnce(int pass) const {
1706 if (pass == 0)
1707 initSymbolAnchors(ctx);
1708
1709 SmallVector<InputSection *, 0> storage;
1710 bool changed = false;
1711 for (OutputSection *osec : ctx.outputSections) {
1712 if (!(osec->flags & SHF_EXECINSTR))
1713 continue;
1714 for (InputSection *sec : getInputSections(os: *osec, storage))
1715 if (sec->relaxAux)
1716 changed |= relax(ctx, pass, sec&: *sec);
1717 }
1718 return changed;
1719}
1720
1721void LoongArch::finalizeRelax(int passes) const {
1722 Log(ctx) << "relaxation passes: " << passes;
1723 SmallVector<InputSection *, 0> storage;
1724 for (OutputSection *osec : ctx.outputSections) {
1725 if (!(osec->flags & SHF_EXECINSTR))
1726 continue;
1727 for (InputSection *sec : getInputSections(os: *osec, storage)) {
1728 if (!sec->relaxAux)
1729 continue;
1730 RelaxAux &aux = *sec->relaxAux;
1731 if (!aux.relocDeltas)
1732 continue;
1733
1734 MutableArrayRef<Relocation> rels = sec->relocs();
1735 ArrayRef<uint8_t> old = sec->content();
1736 size_t newSize = old.size() - aux.relocDeltas[rels.size() - 1];
1737 size_t writesIdx = 0;
1738 uint8_t *p = ctx.bAlloc.Allocate<uint8_t>(Num: newSize);
1739 uint64_t offset = 0;
1740 int64_t delta = 0;
1741 sec->content_ = p;
1742 sec->size = newSize;
1743 sec->bytesDropped = 0;
1744
1745 // Update section content: remove NOPs for R_LARCH_ALIGN and rewrite
1746 // instructions for relaxed relocations.
1747 for (size_t i = 0, e = rels.size(); i != e; ++i) {
1748 uint32_t remove = aux.relocDeltas[i] - delta;
1749 delta = aux.relocDeltas[i];
1750 if (remove == 0 && aux.relocTypes[i] == R_LARCH_NONE)
1751 continue;
1752
1753 // Copy from last location to the current relocated location.
1754 Relocation &r = rels[i];
1755 uint64_t size = r.offset - offset;
1756 memcpy(dest: p, src: old.data() + offset, n: size);
1757 p += size;
1758
1759 int64_t skip = 0;
1760 if (RelType newType = aux.relocTypes[i]) {
1761 switch (newType) {
1762 case R_LARCH_RELAX:
1763 break;
1764 case R_LARCH_PCREL20_S2:
1765 skip = 4;
1766 write32le(P: p, V: aux.writes[writesIdx++]);
1767 // RelExpr is needed for relocating.
1768 r.expr = r.sym->hasFlag(bit: NEEDS_PLT) ? R_PLT_PC : R_PC;
1769 break;
1770 case R_LARCH_B26:
1771 case R_LARCH_TLS_LE_LO12_R:
1772 skip = 4;
1773 write32le(P: p, V: aux.writes[writesIdx++]);
1774 break;
1775 case R_LARCH_TLS_GD_PCREL20_S2:
1776 // Note: R_LARCH_TLS_LD_PCREL20_S2 must also use R_TLSGD_PC instead
1777 // of R_TLSLD_PC due to historical reasons. In fact, right now TLSLD
1778 // behaves exactly like TLSGD on LoongArch.
1779 //
1780 // This reason has also been mentioned in mold commit:
1781 // https://github.com/rui314/mold/commit/5dfa1cf07c03bd57cb3d493b652ef22441bcd71c
1782 case R_LARCH_TLS_LD_PCREL20_S2:
1783 skip = 4;
1784 write32le(P: p, V: aux.writes[writesIdx++]);
1785 r.expr = R_TLSGD_PC;
1786 break;
1787 case R_LARCH_TLS_DESC_PCREL20_S2:
1788 skip = 4;
1789 write32le(P: p, V: aux.writes[writesIdx++]);
1790 r.expr = R_TLSDESC_PC;
1791 break;
1792 default:
1793 llvm_unreachable("unsupported type");
1794 }
1795 }
1796
1797 p += skip;
1798 offset = r.offset + skip + remove;
1799 }
1800 memcpy(dest: p, src: old.data() + offset, n: old.size() - offset);
1801
1802 // Subtract the previous relocDeltas value from the relocation offset.
1803 // For a pair of R_LARCH_XXX/R_LARCH_RELAX with the same offset, decrease
1804 // their r_offset by the same delta.
1805 delta = 0;
1806 for (size_t i = 0, e = rels.size(); i != e;) {
1807 uint64_t cur = rels[i].offset;
1808 do {
1809 rels[i].offset -= delta;
1810 if (aux.relocTypes[i] != R_LARCH_NONE)
1811 rels[i].type = aux.relocTypes[i];
1812 } while (++i != e && rels[i].offset == cur);
1813 delta = aux.relocDeltas[i - 1];
1814 }
1815 }
1816 }
1817}
1818
1819void elf::setLoongArchTargetInfo(Ctx &ctx) {
1820 ctx.target.reset(p: new LoongArch(ctx));
1821}
1822