[clang] [Clang] Honor asm labels on library functions for compiler-emitted calls (PR #244853)
Brad Smith via cfe-commits
cfe-commits at lists.llvm.org
Wed Dec 2 14:55:01 PST 2026
https://github.com/brad0 updated https://github.com/llvm/llvm-project/pull/244853
>From cac8409b0bac050b8672aa1e8bbca6a5239df21d Mon Sep 17 00:00:00 2001
From: Brad Smith <brad at comstyle.com>
Date: Sat, 21 Nov 2026 03:45:44 -0500
Subject: [PATCH] [Clang] Honor asm labels on library functions for
compiler-emitted calls
When a library function is redeclared with an asm label, Clang used the
label for direct calls but not for calls it emits itself:
- calls through the matching __builtin_* alias (e.g. __builtin_stpcpy,
__builtin_abort), which getBuiltinLibFunction() emitted using the
plain library name, since only the __builtin_ decl was checked for
an asm label.
- the abort() call in the terminate landing pad for EH cleanups in C,
which getTerminateFn() always emitted as plain abort.
Look up the library function in the translation unit and use the
mangled name of a declaration with an asm label (or #pragma
redefine_extname), matching GCC.
Like GCC, also apply a label that is declared after such a call was
emitted: these calls are noted and retargeted at the end of the
translation unit. Only calls Clang emitted itself are changed.
glibc relies on this to keep internal calls off the PLT; a Clang-built
libc.so had PLT calls to stpcpy and abort, failing elf/check-localplt.
Fixes #244638
Assisted-by: Claude Opus 5.5
---
clang/lib/CodeGen/CGBuiltin.cpp | 65 +++++++++++++++++++++++++----
clang/lib/CodeGen/CGException.cpp | 5 +++
clang/lib/CodeGen/CodeGenModule.cpp | 3 ++
clang/lib/CodeGen/CodeGenModule.h | 18 ++++++++
clang/test/CodeGen/asm-label-late.c | 32 ++++++++++++++
clang/test/CodeGen/asm-label.c | 39 +++++++++++++++++
6 files changed, 154 insertions(+), 8 deletions(-)
create mode 100644 clang/test/CodeGen/asm-label-late.c
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index bdcd9ee43ce1c7..418304303f1c57 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -190,17 +190,22 @@ llvm::Constant *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
llvm::SmallString<64> Name;
GlobalDecl D(FD);
+ std::string LibName = Context.BuiltinInfo.getName(BuiltinID).substr(10);
+
// If the builtin has been declared explicitly with an assembler label,
// use the mangled name. This differs from the plain label on platforms
- // that prefix labels.
+ // that prefix labels. Likewise, if the library function the builtin maps to
+ // has been declared with an assembler label, use that, as GCC does.
if (FD->hasAttr<AsmLabelAttr>())
Name = getMangledName(D);
+ else if (const FunctionDecl *LibFD = getAsmLabeledLibFunction(LibName))
+ Name = getMangledName(GlobalDecl(LibFD));
else if (StringRef TargetName = CodeGenUtils::getTargetBuiltinLibFunctionName(
BuiltinID, getTarget());
!TargetName.empty())
Name = TargetName;
else
- Name = Context.BuiltinInfo.getName(BuiltinID).substr(10);
+ Name = LibName;
llvm::FunctionType *Ty =
cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
@@ -208,6 +213,40 @@ llvm::Constant *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
return GetOrCreateLLVMFunction(Name, Ty, D, /*ForVTable=*/false);
}
+const FunctionDecl *CodeGenModule::getAsmLabeledLibFunction(StringRef Name) {
+ for (const NamedDecl *ND :
+ Context.getTranslationUnitDecl()->lookup(&Context.Idents.get(Name)))
+ if (const auto *FD = dyn_cast<FunctionDecl>(ND))
+ if (FD->isExternC() && FD->hasAttr<AsmLabelAttr>())
+ return FD;
+ return nullptr;
+}
+
+void CodeGenModule::noteLibFunctionCall(llvm::CallBase *Call) {
+ if (Call)
+ LibFunctionCalls.emplace_back(Call);
+}
+
+void CodeGenModule::applyLateLibFunctionAsmLabels() {
+ for (llvm::WeakVH &VH : LibFunctionCalls) {
+ auto *Call = dyn_cast_or_null<llvm::CallBase>(VH);
+ if (!Call)
+ continue;
+ llvm::Function *Old = Call->getCalledFunction();
+ if (!Old)
+ continue;
+ const FunctionDecl *FD = getAsmLabeledLibFunction(Old->getName());
+ if (!FD || getMangledName(GlobalDecl(FD)) == Old->getName())
+ continue;
+ Call->setCalledFunction(
+ Call->getFunctionType(),
+ GetAddrOfFunction(GlobalDecl(FD), Call->getFunctionType()));
+ if (Old->use_empty())
+ Old->eraseFromParent();
+ }
+ LibFunctionCalls.clear();
+}
+
void appendDefaultIntrinsicArgs(SmallVectorImpl<llvm::Value *> &Args,
llvm::Function *F) {
llvm::FunctionType *FTy = F->getFunctionType();
@@ -772,13 +811,18 @@ static Value *EmitSignBit(CodeGenFunction &CGF, Value *V) {
}
static RValue emitLibraryCall(CodeGenFunction &CGF, const FunctionDecl *FD,
- const CallExpr *E, llvm::Constant *calleeValue) {
+ const CallExpr *E, llvm::Constant *calleeValue,
+ llvm::CallBase **CallOut = nullptr) {
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
CGCallee callee = CGCallee::forDirect(calleeValue, GlobalDecl(FD));
llvm::CallBase *callOrInvoke = nullptr;
CGFunctionInfo const *FnInfo = nullptr;
- return CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot(),
- /*Chain=*/nullptr, &callOrInvoke, &FnInfo);
+ RValue RV =
+ CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot(),
+ /*Chain=*/nullptr, &callOrInvoke, &FnInfo);
+ if (CallOut)
+ *CallOut = callOrInvoke;
+ return RV;
}
/// Emit a call to llvm.{sadd,uadd,ssub,usub,smul,umul}.with.overflow.*
@@ -6908,9 +6952,14 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
// version of the function name.
const auto &BI = getContext().BuiltinInfo;
if (!shouldEmitBuiltinAsIR(BuiltinID, BI, *this) &&
- BI.isLibFunction(BuiltinID))
- return emitLibraryCall(*this, FD, E,
- CGM.getBuiltinLibFunction(FD, BuiltinID));
+ BI.isLibFunction(BuiltinID)) {
+ llvm::CallBase *Call = nullptr;
+ RValue RV = emitLibraryCall(
+ *this, FD, E, CGM.getBuiltinLibFunction(FD, BuiltinID), &Call);
+ if (!FD->hasAttr<AsmLabelAttr>())
+ CGM.noteLibFunctionCall(Call);
+ return RV;
+ }
// If this is a predefined lib function (e.g. malloc), emit the call
// using exactly the normal call path.
diff --git a/clang/lib/CodeGen/CGException.cpp b/clang/lib/CodeGen/CGException.cpp
index 75d8a91e034360..62ab23a2a4eac7 100644
--- a/clang/lib/CodeGen/CGException.cpp
+++ b/clang/lib/CodeGen/CGException.cpp
@@ -69,6 +69,8 @@ llvm::FunctionCallee CodeGenModule::getTerminateFn() {
} else if (getLangOpts().ObjC &&
getLangOpts().ObjCRuntime.hasTerminate())
name = "objc_terminate";
+ else if (const FunctionDecl *FD = getAsmLabeledLibFunction("abort"))
+ name = getMangledName(GlobalDecl(FD));
else
name = "abort";
return CreateRuntimeFunction(FTy, name);
@@ -1442,6 +1444,7 @@ llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
llvm::CallInst *terminateCall =
CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
terminateCall->setDoesNotReturn();
+ CGM.noteLibFunctionCall(terminateCall);
Builder.CreateUnreachable();
// Restore the saved insertion state.
@@ -1466,6 +1469,7 @@ llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
llvm::CallInst *terminateCall =
CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
terminateCall->setDoesNotReturn();
+ CGM.noteLibFunctionCall(terminateCall);
Builder.CreateUnreachable();
// Restore the saved insertion state.
@@ -1501,6 +1505,7 @@ llvm::BasicBlock *CodeGenFunction::getTerminateFunclet() {
llvm::CallInst *terminateCall =
CGM.getCXXABI().emitTerminateForUnexpectedException(*this, nullptr);
terminateCall->setDoesNotReturn();
+ CGM.noteLibFunctionCall(terminateCall);
Builder.CreateUnreachable();
// Restore the saved insertion state.
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp
index f0ea493e172229..237a033bfdd874 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -1220,6 +1220,9 @@ void CodeGenModule::Release() {
Module *Primary = getContext().getCurrentNamedModule();
if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule())
EmitModuleInitializers(Primary);
+ // Done before EmitDeferred(): anything emitted from here on sees the whole
+ // translation unit, and a labeled declaration may have a deferred body.
+ applyLateLibFunctionAsmLabels();
EmitDeferred();
DeferredDecls.insert_range(EmittedDeferredDecls);
EmittedDeferredDecls.clear();
diff --git a/clang/lib/CodeGen/CodeGenModule.h b/clang/lib/CodeGen/CodeGenModule.h
index c6b13f58817843..df7cc39966e972 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -412,6 +412,10 @@ class CodeGenModule : public CodeGenTypeCache {
// or a definition.
llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
+ /// Calls the compiler emitted itself to C library functions under their
+ /// plain names, see noteLibFunctionCall().
+ llvm::SmallVector<llvm::WeakVH, 0> LibFunctionCalls;
+
/// This contains all the decls which have definitions but/ which are deferred
/// for emission and therefore should only be output if they are actually
/// used. If a decl is in this, then it is known to have not been referenced
@@ -1338,6 +1342,16 @@ class CodeGenModule : public CodeGenTypeCache {
llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD,
unsigned BuiltinID);
+ /// If the C library function \p Name has been declared with an asm label
+ /// (or \#pragma redefine_extname), return that declaration so that calls
+ /// the compiler emits itself use the same symbol as direct calls.
+ const FunctionDecl *getAsmLabeledLibFunction(StringRef Name);
+
+ /// Note a call the compiler emitted itself to a C library function under
+ /// its plain name. Like GCC, an asm label declared later in the translation
+ /// unit still applies to it; see applyLateLibFunctionAsmLabels().
+ void noteLibFunctionCall(llvm::CallBase *Call);
+
llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type *> Tys = {});
void AddCXXGlobalInit(llvm::Function *F) { CXXGlobalInits.push_back(F); }
@@ -2106,6 +2120,10 @@ class CodeGenModule : public CodeGenTypeCache {
/// Call replaceAllUsesWith on all pairs in Replacements.
void applyReplacements();
+ /// Redirect the calls noted by noteLibFunctionCall() to a library function
+ /// that was declared with an asm label after they were emitted.
+ void applyLateLibFunctionAsmLabels();
+
/// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
void applyGlobalValReplacements();
diff --git a/clang/test/CodeGen/asm-label-late.c b/clang/test/CodeGen/asm-label-late.c
new file mode 100644
index 00000000000000..e4c8a396aaa549
--- /dev/null
+++ b/clang/test/CodeGen/asm-label-late.c
@@ -0,0 +1,32 @@
+// RUN: %clang_cc1 -triple=i686-pc-linux-gnu -fexceptions -emit-llvm %s -o - \
+// RUN: | FileCheck %s --implicit-check-not=@stpcpy --implicit-check-not=@abort
+
+/// As with GCC, an asm label on a library function also applies to the calls
+/// the compiler emitted itself before the label was declared.
+
+void test_builtin_stpcpy(char *x, char *y) { __builtin_stpcpy(x, y); }
+// CHECK-LABEL: @test_builtin_stpcpy(
+// CHECK: call ptr @__GI_stpcpy(
+
+void release(int *);
+void use(int *);
+void test_cleanup_terminate(void) {
+ int v __attribute__((cleanup(release))) = 0;
+ use(&v);
+}
+// CHECK-LABEL: @test_cleanup_terminate(
+// CHECK: terminate.lpad:
+// CHECK: call void @__GI_abort()
+
+typedef char *stpcpy_t(char *__restrict, const char *__restrict);
+extern stpcpy_t stpcpy asm("__GI_stpcpy");
+void abort(void) asm("__GI_abort") __attribute__((noreturn));
+
+/// Calls emitted after the labels are seen use them directly.
+static char *deferred(char *x, char *y) { return __builtin_stpcpy(x, y); }
+char *test_deferred(char *x, char *y) { return deferred(x, y); }
+// CHECK-LABEL: @deferred(
+// CHECK: call ptr @__GI_stpcpy(
+
+// CHECK: declare ptr @__GI_stpcpy(
+// CHECK: declare void @__GI_abort()
diff --git a/clang/test/CodeGen/asm-label.c b/clang/test/CodeGen/asm-label.c
index c901223db990d0..f9c9b4c724dd7e 100644
--- a/clang/test/CodeGen/asm-label.c
+++ b/clang/test/CodeGen/asm-label.c
@@ -1,5 +1,6 @@
// RUN: %clang_cc1 -triple=i686-pc-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,LINUX
// RUN: %clang_cc1 -triple=i686-apple-darwin9 -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,DARWIN
+// RUN: %clang_cc1 -triple=i686-pc-linux-gnu -fexceptions -emit-llvm %s -o - | FileCheck %s --check-prefix=EH
char *strerror(int) asm("alias");
int x __asm("foo");
@@ -53,3 +54,41 @@ double sin(double x) asm("real_sin");
double test_sin(double d) { return __builtin_sin(d); }
// CHECK-LABEL: @test_sin(
// LINUX: call double @llvm.sin.f64(
+
+/// A call through the __builtin_ alias of a library function uses the asm
+/// label of the library function, as a direct call does.
+extern char *stpcpy(char *__restrict, const char *__restrict);
+extern __typeof(stpcpy) stpcpy asm("__GI_stpcpy");
+char *test_builtin_stpcpy(char *d, const char *s) {
+ return __builtin_stpcpy(d, s);
+}
+// CHECK-LABEL: @test_builtin_stpcpy(
+// LINUX: call ptr @__GI_stpcpy(
+// DARWIN: call ptr @"\01__GI_stpcpy"(
+
+extern void abort(void) __attribute__((noreturn));
+extern __typeof(abort) abort asm("__GI_abort");
+void test_builtin_abort(int x) {
+ if (x)
+ __builtin_abort();
+}
+// CHECK-LABEL: @test_builtin_abort(
+// LINUX: call void @__GI_abort(
+// DARWIN: call void @"\01__GI_abort"(
+
+/// The abort call in the terminate landing pad for an EH cleanup also uses
+/// the asm label.
+void release(int *);
+void use(int *);
+void test_cleanup_terminate(void) {
+ int v __attribute__((cleanup(release))) = 0;
+ use(&v);
+}
+// EH-LABEL: @test_cleanup_terminate(
+// EH: invoke void @release(
+// EH-NEXT: to label %{{.*}} unwind label %[[TERM:.*]]
+// EH: [[TERM]]:
+// EH-NEXT: landingpad { ptr, i32 }
+// EH-NEXT: catch ptr null
+// EH-NEXT: call void @__GI_abort()
+// EH-NOT: call void @abort()
More information about the cfe-commits
mailing list