[clang] [compiler-rt] [lld] [llvm] ARM and Thumb support for GCC-compatible static-base PIC data addressing with `-mno-pic-data-is-text-relative`. (PR #239188)
Mark Murray via cfe-commits
cfe-commits at lists.llvm.org
Thu Nov 5 05:08:00 PST 2026
https://github.com/MarkMurrayARM updated https://github.com/llvm/llvm-project/pull/239188
>From 8444714b5de662be64be8f933d832b513fbef208 Mon Sep 17 00:00:00 2001
From: Mark Murray <Mark.Murray at arm.com>
Date: Thu, 5 Nov 2026 13:01:11 +0000
Subject: [PATCH 1/3] [ARM] Support static-base PIC data mode
Implement ARM and Thumb support for -mno-pic-data-is-text-relative in PIC and PIE code. In the implemented EABI mode, Clang lowers data references through GOT offsets relative to a fixed incoming r9 static base, matching GCC's default single-pic-base behavior for this option.
Plumb the option through Clang and LLVM target options, reserve r9 when the mode is active, describe r9 with the ARM build attributes, and define __ARM_PIC_DATA_STATIC_BASE for C and assembly code that needs to adapt to the ABI contract.
Cover driver forwarding and diagnostics, multilib flag selection, preprocessor state, SelectionDAG, FastISel, GlobalISel, ARM and Thumb code generation, PIE code generation, and r9 reservation under register pressure. Add documentation for the scoped LLVM option surface and runtime contract.
---
clang/include/clang/Basic/CodeGenOptions.def | 3 +
clang/include/clang/Options/Options.td | 10 +-
clang/lib/CodeGen/BackendUtil.cpp | 1 +
clang/lib/Driver/ToolChain.cpp | 9 ++
clang/lib/Driver/ToolChains/Clang.cpp | 11 +-
clang/lib/Frontend/InitPreprocessor.cpp | 3 +
.../CodeGen/arm-pic-data-is-text-relative.c | 90 +++++++++++
.../CodeGen/arm-pic-data-static-base-proof.c | 74 +++++++++
.../CodeGen/arm-pic-data-static-base-r9.c | 26 +++
clang/test/Driver/arm-pic-data-multilib.yaml | 20 +++
clang/test/Driver/pic.c | 41 ++++-
clang/test/Preprocessor/arm-pic-predefines.c | 14 +-
llvm/docs/ARMNoPICDataIsTextRelative.md | 148 ++++++++++++++++++
llvm/docs/UserGuides.md | 1 +
llvm/include/llvm/Target/TargetOptions.h | 19 ++-
llvm/lib/Target/ARM/ARMAsmPrinter.cpp | 9 +-
llvm/lib/Target/ARM/ARMConstantPoolValue.cpp | 2 +
llvm/lib/Target/ARM/ARMConstantPoolValue.h | 1 +
llvm/lib/Target/ARM/ARMFastISel.cpp | 41 ++++-
llvm/lib/Target/ARM/ARMISelLowering.cpp | 23 ++-
.../lib/Target/ARM/ARMInstructionSelector.cpp | 50 ++++--
llvm/lib/Target/ARM/ARMSubtarget.cpp | 17 +-
llvm/lib/Target/ARM/ARMSubtarget.h | 2 +
23 files changed, 574 insertions(+), 41 deletions(-)
create mode 100644 clang/test/CodeGen/arm-pic-data-is-text-relative.c
create mode 100644 clang/test/CodeGen/arm-pic-data-static-base-proof.c
create mode 100644 clang/test/CodeGen/arm-pic-data-static-base-r9.c
create mode 100644 clang/test/Driver/arm-pic-data-multilib.yaml
create mode 100644 llvm/docs/ARMNoPICDataIsTextRelative.md
diff --git a/clang/include/clang/Basic/CodeGenOptions.def b/clang/include/clang/Basic/CodeGenOptions.def
index ff33f5be424ecd..6a7e04afd6edf3 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -449,6 +449,9 @@ CODEGENOPT(DiagnosticsWithHotness, 1, 0, Benign)
/// Whether to use direct access relocations (instead of GOT) to reference external data symbols.
CODEGENOPT(DirectAccessExternalData, 1, 0, Benign)
+/// Whether ARM PIC data references may use text-relative addressing.
+CODEGENOPT(PicDataIsTextRelative, 1, 1, Benign)
+
/// Whether we should use the undefined behaviour optimization for control flow
/// paths that reach the end of a function without executing a required return.
CODEGENOPT(StrictReturn, 1, 1, Benign)
diff --git a/clang/include/clang/Options/Options.td b/clang/include/clang/Options/Options.td
index d9abc9b6e37d01..8d0dea19b5095e 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -4514,8 +4514,14 @@ def fpcc_struct_return : Flag<["-"], "fpcc-struct-return">, Group<f_Group>,
Visibility<[ClangOption, CC1Option]>,
HelpText<"Override the default ABI to return all structs on the stack">;
def fpch_preprocess : Flag<["-"], "fpch-preprocess">, Group<f_Group>;
-defm pic_data_is_text_relative : SimpleMFlag<"pic-data-is-text-relative",
- "Assume", "Don't assume", " data segments are relative to text segment">;
+defm pic_data_is_text_relative
+ : BoolMOption<
+ "pic-data-is-text-relative",
+ CodeGenOpts<"PicDataIsTextRelative">, DefaultTrue,
+ PosFlag<SetTrue, [], [ClangOption, CC1Option],
+ "Assume data segments are relative to text segment">,
+ NegFlag<SetFalse, [], [ClangOption, CC1Option],
+ "Don't assume data segments are relative to text segment">>;
def fdirect_access_external_data : Flag<["-"], "fdirect-access-external-data">, Group<f_Group>,
Visibility<[ClangOption, CC1Option]>,
HelpText<"Don't use GOT indirection to reference external data symbols">;
diff --git a/clang/lib/CodeGen/BackendUtil.cpp b/clang/lib/CodeGen/BackendUtil.cpp
index f226878f64f6f8..dc615b1470f77a 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -431,6 +431,7 @@ static bool initTargetOptions(const CompilerInstance &CI,
Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
Options.TLSSize = CodeGenOpts.TLSSize;
Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
+ Options.PicDataIsTextRelative = CodeGenOpts.PicDataIsTextRelative;
Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index b3e7043a64fe56..30abe5bbb43217 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -528,6 +528,15 @@ ToolChain::getMultilibFlags(const llvm::opt::ArgList &Args) const {
else
Result.push_back("-fno-pic");
+ if (RelocationModel == llvm::Reloc::PIC_ &&
+ (Triple.isARM() || Triple.isThumb())) {
+ bool PicDataIsTextRelative =
+ Args.hasFlag(options::OPT_mpic_data_is_text_relative,
+ options::OPT_mno_pic_data_is_text_relative, true);
+ Result.push_back(PicDataIsTextRelative ? "-mpic-data-is-text-relative"
+ : "-mno-pic-data-is-text-relative");
+ }
+
// Sort and remove duplicates.
std::sort(Result.begin(), Result.end());
Result.erase(llvm::unique(Result), Result.end());
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp
index d8819c952e5add..688beb077c9561 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5980,8 +5980,13 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
D.Diag(diag::err_drv_argument_only_allowed_with)
<< "-mno-pic-data-is-text-relative"
<< "-fpic/-fpie";
+ if ((Triple.isARM() || Triple.isThumb()) &&
+ Args.hasArg(options::OPT_ffixed_r9))
+ D.Diag(diag::err_drv_argument_not_allowed_with)
+ << "-mno-pic-data-is-text-relative"
+ << "-ffixed-r9";
}
- if (!Triple.isSystemZ())
+ if (!Triple.isSystemZ() && !Triple.isARM() && !Triple.isThumb())
D.Diag(diag::err_drv_unsupported_opt_for_target)
<< (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
: "-mpic-data-is-text-relative")
@@ -6015,8 +6020,10 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
if (IsPIE)
CmdArgs.push_back("-pic-is-pie");
- if (NoPICDataIsTextRelative)
+ if (NoPICDataIsTextRelative && Triple.isSystemZ())
CmdArgs.push_back("-mcmodel=medium");
+ if (LastPICDataRelArg && (Triple.isARM() || Triple.isThumb()))
+ LastPICDataRelArg->render(Args, CmdArgs);
}
if (RelocationModel == llvm::Reloc::ROPI ||
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp b/clang/lib/Frontend/InitPreprocessor.cpp
index 3e22b6e64676cc..e04b5d2231c706 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -1409,6 +1409,9 @@ static void InitializePredefinedMacros(const TargetInfo &TI,
Builder.defineMacro("__PIE__", Twine(PICLevel));
Builder.defineMacro("__pie__", Twine(PICLevel));
}
+ if ((TI.getTriple().isARM() || TI.getTriple().isThumb()) &&
+ !CGOpts.PicDataIsTextRelative)
+ Builder.defineMacro("__ARM_PIC_DATA_STATIC_BASE", "1");
}
// Macros to control C99 numerics and <float.h>
diff --git a/clang/test/CodeGen/arm-pic-data-is-text-relative.c b/clang/test/CodeGen/arm-pic-data-is-text-relative.c
new file mode 100644
index 00000000000000..0fc9a7ceae2468
--- /dev/null
+++ b/clang/test/CodeGen/arm-pic-data-is-text-relative.c
@@ -0,0 +1,90 @@
+// REQUIRES: arm-registered-target
+// RUN: %clang_cc1 -triple armv7-unknown-linux-gnueabihf -mrelocation-model pic -pic-level 1 -mllvm -fast-isel=false -S -o - %s | FileCheck %s --check-prefixes=COMMON,TEXTREL
+// RUN: %clang_cc1 -triple armv7-unknown-linux-gnueabihf -mrelocation-model pic -pic-level 2 -mpic-data-is-text-relative -mllvm -fast-isel=false -S -o - %s | FileCheck %s --check-prefixes=COMMON,TEXTREL
+// RUN: %clang_cc1 -triple armv7-unknown-linux-gnueabihf -mrelocation-model pic -pic-level 2 -mno-pic-data-is-text-relative -mllvm -fast-isel=false -S -o - %s | FileCheck %s --check-prefixes=COMMON,GOT
+// RUN: %clang_cc1 -triple armv7-unknown-linux-gnueabihf -mrelocation-model pic -pic-level 2 -pic-is-pie -mno-pic-data-is-text-relative -mllvm -fast-isel=false -S -o - %s | FileCheck %s --check-prefixes=COMMON,GOT
+// RUN: %clang_cc1 -triple thumbv7-unknown-linux-gnueabihf -mrelocation-model pic -pic-level 2 -mno-pic-data-is-text-relative -mllvm -fast-isel=false -S -o - %s | FileCheck %s --check-prefixes=COMMON,GOT
+// RUN: %clang_cc1 -triple thumbv7-unknown-linux-gnueabihf -mrelocation-model pic -pic-level 2 -mno-pic-data-is-text-relative -O0 -mllvm -fast-isel -mllvm -fast-isel-abort=1 -mllvm -arm-force-fast-isel -S -o - %s | FileCheck %s --check-prefixes=COMMON,GOT
+// RUN: %clang_cc1 -triple armv7-unknown-linux-gnueabihf -mrelocation-model pic -pic-level 2 -mno-pic-data-is-text-relative -O2 -mllvm -global-isel=1 -mllvm -global-isel-abort=1 -S -o - %s | FileCheck %s --check-prefixes=COMMON,GOT
+// RUN: %clang_cc1 -triple armebv7-unknown-linux-gnueabihf -mrelocation-model pic -pic-level 2 -mno-pic-data-is-text-relative -mllvm -fast-isel=false -S -o - %s | FileCheck %s --check-prefixes=COMMON,GOT
+// RUN: %clang_cc1 -triple thumbv6m-unknown-none-eabi -mrelocation-model pic -pic-level 2 -mno-pic-data-is-text-relative -mllvm -fast-isel=false -S -o - %s | FileCheck %s --check-prefixes=COMMON,GOT
+// RUN: %clang -target armv7-unknown-linux-gnueabihf -fPIC -mno-pic-data-is-text-relative -c -o %t.o %s
+// RUN: llvm-readobj --relocations --arch-specific %t.o | FileCheck %s --check-prefix=OBJ
+// RUN: %clang -target armv7-unknown-linux-gnueabihf -fPIE -mno-pic-data-is-text-relative -c -o %t.pie.o %s
+// RUN: llvm-readobj --relocations --arch-specific %t.pie.o | FileCheck %s --check-prefix=OBJ
+
+// TEXTREL: .eabi_attribute 15, 1
+// TEXTREL: .eabi_attribute 14, 0
+
+// GOT: .eabi_attribute 15, 2
+// GOT: .eabi_attribute 14, 1
+
+// OBJ: R_ARM_GOT_BREL local_data
+// OBJ: R_ARM_GOT_BREL local_const
+// OBJ: R_ARM_GOT_BREL external_data
+// OBJ: R_ARM_GOT_BREL hidden_data
+// OBJ: R_ARM_GOT_BREL weak_data
+// OBJ-NOT: R_ARM_GOT_BREL local_function
+// OBJ: TagName: ABI_PCS_R9_use
+// OBJ: Description: Static Base
+// OBJ: TagName: ABI_PCS_RW_data
+// OBJ: Description: SB-relative
+
+static int local_data;
+static const int local_const = 1;
+extern int external_data;
+__attribute__((visibility("hidden"))) extern int hidden_data;
+__attribute__((weak)) int weak_data;
+
+static int local_function(void) { return 0; }
+
+int *local_data_addr(void) { return &local_data; }
+const int *local_const_addr(void) { return &local_const; }
+int *external_data_addr(void) { return &external_data; }
+int *hidden_data_addr(void) { return &hidden_data; }
+int *weak_data_addr(void) { return &weak_data; }
+int (*local_function_addr(void))(void) { return local_function; }
+
+// TEXTREL-LABEL: local_data_addr:
+// TEXTREL: .long local_data-(
+// TEXTREL-NOT: local_data(GOT)
+// TEXTREL-NOT: local_data(GOT_PREL)
+
+// GOT-LABEL: local_data_addr:
+// GOT: {{.*}}r9
+// GOT: .long local_data(GOT)
+// GOT-NOT: local_data(GOT_PREL)
+
+// TEXTREL-LABEL: local_const_addr:
+// TEXTREL: .long local_const-(
+// TEXTREL-NOT: local_const(GOT)
+// TEXTREL-NOT: local_const(GOT_PREL)
+
+// GOT-LABEL: local_const_addr:
+// GOT: {{.*}}r9
+// GOT: .long local_const(GOT)
+// GOT-NOT: local_const(GOT_PREL)
+
+// COMMON-LABEL: external_data_addr:
+// TEXTREL: .long external_data(GOT_PREL)-(
+// GOT: {{.*}}r9
+// GOT: .long external_data(GOT)
+
+// TEXTREL-LABEL: hidden_data_addr:
+// TEXTREL: .long hidden_data-(
+// TEXTREL-NOT: hidden_data(GOT)
+// TEXTREL-NOT: hidden_data(GOT_PREL)
+
+// GOT-LABEL: hidden_data_addr:
+// GOT: {{.*}}r9
+// GOT: .long hidden_data(GOT)
+// GOT-NOT: hidden_data(GOT_PREL)
+
+// COMMON-LABEL: weak_data_addr:
+// TEXTREL: .long weak_data(GOT_PREL)-(
+// GOT: {{.*}}r9
+// GOT: .long weak_data(GOT)
+
+// GOT-LABEL: local_function_addr:
+// GOT: .long local_function-(
+// GOT-NOT: local_function(GOT_PREL)
diff --git a/clang/test/CodeGen/arm-pic-data-static-base-proof.c b/clang/test/CodeGen/arm-pic-data-static-base-proof.c
new file mode 100644
index 00000000000000..feb8c32a48b791
--- /dev/null
+++ b/clang/test/CodeGen/arm-pic-data-static-base-proof.c
@@ -0,0 +1,74 @@
+// REQUIRES: arm-registered-target
+
+// RUN: rm -rf %t && split-file %s %t
+// RUN: %clang --target=armv7-unknown-none-eabi -march=armv7a \
+// RUN: -fPIC -mno-pic-data-is-text-relative -ffreestanding -fno-builtin \
+// RUN: -c %t/main.c -o %t/main.o
+// RUN: %clang --target=armv7-unknown-none-eabi -march=armv7a \
+// RUN: -fPIC -mno-pic-data-is-text-relative -x assembler-with-cpp \
+// RUN: -c %t/start.S -o %t/start.o
+// RUN: llvm-readobj --relocations %t/main.o | FileCheck %s --check-prefix=MAIN-REL
+// RUN: llvm-readobj --relocations %t/start.o | FileCheck %s --check-prefix=STARTUP-REL
+// RUN: ld.lld -T %t/proof.ld %t/start.o %t/main.o -o %t/proof.elf
+// RUN: llvm-readobj --sections --symbols %t/proof.elf | FileCheck %s --check-prefix=LINK
+
+// MAIN-REL-DAG: R_ARM_GOT_BREL global_counter
+// MAIN-REL-DAG: R_ARM_GOT_BREL global_delta
+
+// STARTUP-REL: R_ARM_REL32 __pic_static_base
+
+// LINK: Name: .got
+// LINK: Name: __pic_static_base
+// LINK: Name: global_counter
+
+//--- main.c
+volatile int global_counter = 41;
+volatile const int global_delta = 1;
+
+int main(void) {
+ global_counter += global_delta;
+ return global_counter;
+}
+
+//--- start.S
+#ifndef __ARM_PIC_DATA_STATIC_BASE
+#error "static-base PIC data macro missing"
+#endif
+
+ .syntax unified
+ .arm
+ .globl _start
+ .type _start, %function
+_start:
+ adr r9, .Lpic_static_base
+ ldr r12, [r9]
+ add r9, r9, r12
+ bl main
+.Lhang:
+ b .Lhang
+ .balign 4
+.Lpic_static_base:
+ .word __pic_static_base - .
+ .size _start, . - _start
+
+//--- proof.ld
+ENTRY(_start)
+
+SECTIONS {
+ . = 0x10000;
+
+ .text : {
+ *(.text*)
+ *(.rodata*)
+ }
+
+ .got : {
+ PROVIDE_HIDDEN(__pic_static_base = .);
+ PROVIDE_HIDDEN(_GLOBAL_OFFSET_TABLE_ = .);
+ *(.got)
+ *(.got.*)
+ }
+
+ .data : { *(.data*) }
+ .bss : { *(.bss*) *(COMMON) }
+}
diff --git a/clang/test/CodeGen/arm-pic-data-static-base-r9.c b/clang/test/CodeGen/arm-pic-data-static-base-r9.c
new file mode 100644
index 00000000000000..c31330a3dbd0ed
--- /dev/null
+++ b/clang/test/CodeGen/arm-pic-data-static-base-r9.c
@@ -0,0 +1,26 @@
+// REQUIRES: arm-registered-target
+// RUN: %clang_cc1 -triple armv7-unknown-linux-gnueabihf -O2 \
+// RUN: -mrelocation-model pic -pic-level 2 -mno-pic-data-is-text-relative \
+// RUN: -S -o - %s | FileCheck %s
+
+// r9 is the incoming static-base register under
+// -mno-pic-data-is-text-relative, so ordinary register allocation must not use
+// it even in a register-pressure-heavy function that does not reference data.
+
+int pressure(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7,
+ int a8, int a9, int a10, int a11) {
+ int s0 = a0 + a1;
+ int s1 = a2 + a3;
+ int s2 = a4 + a5;
+ int s3 = a6 + a7;
+ int s4 = a8 + a9;
+ int s5 = a10 + a11;
+ int p0 = s0 * s3;
+ int p1 = s1 * s4;
+ int p2 = s2 * s5;
+ return (p0 ^ p1) + p2 + s0 + s1 + s2 + s3 + s4 + s5;
+}
+
+// CHECK-LABEL: pressure:
+// CHECK-NOT: r9
+// CHECK: .fnend
diff --git a/clang/test/Driver/arm-pic-data-multilib.yaml b/clang/test/Driver/arm-pic-data-multilib.yaml
new file mode 100644
index 00000000000000..0172778d9aa1b3
--- /dev/null
+++ b/clang/test/Driver/arm-pic-data-multilib.yaml
@@ -0,0 +1,20 @@
+# UNSUPPORTED: system-windows
+
+# RUN: %clang --multi-lib-config=%s -no-canonical-prefixes -print-multi-directory \
+# RUN: --target=armv7-unknown-none-eabi -fPIC --sysroot= 2>&1 \
+# RUN: | FileCheck %s --check-prefix=CHECK-TEXTREL
+# CHECK-TEXTREL: pic-textrel
+
+# RUN: %clang --multi-lib-config=%s -no-canonical-prefixes -print-multi-directory \
+# RUN: --target=armv7-unknown-none-eabi -fPIC -mno-pic-data-is-text-relative --sysroot= 2>&1 \
+# RUN: | FileCheck %s --check-prefix=CHECK-GOT
+# CHECK-GOT: pic-got
+
+---
+MultilibVersion: 1.0
+Variants:
+- Dir: pic-textrel
+ Flags: [--target=armv7-unknown-none-eabi, -fPIC, -mpic-data-is-text-relative]
+- Dir: pic-got
+ Flags: [--target=armv7-unknown-none-eabi, -fPIC, -mno-pic-data-is-text-relative]
+...
diff --git a/clang/test/Driver/pic.c b/clang/test/Driver/pic.c
index 5d85c166074797..0fd081fdbf05ac 100644
--- a/clang/test/Driver/pic.c
+++ b/clang/test/Driver/pic.c
@@ -47,8 +47,17 @@
//
// CHECK-NO-PIC-DATA-TEXT-REL: "-mcmodel=medium"
// CHECK-PIC-DATA-TEXT-REL-NOT: "-mcmodel=medium"
-// CHECK-NO-PIC-DATA-TEXT-REL-NON-SYSTEMZ: error: unsupported option '-mno-pic-data-is-text-relative' for target 'arm-arm-none-eabi'
-// CHECK-PIC-DATA-TEXT-REL-NON-SYSTEMZ: error: unsupported option '-mpic-data-is-text-relative' for target 'arm-arm-none-eabi'
+// CHECK-NO-PIC-DATA-TEXT-REL-ARM: "-mno-pic-data-is-text-relative"
+// CHECK-PIC-DATA-TEXT-REL-ARM: "-mpic-data-is-text-relative"
+// CHECK-NO-PIC-DATA-TEXT-REL-THUMB: "-mno-pic-data-is-text-relative"
+// CHECK-PIC-DATA-TEXT-REL-THUMB: "-mpic-data-is-text-relative"
+// CHECK-NO-PIC-DATA-TEXT-REL-NON-SYSTEMZ-ARM: error: unsupported option '-mno-pic-data-is-text-relative' for target 'i386-unknown-unknown'
+// CHECK-PIC-DATA-TEXT-REL-NON-SYSTEMZ-ARM: error: unsupported option '-mpic-data-is-text-relative' for target 'i386-unknown-unknown'
+// CHECK-NO-PIC-DATA-TEXT-REL-NO-PIC: error: invalid argument '-mno-pic-data-is-text-relative' only allowed with '-fpic/-fpie'
+// CHECK-NO-PIC-DATA-TEXT-REL-FIXED-R9: error: invalid argument '-mno-pic-data-is-text-relative' not allowed with '-ffixed-r9'
+// CHECK-NO-PIC-DATA-TEXT-REL-ROPI-RWPI: error: embedded and GOT-based position independence are incompatible
+// CHECK-MULTILIB-NO-PIC-DATA-TEXT-REL-ARM: -mno-pic-data-is-text-relative
+// CHECK-MULTILIB-PIC-DATA-TEXT-REL-ARM: -mpic-data-is-text-relative
//
// RUN: %clang -c %s -target i386-unknown-unknown -### 2>&1 \
// RUN: | FileCheck %s --check-prefix=CHECK-NO-PIC
@@ -319,10 +328,30 @@
// RUN: -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-PIC-DATA-TEXT-REL
// RUN: %clang -fpic -c --target=s390x-linux-gnu -mpic-data-is-text-relative %s -### \
// RUN: 2>&1 | FileCheck %s --check-prefix=CHECK-PIC-DATA-TEXT-REL
-// RUN: not %clang -fpic -c --target=arm-arm-none-eabi -mno-pic-data-is-text-relative %s \
-// RUN: -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-PIC-DATA-TEXT-REL-NON-SYSTEMZ
-// RUN: not %clang -fpic -c --target=arm-arm-none-eabi -mpic-data-is-text-relative %s \
-// RUN: -### 2>&1 | FileCheck %s --check-prefix=CHECK-PIC-DATA-TEXT-REL-NON-SYSTEMZ
+// RUN: %clang -fpic -c --target=arm-arm-none-eabi -mno-pic-data-is-text-relative %s \
+// RUN: -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-PIC-DATA-TEXT-REL-ARM
+// RUN: %clang -fpic -c --target=arm-arm-none-eabi -mpic-data-is-text-relative %s \
+// RUN: -### 2>&1 | FileCheck %s --check-prefix=CHECK-PIC-DATA-TEXT-REL-ARM
+// RUN: %clang -fpic -mthumb -c --target=arm-none-eabi -mno-pic-data-is-text-relative %s \
+// RUN: -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-PIC-DATA-TEXT-REL-THUMB
+// RUN: %clang -fpic -mthumb -c --target=arm-none-eabi -mpic-data-is-text-relative %s \
+// RUN: -### 2>&1 | FileCheck %s --check-prefix=CHECK-PIC-DATA-TEXT-REL-THUMB
+// RUN: not %clang -c --target=arm-arm-none-eabi -mno-pic-data-is-text-relative %s \
+// RUN: -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-PIC-DATA-TEXT-REL-NO-PIC
+// RUN: not %clang -fpic -c --target=arm-arm-none-eabi -mno-pic-data-is-text-relative -ffixed-r9 %s \
+// RUN: -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-PIC-DATA-TEXT-REL-FIXED-R9
+// RUN: not %clang -fpic -fropi -c --target=arm-arm-none-eabi -mno-pic-data-is-text-relative %s \
+// RUN: -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-PIC-DATA-TEXT-REL-ROPI-RWPI
+// RUN: not %clang -fpic -frwpi -c --target=arm-arm-none-eabi -mno-pic-data-is-text-relative %s \
+// RUN: -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-PIC-DATA-TEXT-REL-ROPI-RWPI
+// RUN: %clang -print-multi-flags-experimental -S -x c -v - '-###' --target=armv7-unknown-none-eabi -fPIC -mno-pic-data-is-text-relative 2>&1 \
+// RUN: | FileCheck %s --check-prefix=CHECK-MULTILIB-NO-PIC-DATA-TEXT-REL-ARM
+// RUN: %clang -print-multi-flags-experimental -S -x c -v - '-###' --target=armv7-unknown-none-eabi -fPIC 2>&1 \
+// RUN: | FileCheck %s --check-prefix=CHECK-MULTILIB-PIC-DATA-TEXT-REL-ARM
+// RUN: not %clang -fpic -c --target=i386-unknown-unknown -mno-pic-data-is-text-relative %s \
+// RUN: -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-PIC-DATA-TEXT-REL-NON-SYSTEMZ-ARM
+// RUN: not %clang -fpic -c --target=i386-unknown-unknown -mpic-data-is-text-relative %s \
+// RUN: -### 2>&1 | FileCheck %s --check-prefix=CHECK-PIC-DATA-TEXT-REL-NON-SYSTEMZ-ARM
// On Haiku, PIC is enabled by default, and PIE is disabled by default.
// RUN: %clang -c %s --target=x86_64-unknown-haiku -### 2>&1 \
diff --git a/clang/test/Preprocessor/arm-pic-predefines.c b/clang/test/Preprocessor/arm-pic-predefines.c
index 9082d794851128..cc76cd1dc518e5 100644
--- a/clang/test/Preprocessor/arm-pic-predefines.c
+++ b/clang/test/Preprocessor/arm-pic-predefines.c
@@ -1,9 +1,12 @@
// REQUIRES: arm-registered-target
-// RUN: %clang -target armv8--none-eabi -x c -E -dM %s -o - | FileCheck %s --check-prefix=NO-ROPI --check-prefix=NO-RWPI
-// RUN: %clang -target armv8--none-eabi -x c -E -dM %s -o - -fropi | FileCheck %s --check-prefix=ROPI --check-prefix=NO-RWPI
-// RUN: %clang -target armv8--none-eabi -x c -E -dM %s -o - -frwpi | FileCheck %s --check-prefix=NO-ROPI --check-prefix=RWPI
-// RUN: %clang -target armv8--none-eabi -x c -E -dM %s -o - -fropi -frwpi | FileCheck %s --check-prefix=ROPI --check-prefix=RWPI
+// RUN: %clang -target armv8--none-eabi -x c -E -dM %s -o - | FileCheck %s --check-prefix=NO-ROPI --check-prefix=NO-RWPI --check-prefix=NO-STATIC-BASE
+// RUN: %clang -target armv8--none-eabi -x c -E -dM %s -o - -fropi | FileCheck %s --check-prefix=ROPI --check-prefix=NO-RWPI --check-prefix=NO-STATIC-BASE
+// RUN: %clang -target armv8--none-eabi -x c -E -dM %s -o - -frwpi | FileCheck %s --check-prefix=NO-ROPI --check-prefix=RWPI --check-prefix=NO-STATIC-BASE
+// RUN: %clang -target armv8--none-eabi -x c -E -dM %s -o - -fropi -frwpi | FileCheck %s --check-prefix=ROPI --check-prefix=RWPI --check-prefix=NO-STATIC-BASE
+// RUN: %clang -target armv8--none-eabi -x c -E -dM %s -o - -fPIC | FileCheck %s --check-prefix=NO-STATIC-BASE
+// RUN: %clang -target armv8--none-eabi -x c -E -dM %s -o - -fPIC -mno-pic-data-is-text-relative | FileCheck %s --check-prefix=STATIC-BASE
+// RUN: %clang -target thumbv8--none-eabi -x c -E -dM %s -o - -fPIE -mno-pic-data-is-text-relative | FileCheck %s --check-prefix=STATIC-BASE
// Pre-defined macros for position-independence modes
@@ -12,3 +15,6 @@
// NO-RWPI-NOT: #define __APCS_RWPI
// RWPI: #define __ARM_RWPI
+
+// NO-STATIC-BASE-NOT: #define __ARM_PIC_DATA_STATIC_BASE
+// STATIC-BASE: #define __ARM_PIC_DATA_STATIC_BASE 1
diff --git a/llvm/docs/ARMNoPICDataIsTextRelative.md b/llvm/docs/ARMNoPICDataIsTextRelative.md
new file mode 100644
index 00000000000000..9c4a4df791ff9a
--- /dev/null
+++ b/llvm/docs/ARMNoPICDataIsTextRelative.md
@@ -0,0 +1,148 @@
+# ARM `-mno-pic-data-is-text-relative`
+
+This document records the ARM semantics expected from Clang and LLVM for
+`-mno-pic-data-is-text-relative`. The contract is based on GCC's ARM option
+model, with the initial LLVM implementation deliberately scoped to the fixed
+EABI static-base form.
+
+## Problem Model
+
+Normal ARM PIC code may assume that the displacement between the text segment
+and the data segment is fixed at static link time. With that assumption, the
+compiler can address eligible local data with PC-relative relocations. This is
+the default GCC behavior for non-VxWorks RTP ARM targets.
+
+`-mno-pic-data-is-text-relative` removes that assumption. Code may remain fixed
+while the writable data segment is independently relocated. Data references
+that cannot be proven text-relative must therefore be addressed through a GOT
+base instead of through the text segment.
+
+The option is meaningful only for PIC or PIE code generation. Clang diagnoses
+`-mno-pic-data-is-text-relative` without `-fpic`, `-fPIC`, `-fpie`, or `-fPIE`.
+
+## GCC ARM Semantics
+
+GCC exposes three related ARM options:
+
+* `-mpic-data-is-text-relative` and `-mno-pic-data-is-text-relative` select
+ whether known data may be addressed relative to text.
+* `-msingle-pic-base` tells GCC that the PIC base register is read-only and is
+ initialized by the runtime before execution.
+* `-mpic-register=<reg>` chooses the PIC base register.
+
+For GCC ARM EABI targets, disabling text-relative data also enables
+`-msingle-pic-base` by default, unless the user explicitly selected
+`-mno-single-pic-base`. In that default single-base mode, GCC uses `r9` as the
+PIC base register. A runtime or loader must initialize `r9` before executing the
+generated code.
+
+GCC still allows an explicit `-mno-single-pic-base` override. In that mode it
+does not rely on a pre-initialized `r9`; it computes the GOT base in generated
+code. GCC also allows `-mpic-register=<reg>` for explicit PIC register
+selection, subject to target validity checks.
+
+GCC's address selection has these important properties:
+
+* Local non-weak data symbols and labels may use text-relative addressing when
+ `-mpic-data-is-text-relative` is active.
+* External data, interposable data, and weak data use GOT addressing.
+* With `-mno-pic-data-is-text-relative`, data references use GOT addressing.
+* Non-FDPIC function references are not data references and may remain
+ text-relative.
+* Text constant-pool entries follow the same distinction: GCC emits GOT-style
+ relocations when text-relative data is disabled, and GOTOFF-style relocations
+ for eligible local references when it is enabled.
+
+## LLVM Scope
+
+The first LLVM implementation follows GCC's default EABI behavior for
+`-mno-pic-data-is-text-relative`: data is addressed through the GOT using `r9`
+as the static base register. This matches the GCC mode that is selected by
+default when text-relative data is disabled on ARM EABI targets.
+
+The LLVM option surface is intentionally narrower than GCC's for this branch:
+
+* Clang accepts `-mpic-data-is-text-relative` and
+ `-mno-pic-data-is-text-relative` for ARM, Thumb, and SystemZ.
+* LLVM does not currently expose ARM `-msingle-pic-base`,
+ `-mno-single-pic-base`, or `-mpic-register=<reg>`.
+* Because custom PIC registers are not exposed, the static base register is
+ fixed to `r9`.
+
+This means LLVM does not yet duplicate GCC's explicit `-mno-single-pic-base`
+mode, where the GOT base is recomputed instead of read from a fixed runtime
+register. It also does not yet duplicate GCC's user-selected PIC register mode.
+
+## Code Generation Contract
+
+For ARM and Thumb PIC or PIE code:
+
+* The default is `-mpic-data-is-text-relative`.
+* Under `-mpic-data-is-text-relative`, local non-weak data may use
+ text-relative addressing.
+* Under `-mno-pic-data-is-text-relative`, data addresses must be materialized
+ through GOT relocations and the static base register.
+* External, interposable, and weak data must use GOT addressing in both modes.
+* Non-FDPIC local function addresses may stay text-relative in both modes.
+* `r9` must be reserved from general register allocation and treated as an
+ incoming ABI register whenever it is used as the static base.
+* The generated object must describe `r9` as the static base register through
+ the ARM build attribute `Tag_ABI_PCS_R9_use = R9IsSB` when the option causes
+ `r9` to be used as the static base.
+
+The runtime contract is the same as GCC's default single-base EABI contract:
+when `-mno-pic-data-is-text-relative` is used, startup or loader code must set
+`r9` to the GOT/static-base value expected by the linked image before entering
+compiled code.
+
+## Implemented Interactions
+
+The implemented driver and code-generation behavior covers these cases:
+
+* `-fpic`, `-fPIC`, `-fpie`, and `-fPIE` driver forwarding.
+* Multilib flag normalization for ARM PIC data mode, so runtime variants can
+ distinguish text-relative PIC data from static-base GOT data.
+* Rejection or diagnosis when the option is used without PIC or PIE.
+* Rejection when `-mno-pic-data-is-text-relative` is combined with
+ `-ffixed-r9`, because the GCC-compatible default mode requires `r9` as the
+ static base register.
+* Existing ROPI/RWPI driver validation prevents combinations with PIC or PIE,
+ so `-mno-pic-data-is-text-relative` cannot be combined with `-fropi`,
+ `-frwpi`, or `-fropi -frwpi`.
+* ARM and Thumb code generation, including Thumb-1.
+* SelectionDAG, FastISel, and GlobalISel lowering paths.
+* Local data, hidden data, external data, weak data, and local function
+ addresses.
+* Object attributes for `Tag_ABI_PCS_R9_use`.
+* The Clang predefined macro `__ARM_PIC_DATA_STATIC_BASE=1` when ARM or Thumb
+ PIC or PIE code uses the fixed-`r9` static-base data mode. GCC does not define
+ an equivalent macro for `-mno-pic-data-is-text-relative`; this macro is added
+ so C or assembly startup code can conditionally initialize the static base.
+
+## Interactions To Review
+
+Review and test coverage should explicitly cover these areas before upstream
+submission:
+
+* Targets that reserve `r9` for platform reasons other than `-ffixed-r9`.
+* Assembly or runtime code that accesses global data without compiler-generated
+ address materialization.
+
+The initial runtime assembly audit found compiler-rt examples that need
+conditional static-base handling when those runtimes are built for this mode:
+
+* `compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors_vfork_arm.inc.S`
+ uses `__ARM_PIC_DATA_STATIC_BASE` to select a GOT-offset load of the
+ `real_vfork` data symbol through `r9`.
+* `compiler-rt/lib/xray/xray_trampoline_arm.S` loads the
+ `__xray::XRayPatchedFunction` data symbol through an `r9`-relative GOT entry
+ when `__ARM_PIC_DATA_STATIC_BASE` is defined.
+* `libunwind/src/UnwindRegistersSave.S` and
+ `libunwind/src/UnwindRegistersRestore.S` save and restore `r9` as part of ARM
+ register state, but do not by themselves access global data through a
+ hand-written address sequence in the audited ARM paths.
+
+The explicit GCC options `-m[no-]single-pic-base` and `-mpic-register=<reg>`
+are design decisions rather than accidental omissions. If LLVM needs complete
+GCC command-line compatibility, those options require separate implementation
+and tests.
diff --git a/llvm/docs/UserGuides.md b/llvm/docs/UserGuides.md
index f7e971915b669b..ee5ad7961f7532 100644
--- a/llvm/docs/UserGuides.md
+++ b/llvm/docs/UserGuides.md
@@ -57,6 +57,7 @@ AddingConstrainedIntrinsics
HowToBuildWindowsItaniumPrograms
HowToCrossCompileBuiltinsOnArm
BigEndianNEON
+ARMNoPICDataIsTextRelative
AArch64SME
CompileCudaWithLLVM
NVPTXUsage
diff --git a/llvm/include/llvm/Target/TargetOptions.h b/llvm/include/llvm/Target/TargetOptions.h
index da83dd76835d6f..c4818e1e892608 100644
--- a/llvm/include/llvm/Target/TargetOptions.h
+++ b/llvm/include/llvm/Target/TargetOptions.h
@@ -106,13 +106,14 @@ class TargetOptions {
UniqueBasicBlockSectionNames(false), SeparateNamedSections(false),
TrapUnreachable(false), NoTrapAfterNoreturn(false), TLSSize(0),
EmulatedTLS(false), EnableTLSDESC(false), EnableIPRA(false),
- EmitStackSizeSection(false), EnableMachineOutliner(false),
- EnableStaticDataPartitioning(false), EnableDefaultMachineVerifier(true),
- EmitAddrsig(false), BBAddrMap(false), EmitCallGraphSection(false),
- EmitCallSiteInfo(false), EnableDebugEntryValues(false),
- ValueTrackingVariableLocations(false), ForceDwarfFrameSection(false),
- XRayFunctionIndex(true), DebugStrictDwarf(false), JMCInstrument(false),
- EnableCFIFixup(false), MisExpect(false), XCOFFReadOnlyPointers(false),
+ PicDataIsTextRelative(true), EmitStackSizeSection(false),
+ EnableMachineOutliner(false), EnableStaticDataPartitioning(false),
+ EnableDefaultMachineVerifier(true), EmitAddrsig(false),
+ BBAddrMap(false), EmitCallGraphSection(false), EmitCallSiteInfo(false),
+ EnableDebugEntryValues(false), ValueTrackingVariableLocations(false),
+ ForceDwarfFrameSection(false), XRayFunctionIndex(true),
+ DebugStrictDwarf(false), JMCInstrument(false), EnableCFIFixup(false),
+ MisExpect(false), XCOFFReadOnlyPointers(false),
VerifyArgABICompliance(false) {}
/// NoZerosInBSS - By default some codegens place zero-initialized data to
@@ -195,6 +196,10 @@ class TargetOptions {
/// This flag enables InterProcedural Register Allocation (IPRA).
unsigned EnableIPRA : 1;
+ /// Assume that PIC data segments are text-relative when selecting
+ /// target-specific data addressing forms.
+ unsigned PicDataIsTextRelative : 1;
+
/// Emit section containing metadata on function stack sizes.
unsigned EmitStackSizeSection : 1;
diff --git a/llvm/lib/Target/ARM/ARMAsmPrinter.cpp b/llvm/lib/Target/ARM/ARMAsmPrinter.cpp
index d118a21d560015..c97dd9d25f3962 100644
--- a/llvm/lib/Target/ARM/ARMAsmPrinter.cpp
+++ b/llvm/lib/Target/ARM/ARMAsmPrinter.cpp
@@ -716,7 +716,10 @@ void ARMAsmPrinter::emitAttributes() {
ATS.emitTargetAttributes(STI);
// RW data addressing.
- if (isPositionIndependent()) {
+ if (STI.isPicDataStaticBase()) {
+ ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
+ ARMBuildAttrs::AddressRWSBRel);
+ } else if (isPositionIndependent()) {
ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
ARMBuildAttrs::AddressRWPCRel);
} else if (STI.isRWPI()) {
@@ -878,7 +881,7 @@ void ARMAsmPrinter::emitAttributes() {
}
// We currently do not support using R9 as the TLS pointer.
- if (STI.isRWPI())
+ if (STI.isRWPI() || STI.isPicDataStaticBase())
ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
ARMBuildAttrs::R9IsSB);
else if (STI.isR9Reserved())
@@ -913,6 +916,8 @@ static uint8_t getModifierSpecifier(ARMCP::ARMCPModifier Modifier) {
return ARM::S_None;
case ARMCP::TLSGD:
return ARM::S_TLSGD;
+ case ARMCP::GOT:
+ return ARM::S_GOT;
case ARMCP::TPOFF:
return ARM::S_TPOFF;
case ARMCP::GOTTPOFF:
diff --git a/llvm/lib/Target/ARM/ARMConstantPoolValue.cpp b/llvm/lib/Target/ARM/ARMConstantPoolValue.cpp
index e688a53a1722c5..a3e93428ffb6db 100644
--- a/llvm/lib/Target/ARM/ARMConstantPoolValue.cpp
+++ b/llvm/lib/Target/ARM/ARMConstantPoolValue.cpp
@@ -58,6 +58,8 @@ StringRef ARMConstantPoolValue::getModifierText() const {
return "none";
case ARMCP::TLSGD:
return "tlsgd";
+ case ARMCP::GOT:
+ return "GOT";
case ARMCP::GOT_PREL:
return "GOT_PREL";
case ARMCP::GOTTPOFF:
diff --git a/llvm/lib/Target/ARM/ARMConstantPoolValue.h b/llvm/lib/Target/ARM/ARMConstantPoolValue.h
index d6b34d68d472ad..ac18fef4fe976e 100644
--- a/llvm/lib/Target/ARM/ARMConstantPoolValue.h
+++ b/llvm/lib/Target/ARM/ARMConstantPoolValue.h
@@ -46,6 +46,7 @@ namespace ARMCP {
enum ARMCPModifier {
no_modifier, /// None
TLSGD, /// Thread Local Storage (General Dynamic Mode)
+ GOT, /// Global Offset Table
GOT_PREL, /// Global Offset Table, PC Relative
GOTTPOFF, /// Global Offset Table, Thread Pointer Offset
TPOFF, /// Thread Pointer Offset
diff --git a/llvm/lib/Target/ARM/ARMFastISel.cpp b/llvm/lib/Target/ARM/ARMFastISel.cpp
index a577f52a3343a6..e01bb5e61b5a41 100644
--- a/llvm/lib/Target/ARM/ARMFastISel.cpp
+++ b/llvm/lib/Target/ARM/ARMFastISel.cpp
@@ -3043,7 +3043,46 @@ bool ARMFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
}
Register ARMFastISel::ARMLowerPICELF(const GlobalValue *GV, MVT VT) {
- bool UseGOT_PREL = !GV->isDSOLocal();
+ if (Subtarget->useStaticBaseForPicData(GV)) {
+ LLVMContext *Context = &MF->getFunction().getContext();
+ ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(GV, ARMCP::GOT);
+
+ Align ConstAlign =
+ MF->getDataLayout().getPrefTypeAlign(PointerType::get(*Context, 0));
+ unsigned Idx = MF->getConstantPool()->getConstantPoolIndex(CPV, ConstAlign);
+ MachineMemOperand *CPMMO =
+ MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
+ MachineMemOperand::MOLoad, 4, Align(4));
+
+ Register OffsetReg =
+ MF->getRegInfo().createVirtualRegister(&ARM::rGPRRegClass);
+ unsigned Opc = isThumb2 ? ARM::t2LDRpci : ARM::LDRcp;
+ MachineInstrBuilder MIB =
+ BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc), OffsetReg)
+ .addConstantPoolIndex(Idx)
+ .addMemOperand(CPMMO);
+ if (Opc == ARM::LDRcp)
+ MIB.addImm(0);
+ MIB.add(predOps(ARMCC::AL));
+
+ Register SBReg = MF->addLiveIn(ARM::R9, &ARM::GPRRegClass);
+ Register GOTEntry = createResultReg(&ARM::GPRRegClass);
+ Opc = isThumb2 ? ARM::t2ADDrr : ARM::ADDrr;
+ AddOptionalDefs(
+ BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc), GOTEntry)
+ .addReg(SBReg)
+ .addReg(OffsetReg));
+
+ Register DestReg = createResultReg(TLI.getRegClassFor(VT));
+ Opc = isThumb2 ? ARM::t2LDRi12 : ARM::LDRi12;
+ MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc), DestReg)
+ .addReg(GOTEntry)
+ .addImm(0);
+ AddOptionalDefs(MIB);
+ return DestReg;
+ }
+
+ bool UseGOT_PREL = Subtarget->isGVInGOT(GV);
LLVMContext *Context = &MF->getFunction().getContext();
unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
diff --git a/llvm/lib/Target/ARM/ARMISelLowering.cpp b/llvm/lib/Target/ARM/ARMISelLowering.cpp
index f01772343a01e7..f7ce05419cf4da 100644
--- a/llvm/lib/Target/ARM/ARMISelLowering.cpp
+++ b/llvm/lib/Target/ARM/ARMISelLowering.cpp
@@ -3706,10 +3706,27 @@ SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
return V;
if (isPositionIndependent()) {
- SDValue G = DAG.getTargetGlobalAddress(
- GV, dl, PtrVT, 0, GV->isDSOLocal() ? 0 : ARMII::MO_GOT);
+ if (Subtarget->useStaticBaseForPicData(GV)) {
+ MachineFunction &MF = DAG.getMachineFunction();
+ ARMConstantPoolValue *CPV =
+ ARMConstantPoolConstant::Create(GV, ARMCP::GOT);
+ SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
+ CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
+ SDValue GOTOffset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
+ MachinePointerInfo::getConstantPool(MF));
+ Register SBReg =
+ MF.addLiveIn(ARM::R9, getRegClassFor(PtrVT.getSimpleVT()));
+ SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, SBReg, PtrVT);
+ SDValue GOTEntry = DAG.getNode(ISD::ADD, dl, PtrVT, SB, GOTOffset);
+ return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), GOTEntry,
+ MachinePointerInfo::getGOT(MF));
+ }
+
+ bool UseGOT = Subtarget->isGVInGOT(GV);
+ SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
+ UseGOT ? ARMII::MO_GOT : 0);
SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
- if (!GV->isDSOLocal())
+ if (UseGOT)
Result =
DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
MachinePointerInfo::getGOT(DAG.getMachineFunction()));
diff --git a/llvm/lib/Target/ARM/ARMInstructionSelector.cpp b/llvm/lib/Target/ARM/ARMInstructionSelector.cpp
index ec5d34407e71bc..cfcb3c3aaf9721 100644
--- a/llvm/lib/Target/ARM/ARMInstructionSelector.cpp
+++ b/llvm/lib/Target/ARM/ARMInstructionSelector.cpp
@@ -626,20 +626,19 @@ bool ARMInstructionSelector::selectGlobal(MachineInstrBuilder &MIB,
LLT PtrTy = MRI.getType(MIB->getOperand(0).getReg());
const Align Alignment(4);
- auto addOpsForConstantPoolLoad = [&MF, Alignment, PtrTy](
- MachineInstrBuilder &MIB,
- const GlobalValue *GV, bool IsSBREL) {
+ auto addOpsForConstantPoolLoad = [&MF, Alignment,
+ PtrTy](MachineInstrBuilder &MIB,
+ const GlobalValue *GV,
+ ARMCP::ARMCPModifier Modifier) {
assert((MIB->getOpcode() == ARM::LDRi12 ||
MIB->getOpcode() == ARM::t2LDRpci) &&
"Unsupported instruction");
auto ConstPool = MF.getConstantPool();
auto CPIndex =
- // For SB relative entries we need a target-specific constant pool.
- // Otherwise, just use a regular constant pool entry.
- IsSBREL
- ? ConstPool->getConstantPoolIndex(
- ARMConstantPoolConstant::Create(GV, ARMCP::SBREL), Alignment)
- : ConstPool->getConstantPoolIndex(GV, Alignment);
+ Modifier == ARMCP::no_modifier
+ ? ConstPool->getConstantPoolIndex(GV, Alignment)
+ : ConstPool->getConstantPoolIndex(
+ ARMConstantPoolConstant::Create(GV, Modifier), Alignment);
MIB.addConstantPoolIndex(CPIndex, /*Offset*/ 0, /*TargetFlags*/ 0)
.addMemOperand(MF.getMachineMemOperand(
MachinePointerInfo::getConstantPool(MF), MachineMemOperand::MOLoad,
@@ -657,7 +656,34 @@ bool ARMInstructionSelector::selectGlobal(MachineInstrBuilder &MIB,
};
if (TM.isPositionIndependent()) {
- bool Indirect = STI.isGVIndirectSymbol(GV);
+ if (STI.useStaticBaseForPicData(GV)) {
+ auto Offset = MRI.createVirtualRegister(&ARM::GPRRegClass);
+ MachineInstrBuilder OffsetMIB =
+ BuildMI(MBB, *MIB, MIB->getDebugLoc(), TII.get(Opcodes.ConstPoolLoad),
+ Offset);
+ addOpsForConstantPoolLoad(OffsetMIB, GV, ARMCP::GOT);
+ constrainSelectedInstRegOperands(*OffsetMIB, TII, TRI, RBI);
+
+ MRI.addLiveIn(ARM::R9);
+ MBB.addLiveIn(ARM::R9);
+ auto GOTEntry = MRI.createVirtualRegister(&ARM::GPRRegClass);
+ auto AddMIB = BuildMI(MBB, *MIB, MIB->getDebugLoc(),
+ TII.get(Opcodes.ADDrr), GOTEntry)
+ .addReg(ARM::R9)
+ .addReg(Offset)
+ .add(predOps(ARMCC::AL))
+ .add(condCodeOp());
+ constrainSelectedInstRegOperands(*AddMIB, TII, TRI, RBI);
+
+ MIB->setDesc(TII.get(Opcodes.LOAD32));
+ MIB->removeOperand(1);
+ MIB.addReg(GOTEntry).addImm(0).add(predOps(ARMCC::AL));
+ addGOTMemOperand(MIB);
+ constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
+ return true;
+ }
+
+ bool Indirect = STI.isGVIndirectSymbol(GV) || STI.isGVInGOT(GV);
// For ARM mode, we have different pseudoinstructions for direct accesses
// and indirect accesses, and the ones for indirect accesses include the
@@ -727,7 +753,7 @@ bool ARMInstructionSelector::selectGlobal(MachineInstrBuilder &MIB,
// Load the offset from the constant pool.
OffsetMIB = BuildMI(MBB, *MIB, MIB->getDebugLoc(),
TII.get(Opcodes.ConstPoolLoad), Offset);
- addOpsForConstantPoolLoad(OffsetMIB, GV, /*IsSBREL*/ true);
+ addOpsForConstantPoolLoad(OffsetMIB, GV, ARMCP::SBREL);
}
constrainSelectedInstRegOperands(*OffsetMIB, TII, TRI, RBI);
@@ -750,7 +776,7 @@ bool ARMInstructionSelector::selectGlobal(MachineInstrBuilder &MIB,
// Load the global's address from the constant pool.
MIB->setDesc(TII.get(Opcodes.ConstPoolLoad));
MIB->removeOperand(1);
- addOpsForConstantPoolLoad(MIB, GV, /*IsSBREL*/ false);
+ addOpsForConstantPoolLoad(MIB, GV, ARMCP::no_modifier);
}
} else if (STI.isTargetMachO()) {
if (UseMovt)
diff --git a/llvm/lib/Target/ARM/ARMSubtarget.cpp b/llvm/lib/Target/ARM/ARMSubtarget.cpp
index 88a51ebe0533aa..25ea3603926c57 100644
--- a/llvm/lib/Target/ARM/ARMSubtarget.cpp
+++ b/llvm/lib/Target/ARM/ARMSubtarget.cpp
@@ -375,7 +375,7 @@ void ARMSubtarget::initSubtargetFeatures(StringRef CPU, StringRef FS) {
HasNEONForFP = true;
const ARM::ArchKind Arch = ARM::parseArch(TargetTriple.getArchName());
- if (isRWPI() ||
+ if (isRWPI() || isPicDataStaticBase() ||
(isTargetIOS() &&
(Arch == ARM::ArchKind::ARMV6K || Arch == ARM::ArchKind::ARMV6) &&
TargetTriple.isOSVersionLT(3, 0)))
@@ -471,12 +471,25 @@ bool ARMSubtarget::isRWPI() const {
TM.getRelocationModel() == Reloc::ROPI_RWPI;
}
+bool ARMSubtarget::isPicDataStaticBase() const {
+ return isTargetELF() && TM.isPositionIndependent() &&
+ !TM.Options.PicDataIsTextRelative;
+}
+
+bool ARMSubtarget::useStaticBaseForPicData(const GlobalValue *GV) const {
+ return isPicDataStaticBase() && !GV->getValueType()->isFunctionTy();
+}
+
bool ARMSubtarget::isGVIndirectSymbol(const GlobalValue *GV) const {
return TM.isGVIndirectSymbol(GV);
}
bool ARMSubtarget::isGVInGOT(const GlobalValue *GV) const {
- return isTargetELF() && TM.isPositionIndependent() && !GV->isDSOLocal();
+ if (!isTargetELF() || !TM.isPositionIndependent())
+ return false;
+ if (!GV->isDSOLocal())
+ return true;
+ return useStaticBaseForPicData(GV);
}
bool ARMSubtarget::enableMachineScheduler() const {
diff --git a/llvm/lib/Target/ARM/ARMSubtarget.h b/llvm/lib/Target/ARM/ARMSubtarget.h
index e5284de5f8ce79..59be0866ee9444 100644
--- a/llvm/lib/Target/ARM/ARMSubtarget.h
+++ b/llvm/lib/Target/ARM/ARMSubtarget.h
@@ -396,6 +396,8 @@ class ARMSubtarget : public ARMGenSubtargetInfo {
bool isROPI() const;
bool isRWPI() const;
+ bool isPicDataStaticBase() const;
+ bool useStaticBaseForPicData(const GlobalValue *GV) const;
bool useMachineScheduler() const { return UseMISched; }
bool useMachinePipeliner() const { return UseMIPipeliner; }
>From e4db957c367beea62b77503a5bbfb02f0f757dd6 Mon Sep 17 00:00:00 2001
From: Mark Murray <Mark.Murray at arm.com>
Date: Thu, 5 Nov 2026 13:01:20 +0000
Subject: [PATCH 2/3] [compiler-rt][ARM] Use static-base GOT loads in assembly
When __ARM_PIC_DATA_STATIC_BASE is defined, ARM runtime assembly must not use hand-written PC-relative sequences to load data symbols. Those sequences assume data remains text-relative, which is not true for -mno-pic-data-is-text-relative.
Teach the sanitizer vfork interceptor and XRay ARM trampolines to load their global function-pointer data through r9-relative GOT entries in static-base mode, while preserving the existing PC-relative sequences otherwise. Add a builtins test that assembles the real runtime assembly files in both modes and checks the static-base source path without relying on LLVM object tools being present in standalone builtins test environments.
---
...itizer_common_interceptors_vfork_arm.inc.S | 9 ++++++
compiler-rt/lib/xray/xray_trampoline_arm.S | 24 +++++++++++++++
.../arm-static-base-runtime-asm.test | 29 +++++++++++++++++++
3 files changed, 62 insertions(+)
create mode 100644 compiler-rt/test/builtins/TestCases/arm-static-base-runtime-asm.test
diff --git a/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors_vfork_arm.inc.S b/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors_vfork_arm.inc.S
index 87bb483805691e..06dcc9c35f3d9a 100644
--- a/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors_vfork_arm.inc.S
+++ b/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors_vfork_arm.inc.S
@@ -17,8 +17,13 @@ ASM_WRAPPER_NAME(vfork):
// Call real vfork. This may return twice. User code that runs between the first and the second return
// may clobber the stack frame of the interceptor; that's why it does not have a frame.
ldr r0, .LCPI0_0
+#if defined(__ARM_PIC_DATA_STATIC_BASE)
+ ldr r0, [r9, r0]
+ ldr r0, [r0]
+#else
.LPC0_0:
ldr r0, [pc, r0]
+#endif
mov lr, pc
bx r0
@@ -39,7 +44,11 @@ ASM_WRAPPER_NAME(vfork):
mov pc, lr
.LCPI0_0:
+#if defined(__ARM_PIC_DATA_STATIC_BASE)
+ .long _ZN14__interception10real_vforkE(GOT)
+#else
.long _ZN14__interception10real_vforkE - (.LPC0_0+8)
+#endif
ASM_SIZE(vfork)
diff --git a/compiler-rt/lib/xray/xray_trampoline_arm.S b/compiler-rt/lib/xray/xray_trampoline_arm.S
index 3ffc1e44376108..937fc89a6136b0 100644
--- a/compiler-rt/lib/xray/xray_trampoline_arm.S
+++ b/compiler-rt/lib/xray/xray_trampoline_arm.S
@@ -21,9 +21,15 @@ __xray_FunctionEntry:
PUSH {r1-r3,lr}
@ Save floating-point parameters of the instrumented function
VPUSH {d0-d7}
+#ifdef __ARM_PIC_DATA_STATIC_BASE
+ LDR r1, .LXRayPatchedFunctionGOT
+ LDR r1, [r9, r1]
+ LDR r2, [r1]
+#else
MOVW r1, #:lower16:_ZN6__xray19XRayPatchedFunctionE - (. + 16)
MOVT r1, #:upper16:_ZN6__xray19XRayPatchedFunctionE - (. + 12)
LDR r2, [pc, r1]
+#endif
@ Handler address is nullptr if handler is not set
CMP r2, #0
BEQ FunctionEntry_restore
@@ -53,9 +59,15 @@ __xray_FunctionExit:
@ Save the floating-point return value of the instrumented function
VPUSH {d0}
@ Load the handler address
+#ifdef __ARM_PIC_DATA_STATIC_BASE
+ LDR r1, .LXRayPatchedFunctionGOT
+ LDR r1, [r9, r1]
+ LDR r2, [r1]
+#else
MOVW r1, #:lower16:_ZN6__xray19XRayPatchedFunctionE - (. + 16)
MOVT r1, #:upper16:_ZN6__xray19XRayPatchedFunctionE - (. + 12)
LDR r2, [pc, r1]
+#endif
@ Handler address is nullptr if handler is not set
CMP r2, #0
BEQ FunctionExit_restore
@@ -84,9 +96,15 @@ __xray_FunctionTailExit:
PUSH {r1-r3,lr}
@ Save floating-point parameters of the instrumented function
VPUSH {d0-d7}
+#ifdef __ARM_PIC_DATA_STATIC_BASE
+ LDR r1, .LXRayPatchedFunctionGOT
+ LDR r1, [r9, r1]
+ LDR r2, [r1]
+#else
MOVW r1, #:lower16:_ZN6__xray19XRayPatchedFunctionE - (. + 16)
MOVT r1, #:upper16:_ZN6__xray19XRayPatchedFunctionE - (. + 12)
LDR r2, [pc, r1]
+#endif
@ Handler address is nullptr if handler is not set
CMP r2, #0
BEQ FunctionTailExit_restore
@@ -102,4 +120,10 @@ FunctionTailExit_restore:
VPOP {d0-d7}
POP {r1-r3,pc}
+#ifdef __ARM_PIC_DATA_STATIC_BASE
+ .p2align 2
+.LXRayPatchedFunctionGOT:
+ .long _ZN6__xray19XRayPatchedFunctionE(GOT)
+#endif
+
NO_EXEC_STACK_DIRECTIVE
diff --git a/compiler-rt/test/builtins/TestCases/arm-static-base-runtime-asm.test b/compiler-rt/test/builtins/TestCases/arm-static-base-runtime-asm.test
new file mode 100644
index 00000000000000..32401052651dac
--- /dev/null
+++ b/compiler-rt/test/builtins/TestCases/arm-static-base-runtime-asm.test
@@ -0,0 +1,29 @@
+# RUN: %clang --target=armv7-unknown-linux-gnueabihf -fPIC -I%S/../../../lib \
+# RUN: -x assembler-with-cpp -c \
+# RUN: %S/../../../lib/sanitizer_common/sanitizer_common_interceptors_vfork_arm.inc.S \
+# RUN: -o %t-vfork-pic.o
+# RUN: %clang --target=armv7-unknown-linux-gnueabihf -fPIC \
+# RUN: -D__ARM_PIC_DATA_STATIC_BASE=1 -I%S/../../../lib \
+# RUN: -x assembler-with-cpp -c \
+# RUN: %S/../../../lib/sanitizer_common/sanitizer_common_interceptors_vfork_arm.inc.S \
+# RUN: -o %t-vfork-static-base.o
+# RUN: %clang --target=armv7-unknown-linux-gnueabihf -fPIC \
+# RUN: -D__ARM_PIC_DATA_STATIC_BASE=1 -I%S/../../../lib \
+# RUN: -x assembler-with-cpp -E \
+# RUN: %S/../../../lib/sanitizer_common/sanitizer_common_interceptors_vfork_arm.inc.S | \
+# RUN: FileCheck %s --check-prefix=VFORK
+
+# RUN: %clang --target=armv7-unknown-linux-gnueabihf -fPIC \
+# RUN: -x assembler-with-cpp -c %S/../../../lib/xray/xray_trampoline_arm.S \
+# RUN: -o %t-xray-pic.o
+# RUN: %clang --target=armv7-unknown-linux-gnueabihf -fPIC \
+# RUN: -D__ARM_PIC_DATA_STATIC_BASE=1 -x assembler-with-cpp -c \
+# RUN: %S/../../../lib/xray/xray_trampoline_arm.S \
+# RUN: -o %t-xray-static-base.o
+# RUN: %clang --target=armv7-unknown-linux-gnueabihf -fPIC \
+# RUN: -D__ARM_PIC_DATA_STATIC_BASE=1 -x assembler-with-cpp -E \
+# RUN: %S/../../../lib/xray/xray_trampoline_arm.S | \
+# RUN: FileCheck %s --check-prefix=XRAY
+
+# VFORK: .long _ZN14__interception10real_vforkE(GOT)
+# XRAY: .long _ZN6__xray19XRayPatchedFunctionE(GOT)
>From 80c0ae6b2bc11f2425c6f4e39b9efab9c681b1d5 Mon Sep 17 00:00:00 2001
From: Mark Murray <Mark.Murray at arm.com>
Date: Thu, 5 Nov 2026 13:01:27 +0000
Subject: [PATCH 3/3] [lld][ARM] Test static-base PIE startup sequence
Add a linker-side proof test for the ARM static-base PIC data startup pattern. The test links a tiny PIE image whose entry code initializes r9 from a linker-defined __pic_static_base before using an r9-relative GOT offset to load data.
Check that the local data GOT entry is represented by an R_ARM_RELATIVE dynamic relocation, that the startup literal does not leave ABS32 or REL32 dynamic relocations, and that the linked disassembly keeps the expected r9 initialization and GOT load sequence.
---
lld/test/ELF/arm-pie-static-base-startup.s | 65 ++++++++++++++++++++++
1 file changed, 65 insertions(+)
create mode 100644 lld/test/ELF/arm-pie-static-base-startup.s
diff --git a/lld/test/ELF/arm-pie-static-base-startup.s b/lld/test/ELF/arm-pie-static-base-startup.s
new file mode 100644
index 00000000000000..efe86429a4d9a7
--- /dev/null
+++ b/lld/test/ELF/arm-pie-static-base-startup.s
@@ -0,0 +1,65 @@
+// REQUIRES: arm
+// RUN: llvm-mc -filetype=obj -triple=armv7a-none-linux-gnueabi %s -o %t.o
+// RUN: echo 'SECTIONS { \
+// RUN: . = 0x10000; \
+// RUN: .text : { *(.text) } \
+// RUN: .got : { PROVIDE_HIDDEN(__pic_static_base = .); PROVIDE_HIDDEN(_GLOBAL_OFFSET_TABLE_ = .); *(.got.plt) *(.got) } \
+// RUN: .data : { *(.data) } \
+// RUN: }' > %t.script
+// RUN: ld.lld --pie --script %t.script %t.o -o %t
+// RUN: llvm-readelf -s -r -x .got %t | FileCheck %s --check-prefix=READELF \
+// RUN: --implicit-check-not=R_ARM_ABS32 --implicit-check-not=R_ARM_REL32
+// RUN: llvm-objdump --triple=armv7a-none-linux-gnueabi -d --no-show-raw-insn %t | \
+// RUN: FileCheck %s --check-prefix=DISASM
+
+// This is a minimal static-base PIC startup pattern. The first few
+// instructions initialize r9 without using the GOT, because GOT-based data
+// access itself depends on r9 already being valid. Later code can then use
+// R_ARM_GOT_BREL offsets relative to that base.
+
+.syntax unified
+.text
+.globl _start
+.p2align 2
+_start:
+ adr r9, .Lstatic_base_delta
+ ldr r12, [r9]
+ add r9, r9, r12
+
+ ldr r0, .Ldata_got
+ ldr r0, [r9, r0]
+ ldr r0, [r0]
+ bx lr
+
+.p2align 2
+.Lstatic_base_delta:
+ .word __pic_static_base - .
+.Ldata_got:
+ .word data_object(GOT)
+
+.data
+.globl data_object
+.p2align 2
+data_object:
+ .word 0x12345678
+
+// READELF: Relocation section '.rel.dyn'
+// READELF-NEXT: Offset
+// READELF-NEXT: 00010068 {{.*}} R_ARM_RELATIVE
+
+// READELF: {{[0-9]+}}: 00010068 {{.*}} LOCAL HIDDEN {{.*}} __pic_static_base
+// READELF: {{[0-9]+}}: 000100d4 {{.*}} GLOBAL DEFAULT {{.*}} data_object
+
+// READELF: Hex dump of section '.got':
+// READELF-NEXT: 0x00010068 d4000100
+
+// DISASM: <_start>:
+// DISASM-NEXT: 10044: add r9, pc, #20
+// DISASM-NEXT: 10048: ldr r12, [r9]
+// DISASM-NEXT: 1004c: add r9, r9, r12
+// DISASM-NEXT: 10050: ldr r0, [pc, #0xc]
+// DISASM-NEXT: 10054: ldr r0, [r9, r0]
+// DISASM-NEXT: 10058: ldr r0, [r0]
+// DISASM-NEXT: 1005c: bx lr
+// DISASM-NEXT: 10060: 08 00 00 00
+// DISASM-NEXT: 10064: 00 00 00 00
More information about the cfe-commits
mailing list