https://github.com/higher-performance created 
https://github.com/llvm/llvm-project/pull/241156

AI-generated fix for #78237.

>From 47cac2ceec37f2ef3e57a5f611b54e5effb28ed1 Mon Sep 17 00:00:00 2001
From: higher-performance <[email protected]>
Date: Wed, 11 Nov 2026 02:11:28 -0500
Subject: [PATCH] [clang] avoid __attribute__((target)) being mandated on
 always_inline functions when not necessary

---
 .../clang/Basic/DiagnosticFrontendKinds.td    |   2 +
 .../clang/CodeGenUtils/FunctionUtils.h        |  66 +++++-
 clang/lib/CodeGen/CGCall.cpp                  |   8 +-
 clang/lib/CodeGen/CodeGenFunction.cpp         |   6 +-
 clang/lib/CodeGen/CodeGenModule.cpp           |  61 +++--
 clang/lib/CodeGen/CodeGenModule.h             |  28 +++
 clang/lib/CodeGen/Targets/X86.cpp             | 108 ++++++---
 clang/lib/CodeGenUtils/FunctionUtils.cpp      | 215 ++++++++++++------
 .../target-features-always-inline.cpp         |  58 +++++
 9 files changed, 427 insertions(+), 125 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/target-features-always-inline.cpp

diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td 
b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index b51aa3ff0a0cb4..a941e79d7468e0 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -312,6 +312,8 @@ def err_builtin_needs_feature : Error<"%0 needs target 
feature %1">;
 def err_function_needs_feature : Error<
   "always_inline function %1 requires target feature '%2', but would "
   "be inlined into function %0 that is compiled without support for '%2'">;
+def note_function_needs_feature_call : Note<
+  "always_inline function %0 calls %1 here">;
 
 def err_flatten_function_needs_feature : Error<
   "flatten function %0 calls %1 which requires target feature '%2', but the "
diff --git a/clang/include/clang/CodeGenUtils/FunctionUtils.h 
b/clang/include/clang/CodeGenUtils/FunctionUtils.h
index 4e500aa8d3c0b6..48b2c517fdca39 100644
--- a/clang/include/clang/CodeGenUtils/FunctionUtils.h
+++ b/clang/include/clang/CodeGenUtils/FunctionUtils.h
@@ -17,6 +17,9 @@
 #include "clang/Basic/CodeGenOptions.h"
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceLocation.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringMap.h"
 
 namespace clang {
 class ASTContext;
@@ -31,19 +34,78 @@ namespace clang::CodeGenUtils {
 bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
                                const LangOptions &LangOpts);
 
+/// The target features that always_inline functions inherit from the
+/// always_inline functions they call.
+///
+/// An always_inline function that is only emitted where it is used has no
+/// code of its own that would have to run without the target features of a
+/// callee. Calling an always_inline function that needs more target features
+/// than it was declared with is therefore not an error. It then needs those
+/// features as well, as though it had been declared with them, and it is the
+/// functions it gets inlined into that have to provide them.
+class InheritedTargetFeatures {
+public:
+  /// Whether \p FD inherits the target features that its callees need.
+  static bool canInherit(ASTContext &Ctx, const FunctionDecl *FD);
+
+  /// Whether no function has inherited target features.
+  bool empty() const { return Inherited.empty(); }
+
+  /// Whether \p FD has inherited target features.
+  bool contains(const FunctionDecl *FD) const;
+
+  /// Enables the target features that \p FD has inherited in \p FeatureMap.
+  void addTo(ASTContext &Ctx, const FunctionDecl *FD,
+             llvm::StringMap<bool> &FeatureMap) const;
+
+  /// Records that \p Caller calls the always_inline function \p Callee at
+  /// \p Loc, and diagnoses the target features that the functions which the
+  /// code of \p Callee ends up in lack.
+  void addCall(ASTContext &Ctx, DiagnosticsEngine &Diags, SourceLocation Loc,
+               const FunctionDecl *Caller, const FunctionDecl *Callee);
+
+private:
+  struct CallSite {
+    const FunctionDecl *Caller;
+    SourceLocation Loc;
+  };
+
+  /// A call to an always_inline function whose target features have to be
+  /// provided by whichever function its code ends up in.
+  struct InlinedCall {
+    const FunctionDecl *Callee;
+    CallSite Site;
+  };
+
+  void require(ASTContext &Ctx, DiagnosticsEngine &Diags,
+               const FunctionDecl *Host, SourceLocation Loc, InlinedCall Call);
+
+  /// The calls to each always_inline function. They are needed once its body
+  /// shows which target features it inherits, which is usually after its
+  /// callers were emitted.
+  llvm::DenseMap<const FunctionDecl *, llvm::SmallVector<CallSite, 1>> CallsTo;
+
+  /// The calls whose callees each function inherits target features from.
+  llvm::DenseMap<const FunctionDecl *, llvm::SmallVector<InlinedCall, 1>>
+      Inherited;
+};
+
 /// Check that a call to a target-specific builtin has the required target
 /// features enabled in the caller, emitting an error diagnostic if not.
 /// \p Caller is the FunctionDecl of the enclosing function (may be null).
+/// Without \p Inherited, no function inherits target features.
 void checkTargetFeatures(ASTContext &Ctx, DiagnosticsEngine &Diags,
                          const LangOptions &LangOpts, const CallExpr *E,
                          const FunctionDecl *Caller,
-                         const FunctionDecl *TargetDecl);
+                         const FunctionDecl *TargetDecl,
+                         InheritedTargetFeatures *Inherited = nullptr);
 
 /// Overload taking a raw source location instead of a CallExpr.
 void checkTargetFeatures(ASTContext &Ctx, DiagnosticsEngine &Diags,
                          const LangOptions &LangOpts, SourceLocation Loc,
                          const FunctionDecl *Caller,
-                         const FunctionDecl *TargetDecl);
+                         const FunctionDecl *TargetDecl,
+                         InheritedTargetFeatures *Inherited = nullptr);
 
 } // namespace clang::CodeGenUtils
 
diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 1d7f9f742b87e9..e774cbb5c15fd3 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -5725,10 +5725,10 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo 
&CallInfo,
     // so only check in the case where we have both always_inline and target
     // since otherwise we could be making a conditional call after a check for
     // the proper cpu features (and it won't cause code generation issues due 
to
-    // function based code generation).
-    if ((TargetDecl->hasAttr<AlwaysInlineAttr>() &&
-         (TargetDecl->hasAttr<TargetAttr>() ||
-          (CurFuncDecl && CurFuncDecl->hasAttr<TargetAttr>()))) ||
+    // function based code generation). An always_inline callee is checked even
+    // without a target attribute, because it can inherit target features from
+    // the always_inline functions that it calls in turn.
+    if (TargetDecl->hasAttr<AlwaysInlineAttr>() ||
         (CurFuncDecl && CurFuncDecl->hasAttr<FlattenAttr>() &&
          (CurFuncDecl->hasAttr<TargetAttr>() ||
           TargetDecl->hasAttr<TargetAttr>())))
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index 33434526d86325..8d6af8d2bc0e8c 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -2914,7 +2914,8 @@ void CodeGenFunction::checkTargetFeatures(const CallExpr 
*E,
                                           const FunctionDecl *TargetDecl) {
   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
   CodeGenUtils::checkTargetFeatures(CGM.getContext(), CGM.getDiags(),
-                                    getLangOpts(), E, FD, TargetDecl);
+                                    getLangOpts(), E, FD, TargetDecl,
+                                    &CGM.getInheritedTargetFeatures());
 }
 
 // Emits an error if we don't have a valid set of target features for the
@@ -2923,7 +2924,8 @@ void CodeGenFunction::checkTargetFeatures(SourceLocation 
Loc,
                                           const FunctionDecl *TargetDecl) {
   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
   CodeGenUtils::checkTargetFeatures(CGM.getContext(), CGM.getDiags(),
-                                    getLangOpts(), Loc, FD, TargetDecl);
+                                    getLangOpts(), Loc, FD, TargetDecl,
+                                    &CGM.getInheritedTargetFeatures());
 }
 
 void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index bdfbdeb1059384..b87980e0134eef 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -1261,6 +1261,7 @@ void CodeGenModule::Release() {
   EmitGlobalAnnotations();
   EmitStaticExternCAliases();
   checkAliases();
+  finalizeInheritedTargetFeatures();
   EmitDeferredUnusedCoverageMappings();
   CodeGenPGO(*this).setValueProfilingFlag(getModule());
   CodeGenPGO(*this).setProfileVersion(getModule());
@@ -3509,9 +3510,10 @@ bool 
CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
   const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
   const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr;
   bool AddedAttr = false;
-  if (TD || TV || SD || TC) {
+  if (TD || TV || SD || TC || (FD && InheritedFeatures.contains(FD))) {
     llvm::StringMap<bool> FeatureMap;
     getContext().getFunctionFeatureMap(FeatureMap, GD);
+    InheritedFeatures.addTo(getContext(), FD, FeatureMap);
 
     // Now add the target-cpu and target-features to the function.
     // While we populated the feature map above, we still need to
@@ -3617,6 +3619,49 @@ bool 
CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
   return AddedAttr;
 }
 
+void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
+                                          const FunctionDecl *FD) {
+  getContext().getFunctionFeatureMap(FeatureMap, FD);
+  if (FD)
+    InheritedFeatures.addTo(getContext(), FD, FeatureMap);
+}
+
+void CodeGenModule::setCPUAndFeaturesAttributes(GlobalDecl GD,
+                                                llvm::Function *F) {
+  llvm::AttrBuilder Attrs(F->getContext());
+  if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
+    // We know that GetCPUAndFeaturesAttributes will always have the
+    // newest set, since it has the newest possible FunctionDecl, so the
+    // new ones should replace the old.
+    llvm::AttributeMask RemoveAttrs;
+    RemoveAttrs.addAttribute("target-cpu");
+    RemoveAttrs.addAttribute("target-features");
+    RemoveAttrs.addAttribute("fmv-features");
+    RemoveAttrs.addAttribute("tune-cpu");
+    F->removeFnAttrs(RemoveAttrs);
+    F->addFnAttrs(Attrs);
+  }
+}
+
+void CodeGenModule::finalizeInheritedTargetFeatures() {
+  // Functions got their attributes before their bodies, and those of their
+  // callees, showed what they inherit.
+  if (!InheritedFeatures.empty()) {
+    for (const auto &[GD, MangledName] : MangledDeclNames) {
+      const auto *FD = dyn_cast<FunctionDecl>(GD.getDecl());
+      if (!FD || !InheritedFeatures.contains(FD))
+        continue;
+      if (auto *F =
+              dyn_cast_or_null<llvm::Function>(GetGlobalValue(MangledName)))
+        setCPUAndFeaturesAttributes(GD, F);
+    }
+  }
+
+  for (llvm::unique_function<void()> &Check : DeferredTargetFeatureChecks)
+    Check();
+  DeferredTargetFeatureChecks.clear();
+}
+
 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
                                           llvm::GlobalObject *GO) {
   const Decl *D = GD.getDecl();
@@ -3643,19 +3688,7 @@ void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
         if (!D->getAttr<SectionAttr>())
           F->setSection(SA->getName());
 
-      llvm::AttrBuilder Attrs(F->getContext());
-      if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
-        // We know that GetCPUAndFeaturesAttributes will always have the
-        // newest set, since it has the newest possible FunctionDecl, so the
-        // new ones should replace the old.
-        llvm::AttributeMask RemoveAttrs;
-        RemoveAttrs.addAttribute("target-cpu");
-        RemoveAttrs.addAttribute("target-features");
-        RemoveAttrs.addAttribute("fmv-features");
-        RemoveAttrs.addAttribute("tune-cpu");
-        F->removeFnAttrs(RemoveAttrs);
-        F->addFnAttrs(Attrs);
-      }
+      setCPUAndFeaturesAttributes(GD, F);
     }
 
     if (const auto *CSA = D->getAttr<CodeSegAttr>())
diff --git a/clang/lib/CodeGen/CodeGenModule.h 
b/clang/lib/CodeGen/CodeGenModule.h
index e2bd6bc4701fda..74dc3760b15865 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -30,8 +30,10 @@
 #include "clang/Basic/StackExhaustionHandler.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/XRayLists.h"
+#include "clang/CodeGenUtils/FunctionUtils.h"
 #include "clang/Lex/PreprocessorOptions.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/FunctionExtras.h"
 #include "llvm/ADT/MapVector.h"
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/SmallPtrSet.h"
@@ -501,6 +503,13 @@ class CodeGenModule : public CodeGenTypeCache {
   llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
   llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
 
+  /// The target features that always_inline functions inherit from their
+  /// callees, which are not all known until every function is emitted.
+  CodeGenUtils::InheritedTargetFeatures InheritedFeatures;
+
+  /// Checks that depend on the target features that functions inherit.
+  std::vector<llvm::unique_function<void()>> DeferredTargetFeatureChecks;
+
   /// Global annotations.
   std::vector<llvm::Constant*> Annotations;
 
@@ -906,6 +915,20 @@ class CodeGenModule : public CodeGenTypeCache {
   const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
   llvm::Module &getModule() const { return TheModule; }
   DiagnosticsEngine &getDiags() const { return Diags; }
+
+  CodeGenUtils::InheritedTargetFeatures &getInheritedTargetFeatures() {
+    return InheritedFeatures;
+  }
+
+  /// Like ASTContext::getFunctionFeatureMap, but with the target features
+  /// that \p FD has inherited so far.
+  void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
+                             const FunctionDecl *FD);
+
+  /// Runs \p Check once the target features that functions inherit are final.
+  void addDeferredTargetFeatureCheck(llvm::unique_function<void()> Check) {
+    DeferredTargetFeatureChecks.push_back(std::move(Check));
+  }
   const llvm::DataLayout &getDataLayout() const {
     return TheModule.getDataLayout();
   }
@@ -2042,8 +2065,13 @@ class CodeGenModule : public CodeGenTypeCache {
   bool GetCPUAndFeaturesAttributes(GlobalDecl GD,
                                    llvm::AttrBuilder &AttrBuilder,
                                    bool SetTargetFeatures = true);
+  void setCPUAndFeaturesAttributes(GlobalDecl GD, llvm::Function *F);
   void setNonAliasAttributes(GlobalDecl GD, llvm::GlobalObject *GO);
 
+  /// Gives functions the target features that they inherited, and runs the
+  /// checks that were waiting for them.
+  void finalizeInheritedTargetFeatures();
+
   /// Set function attributes for a function declaration.
   void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
                              bool IsIncompleteFunction, bool IsThunk);
diff --git a/clang/lib/CodeGen/Targets/X86.cpp 
b/clang/lib/CodeGen/Targets/X86.cpp
index 5324c8d366b829..81a9e45864d06b 100644
--- a/clang/lib/CodeGen/Targets/X86.cpp
+++ b/clang/lib/CodeGen/Targets/X86.cpp
@@ -10,6 +10,7 @@
 #include "TargetInfo.h"
 #include "clang/Basic/DiagnosticFrontend.h"
 #include "clang/Basic/SourceLocation.h"
+#include "clang/CodeGenUtils/FunctionUtils.h"
 #include "llvm/ADT/SmallBitVector.h"
 
 using namespace clang;
@@ -1622,20 +1623,6 @@ class X86_64TargetCodeGenInfo : public TargetCodeGenInfo 
{
 };
 } // namespace
 
-static void initFeatureMaps(const ASTContext &Ctx,
-                            llvm::StringMap<bool> &CallerMap,
-                            const FunctionDecl *Caller,
-                            llvm::StringMap<bool> &CalleeMap,
-                            const FunctionDecl *Callee) {
-  if (CalleeMap.empty() && CallerMap.empty()) {
-    // The caller is potentially nullptr in the case where the call isn't in a
-    // function.  In this case, the getFunctionFeatureMap ensures we just get
-    // the TU level setting (since it cannot be modified by 'target'..
-    Ctx.getFunctionFeatureMap(CallerMap, Caller);
-    Ctx.getFunctionFeatureMap(CalleeMap, Callee);
-  }
-}
-
 static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
                                  SourceLocation CallLoc,
                                  const FunctionDecl &Callee,
@@ -1681,8 +1668,7 @@ static bool checkAVXParam(DiagnosticsEngine &Diag, 
ASTContext &Ctx,
   return false;
 }
 
-void X86_64TargetCodeGenInfo::checkFunctionABI(CodeGenModule &CGM,
-                                               const FunctionDecl *FD) const {
+static void checkAVXFunctionABI(CodeGenModule &CGM, const FunctionDecl *FD) {
   auto GetReturnTypeLoc = [](const FunctionDecl *FD) {
     if (const TypeSourceInfo *TSI = FD->getTypeSourceInfo()) {
       TypeLoc TL = TSI->getTypeLoc();
@@ -1711,7 +1697,7 @@ void 
X86_64TargetCodeGenInfo::checkFunctionABI(CodeGenModule &CGM,
         CGM.getContext().getTypeSize(Ty) > 256 ? "avx512f" : "avx";
 
     llvm::StringMap<bool> FeatureMap;
-    CGM.getContext().getFunctionFeatureMap(FeatureMap, FD);
+    CGM.getFunctionFeatureMap(FeatureMap, FD);
     if (!FeatureMap.lookup(Feature)) {
       CGM.getDiags().Report(Loc, diag::warn_avx_calling_convention)
           << !IsReturn << Ty << Feature;
@@ -1740,6 +1726,58 @@ void 
X86_64TargetCodeGenInfo::checkFunctionABI(CodeGenModule &CGM,
   }
 }
 
+void X86_64TargetCodeGenInfo::checkFunctionABI(CodeGenModule &CGM,
+                                               const FunctionDecl *FD) const {
+  // An always_inline function inherits the target features that its callees
+  // need, which are not all known until every function is emitted.
+  if (CodeGenUtils::InheritedTargetFeatures::canInherit(CGM.getContext(), FD))
+    CGM.addDeferredTargetFeatureCheck(
+        [&CGM, FD] { checkAVXFunctionABI(CGM, FD); });
+  else
+    checkAVXFunctionABI(CGM, FD);
+}
+
+// Diagnoses passing each of Vectors, a type paired with whether it is that of
+// an argument rather than of the return value, from Caller to Callee.
+static void checkAVXParams(CodeGenModule &CGM, SourceLocation CallLoc,
+                           const FunctionDecl *Caller,
+                           const FunctionDecl *Callee,
+                           SmallVector<std::pair<QualType, bool>, 2> Vectors,
+                           bool AreFeaturesFinal) {
+  ASTContext &Ctx = CGM.getContext();
+  llvm::StringMap<bool> CallerMap;
+  llvm::StringMap<bool> CalleeMap;
+  // The caller is potentially nullptr in the case where the call isn't in a
+  // function.  In this case, the getFunctionFeatureMap ensures we just get
+  // the TU level setting (since it cannot be modified by 'target'..
+  CGM.getFunctionFeatureMap(CallerMap, Caller);
+  CGM.getFunctionFeatureMap(CalleeMap, Callee);
+
+  // An always_inline function inherits the target features that its callees
+  // need, which are not all known until every function is emitted.
+  auto CanGainFeature = [&](const FunctionDecl *FD,
+                            const llvm::StringMap<bool> &FeatureMap) {
+    return FD && CodeGenUtils::InheritedTargetFeatures::canInherit(Ctx, FD) &&
+           llvm::any_of(Vectors, [&](const std::pair<QualType, bool> &Vector) {
+             return !FeatureMap.lookup(
+                 Ctx.getTypeSize(Vector.first) > 256 ? "avx512f" : "avx");
+           });
+  };
+  if (!AreFeaturesFinal && (CanGainFeature(Caller, CallerMap) ||
+                            CanGainFeature(Callee, CalleeMap))) {
+    CGM.addDeferredTargetFeatureCheck([=, &CGM] {
+      checkAVXParams(CGM, CallLoc, Caller, Callee, Vectors,
+                     /*AreFeaturesFinal=*/true);
+    });
+    return;
+  }
+
+  for (const auto &[Ty, IsArgument] : Vectors)
+    if (checkAVXParam(CGM.getDiags(), Ctx, CallLoc, *Callee, CallerMap,
+                      CalleeMap, Ty, IsArgument))
+      return;
+}
+
 void X86_64TargetCodeGenInfo::checkFunctionCallABI(CodeGenModule &CGM,
                                                    SourceLocation CallLoc,
                                                    const FunctionDecl *Caller,
@@ -1749,8 +1787,11 @@ void 
X86_64TargetCodeGenInfo::checkFunctionCallABI(CodeGenModule &CGM,
   if (!Callee)
     return;
 
-  llvm::StringMap<bool> CallerMap;
-  llvm::StringMap<bool> CalleeMap;
+  ASTContext &Ctx = CGM.getContext();
+  auto IsLargeVector = [&](QualType Ty) {
+    return Ty->isVectorType() && Ctx.getTypeSize(Ty) > 128;
+  };
+  SmallVector<std::pair<QualType, bool>, 2> Vectors;
   unsigned ArgIndex = 0;
 
   // We need to loop through the actual call arguments rather than the
@@ -1763,31 +1804,24 @@ void 
X86_64TargetCodeGenInfo::checkFunctionCallABI(CodeGenModule &CGM,
     // the caller and callee features are mismatched.
     // Unfortunately, we cannot do this diagnostic in SEMA, since the callee 
can
     // change its ABI with attribute-target after this call.
-    if (Arg.getType()->isVectorType() &&
-        CGM.getContext().getTypeSize(Arg.getType()) > 128) {
-      initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
-      QualType Ty = Arg.getType();
+    if (IsLargeVector(Arg.getType()))
       // The CallArg seems to have desugared the type already, so for clearer
       // diagnostics, replace it with the type in the FunctionDecl if possible.
-      if (ArgIndex < Callee->getNumParams())
-        Ty = Callee->getParamDecl(ArgIndex)->getType();
-
-      if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, *Callee,
-                        CallerMap, CalleeMap, Ty, /*IsArgument*/ true))
-        return;
-    }
+      Vectors.push_back({ArgIndex < Callee->getNumParams()
+                             ? Callee->getParamDecl(ArgIndex)->getType()
+                             : Arg.getType(),
+                         /*IsArgument=*/true});
     ++ArgIndex;
   }
 
   // Check return always, as we don't have a good way of knowing in codegen
   // whether this value is used, tail-called, etc.
-  if (Callee->getReturnType()->isVectorType() &&
-      CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
-    initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
-    checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, *Callee, 
CallerMap,
-                  CalleeMap, Callee->getReturnType(),
-                  /*IsArgument*/ false);
-  }
+  if (IsLargeVector(Callee->getReturnType()))
+    Vectors.push_back({Callee->getReturnType(), /*IsArgument=*/false});
+
+  if (!Vectors.empty())
+    checkAVXParams(CGM, CallLoc, Caller, Callee, std::move(Vectors),
+                   /*AreFeaturesFinal=*/false);
 }
 
 std::string TargetCodeGenInfo::qualifyWindowsLibrary(StringRef Lib) {
diff --git a/clang/lib/CodeGenUtils/FunctionUtils.cpp 
b/clang/lib/CodeGenUtils/FunctionUtils.cpp
index 083c04d30bec4c..efe3648fb8bf33 100644
--- a/clang/lib/CodeGenUtils/FunctionUtils.cpp
+++ b/clang/lib/CodeGenUtils/FunctionUtils.cpp
@@ -14,6 +14,7 @@
 #include "clang/Basic/DiagnosticFrontend.h"
 #include "clang/Basic/TargetBuiltins.h"
 #include "clang/Basic/TargetInfo.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringMap.h"
 
 namespace clang::CodeGenUtils {
@@ -39,7 +40,8 @@ bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
 void checkTargetFeatures(ASTContext &Ctx, DiagnosticsEngine &Diags,
                          const LangOptions &LangOpts, const CallExpr *E,
                          const FunctionDecl *Caller,
-                         const FunctionDecl *TargetDecl) {
+                         const FunctionDecl *TargetDecl,
+                         InheritedTargetFeatures *Inherited) {
   // SemaChecking cannot handle these x86 builtins because they have different
   // parameter ranges depending on the caller's TargetAttribute.
   if (Ctx.getTargetInfo().getTriple().isX86()) {
@@ -57,47 +59,26 @@ void checkTargetFeatures(ASTContext &Ctx, DiagnosticsEngine 
&Diags,
     }
   }
   checkTargetFeatures(Ctx, Diags, LangOpts, E->getBeginLoc(), Caller,
-                      TargetDecl);
+                      TargetDecl, Inherited);
 }
 
-// Emits an error if we don't have a valid set of target features for the
-// called function.
-void checkTargetFeatures(ASTContext &Ctx, DiagnosticsEngine &Diags,
-                         const LangOptions &LangOpts, SourceLocation Loc,
-                         const FunctionDecl *Caller,
-                         const FunctionDecl *TargetDecl) {
-  if (!TargetDecl || !Caller)
-    return;
-
-  bool IsAlwaysInline = TargetDecl->hasAttr<AlwaysInlineAttr>();
-  bool IsFlatten = Caller->hasAttr<FlattenAttr>();
-
-  unsigned BuiltinID = TargetDecl->getBuiltinID();
-  std::string MissingFeature;
+// Returns the target features that the code of TargetDecl relies on and that
+// Caller lacks.
+static SmallVector<std::string, 1>
+getMissingFeatures(ASTContext &Ctx, const FunctionDecl *Caller,
+                   const FunctionDecl *TargetDecl) {
+  SmallVector<std::string, 1> Missing;
   llvm::StringMap<bool> CallerFeatureMap;
-  Ctx.getFunctionFeatureMap(CallerFeatureMap, Caller);
-  // When compiling in HipStdPar mode we have to be conservative in rejecting
-  // target specific features in the FE, and defer the possible error to the
-  // AcceleratorCodeSelection pass, wherein iff an unsupported target builtin 
is
-  // referenced by an accelerator executable function, we emit an error.
-  bool IsHipStdPar = LangOpts.HIPStdPar && LangOpts.CUDAIsDevice;
-  if (BuiltinID) {
-    StringRef FeatureList(Ctx.BuiltinInfo.getRequiredFeatures(BuiltinID));
-    if (!Builtin::evaluateRequiredTargetFeatures(FeatureList,
-                                                 CallerFeatureMap) &&
-        !IsHipStdPar)
-      Diags.Report(Loc, diag::err_builtin_needs_feature)
-          << TargetDecl->getDeclName() << FeatureList;
-  } else if (!TargetDecl->isMultiVersion() &&
-             TargetDecl->hasAttr<TargetAttr>()) {
+  llvm::StringMap<bool> CalleeFeatureMap;
+  if (!TargetDecl->isMultiVersion() && TargetDecl->hasAttr<TargetAttr>()) {
+    Ctx.getFunctionFeatureMap(CallerFeatureMap, Caller);
+    Ctx.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
+
     // Get the required features for the callee.
     const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
     ParsedTargetAttr ParsedAttr = Ctx.filterFunctionTargetAttrs(TD);
 
     SmallVector<StringRef, 1> ReqFeatures;
-    llvm::StringMap<bool> CalleeFeatureMap;
-    Ctx.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
-
     for (const auto &F : ParsedAttr.Features) {
       if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
         ReqFeatures.push_back(StringRef(F).substr(1));
@@ -106,44 +87,146 @@ void checkTargetFeatures(ASTContext &Ctx, 
DiagnosticsEngine &Diags,
       if (F.getValue())
         ReqFeatures.push_back(F.getKey());
     }
-    if (!llvm::all_of(ReqFeatures,
-                      [&](StringRef Feature) {
-                        if (!CallerFeatureMap.lookup(Feature)) {
-                          MissingFeature = Feature.str();
-                          return false;
-                        }
-                        return true;
-                      }) &&
-        !IsHipStdPar) {
-      if (IsAlwaysInline)
-        Diags.Report(Loc, diag::err_function_needs_feature)
-            << Caller->getDeclName() << TargetDecl->getDeclName()
-            << MissingFeature;
-      else if (IsFlatten)
-        Diags.Report(Loc, diag::err_flatten_function_needs_feature)
-            << Caller->getDeclName() << TargetDecl->getDeclName()
-            << MissingFeature;
-    }
+    auto It = llvm::find_if(ReqFeatures, [&](StringRef Feature) {
+      return !CallerFeatureMap.lookup(Feature);
+    });
+    if (It != ReqFeatures.end())
+      Missing.push_back(It->str());
   } else if (!Caller->isMultiVersion() && Caller->hasAttr<TargetAttr>()) {
-    llvm::StringMap<bool> CalleeFeatureMap;
+    Ctx.getFunctionFeatureMap(CallerFeatureMap, Caller);
     Ctx.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
 
     for (const auto &F : CalleeFeatureMap) {
-      if (F.getValue() &&
-          (!CallerFeatureMap.lookup(F.getKey()) ||
-           !CallerFeatureMap.find(F.getKey())->getValue()) &&
-          !IsHipStdPar) {
-        if (IsAlwaysInline)
-          Diags.Report(Loc, diag::err_function_needs_feature)
-              << Caller->getDeclName() << TargetDecl->getDeclName()
-              << F.getKey();
-        else if (IsFlatten)
-          Diags.Report(Loc, diag::err_flatten_function_needs_feature)
-              << Caller->getDeclName() << TargetDecl->getDeclName()
-              << F.getKey();
-      }
+      if (F.getValue() && !CallerFeatureMap.lookup(F.getKey()))
+        Missing.push_back(F.getKey().str());
     }
   }
+  return Missing;
+}
+
+static void reportMissingFeatures(DiagnosticsEngine &Diags, unsigned DiagID,
+                                  SourceLocation Loc,
+                                  const FunctionDecl *Caller,
+                                  const FunctionDecl *TargetDecl,
+                                  ArrayRef<std::string> Missing) {
+  for (const std::string &Feature : Missing)
+    Diags.Report(Loc, DiagID)
+        << Caller->getDeclName() << TargetDecl->getDeclName() << Feature;
+}
+
+bool InheritedTargetFeatures::canInherit(ASTContext &Ctx,
+                                         const FunctionDecl *FD) {
+  // A function that is emitted even when unused has callers that are not
+  // known here, which could not provide the features that it would inherit.
+  return FD->hasAttr<AlwaysInlineAttr>() && !FD->isMultiVersion() &&
+         !Ctx.DeclMustBeEmitted(FD);
+}
+
+bool InheritedTargetFeatures::contains(const FunctionDecl *FD) const {
+  return Inherited.contains(FD->getCanonicalDecl());
+}
+
+void InheritedTargetFeatures::addTo(ASTContext &Ctx, const FunctionDecl *FD,
+                                    llvm::StringMap<bool> &FeatureMap) const {
+  auto Calls = Inherited.find(FD->getCanonicalDecl());
+  if (Calls == Inherited.end())
+    return;
+
+  for (const InlinedCall &Call : Calls->second) {
+    llvm::StringMap<bool> CalleeFeatureMap;
+    Ctx.getFunctionFeatureMap(CalleeFeatureMap, Call.Callee);
+    for (const auto &F : CalleeFeatureMap) {
+      if (F.getValue())
+        FeatureMap[F.getKey()] = true;
+    }
+  }
+}
+
+void InheritedTargetFeatures::addCall(ASTContext &Ctx, DiagnosticsEngine 
&Diags,
+                                      SourceLocation Loc,
+                                      const FunctionDecl *Caller,
+                                      const FunctionDecl *Callee) {
+  require(Ctx, Diags, Caller, Loc, {Callee, {Caller, Loc}});
+
+  // This iterates over a copy, because require() can add to Inherited.
+  for (const InlinedCall &Call : Inherited.lookup(Callee->getCanonicalDecl()))
+    require(Ctx, Diags, Caller, Loc, Call);
+
+  CallsTo[Callee->getCanonicalDecl()].push_back({Caller, Loc});
+}
+
+// Makes Host, which gets the code of the callee of Call through its call at
+// Loc, provide the target features that this code relies on.
+void InheritedTargetFeatures::require(ASTContext &Ctx, DiagnosticsEngine 
&Diags,
+                                      const FunctionDecl *Host,
+                                      SourceLocation Loc, InlinedCall Call) {
+  SmallVector<std::string, 1> Missing =
+      getMissingFeatures(Ctx, Host, Call.Callee);
+  if (Missing.empty())
+    return;
+
+  if (!canInherit(Ctx, Host)) {
+    reportMissingFeatures(Diags, diag::err_function_needs_feature, Loc, Host,
+                          Call.Callee, Missing);
+    if (Call.Site.Caller != Host)
+      Diags.Report(Call.Site.Loc, diag::note_function_needs_feature_call)
+          << Call.Site.Caller->getDeclName() << Call.Callee->getDeclName();
+    return;
+  }
+
+  SmallVectorImpl<InlinedCall> &Calls = Inherited[Host->getCanonicalDecl()];
+  // This also ends the recursion below for functions that call each other.
+  if (llvm::any_of(Calls, [&](const InlinedCall &Other) {
+        return declaresSameEntity(Other.Callee, Call.Callee);
+      }))
+    return;
+  Calls.push_back(Call);
+
+  auto Callers = CallsTo.find(Host->getCanonicalDecl());
+  if (Callers == CallsTo.end())
+    return;
+  for (const CallSite &Site : Callers->second)
+    require(Ctx, Diags, Site.Caller, Site.Loc, Call);
+}
+
+// Emits an error if we don't have a valid set of target features for the
+// called function.
+void checkTargetFeatures(ASTContext &Ctx, DiagnosticsEngine &Diags,
+                         const LangOptions &LangOpts, SourceLocation Loc,
+                         const FunctionDecl *Caller,
+                         const FunctionDecl *TargetDecl,
+                         InheritedTargetFeatures *Inherited) {
+  if (!TargetDecl || !Caller)
+    return;
+
+  // When compiling in HipStdPar mode we have to be conservative in rejecting
+  // target specific features in the FE, and defer the possible error to the
+  // AcceleratorCodeSelection pass, wherein iff an unsupported target builtin 
is
+  // referenced by an accelerator executable function, we emit an error.
+  if (LangOpts.HIPStdPar && LangOpts.CUDAIsDevice)
+    return;
+
+  if (unsigned BuiltinID = TargetDecl->getBuiltinID()) {
+    StringRef FeatureList(Ctx.BuiltinInfo.getRequiredFeatures(BuiltinID));
+    if (FeatureList.empty())
+      return;
+
+    llvm::StringMap<bool> CallerFeatureMap;
+    Ctx.getFunctionFeatureMap(CallerFeatureMap, Caller);
+    if (!Builtin::evaluateRequiredTargetFeatures(FeatureList, 
CallerFeatureMap))
+      Diags.Report(Loc, diag::err_builtin_needs_feature)
+          << TargetDecl->getDeclName() << FeatureList;
+  } else if (TargetDecl->hasAttr<AlwaysInlineAttr>() && Inherited) {
+    Inherited->addCall(Ctx, Diags, Loc, Caller, TargetDecl);
+  } else if (TargetDecl->hasAttr<AlwaysInlineAttr>()) {
+    reportMissingFeatures(Diags, diag::err_function_needs_feature, Loc, Caller,
+                          TargetDecl,
+                          getMissingFeatures(Ctx, Caller, TargetDecl));
+  } else if (Caller->hasAttr<FlattenAttr>()) {
+    reportMissingFeatures(Diags, diag::err_flatten_function_needs_feature, Loc,
+                          Caller, TargetDecl,
+                          getMissingFeatures(Ctx, Caller, TargetDecl));
+  }
 }
 
 } // namespace clang::CodeGenUtils
diff --git a/clang/test/CodeGenCXX/target-features-always-inline.cpp 
b/clang/test/CodeGenCXX/target-features-always-inline.cpp
new file mode 100644
index 00000000000000..109afd98bbc4b6
--- /dev/null
+++ b/clang/test/CodeGenCXX/target-features-always-inline.cpp
@@ -0,0 +1,58 @@
+// REQUIRES: x86-registered-target
+// RUN: %clang_cc1 %s -triple=x86_64-linux-gnu -emit-llvm -o - -verify=ok | 
FileCheck %s
+// RUN: %clang_cc1 %s -triple=x86_64-linux-gnu -emit-llvm -o - -verify=ok 
-disable-llvm-passes | FileCheck %s --check-prefix=ATTRS
+// RUN: %clang_cc1 %s -triple=x86_64-linux-gnu -emit-llvm -o /dev/null -verify 
-DLACKS_FEATURE
+// RUN: %clang_cc1 %s -triple=x86_64-linux-gnu -emit-llvm -o /dev/null 
-verify=external -DEXTERNAL
+// RUN: %clang_cc1 %s -triple=x86_64-linux-gnu -emit-llvm -o /dev/null 
-verify=abi -DABI
+
+// ok-no-diagnostics
+
+typedef long long avx_vector __attribute__((vector_size(32)));
+
+template <class T> [[gnu::always_inline, gnu::target("avx")]] T needs_avx() { 
return T(); }
+
+// A template cannot name the target features of each of its instantiations, so
+// an always_inline function takes on those that its always_inline callees 
need.
+template <class T> [[gnu::always_inline]] T wrapper() { return needs_avx<T>(); 
} // #wrapper
+template <class T> [[gnu::always_inline]] T outer_wrapper() { return 
wrapper<T>(); }
+[[gnu::always_inline]] inline int inline_wrapper() { return needs_avx<int>(); 
} // #inline-wrapper
+
+// CHECK-LABEL: define {{.*}} @_Z7has_avxv(
+// CHECK-NOT: call {{.*}} @_Z
+// CHECK: ret
+// ATTRS: define linkonce_odr {{.*}} @_Z13outer_wrapperI{{.*}}#[[OUTER:[0-9]+]]
+// ATTRS: attributes #[[OUTER]] = { 
{{.*}}"target-features"="{{[^"]*}}+avx{{[,"]}}
+[[gnu::target("avx")]] avx_vector has_avx() { return 
outer_wrapper<avx_vector>(); }
+[[gnu::target("avx")]] int has_avx_too() { return inline_wrapper(); }
+
+#ifdef LACKS_FEATURE
+// The wrappers are emitted after this caller.
+// expected-note@#wrapper {{always_inline function 'wrapper' calls 'needs_avx' 
here}}
+int lacks_avx() { return outer_wrapper<int>(); } // expected-error 
{{always_inline function 'needs_avx' requires target feature 'avx', but would 
be inlined into function 'lacks_avx' that is compiled without support for 
'avx'}}
+
+// The wrapper is emitted before this caller.
+// expected-note@#inline-wrapper {{always_inline function 'inline_wrapper' 
calls 'needs_avx' here}}
+inline int inline_lacks_avx() { return inline_wrapper(); } // expected-error 
{{always_inline function 'needs_avx' requires target feature 'avx', but would 
be inlined into function 'inline_lacks_avx' that is compiled without support 
for 'avx'}}
+int use_inline_lacks_avx() { return inline_lacks_avx(); }
+#endif
+
+#ifdef EXTERNAL
+// This is emitted even when unused, for callers that cannot be checked here.
+[[gnu::always_inline]] int external_wrapper() { return needs_avx<int>(); } // 
external-error {{always_inline function 'needs_avx' requires target feature 
'avx', but would be inlined into function 'external_wrapper' that is compiled 
without support for 'avx'}}
+#endif
+
+#ifdef ABI
+// An inherited target feature changes how vectors are passed, just like a
+// declared one.
+avx_vector lacks_avx_abi(avx_vector);
+// abi-error@+1 {{AVX vector argument of type 'avx_vector' (vector of 4 'long 
long' values) without 'avx' enabled changes the ABI}}
+template <class T> [[gnu::always_inline]] T abi_wrapper() { return 
lacks_avx_abi(needs_avx<T>()); }
+[[gnu::target("avx")]] avx_vector has_avx_abi() { return 
abi_wrapper<avx_vector>(); }
+
+// Nothing is inherited here, so this is diagnosed as it would be otherwise.
+// abi-warning@+2 {{AVX vector return of type 'avx_vector' (vector of 4 'long 
long' values) without 'avx' enabled changes the ABI}}
+// abi-warning@+1 {{AVX vector argument of type 'avx_vector' (vector of 4 
'long long' values) without 'avx' enabled changes the ABI}}
+[[gnu::always_inline]] inline avx_vector identity(avx_vector v) { return v; }
+// abi-error@+1 {{AVX vector argument of type 'avx_vector' (vector of 4 'long 
long' values) without 'avx' enabled changes the ABI}}
+[[gnu::target("avx")]] avx_vector calls_identity(avx_vector v) { return 
identity(v); }
+#endif

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

Reply via email to