https://github.com/wpcwzy updated 
https://github.com/llvm/llvm-project/pull/193881

From caa334f40343f3e98862de3d45bc671a46365705 Mon Sep 17 00:00:00 2001
From: Pincheng Wang <[email protected]>
Date: Sat, 14 Nov 2026 20:56:08 +0800
Subject: [PATCH] [Clang][OpenMP] Preserve libcalls for declare simd redecls

Clang folds libm calls into LLVM intrinsics, which hides the
vector-function-abi-variant mapping of a declare simd redeclaration.
Keep the scalar libcall in that case and emit the VFABI mapping from the
_ZGV* variant names in the header, filtered by the target ISA and the
preferred vector width. Keep the vector variant declarations in
llvm.compiler.used so they survive GlobalOpt, and do not let
SimplifyLibCalls fold the call back into an intrinsic at -O2.
---
 clang/lib/CodeGen/CGBuiltin.cpp               |  15 ++
 clang/lib/CodeGen/CGOpenMPRuntime.cpp         | 153 ++++++++++++++++++
 clang/lib/CodeGen/CodeGenModule.cpp           |   4 +-
 clang/test/OpenMP/Inputs/declare-simd-math.h  |   5 +
 clang/test/OpenMP/declare_simd_math_header.c  |  57 +++++++
 .../OpenMP/declare_simd_preserve_builtin.cpp  |  14 ++
 .../lib/Transforms/Utils/SimplifyLibCalls.cpp |  13 +-
 .../Transforms/InstCombine/vfabi-mapping.ll   |  26 +++
 8 files changed, 281 insertions(+), 6 deletions(-)
 create mode 100644 clang/test/OpenMP/Inputs/declare-simd-math.h
 create mode 100644 clang/test/OpenMP/declare_simd_math_header.c
 create mode 100644 clang/test/OpenMP/declare_simd_preserve_builtin.cpp
 create mode 100644 llvm/test/Transforms/InstCombine/vfabi-mapping.ll

diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index e154b9e752fd5c..187940c5b34703 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -30,6 +30,7 @@
 #include "clang/Basic/TargetInfo.h"
 #include "clang/CodeGenUtils/TargetUtils.h"
 #include "llvm/ADT/APFloat.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/IR/InlineAsm.h"
 #include "llvm/IR/Instruction.h"
 #include "llvm/IR/Intrinsics.h"
@@ -72,6 +73,16 @@ static bool shouldEmitBuiltinAsIR(unsigned BuiltinID,
   return false;
 }
 
+static bool shouldPreserveLibCallForDeclareSimd(const FunctionDecl *FD,
+                                                const LangOptions &LangOpts) {
+  if (!FD || !LangOpts.OpenMP)
+    return false;
+
+  return llvm::any_of(FD->redecls(), [](const FunctionDecl *Redecl) {
+    return Redecl->hasAttr<OMPDeclareSimdDeclAttr>();
+  });
+}
+
 static Value *EmitTargetArchBuiltinExpr(CodeGenFunction *CGF,
                                         unsigned BuiltinID, const CallExpr *E,
                                         ReturnValueSlot ReturnValue,
@@ -2769,6 +2780,10 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
           BuiltinID, CGM.getTriple(), ErrnoOverriden, getLangOpts().MathErrno,
           OptNone, IsOptimizationEnabled);
 
+  if (GenerateFPMathIntrinsics &&
+      shouldPreserveLibCallForDeclareSimd(FD, getLangOpts()))
+    GenerateFPMathIntrinsics = false;
+
   if (GenerateFPMathIntrinsics) {
     switch (BuiltinIDIfNoAsmLabel) {
     case Builtin::BIacos:
diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index d3a6ffee3ea748..028bf7f8dd0a81 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -40,6 +40,7 @@
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/GlobalValue.h"
 #include "llvm/IR/InstrTypes.h"
+#include "llvm/IR/VFABIDemangler.h"
 #include "llvm/IR/Value.h"
 #include "llvm/Support/AtomicOrdering.h"
 #include "llvm/Support/VirtualFileSystem.h"
@@ -12254,6 +12255,153 @@ evaluateCDTSize(const FunctionDecl *FD,
   return C.getTypeSize(CDT);
 }
 
+/// Returns true if the current target can execute vector functions of \p ISA.
+static bool isVFISASupported(llvm::VFISAKind ISA, const TargetInfo &TI) {
+  switch (ISA) {
+  case llvm::VFISAKind::SSE:
+    return TI.hasFeature("sse2");
+  case llvm::VFISAKind::AVX:
+    return TI.hasFeature("avx");
+  case llvm::VFISAKind::AVX2:
+    return TI.hasFeature("avx2");
+  case llvm::VFISAKind::AVX512:
+    return TI.hasFeature("avx512f");
+  case llvm::VFISAKind::AdvancedSIMD:
+    return TI.hasFeature("neon");
+  case llvm::VFISAKind::SVE:
+    return TI.hasFeature("sve");
+  case llvm::VFISAKind::RVV:
+    return TI.hasFeature("v");
+  case llvm::VFISAKind::LLVM:
+    // The LLVM ISA is target independent.
+    return true;
+  case llvm::VFISAKind::Unknown:
+    // Unrecognized ISA field; be conservative and drop the variant.
+    return false;
+  }
+  llvm_unreachable("Unhandled VFISAKind");
+}
+
+/// Returns the vector register width used by \p ISA, or 0 if the width is not
+/// fixed by the ISA.
+static unsigned getVFISARegisterWidth(llvm::VFISAKind ISA) {
+  switch (ISA) {
+  case llvm::VFISAKind::SSE:
+  case llvm::VFISAKind::AdvancedSIMD:
+    return 128;
+  case llvm::VFISAKind::AVX:
+  case llvm::VFISAKind::AVX2:
+    return 256;
+  case llvm::VFISAKind::AVX512:
+    return 512;
+  default:
+    return 0;
+  }
+}
+
+/// Returns how much \p ISA is preferred when several variants have the same 
VF.
+/// The vectorizer uses the first mapping it finds, so the most capable ISA has
+/// to come first.
+static unsigned getVFISAPreference(llvm::VFISAKind ISA) {
+  switch (ISA) {
+  case llvm::VFISAKind::SSE:
+    return 1;
+  case llvm::VFISAKind::AVX:
+    return 2;
+  case llvm::VFISAKind::AVX2:
+    return 3;
+  case llvm::VFISAKind::AVX512:
+    return 4;
+  default:
+    return 0;
+  }
+}
+
+static void emitDeclareSimdVariantMetadata(CodeGenModule &CGM,
+                                           llvm::Function *Fn) {
+  // Respect -mprefer-vector-width, otherwise the vectorizer can pick a variant
+  // wider than the preferred width, e.g. a 512-bit call with
+  // -mprefer-vector-width=256.
+  unsigned PreferWidth = 0;
+  StringRef PreferVectorWidth = CGM.getCodeGenOpts().PreferVectorWidth;
+  if (!PreferVectorWidth.empty() && PreferVectorWidth != "none")
+    (void)PreferVectorWidth.getAsInteger(10, PreferWidth);
+
+  llvm::SmallVector<std::pair<unsigned, std::string>, 8> VariantMappings;
+  for (llvm::Attribute Attr : Fn->getAttributes().getFnAttrs()) {
+    if (!Attr.isStringAttribute())
+      continue;
+
+    StringRef VariantName = Attr.getKindAsString();
+    if (!VariantName.starts_with("_ZGV"))
+      continue;
+
+    std::optional<llvm::VFInfo> Info =
+        llvm::VFABI::tryDemangleForVFABI(VariantName, Fn->getFunctionType());
+    if (!Info || !isVFISASupported(Info->ISA, CGM.getTarget()))
+      continue;
+
+    unsigned RegisterWidth = getVFISARegisterWidth(Info->ISA);
+    if (PreferWidth && RegisterWidth > PreferWidth)
+      continue;
+
+    llvm::FunctionType *VectorTy =
+        llvm::VFABI::createFunctionType(*Info, Fn->getFunctionType());
+    llvm::Function *VecFn = llvm::cast<llvm::Function>(
+        Fn->getParent()
+            ->getOrInsertFunction(Info->VectorName, VectorTy)
+            .getCallee());
+    // The mapping attribute is not a use, so keep the vector function in the
+    // module; otherwise GlobalOpt drops its declaration before vectorization.
+    CGM.addCompilerUsedGlobal(VecFn);
+    VariantMappings.emplace_back(getVFISAPreference(Info->ISA),
+                                 std::string(VariantName));
+  }
+
+  if (VariantMappings.empty())
+    return;
+
+  llvm::stable_sort(VariantMappings, [](const auto &L, const auto &R) {
+    return L.first > R.first;
+  });
+
+  SmallString<256> Buffer;
+  llvm::raw_svector_ostream Out(Buffer);
+  for (const auto &Mapping : VariantMappings)
+    Out << Mapping.second << ',';
+  Buffer.pop_back();
+
+  Fn->removeFnAttr(llvm::VFABI::MappingsAttrName);
+  Fn->addFnAttr(llvm::VFABI::MappingsAttrName, Buffer.str());
+}
+
+// Clang does not emit vector variant definitions, so only the C library is
+// known to provide them. The declaration also has to come from a header,
+// otherwise the vector functions it names may not exist.
+static bool shouldEmitDeclareSimdVariantMetadata(const FunctionDecl *FD,
+                                                 const SourceManager &SM) {
+  if (!FD)
+    return false;
+
+  for (const FunctionDecl *Redecl : FD->redecls()) {
+    if (!Redecl->hasAttr<OMPDeclareSimdDeclAttr>())
+      continue;
+
+    unsigned BuiltinID = Redecl->getBuiltinID();
+    if (!BuiltinID ||
+        
!Redecl->getASTContext().BuiltinInfo.isPredefinedLibFunction(BuiltinID))
+      continue;
+
+    // The declaration has to come from a header, otherwise the vector 
functions
+    // it names may not exist.
+    SourceLocation Loc = SM.getExpansionLoc(Redecl->getLocation());
+    if (Loc.isValid() && !SM.isWrittenInMainFile(Loc))
+      return true;
+  }
+
+  return false;
+}
+
 // This are the Functions that are needed to mangle the name of the
 // vector functions generated by the compiler, according to the rules
 // defined in the "Vector Function ABI specifications for AArch64",
@@ -12404,6 +12552,7 @@ void CGOpenMPRuntime::emitDeclareSimdFunction(const 
FunctionDecl *FD,
                                               llvm::Function *Fn) {
   ASTContext &C = CGM.getContext();
   FD = FD->getMostRecentDecl();
+  const FunctionDecl *MostRecentFD = FD;
   while (FD) {
     // Map params to their positions in function decl.
     llvm::DenseMap<const Decl *, unsigned> ParamPositions;
@@ -12567,6 +12716,10 @@ void CGOpenMPRuntime::emitDeclareSimdFunction(const 
FunctionDecl *FD,
     }
     FD = FD->getPreviousDecl();
   }
+
+  if (shouldEmitDeclareSimdVariantMetadata(MostRecentFD,
+                                           
CGM.getContext().getSourceManager()))
+    emitDeclareSimdVariantMetadata(CGM, Fn);
 }
 
 namespace {
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index eec4d9e714abe6..2667a2d43b0d3a 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3907,8 +3907,8 @@ void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
 }
 
 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
-  assert(!GV->isDeclaration() &&
-         "Only globals with definition can force usage.");
+  assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
+         "Only functions can be used without a definition.");
   LLVMCompilerUsed.emplace_back(GV);
 }
 
diff --git a/clang/test/OpenMP/Inputs/declare-simd-math.h 
b/clang/test/OpenMP/Inputs/declare-simd-math.h
new file mode 100644
index 00000000000000..47972a616d49ed
--- /dev/null
+++ b/clang/test/OpenMP/Inputs/declare-simd-math.h
@@ -0,0 +1,5 @@
+#pragma omp declare simd notinbranch
+double acosh(double);
+
+#pragma omp declare simd notinbranch
+double sin(double);
diff --git a/clang/test/OpenMP/declare_simd_math_header.c 
b/clang/test/OpenMP/declare_simd_math_header.c
new file mode 100644
index 00000000000000..56d2579d779e66
--- /dev/null
+++ b/clang/test/OpenMP/declare_simd_math_header.c
@@ -0,0 +1,57 @@
+// REQUIRES: x86-registered-target
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O2 -fopenmp -ffast-math \
+// RUN:   -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O2 -fopenmp -ffast-math \
+// RUN:   -target-feature +avx -target-feature +avx2 -emit-llvm %s -o - \
+// RUN:   | FileCheck %s --check-prefix=AVX2
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O2 -fopenmp -ffast-math \
+// RUN:   -target-feature +avx -target-feature +avx2 \
+// RUN:   -target-feature +avx512f -mprefer-vector-width=256 -emit-llvm %s -o 
- \
+// RUN:   | FileCheck %s --check-prefix=PREFER256
+
+// Check declare-simd libm functions declared in a header: the vector variant
+// mappings are attached to the scalar declaration, only for ISAs the target
+// supports and no wider than -mprefer-vector-width, and the loop uses the
+// variant instead of the intrinsic.
+
+#include "Inputs/declare-simd-math.h"
+
+void loop_acosh(double *restrict d, const double *restrict x, int n) {
+#pragma omp simd
+  for (int i = 0; i < n; i++)
+    d[i] = acosh(x[i]);
+}
+
+void loop_sin(double *restrict d, const double *restrict x, int n) {
+#pragma omp simd
+  for (int i = 0; i < n; i++)
+    d[i] = sin(x[i]);
+}
+
+// The vector functions are kept in llvm.compiler.used so that GlobalOpt does
+// not drop their declarations before vectorization.
+// CHECK: @llvm.compiler.used = appending global [2 x ptr] 
{{.*}}_ZGVbN2v_acosh{{.*}}_ZGVbN2v_sin
+// Both loops use the SSE variants on the base x86-64 target, and the
+// middle-end must not fold the calls back into intrinsics.
+// CHECK: call{{.*}}<2 x double> @_ZGVbN2v_acosh(
+// CHECK: call{{.*}}<2 x double> @_ZGVbN2v_sin(
+// CHECK-NOT: llvm.acosh
+// CHECK-NOT: llvm.sin
+// CHECK: "vector-function-abi-variant"="_ZGVbN2v_acosh"
+// CHECK: "vector-function-abi-variant"="_ZGVbN2v_sin"
+
+// AVX2 additionally gets the 256-bit variants, the AVX2 one being preferred
+// over the AVX one, but not the AVX-512 one.
+// AVX2: @llvm.compiler.used = appending global [6 x ptr] 
{{.*}}_ZGVcN4v_acosh{{.*}}_ZGVdN4v_sin
+// AVX2-NOT: ptr @_ZGVeN8v
+// AVX2: call{{.*}}<4 x double> @_ZGVdN4v_acosh(
+// AVX2: 
"vector-function-abi-variant"="_ZGVdN4v_acosh,_ZGVcN4v_acosh,_ZGVbN2v_acosh"
+
+// -mprefer-vector-width=256 on an AVX-512 target must not offer or use the
+// 512-bit variants.
+// PREFER256: @llvm.compiler.used = appending global [6 x ptr] 
{{.*}}_ZGVdN4v_sin
+// PREFER256-NOT: ptr @_ZGVeN8v
+// PREFER256: call{{.*}}<4 x double> @_ZGVdN4v_acosh(
+// PREFER256: 
"vector-function-abi-variant"="_ZGVdN4v_acosh,_ZGVcN4v_acosh,_ZGVbN2v_acosh"
+
diff --git a/clang/test/OpenMP/declare_simd_preserve_builtin.cpp 
b/clang/test/OpenMP/declare_simd_preserve_builtin.cpp
new file mode 100644
index 00000000000000..7b6a808de13da3
--- /dev/null
+++ b/clang/test/OpenMP/declare_simd_preserve_builtin.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O2 -ffast-math -fopenmp 
-emit-llvm %s -o - | FileCheck %s
+
+double sqrt(double);
+
+#pragma omp declare simd notinbranch
+double sqrt(double);
+
+double test(double x) {
+  return sqrt(x);
+}
+
+// CHECK-LABEL: define{{.*}}@_Z4testd(
+// CHECK: call{{.*}}@_Z4sqrtd(
+// CHECK-NOT: llvm.sqrt
diff --git a/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp 
b/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
index 4b21e3a02b1d77..dcc0791391031a 100644
--- a/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
+++ b/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
@@ -32,6 +32,7 @@
 #include "llvm/IR/Module.h"
 #include "llvm/IR/PatternMatch.h"
 #include "llvm/IR/ProfDataUtils.h"
+#include "llvm/IR/VFABIDemangler.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/KnownBits.h"
@@ -4208,6 +4209,10 @@ Value 
*LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
   if (CI->isStrictFP())
     return nullptr;
 
+  // The mappings live on the callee declaration and an intrinsic call drops
+  // them.
+  bool HasVectorMappings = CI->hasFnAttr(VFABI::MappingsAttrName);
+
   if (Value *V = optimizeSymmetric(CI, Func, Builder))
     return V;
 
@@ -4220,12 +4225,12 @@ Value 
*LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
     return optimizeSinCosPi(CI, /*IsSin*/false, Builder);
   case LibFunc_sinf:
   case LibFunc_sinl:
-    if (CI->doesNotAccessMemory())
+    if (CI->doesNotAccessMemory() && !HasVectorMappings)
       return replaceUnaryCall(CI, Builder, Intrinsic::sin);
     return nullptr;
   case LibFunc_cosf:
   case LibFunc_cosl:
-    if (CI->doesNotAccessMemory())
+    if (CI->doesNotAccessMemory() && !HasVectorMappings)
       return replaceUnaryCall(CI, Builder, Intrinsic::cos);
     return nullptr;
   case LibFunc_powf:
@@ -4326,11 +4331,11 @@ Value 
*LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
     return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
   case LibFunc_sin:
   case LibFunc_cos:
-    if (UnsafeFPShrink &&
+    if (UnsafeFPShrink && !HasVectorMappings &&
         hasFloatVersion(M, CI->getCalledFunction()->getName()))
       if (Value *V = optimizeUnaryDoubleFP(CI, Builder, TLI, true))
         return V;
-    if (CI->doesNotAccessMemory())
+    if (CI->doesNotAccessMemory() && !HasVectorMappings)
       return replaceUnaryCall(
           CI, Builder, Func == LibFunc_sin ? Intrinsic::sin : Intrinsic::cos);
     return nullptr;
diff --git a/llvm/test/Transforms/InstCombine/vfabi-mapping.ll 
b/llvm/test/Transforms/InstCombine/vfabi-mapping.ll
new file mode 100644
index 00000000000000..6a72a0188cfa5c
--- /dev/null
+++ b/llvm/test/Transforms/InstCombine/vfabi-mapping.ll
@@ -0,0 +1,26 @@
+; RUN: opt -passes=instcombine -S < %s | FileCheck %s
+
+declare double @sin(double) #0
+declare double @cos(double) #1
+
+; The VFABI mapping is on the callee declaration, so the call has to stay a
+; call, otherwise the loop vectorizer cannot replace it with a vector variant.
+define double @mapped_sin(double %x) {
+; CHECK-LABEL: @mapped_sin(
+; CHECK-NEXT:    [[CALL:%.*]] = call double @sin(double %x)
+; CHECK-NEXT:    ret double [[CALL]]
+  %r = call double @sin(double %x)
+  ret double %r
+}
+
+; A call without a mapping is folded to the intrinsic as usual.
+define double @plain_cos(double %x) {
+; CHECK-LABEL: @plain_cos(
+; CHECK:         [[CALL:%.*]] = call double @llvm.cos.f64(double %x)
+; CHECK-NEXT:    ret double [[CALL]]
+  %r = call double @cos(double %x)
+  ret double %r
+}
+
+attributes #0 = { memory(none) 
"vector-function-abi-variant"="_ZGV_LLVM_N2v_sin(vector_sin)" }
+attributes #1 = { memory(none) }

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to