[llvm] [MergeFunctions] keep the symbol of a function an alias points at on COFF (PR #222024)

Charles Zablit via llvm-commits llvm-commits at lists.llvm.org
Tue Sep 15 04:21:02 PDT 2026


https://github.com/charles-zablit updated https://github.com/llvm/llvm-project/pull/222024

>From 4bf7a1bf3fdff67ffe7afe1d5acd063dfc3970c7 Mon Sep 17 00:00:00 2001
From: Charles Zablit <c_zablit at apple.com>
Date: Tue, 15 Sep 2026 12:18:25 +0100
Subject: [PATCH] [MergeFunctions] Give a COFF-aliased shared body a COMDAT and
 a stable name

---
 llvm/lib/Transforms/IPO/MergeFunctions.cpp    | 71 ++++++++++++--
 .../MergeFunc/coff-weak-alias-object.ll       | 35 +++++++
 .../Transforms/MergeFunc/coff-weak-alias.ll   | 98 +++++++++++++++++++
 3 files changed, 196 insertions(+), 8 deletions(-)
 create mode 100644 llvm/test/Transforms/MergeFunc/coff-weak-alias-object.ll
 create mode 100644 llvm/test/Transforms/MergeFunc/coff-weak-alias.ll

diff --git a/llvm/lib/Transforms/IPO/MergeFunctions.cpp b/llvm/lib/Transforms/IPO/MergeFunctions.cpp
index 9bb18c2f3cb04..ebf8d20c83840 100644
--- a/llvm/lib/Transforms/IPO/MergeFunctions.cpp
+++ b/llvm/lib/Transforms/IPO/MergeFunctions.cpp
@@ -307,7 +307,8 @@ class MergeFunctions {
   // If needed, replace G with an alias to F if possible, or a thunk to F if
   // profitable. Returns false if neither is the case. If \p G is not needed
   // (i.e. it is discardable and not used), \p G is removed directly.
-  bool writeThunkOrAliasIfNeeded(Function *F, Function *G);
+  bool writeThunkOrAliasIfNeeded(Function *F, Function *G,
+                                 bool AllowAlias = true);
 
   /// Replace function F with function G in the function tree.
   void replaceFunctionInTree(const FunctionNode &FN, Function *G);
@@ -860,6 +861,45 @@ static bool canCreateAliasFor(Function *F) {
   return true;
 }
 
+static bool hasNonLocalAlias(const Function *F) {
+  for (const GlobalAlias &GA : F->getParent()->aliases())
+    if (!GA.hasLocalLinkage() && GA.getAliaseeObject() == F)
+      return true;
+  return false;
+}
+
+/// COFF names a local alias target's fallback symbol after unrelated contents
+/// of the object, so two objects defining the alias disagree (LNK1227).
+static bool needsStableSymbolForAlias(const Function *F) {
+  return F->getParent()->getTargetTriple().isOSBinFormatCOFF();
+}
+
+/// Renames \p F after its contents and puts it in a COMDAT, so every object
+/// merging this body agrees on the symbol. False if \p F cannot be renamed.
+static bool tryConvertToMergedFunction(Function *F) {
+  // An externally visible name is fixed and cannot be renamed. The ODR path
+  // calls this on the nameless shared body, whose name went to the thunk.
+  if (F->hasName() && !F->hasLocalLinkage())
+    return false;
+
+  Module *M = F->getParent();
+  std::string Name =
+      ("__llvm_mergefunc$" + Twine::utohexstr(StructuralHash(*F))).str();
+  // setName would silently unique a clash, which this name may not do.
+  if (M->getNamedValue(Name))
+    return false;
+
+  F->setName(Name);
+  F->setLinkage(GlobalValue::LinkOnceODRLinkage);
+  F->setDLLStorageClass(GlobalValue::DefaultStorageClass);
+  Comdat *C = M->getOrInsertComdat(Name);
+  // StructuralHash is coarse: let the linker reject a collision rather than
+  // keep either body.
+  C->setSelectionKind(Comdat::ExactMatch);
+  F->setComdat(C);
+  return true;
+}
+
 // Replace G with an alias to F (deleting function G)
 void MergeFunctions::writeAlias(Function *F, Function *G) {
   PointerType *PtrType = G->getType();
@@ -910,10 +950,11 @@ static void mergeEntryCountsAndImportsInto(Function &F, Function &G) {
   F.setEntryCount(Sum, AllImports.empty() ? nullptr : &AllImports);
 }
 
-bool MergeFunctions::writeThunkOrAliasIfNeeded(Function *F, Function *G) {
+bool MergeFunctions::writeThunkOrAliasIfNeeded(Function *F, Function *G,
+                                               bool AllowAlias) {
   bool ShouldErase =
       G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI;
-  bool ShouldAlias = canCreateAliasFor(G);
+  bool ShouldAlias = AllowAlias && canCreateAliasFor(G);
   bool ShouldThunk = canCreateThunkFor(F);
 
   if (!ShouldErase && !ShouldAlias && !ShouldThunk)
@@ -1149,6 +1190,17 @@ void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
     if (isODR(F))
       replaceDirectCallers(NewF, F);
 
+    // Settle F's symbol before the thunks and aliases below name it.
+    const bool MightBeAliased =
+        (canCreateAliasFor(G) && !G->hasLocalLinkage()) ||
+        (canCreateAliasFor(NewF) && !NewF->hasLocalLinkage());
+    const bool NeedsStableSymbol =
+        MightBeAliased && needsStableSymbolForAlias(F);
+    const bool Converted = NeedsStableSymbol && tryConvertToMergedFunction(F);
+    if (!Converted)
+      F->setLinkage(GlobalValue::PrivateLinkage);
+    const bool AllowAlias = !NeedsStableSymbol || Converted;
+
     // We collect alignment before writeThunkOrAliasIfNeeded that overwrites
     // NewF and G's content.
     const MaybeAlign NewFAlign = NewF->getAlign();
@@ -1158,18 +1210,17 @@ void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
     mergeInstrAnnotations(F, G);
     mergeEntryCountsAndImportsInto(*F, *G);
 
-    writeThunkOrAliasIfNeeded(F, G);
+    writeThunkOrAliasIfNeeded(F, G, AllowAlias);
     if (FEntryCount)
       NewF->setEntryCount(*FEntryCount);
     // NewF becomes thunk/alias to the shared body F, it has no annotations to
     // be merged.
-    writeThunkOrAliasIfNeeded(F, NewF);
+    writeThunkOrAliasIfNeeded(F, NewF, AllowAlias);
 
     if (NewFAlign || GAlign)
       F->setAlignment(std::max(NewFAlign.valueOrOne(), GAlign.valueOrOne()));
     else
       F->setAlignment(std::nullopt);
-    F->setLinkage(GlobalValue::PrivateLinkage);
     ++NumDoubleWeak;
     ++NumFunctionsMerged;
   } else {
@@ -1178,8 +1229,12 @@ void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
     if (!G->isInterposable() && !MergeFunctionsPDI) {
       // Functions referred to by llvm.used/llvm.compiler.used are special:
       // there are uses of the symbol name that are not visible to LLVM,
-      // usually from inline asm.
-      if (G->hasGlobalUnnamedAddr() && !Used.contains(G)) {
+      // usually from inline asm. An alias visible to other objects is about to
+      // name F, so keep G unless F can take a symbol they agree on.
+      const bool CanRetargetAlias = !needsStableSymbolForAlias(F) ||
+                                    !hasNonLocalAlias(G) ||
+                                    tryConvertToMergedFunction(F);
+      if (G->hasGlobalUnnamedAddr() && !Used.contains(G) && CanRetargetAlias) {
         // G might have been a key in our GlobalNumberState, and it's illegal
         // to replace a key in ValueMap<GlobalValue *> with a non-global.
         GlobalNumbers.erase(G);
diff --git a/llvm/test/Transforms/MergeFunc/coff-weak-alias-object.ll b/llvm/test/Transforms/MergeFunc/coff-weak-alias-object.ll
new file mode 100644
index 0000000000000..904013b96c07d
--- /dev/null
+++ b/llvm/test/Transforms/MergeFunc/coff-weak-alias-object.ll
@@ -0,0 +1,35 @@
+; The weak external must name a symbol every object defining the alias agrees
+; on. Any COFF target will do; this is a property of the object format.
+
+; REQUIRES: aarch64-registered-target
+; RUN: opt -S -passes=mergefunc %s | \
+; RUN:   llc -filetype=obj -mtriple=aarch64-pc-windows-msvc -o %t.obj
+; RUN: llvm-readobj --symbols %t.obj | FileCheck %s
+
+; CHECK:      Name: alias_g
+; CHECK:      StorageClass: WeakExternal
+; CHECK:      AuxWeakExternal {
+; CHECK-NEXT:   Linked: __llvm_mergefunc$
+; CHECK-NOT:  .weak.alias_g.default
+
+target triple = "aarch64-pc-windows-msvc"
+
+ at alias_g = weak alias i32 (i32), ptr @g
+
+define internal i32 @f(i32 %x) {
+  %a = mul i32 %x, 3
+  %b = add i32 %a, 7
+  ret i32 %b
+}
+
+define linkonce_odr i32 @g(i32 %x) unnamed_addr {
+  %a = mul i32 %x, 3
+  %b = add i32 %a, 7
+  ret i32 %b
+}
+
+; A local body would instead get .weak.alias_g.default.keep, named after this.
+define i32 @keep() {
+  %r = call i32 @alias_g(i32 1)
+  ret i32 %r
+}
diff --git a/llvm/test/Transforms/MergeFunc/coff-weak-alias.ll b/llvm/test/Transforms/MergeFunc/coff-weak-alias.ll
new file mode 100644
index 0000000000000..3ee9ff6324fd5
--- /dev/null
+++ b/llvm/test/Transforms/MergeFunc/coff-weak-alias.ll
@@ -0,0 +1,98 @@
+; RUN: split-file %s %t
+; RUN: opt -S -passes=mergefunc %t/coff.ll | FileCheck %s --check-prefix=COFF
+; RUN: opt -S -passes=mergefunc %t/coff-noalias.ll | FileCheck %s --check-prefix=NOALIAS
+; RUN: opt -S -passes=mergefunc -mergefunc-use-aliases %t/coff-odr.ll | FileCheck %s --check-prefix=ODR
+; RUN: opt -S -passes=mergefunc %t/elf.ll | FileCheck %s --check-prefix=ELF
+
+; On COFF the merged body is named after its structural hash and put in a COMDAT,
+; so every object defining the alias names the same fallback symbol.
+
+;--- coff.ll
+target triple = "x86_64-pc-windows-msvc"
+
+; COFF: $[[BODY:"__llvm_mergefunc\$[0-9a-f]+"]] = comdat exactmatch
+; COFF: @alias_g = weak alias i32 (i32), ptr @[[BODY]]
+; COFF: define linkonce_odr {{.*}}i32 @[[BODY]](i32 %x) comdat
+; COFF-NOT: define {{.*}} @g
+
+ at alias_g = weak alias i32 (i32), ptr @g
+
+define internal i32 @f(i32 %x) {
+  %a = mul i32 %x, 3
+  %b = add i32 %a, 7
+  ret i32 %b
+}
+
+define linkonce_odr i32 @g(i32 %x) unnamed_addr {
+  %a = mul i32 %x, 3
+  %b = add i32 %a, 7
+  ret i32 %b
+}
+
+;--- coff-noalias.ll
+target triple = "x86_64-pc-windows-msvc"
+
+; NOALIAS-NOT: comdat
+; NOALIAS: define internal i32 @f
+; NOALIAS: call i32 @f
+
+define internal i32 @f(i32 %x) {
+  %a = mul i32 %x, 3
+  %b = add i32 %a, 7
+  ret i32 %b
+}
+
+define linkonce_odr i32 @g(i32 %x) unnamed_addr {
+  %a = mul i32 %x, 3
+  %b = add i32 %a, 7
+  ret i32 %b
+}
+
+define i32 @use() {
+  %r = call i32 @g(i32 1)
+  ret i32 %r
+}
+
+;--- coff-odr.ll
+target triple = "x86_64-pc-windows-msvc"
+
+; ODR: $[[BODY:"__llvm_mergefunc\$[0-9a-f]+"]] = comdat exactmatch
+; ODR-DAG: @g = weak_odr unnamed_addr alias i32 (i32), ptr @[[BODY]]
+; ODR-DAG: @f = weak_odr unnamed_addr alias i32 (i32), ptr @[[BODY]]
+; ODR: define linkonce_odr i32 @[[BODY]](i32 %x) unnamed_addr comdat
+
+define weak_odr i32 @f(i32 %x) unnamed_addr {
+  %a = mul i32 %x, 3
+  %b = add i32 %a, 7
+  %c = add i32 %b, 1
+  ret i32 %c
+}
+
+define weak_odr i32 @g(i32 %x) unnamed_addr {
+  %a = mul i32 %x, 3
+  %b = add i32 %a, 7
+  %c = add i32 %b, 1
+  ret i32 %c
+}
+
+;--- elf.ll
+target triple = "x86_64-unknown-linux-gnu"
+
+; ELF-NOT: comdat
+; ELF: @alias_g = weak alias i32 (i32), ptr @f
+; ELF: define internal i32 @f
+; ELF-NOT: define {{.*}} @g
+
+ at alias_g = weak alias i32 (i32), ptr @g
+
+define internal i32 @f(i32 %x) {
+  %a = mul i32 %x, 3
+  %b = add i32 %a, 7
+  ret i32 %b
+}
+
+define linkonce_odr i32 @g(i32 %x) unnamed_addr {
+  %a = mul i32 %x, 3
+  %b = add i32 %a, 7
+  ret i32 %b
+}



More information about the llvm-commits mailing list