Skip to content

Conversation

@stmuench
Copy link
Contributor

@stmuench stmuench commented Mar 25, 2025

So far, the clang-tidy check modernize-avoid-c-arrays also diagnosed array types for type template parameters even though no actual array type got written there but it got deduced to one. In such case, there is nothing a developer can do at that location to fix the diagnostic. Since in this case, the location where the template got actually instantiated would have to be adjusted. And this is in most cases some totally distant code where implementers of a template do not have access to. Also adding suppressions to the declaration of the template is not an option since that would clutter the code unnecessarily and is in many cases also simply not possible (e.g. for users of a template). Hence, we propose to not diagnose any occurrence of an array type in an implicit instantiation of a template but rather at the point where template arguments involve array types.

@github-actions
Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@stmuench stmuench force-pushed the sm_revise_avoid_c_arrays_check branch 2 times, most recently from 823475c to 8b720d2 Compare March 25, 2025 18:11
@stmuench stmuench marked this pull request as ready for review March 25, 2025 18:12
@llvmbot
Copy link
Member

llvmbot commented Mar 25, 2025

@llvm/pr-subscribers-clang-tools-extra

Author: St. Muench (stmuench)

Changes

So far, the clang-tidy check modernize-avoid-c-arrays also diagnosed array types for type template parameters even though no actual array type got written there but it got deduced to one. In such case, there is nothing a developer can do at that location to fix the diagnostic. Since actually, the location where the template got instantiated would have to be adjusted. And this is in most cases some totally distant code where implementers of a template do not have access to. Also adding suppressions to the declaration of the template is not an option since that would clutter the code unnecessarily and is in many cases also simply not possible. Hence, we propose to not diagnose any occurrence of an array type in an implicit instantiation of a template but rather at the point where template arguments involve array types.


Full diff: https://github.com/llvm/llvm-project/pull/132924.diff

3 Files Affected:

  • (modified) clang-tools-extra/clang-tidy/modernize/AvoidCArraysCheck.cpp (+56-4)
  • (modified) clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays-ignores-strings.cpp (+12)
  • (modified) clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays.cpp (+159)
diff --git a/clang-tools-extra/clang-tidy/modernize/AvoidCArraysCheck.cpp b/clang-tools-extra/clang-tidy/modernize/AvoidCArraysCheck.cpp
index 0804aa76d953c..e26b8cf885ea3 100644
--- a/clang-tools-extra/clang-tidy/modernize/AvoidCArraysCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/AvoidCArraysCheck.cpp
@@ -39,6 +39,30 @@ AST_MATCHER(clang::ParmVarDecl, isArgvOfMain) {
   return FD ? FD->isMain() : false;
 }
 
+bool isWithinImplicitTemplateInstantiation(const TypeLoc *ArrayType,
+                                           ASTContext *Context) {
+  const auto IsImplicitTemplateInstantiation = [](const auto *Node) {
+    return (Node != nullptr) &&
+           (Node->getTemplateSpecializationKind() == TSK_ImplicitInstantiation);
+  };
+
+  auto ParentNodes = Context->getParents(*ArrayType);
+  while (!ParentNodes.empty()) {
+    const auto &ParentNode = ParentNodes[0];
+    if (IsImplicitTemplateInstantiation(
+            ParentNode.template get<clang::CXXRecordDecl>()) ||
+        IsImplicitTemplateInstantiation(
+            ParentNode.template get<clang::FunctionDecl>()) ||
+        IsImplicitTemplateInstantiation(
+            ParentNode.template get<clang::VarDecl>())) {
+      return true;
+    }
+    ParentNodes = Context->getParents(ParentNode);
+  }
+
+  return false;
+}
+
 } // namespace
 
 AvoidCArraysCheck::AvoidCArraysCheck(StringRef Name, ClangTidyContext *Context)
@@ -70,18 +94,45 @@ void AvoidCArraysCheck::registerMatchers(MatchFinder *Finder) {
               std::move(IgnoreStringArrayIfNeededMatcher))
           .bind("typeloc"),
       this);
+
+  Finder->addMatcher(templateArgumentLoc(hasTypeLoc(
+                         loc(arrayType()).bind("typeloc_in_template_arg"))),
+                     this);
 }
 
 void AvoidCArraysCheck::check(const MatchFinder::MatchResult &Result) {
-  const auto *ArrayType = Result.Nodes.getNodeAs<TypeLoc>("typeloc");
+  clang::TypeLoc ArrayTypeLoc{};
+
+  if (const auto *ArrayType = Result.Nodes.getNodeAs<TypeLoc>("typeloc");
+      ArrayType != nullptr &&
+      not(isWithinImplicitTemplateInstantiation(ArrayType, Result.Context))) {
+    ArrayTypeLoc = *ArrayType;
+  }
+
+  if (const auto *ArrayTypeInTemplateArg =
+          Result.Nodes.getNodeAs<TypeLoc>("typeloc_in_template_arg");
+      ArrayTypeInTemplateArg != nullptr) {
+    if (ArrayTypeInTemplateArg->getSourceRange() !=
+        ArrayTypeInTemplateArg->getLocalSourceRange()) {
+      // only in case the above condition is fulfilled, we matched a written
+      // array type and not a template type parameter which got deduced to one
+      ArrayTypeLoc = *ArrayTypeInTemplateArg;
+    }
+  }
+
+  // check whether the match result is a real array type (based on above checks)
+  if (ArrayTypeLoc.isNull()) {
+    return;
+  }
+
   const bool IsInParam =
       Result.Nodes.getNodeAs<ParmVarDecl>("param_decl") != nullptr;
-  const bool IsVLA = ArrayType->getTypePtr()->isVariableArrayType();
+  const bool IsVLA = ArrayTypeLoc.getTypePtr()->isVariableArrayType();
   enum class RecommendType { Array, Vector, Span };
   llvm::SmallVector<const char *> RecommendTypes{};
   if (IsVLA) {
     RecommendTypes.push_back("'std::vector'");
-  } else if (ArrayType->getTypePtr()->isIncompleteArrayType() && IsInParam) {
+  } else if (ArrayTypeLoc.getTypePtr()->isIncompleteArrayType() && IsInParam) {
     // in function parameter, we also don't know the size of
     // IncompleteArrayType.
     if (Result.Context->getLangOpts().CPlusPlus20)
@@ -93,7 +144,8 @@ void AvoidCArraysCheck::check(const MatchFinder::MatchResult &Result) {
   } else {
     RecommendTypes.push_back("'std::array'");
   }
-  diag(ArrayType->getBeginLoc(),
+
+  diag(ArrayTypeLoc.getBeginLoc(),
        "do not declare %select{C-style|C VLA}0 arrays, use %1 instead")
       << IsVLA << llvm::join(RecommendTypes, " or ");
 }
diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays-ignores-strings.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays-ignores-strings.cpp
index 906663828a547..18458bd47d347 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays-ignores-strings.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays-ignores-strings.cpp
@@ -7,3 +7,15 @@ const char array[] = {'n', 'a', 'm', 'e', '\0'};
 
 void takeCharArray(const char name[]);
 // CHECK-MESSAGES: :[[@LINE-1]]:26: warning: do not declare C-style arrays, use 'std::array' or 'std::vector' instead [modernize-avoid-c-arrays]
+
+template <typename T = const char[10], typename U = char[10], char[10]>
+// CHECK-MESSAGES: :[[@LINE-1]]:30: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+// CHECK-MESSAGES: :[[@LINE-2]]:53: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+// CHECK-MESSAGES: :[[@LINE-3]]:63: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+void func() {}
+
+template <typename T = const char[], typename U = char[], char[]>
+// CHECK-MESSAGES: :[[@LINE-1]]:30: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+// CHECK-MESSAGES: :[[@LINE-2]]:51: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+// CHECK-MESSAGES: :[[@LINE-3]]:59: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+void fun() {}
diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays.cpp
index 14eb2852c639a..0b474cc69db36 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays.cpp
@@ -92,3 +92,162 @@ const char name[] = "Some string";
 
 void takeCharArray(const char name[]);
 // CHECK-MESSAGES: :[[@LINE-1]]:26: warning: do not declare C-style arrays, use 'std::array' or 'std::vector' instead [modernize-avoid-c-arrays]
+
+namespace std {
+  template<class T, class U>
+  struct is_same { constexpr static bool value{false}; };
+
+  template<class T>
+  struct is_same<T, T> { constexpr static bool value{true}; };
+
+  template<class T, class U>
+  constexpr bool is_same_v = is_same<T, U>::value;
+
+  template<class T> struct remove_const { typedef T type; };
+  template<class T> struct remove_const<const T> { typedef T type; };
+
+  template<class T>
+  using remove_const_t = typename remove_const<T>::type;
+
+  template<bool B, class T = void> struct enable_if {};
+  template<class T> struct enable_if<true, T> { typedef T type; };
+
+  template< bool B, class T = void >
+  using enable_if_t = typename enable_if<B, T>::type;
+}
+
+// below, no array type findings are expected within the template parameter declarations since no array type gets written explicitly
+template <typename T,
+          bool = std::is_same_v<T, int>,
+          bool = std::is_same<T, int>::value,
+          bool = std::is_same_v<std::remove_const_t<T>, int>,
+          bool = std::is_same<std::remove_const_t<T>, int>::value,
+          bool = std::is_same_v<typename std::remove_const<T>::type, int>,
+          bool = std::is_same<typename std::remove_const<T>::type, int>::value,
+          std::enable_if_t<not(std::is_same_v<std::remove_const_t<T>, int>) && not(std::is_same_v<typename std::remove_const<T>::type, char>), bool> = true,
+          typename std::enable_if<not(std::is_same_v<std::remove_const_t<T>, int>) && not(std::is_same_v<typename std::remove_const<T>::type, char>), bool>::type = true,
+          typename = std::enable_if_t<not(std::is_same_v<std::remove_const_t<T>, int>) && not(std::is_same_v<typename std::remove_const<T>::type, char>)>,
+          typename = typename std::remove_const<T>::type,
+          typename = std::remove_const_t<T>>
+class MyClassTemplate {
+ public:
+  // here, plenty of array type findings are expected for below template parameter declarations since array types get written explicitly
+  template <typename U = T,
+            bool = std::is_same_v<U, int[]>,
+            // CHECK-MESSAGES: :[[@LINE-1]]:38: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+            bool = std::is_same<U, int[10]>::value,
+            // CHECK-MESSAGES: :[[@LINE-1]]:36: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+            std::enable_if_t<not(std::is_same_v<std::remove_const_t<U>, int[]>) && not(std::is_same_v<typename std::remove_const<U>::type, char[10]>), bool> = true,
+            // CHECK-MESSAGES: :[[@LINE-1]]:73: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+            // CHECK-MESSAGES: :[[@LINE-2]]:140: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+            typename = typename std::remove_const<int[10]>::type,
+            // CHECK-MESSAGES: :[[@LINE-1]]:51: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+            typename = std::remove_const_t<int[]>>
+            // CHECK-MESSAGES: :[[@LINE-1]]:44: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+    class MyInnerClassTemplate {
+     public:
+      MyInnerClassTemplate(const U&) {}
+     private:
+      U field[3];
+      // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+    };
+
+    MyClassTemplate(const T&) {}
+
+ private:
+    T field[7];
+    // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+};
+
+// an explicit instantiation
+template
+class MyClassTemplate<int[2]>;
+// CHECK-MESSAGES: :[[@LINE-1]]:23: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+
+using MyArrayType = int[3];
+// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+
+// another explicit instantiation
+template
+class MyClassTemplate<MyArrayType>;
+
+// below, no array type findings are expected within the template parameter declarations since no array type gets written explicitly
+template <typename T,
+          bool = std::is_same_v<T, int>,
+          bool = std::is_same<T, int>::value,
+          bool = std::is_same_v<std::remove_const_t<T>, int>,
+          bool = std::is_same<std::remove_const_t<T>, int>::value,
+          bool = std::is_same_v<typename std::remove_const<T>::type, int>,
+          bool = std::is_same<typename std::remove_const<T>::type, int>::value,
+          std::enable_if_t<not(std::is_same_v<std::remove_const_t<T>, int>) && not(std::is_same_v<typename std::remove_const<T>::type, char>), bool> = true,
+          typename std::enable_if<not(std::is_same_v<std::remove_const_t<T>, int>) && not(std::is_same_v<typename std::remove_const<T>::type, char>), bool>::type = true,
+          typename = std::enable_if_t<not(std::is_same_v<std::remove_const_t<T>, int>) && not(std::is_same_v<typename std::remove_const<T>::type, char>)>,
+          typename = typename std::remove_const<T>::type,
+          typename = std::remove_const_t<T>>
+void func(const T& param) {
+  int array1[1];
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+
+  T array2[2];
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+
+  T value;
+}
+
+// here, plenty of array type findings are expected for below template parameter declarations since array types get written explicitly
+template <typename T = int[],
+          // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+          bool = std::is_same_v<T, int[]>,
+          // CHECK-MESSAGES: :[[@LINE-1]]:36: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+          bool = std::is_same<T, int[10]>::value,
+          // CHECK-MESSAGES: :[[@LINE-1]]:34: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+          std::enable_if_t<not(std::is_same_v<std::remove_const_t<T>, int[]>) && not(std::is_same_v<typename std::remove_const<T>::type, char[10]>), bool> = true,
+          // CHECK-MESSAGES: :[[@LINE-1]]:71: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+          // CHECK-MESSAGES: :[[@LINE-2]]:138: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+          typename = typename std::remove_const<int[10]>::type,
+          // CHECK-MESSAGES: :[[@LINE-1]]:49: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+          typename = std::remove_const_t<int[]>>
+          // CHECK-MESSAGES: :[[@LINE-1]]:42: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+void fun(const T& param) {
+  int array3[3];
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+
+  T array4[4];
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+
+  T value;
+}
+
+template<typename T>
+T some_constant{};
+
+// explicit instantiation
+template
+int some_constant<int[5]>[5];
+// FIXME: why no diagnostics here?
+
+// explicit specialization
+template<>
+int some_constant<int[7]>[7]{};
+// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+// CHECK-MESSAGES: :[[@LINE-2]]:19: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+
+void testArrayInTemplateType() {
+  int t[10];
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+
+  func(t);
+  fun(t);
+
+  func<decltype(t)>({});
+  fun<decltype(t)>({});
+
+  MyClassTemplate var1{t};
+  MyClassTemplate<decltype(t)> var2{{}};
+
+  decltype(var1)::MyInnerClassTemplate var3{t};
+  decltype(var1)::MyInnerClassTemplate<decltype(t)> var4{{}};
+
+  MyClassTemplate<decltype(t)>::MyInnerClassTemplate var5{t};
+  MyClassTemplate<decltype(t)>::MyInnerClassTemplate<decltype(t)> var6{{}};
+}

@llvmbot
Copy link
Member

llvmbot commented Mar 25, 2025

@llvm/pr-subscribers-clang-tidy

Author: St. Muench (stmuench)

Changes

So far, the clang-tidy check modernize-avoid-c-arrays also diagnosed array types for type template parameters even though no actual array type got written there but it got deduced to one. In such case, there is nothing a developer can do at that location to fix the diagnostic. Since actually, the location where the template got instantiated would have to be adjusted. And this is in most cases some totally distant code where implementers of a template do not have access to. Also adding suppressions to the declaration of the template is not an option since that would clutter the code unnecessarily and is in many cases also simply not possible. Hence, we propose to not diagnose any occurrence of an array type in an implicit instantiation of a template but rather at the point where template arguments involve array types.


Full diff: https://github.com/llvm/llvm-project/pull/132924.diff

3 Files Affected:

  • (modified) clang-tools-extra/clang-tidy/modernize/AvoidCArraysCheck.cpp (+56-4)
  • (modified) clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays-ignores-strings.cpp (+12)
  • (modified) clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays.cpp (+159)
diff --git a/clang-tools-extra/clang-tidy/modernize/AvoidCArraysCheck.cpp b/clang-tools-extra/clang-tidy/modernize/AvoidCArraysCheck.cpp
index 0804aa76d953c..e26b8cf885ea3 100644
--- a/clang-tools-extra/clang-tidy/modernize/AvoidCArraysCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/AvoidCArraysCheck.cpp
@@ -39,6 +39,30 @@ AST_MATCHER(clang::ParmVarDecl, isArgvOfMain) {
   return FD ? FD->isMain() : false;
 }
 
+bool isWithinImplicitTemplateInstantiation(const TypeLoc *ArrayType,
+                                           ASTContext *Context) {
+  const auto IsImplicitTemplateInstantiation = [](const auto *Node) {
+    return (Node != nullptr) &&
+           (Node->getTemplateSpecializationKind() == TSK_ImplicitInstantiation);
+  };
+
+  auto ParentNodes = Context->getParents(*ArrayType);
+  while (!ParentNodes.empty()) {
+    const auto &ParentNode = ParentNodes[0];
+    if (IsImplicitTemplateInstantiation(
+            ParentNode.template get<clang::CXXRecordDecl>()) ||
+        IsImplicitTemplateInstantiation(
+            ParentNode.template get<clang::FunctionDecl>()) ||
+        IsImplicitTemplateInstantiation(
+            ParentNode.template get<clang::VarDecl>())) {
+      return true;
+    }
+    ParentNodes = Context->getParents(ParentNode);
+  }
+
+  return false;
+}
+
 } // namespace
 
 AvoidCArraysCheck::AvoidCArraysCheck(StringRef Name, ClangTidyContext *Context)
@@ -70,18 +94,45 @@ void AvoidCArraysCheck::registerMatchers(MatchFinder *Finder) {
               std::move(IgnoreStringArrayIfNeededMatcher))
           .bind("typeloc"),
       this);
+
+  Finder->addMatcher(templateArgumentLoc(hasTypeLoc(
+                         loc(arrayType()).bind("typeloc_in_template_arg"))),
+                     this);
 }
 
 void AvoidCArraysCheck::check(const MatchFinder::MatchResult &Result) {
-  const auto *ArrayType = Result.Nodes.getNodeAs<TypeLoc>("typeloc");
+  clang::TypeLoc ArrayTypeLoc{};
+
+  if (const auto *ArrayType = Result.Nodes.getNodeAs<TypeLoc>("typeloc");
+      ArrayType != nullptr &&
+      not(isWithinImplicitTemplateInstantiation(ArrayType, Result.Context))) {
+    ArrayTypeLoc = *ArrayType;
+  }
+
+  if (const auto *ArrayTypeInTemplateArg =
+          Result.Nodes.getNodeAs<TypeLoc>("typeloc_in_template_arg");
+      ArrayTypeInTemplateArg != nullptr) {
+    if (ArrayTypeInTemplateArg->getSourceRange() !=
+        ArrayTypeInTemplateArg->getLocalSourceRange()) {
+      // only in case the above condition is fulfilled, we matched a written
+      // array type and not a template type parameter which got deduced to one
+      ArrayTypeLoc = *ArrayTypeInTemplateArg;
+    }
+  }
+
+  // check whether the match result is a real array type (based on above checks)
+  if (ArrayTypeLoc.isNull()) {
+    return;
+  }
+
   const bool IsInParam =
       Result.Nodes.getNodeAs<ParmVarDecl>("param_decl") != nullptr;
-  const bool IsVLA = ArrayType->getTypePtr()->isVariableArrayType();
+  const bool IsVLA = ArrayTypeLoc.getTypePtr()->isVariableArrayType();
   enum class RecommendType { Array, Vector, Span };
   llvm::SmallVector<const char *> RecommendTypes{};
   if (IsVLA) {
     RecommendTypes.push_back("'std::vector'");
-  } else if (ArrayType->getTypePtr()->isIncompleteArrayType() && IsInParam) {
+  } else if (ArrayTypeLoc.getTypePtr()->isIncompleteArrayType() && IsInParam) {
     // in function parameter, we also don't know the size of
     // IncompleteArrayType.
     if (Result.Context->getLangOpts().CPlusPlus20)
@@ -93,7 +144,8 @@ void AvoidCArraysCheck::check(const MatchFinder::MatchResult &Result) {
   } else {
     RecommendTypes.push_back("'std::array'");
   }
-  diag(ArrayType->getBeginLoc(),
+
+  diag(ArrayTypeLoc.getBeginLoc(),
        "do not declare %select{C-style|C VLA}0 arrays, use %1 instead")
       << IsVLA << llvm::join(RecommendTypes, " or ");
 }
diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays-ignores-strings.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays-ignores-strings.cpp
index 906663828a547..18458bd47d347 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays-ignores-strings.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays-ignores-strings.cpp
@@ -7,3 +7,15 @@ const char array[] = {'n', 'a', 'm', 'e', '\0'};
 
 void takeCharArray(const char name[]);
 // CHECK-MESSAGES: :[[@LINE-1]]:26: warning: do not declare C-style arrays, use 'std::array' or 'std::vector' instead [modernize-avoid-c-arrays]
+
+template <typename T = const char[10], typename U = char[10], char[10]>
+// CHECK-MESSAGES: :[[@LINE-1]]:30: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+// CHECK-MESSAGES: :[[@LINE-2]]:53: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+// CHECK-MESSAGES: :[[@LINE-3]]:63: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+void func() {}
+
+template <typename T = const char[], typename U = char[], char[]>
+// CHECK-MESSAGES: :[[@LINE-1]]:30: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+// CHECK-MESSAGES: :[[@LINE-2]]:51: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+// CHECK-MESSAGES: :[[@LINE-3]]:59: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+void fun() {}
diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays.cpp
index 14eb2852c639a..0b474cc69db36 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-c-arrays.cpp
@@ -92,3 +92,162 @@ const char name[] = "Some string";
 
 void takeCharArray(const char name[]);
 // CHECK-MESSAGES: :[[@LINE-1]]:26: warning: do not declare C-style arrays, use 'std::array' or 'std::vector' instead [modernize-avoid-c-arrays]
+
+namespace std {
+  template<class T, class U>
+  struct is_same { constexpr static bool value{false}; };
+
+  template<class T>
+  struct is_same<T, T> { constexpr static bool value{true}; };
+
+  template<class T, class U>
+  constexpr bool is_same_v = is_same<T, U>::value;
+
+  template<class T> struct remove_const { typedef T type; };
+  template<class T> struct remove_const<const T> { typedef T type; };
+
+  template<class T>
+  using remove_const_t = typename remove_const<T>::type;
+
+  template<bool B, class T = void> struct enable_if {};
+  template<class T> struct enable_if<true, T> { typedef T type; };
+
+  template< bool B, class T = void >
+  using enable_if_t = typename enable_if<B, T>::type;
+}
+
+// below, no array type findings are expected within the template parameter declarations since no array type gets written explicitly
+template <typename T,
+          bool = std::is_same_v<T, int>,
+          bool = std::is_same<T, int>::value,
+          bool = std::is_same_v<std::remove_const_t<T>, int>,
+          bool = std::is_same<std::remove_const_t<T>, int>::value,
+          bool = std::is_same_v<typename std::remove_const<T>::type, int>,
+          bool = std::is_same<typename std::remove_const<T>::type, int>::value,
+          std::enable_if_t<not(std::is_same_v<std::remove_const_t<T>, int>) && not(std::is_same_v<typename std::remove_const<T>::type, char>), bool> = true,
+          typename std::enable_if<not(std::is_same_v<std::remove_const_t<T>, int>) && not(std::is_same_v<typename std::remove_const<T>::type, char>), bool>::type = true,
+          typename = std::enable_if_t<not(std::is_same_v<std::remove_const_t<T>, int>) && not(std::is_same_v<typename std::remove_const<T>::type, char>)>,
+          typename = typename std::remove_const<T>::type,
+          typename = std::remove_const_t<T>>
+class MyClassTemplate {
+ public:
+  // here, plenty of array type findings are expected for below template parameter declarations since array types get written explicitly
+  template <typename U = T,
+            bool = std::is_same_v<U, int[]>,
+            // CHECK-MESSAGES: :[[@LINE-1]]:38: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+            bool = std::is_same<U, int[10]>::value,
+            // CHECK-MESSAGES: :[[@LINE-1]]:36: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+            std::enable_if_t<not(std::is_same_v<std::remove_const_t<U>, int[]>) && not(std::is_same_v<typename std::remove_const<U>::type, char[10]>), bool> = true,
+            // CHECK-MESSAGES: :[[@LINE-1]]:73: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+            // CHECK-MESSAGES: :[[@LINE-2]]:140: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+            typename = typename std::remove_const<int[10]>::type,
+            // CHECK-MESSAGES: :[[@LINE-1]]:51: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+            typename = std::remove_const_t<int[]>>
+            // CHECK-MESSAGES: :[[@LINE-1]]:44: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+    class MyInnerClassTemplate {
+     public:
+      MyInnerClassTemplate(const U&) {}
+     private:
+      U field[3];
+      // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+    };
+
+    MyClassTemplate(const T&) {}
+
+ private:
+    T field[7];
+    // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+};
+
+// an explicit instantiation
+template
+class MyClassTemplate<int[2]>;
+// CHECK-MESSAGES: :[[@LINE-1]]:23: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+
+using MyArrayType = int[3];
+// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+
+// another explicit instantiation
+template
+class MyClassTemplate<MyArrayType>;
+
+// below, no array type findings are expected within the template parameter declarations since no array type gets written explicitly
+template <typename T,
+          bool = std::is_same_v<T, int>,
+          bool = std::is_same<T, int>::value,
+          bool = std::is_same_v<std::remove_const_t<T>, int>,
+          bool = std::is_same<std::remove_const_t<T>, int>::value,
+          bool = std::is_same_v<typename std::remove_const<T>::type, int>,
+          bool = std::is_same<typename std::remove_const<T>::type, int>::value,
+          std::enable_if_t<not(std::is_same_v<std::remove_const_t<T>, int>) && not(std::is_same_v<typename std::remove_const<T>::type, char>), bool> = true,
+          typename std::enable_if<not(std::is_same_v<std::remove_const_t<T>, int>) && not(std::is_same_v<typename std::remove_const<T>::type, char>), bool>::type = true,
+          typename = std::enable_if_t<not(std::is_same_v<std::remove_const_t<T>, int>) && not(std::is_same_v<typename std::remove_const<T>::type, char>)>,
+          typename = typename std::remove_const<T>::type,
+          typename = std::remove_const_t<T>>
+void func(const T& param) {
+  int array1[1];
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+
+  T array2[2];
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+
+  T value;
+}
+
+// here, plenty of array type findings are expected for below template parameter declarations since array types get written explicitly
+template <typename T = int[],
+          // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+          bool = std::is_same_v<T, int[]>,
+          // CHECK-MESSAGES: :[[@LINE-1]]:36: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+          bool = std::is_same<T, int[10]>::value,
+          // CHECK-MESSAGES: :[[@LINE-1]]:34: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+          std::enable_if_t<not(std::is_same_v<std::remove_const_t<T>, int[]>) && not(std::is_same_v<typename std::remove_const<T>::type, char[10]>), bool> = true,
+          // CHECK-MESSAGES: :[[@LINE-1]]:71: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+          // CHECK-MESSAGES: :[[@LINE-2]]:138: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+          typename = typename std::remove_const<int[10]>::type,
+          // CHECK-MESSAGES: :[[@LINE-1]]:49: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+          typename = std::remove_const_t<int[]>>
+          // CHECK-MESSAGES: :[[@LINE-1]]:42: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+void fun(const T& param) {
+  int array3[3];
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+
+  T array4[4];
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+
+  T value;
+}
+
+template<typename T>
+T some_constant{};
+
+// explicit instantiation
+template
+int some_constant<int[5]>[5];
+// FIXME: why no diagnostics here?
+
+// explicit specialization
+template<>
+int some_constant<int[7]>[7]{};
+// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+// CHECK-MESSAGES: :[[@LINE-2]]:19: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+
+void testArrayInTemplateType() {
+  int t[10];
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C-style arrays, use 'std::array' instead [modernize-avoid-c-arrays]
+
+  func(t);
+  fun(t);
+
+  func<decltype(t)>({});
+  fun<decltype(t)>({});
+
+  MyClassTemplate var1{t};
+  MyClassTemplate<decltype(t)> var2{{}};
+
+  decltype(var1)::MyInnerClassTemplate var3{t};
+  decltype(var1)::MyInnerClassTemplate<decltype(t)> var4{{}};
+
+  MyClassTemplate<decltype(t)>::MyInnerClassTemplate var5{t};
+  MyClassTemplate<decltype(t)>::MyInnerClassTemplate<decltype(t)> var6{{}};
+}

@stmuench
Copy link
Contributor Author

stmuench commented Apr 3, 2025

Ping

@stmuench stmuench force-pushed the sm_revise_avoid_c_arrays_check branch 2 times, most recently from 29cfb29 to 7f621bc Compare April 28, 2025 19:10
@stmuench
Copy link
Contributor Author

@PiotrZSL if it suits your convenience, could you maybe have a look at this PR? Many thanks in advance.

Copy link
Contributor

@vbvictor vbvictor left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add release notes in this patch.
I think the idea is good, but you can look into my review after PiotrZSL's comments.

@stmuench stmuench force-pushed the sm_revise_avoid_c_arrays_check branch from 7f621bc to fb9f0c3 Compare April 30, 2025 14:11
@stmuench
Copy link
Contributor Author

Please add release notes in this patch. I think the idea is good, but you can look into my review after PiotrZSL's comments.

@vbvictor many thanks for your very valuable comments. I incorporated them as far as possible.

@stmuench stmuench force-pushed the sm_revise_avoid_c_arrays_check branch from fb9f0c3 to 1216ef5 Compare May 6, 2025 10:09
@stmuench stmuench requested a review from vbvictor May 6, 2025 10:10
@stmuench
Copy link
Contributor Author

stmuench commented May 6, 2025

@PiotrZSL would you have any further remarks for this PR?

@stmuench
Copy link
Contributor Author

@vbvictor since is there no further activity by reviewers here, any idea on how to continue with this PR?

@vbvictor
Copy link
Contributor

For now, I think you should wait for an approval/review from one of the clang-tidy maintainers (PiotrZSL, HerrCai0907) that will also help merge this PR. It can take some time, but the new release will only be in July, so don't need to worry about missing your changes for now.
You should "Ping" reviewers with 1-2 week period.

@stmuench
Copy link
Contributor Author

Ping

@vbvictor vbvictor requested a review from 5chmidti June 25, 2025 21:34
@stmuench
Copy link
Contributor Author

Ping

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thinking oud-loud: I'm actually a bit surprised that this whole issue even exists, since the check's traversal kind is set to IgnoreUnlessSpelledInSource

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True. Maybe due to an issue in AST Visitor or even AST itself which leads to template arguments of implicit instantiations not getting recognized as implicit ones?
But I am unfortunately lacking knowlege in that area. In case you have ideas how to check this, please share :)

Copy link
Contributor

@vbvictor vbvictor left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tests lgtm, minor comments on code.
Please rebase on fresh main

@stmuench stmuench force-pushed the sm_revise_avoid_c_arrays_check branch from 1216ef5 to ef2c51b Compare August 20, 2025 20:56
@stmuench
Copy link
Contributor Author

stmuench commented Aug 20, 2025

@5chmidti @vbvictor many thanks for your suggestions, I incorporated all of them

@stmuench stmuench force-pushed the sm_revise_avoid_c_arrays_check branch from ef2c51b to 9d8acb1 Compare August 20, 2025 21:01
@stmuench stmuench force-pushed the sm_revise_avoid_c_arrays_check branch 2 times, most recently from 9603c5a to 6be84a3 Compare August 26, 2025 18:37
@stmuench stmuench requested review from 5chmidti and vbvictor August 26, 2025 18:37
Copy link
Contributor

@vbvictor vbvictor left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, but I'd wait for review from @5chmidti because he had the initiative for optimization.

Copy link
Contributor

@5chmidti 5chmidti left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generally LGTM, but there is one issue that must be fixed

So far, the clang-tidy check `modernize-avoid-c-arrays` also diagnosed
array types for type template parameters even though no actual array
type got written there but it got deduced to one. In such case, there
is nothing a developer can do at that location to fix the diagnostic.
Since actually, the location where the template got instantiated
would have to be adjusted. And this is in most cases some totally
distant code where implementers of a template do not have access to.
Also adding suppressions to the declaration of the template is not an
option since that would clutter the code unnecessarily and is in many
cases also simply not possible. Hence, we propose to not diagnose any
occurrence of an array type in an implicit instantiation of a template
but rather at the point where template arguments involve array types.
@stmuench stmuench force-pushed the sm_revise_avoid_c_arrays_check branch from 6be84a3 to 6acfd25 Compare September 1, 2025 17:43
@stmuench
Copy link
Contributor Author

stmuench commented Sep 2, 2025

@5chmidti @vbvictor how could I proceed in order to merge this PR? I do not have a merge button available (I guess since I do not have write permissions to the repo)

Copy link
Contributor

@vbvictor vbvictor left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will land the patch at the end of the week

@vbvictor vbvictor merged commit 6fc32e9 into llvm:main Sep 7, 2025
10 checks passed
@github-actions
Copy link

github-actions bot commented Sep 7, 2025

@stmuench Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

@stmuench
Copy link
Contributor Author

stmuench commented Sep 7, 2025

I will land the patch at the end of the week

@vbvictor many thanks for taking care

@stmuench stmuench deleted the sm_revise_avoid_c_arrays_check branch September 8, 2025 07:59
@stmuench
Copy link
Contributor Author

@vbvictor @5chmidti would you say it makes sense to cherry-pick these changes to branch release/21.x? If yes, could you maybe edit this PR's milestones?

@vbvictor
Copy link
Contributor

@vbvictor @5chmidti would you say it makes sense to cherry-pick these changes to branch release/21.x? If yes, could you maybe edit this PR's milestones?

Taking into account that we already have an official release (not RC) and reading from https://llvm.org/docs/HowToReleaseLLVM.html#release-patch-rules:

Bug fix releases Patches should be limited to bug fixes or very safe and critical performance improvements. Patches must maintain both API and ABI compatibility with the X.1.0 release.

I'm sorry, I don't see critical bug fixes or performance improvements here. And we generally don't backport bug fixes (unless it's a critical one that reported often)

@vbvictor
Copy link
Contributor

Maybe other has different opinions CC @carlosgalvezp @HerrCai0907

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants