[lld] [lld][ELF] Add range extension thunks for x86-64 (PR #180266)
Peter Smith via llvm-commits
llvm-commits at lists.llvm.org
Wed Feb 11 06:47:12 PST 2026
================
@@ -1234,6 +1283,97 @@ void ThumbV4PILongThunk::addLongMapSyms() {
addSymbol("$d", STT_NOTYPE, 16, *tsec);
}
+// x86-64 Thunk base class.
+// For x86-64, the thunk's addend comes from the original R_X86_64_PLT32
+// relocation. That addend includes a -4 PC-relative compensation (since the
+// CPU adds 4 for the displacement field size during PC-relative addressing).
+// When computing the thunk's jump target, we must add back this +4 to get
+// the actual destination address. For example, a call to a local symbol at
+// section+0x100 produces addend = 0x100 - 4 = 0xFC, so the thunk target
+// should be section.getVA(0xFC + 4) = section + 0x100.
+static uint64_t getX86_64ThunkDestVA(Ctx &ctx, const Symbol &s, int64_t a) {
+ if (s.isInPlt(ctx))
+ return s.getPltVA(ctx);
+ // Add 4 to undo the -4 PC-relative compensation in the addend.
+ return s.getVA(ctx, a + 4);
+}
+
+bool X86_64Thunk::getMayUseShortThunk() {
+ if (!mayUseShortThunk)
+ return false;
+ uint64_t s = getX86_64ThunkDestVA(ctx, destination, addend);
+ uint64_t p = getThunkTargetSym()->getVA(ctx);
+ // The jmp rel32 instruction is 5 bytes, so we check (target - (thunk + 5)).
+ mayUseShortThunk = llvm::isInt<32>(s - p - 5);
+ return mayUseShortThunk;
+}
+
+void X86_64Thunk::writeTo(uint8_t *buf) {
+ if (!getMayUseShortThunk()) {
+ writeLong(buf);
+ return;
+ }
+ // Short thunk: jmp rel32 (5 bytes)
+ uint64_t s = getX86_64ThunkDestVA(ctx, destination, addend);
+ uint64_t p = getThunkTargetSym()->getVA(ctx);
+ buf[0] = 0xe9; // jmp rel32
+ write32le(buf + 1, static_cast<uint32_t>(s - p - 5));
+}
+
+// x86-64 long range thunk implementation.
----------------
smithp35 wrote:
The comment is duplicated later down the file. Not the end of the world but there is a risk that one or other goes stale. I tend to find that most time is spent looking at the member function implementations so you may be able to forward reference the comment here.
https://github.com/llvm/llvm-project/pull/180266
More information about the llvm-commits
mailing list