Skip to content

Allow unnecessary-value-param to match templated functions including lambdas with auto. #97767

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 15, 2024

Conversation

goldvitaly
Copy link
Contributor

Clang-Tidy unnecessary-value-param value param will be triggered for
templated functions if at least one instantiontion with expensive to
copy type is present in translation unit.

It is relatively common mistake to write lambda functions with auto
arguments for expensive to copy types.

Example:
Copy of the vectors will happen on every comparison.

void SortBySize(std::vector<std::vector<int>>& a) {
  std::sort(
      a.begin(), a.end(),
      [](auto x, auto y) { return a.size() < b.size()});
}

%username% added 2 commits July 4, 2024 22:57
…lambdas with auto.

Clang-Tidy unnecessary-value-param value param will be triggered for
templated functions if at least one instantiontion with expensive to
copy type is present in translation unit.

It is relatively common mistake to write lambda functions with auto
arguments for expensive to copy types.

Example:
Copy of the vectors will happen on every comparison.

void SortBySize(std::vector<std::vector<int>>& a) {
  std::sort(
      a.begin(), a.end(),
      [](auto x, auto y) { return a.size() < b.size()});
}
…lambdas with auto.

Clang-Tidy unnecessary-value-param value param will be triggered for
templated functions if at least one instantiontion with expensive to
copy type is present in translation unit.

It is relatively common mistake to write lambda functions with auto
arguments for expensive to copy types.

Example:
Copy of the vectors will happen on every comparison.

void SortBySize(std::vector<std::vector<int>>& a) {
  std::sort(
      a.begin(), a.end(),
      [](auto x, auto y) { return a.size() < b.size()});
}
Copy link

github-actions bot commented Jul 4, 2024

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.

@llvmbot
Copy link
Member

llvmbot commented Jul 4, 2024

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

@llvm/pr-subscribers-clang-tidy

Author: Vitaly Goldshteyn (goldvitaly)

Changes

Clang-Tidy unnecessary-value-param value param will be triggered for
templated functions if at least one instantiontion with expensive to
copy type is present in translation unit.

It is relatively common mistake to write lambda functions with auto
arguments for expensive to copy types.

Example:
Copy of the vectors will happen on every comparison.

void SortBySize(std::vector&lt;std::vector&lt;int&gt;&gt;&amp; a) {
  std::sort(
      a.begin(), a.end(),
      [](auto x, auto y) { return a.size() &lt; b.size()});
}

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

3 Files Affected:

  • (modified) clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp (+2-5)
  • (added) clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-value-param-templates.cpp (+92)
  • (modified) clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-value-param.cpp (-45)
diff --git a/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp b/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
index c507043c367a8..fe8cc11018e1e 100644
--- a/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
+++ b/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
@@ -75,7 +75,7 @@ void UnnecessaryValueParamCheck::registerMatchers(MatchFinder *Finder) {
           functionDecl(hasBody(stmt()), isDefinition(), unless(isImplicit()),
                        unless(cxxMethodDecl(anyOf(isOverride(), isFinal()))),
                        has(typeLoc(forEach(ExpensiveValueParamDecl))),
-                       unless(isInstantiated()), decl().bind("functionDecl"))),
+                       decl().bind("functionDecl"))),
       this);
 }
 
@@ -133,12 +133,9 @@ void UnnecessaryValueParamCheck::check(const MatchFinder::MatchResult &Result) {
   // 2. the function is virtual as it might break overrides
   // 3. the function is referenced outside of a call expression within the
   //    compilation unit as the signature change could introduce build errors.
-  // 4. the function is a primary template or an explicit template
-  // specialization.
   const auto *Method = llvm::dyn_cast<CXXMethodDecl>(Function);
   if (Param->getBeginLoc().isMacroID() || (Method && Method->isVirtual()) ||
-      isReferencedOutsideOfCallExpr(*Function, *Result.Context) ||
-      (Function->getTemplatedKind() != FunctionDecl::TK_NonTemplate))
+      isReferencedOutsideOfCallExpr(*Function, *Result.Context))
     return;
   for (const auto *FunctionDecl = Function; FunctionDecl != nullptr;
        FunctionDecl = FunctionDecl->getPreviousDecl()) {
diff --git a/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-value-param-templates.cpp b/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-value-param-templates.cpp
new file mode 100644
index 0000000000000..4e6ec401f17c8
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-value-param-templates.cpp
@@ -0,0 +1,92 @@
+// RUN: %check_clang_tidy  -std=c++14-or-later %s performance-unnecessary-value-param %t
+
+struct ExpensiveToCopyType {
+  virtual ~ExpensiveToCopyType();
+};
+
+template <typename T> void templateWithNonTemplatizedParameter(const ExpensiveToCopyType S, T V) {
+  // CHECK-MESSAGES: [[@LINE-1]]:90: warning: the const qualified parameter 'S'
+  // CHECK-MESSAGES: [[@LINE-2]]:95: warning: the parameter 'V'
+  // CHECK-FIXES: template <typename T> void templateWithNonTemplatizedParameter(const ExpensiveToCopyType& S, const T& V) {
+}
+
+void instantiatedWithExpensiveValue() {
+  templateWithNonTemplatizedParameter(
+      ExpensiveToCopyType(), ExpensiveToCopyType());
+  templateWithNonTemplatizedParameter(ExpensiveToCopyType(), 5);
+}
+
+template <typename T> void templateWithNonTemplatizedParameterCheapTemplate(const ExpensiveToCopyType S, T V) {
+  // CHECK-MESSAGES: [[@LINE-1]]:103: warning: the const qualified parameter 'S'
+  // CHECK-FIXES: template <typename T> void templateWithNonTemplatizedParameterCheapTemplate(const ExpensiveToCopyType& S, T V) {
+}
+
+void instantiatedWithCheapValue() {
+  templateWithNonTemplatizedParameterCheapTemplate(ExpensiveToCopyType(), 5);
+}
+
+template <typename T> void nonInstantiatedTemplateWithConstValue(const T S) {}
+template <typename T> void nonInstantiatedTemplateWithNonConstValue(T S) {}
+
+template <typename T> void instantiatedTemplateSpecialization(T NoSpecS) {}
+template <>
+void instantiatedTemplateSpecialization<ExpensiveToCopyType>(
+    ExpensiveToCopyType SpecS) {
+  // CHECK-MESSAGES: [[@LINE-1]]:25: warning: the parameter 'SpecS'
+  // CHECK-FIXES: const T& NoSpecS
+  // CHECK-FIXES: const ExpensiveToCopyType& SpecS
+}
+
+void instantiatedTemplateSpecialization() {
+  instantiatedTemplateSpecialization(ExpensiveToCopyType());
+}
+
+template <typename T> void instantiatedTemplateWithConstValue(const T S) {
+  // CHECK-MESSAGES: [[@LINE-1]]:71: warning: the const qualified parameter 'S'
+  // CHECK-FIXES: template <typename T> void instantiatedTemplateWithConstValue(const T& S) {
+}
+
+void instantiatedConstValue() {
+  instantiatedTemplateWithConstValue(ExpensiveToCopyType());
+}
+
+template <typename T> void instantiatedTemplateWithNonConstValue(T S) {
+  // CHECK-MESSAGES: [[@LINE-1]]:68: warning: the parameter 'S'
+  // CHECK-FIXES: template <typename T> void instantiatedTemplateWithNonConstValue(const T& S) {
+}
+
+void instantiatedNonConstValue() {
+  instantiatedTemplateWithNonConstValue(ExpensiveToCopyType());
+}
+
+void lambdaConstValue() {
+  auto fn = [](const ExpensiveToCopyType S) {
+    // CHECK-MESSAGES: [[@LINE-1]]:42: warning: the const qualified parameter 'S'
+    // CHECK-FIXES: auto fn = [](const ExpensiveToCopyType& S) {
+  };
+  fn(ExpensiveToCopyType());
+}
+
+void lambdaNonConstValue() {
+  auto fn = [](ExpensiveToCopyType S) {
+    // CHECK-MESSAGES: [[@LINE-1]]:36: warning: the parameter 'S'
+    // CHECK-FIXES: auto fn = [](const ExpensiveToCopyType& S) {
+  };
+  fn(ExpensiveToCopyType());
+}
+
+void lambdaConstAutoValue() {
+  auto fn = [](const auto S) {
+    // CHECK-MESSAGES: [[@LINE-1]]:27: warning: the const qualified parameter 'S'
+    // CHECK-FIXES: auto fn = [](const auto& S) {
+  };
+  fn(ExpensiveToCopyType());
+}
+
+void lambdaNonConstAutoValue() {
+  auto fn = [](auto S) {
+    // CHECK-MESSAGES: [[@LINE-1]]:21: warning: the parameter 'S'
+    // CHECK-FIXES: auto fn = [](const auto& S) {
+  };
+  fn(ExpensiveToCopyType());
+}
diff --git a/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-value-param.cpp b/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-value-param.cpp
index d578eedd94a39..0dffaefa213a4 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-value-param.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-value-param.cpp
@@ -107,19 +107,6 @@ struct PositiveConstValueConstructor {
   // CHECK-FIXES: PositiveConstValueConstructor(const ExpensiveToCopyType& ConstCopy) {}
 };
 
-template <typename T> void templateWithNonTemplatizedParameter(const ExpensiveToCopyType S, T V) {
-  // CHECK-MESSAGES: [[@LINE-1]]:90: warning: the const qualified parameter 'S'
-  // CHECK-FIXES-NOT: template <typename T> void templateWithNonTemplatizedParameter(const ExpensiveToCopyType& S, T V) {
-}
-
-void instantiated() {
-  templateWithNonTemplatizedParameter(ExpensiveToCopyType(), ExpensiveToCopyType());
-  templateWithNonTemplatizedParameter(ExpensiveToCopyType(), 5);
-}
-
-template <typename T> void negativeTemplateType(const T V) {
-}
-
 void negativeArray(const ExpensiveToCopyType[]) {
 }
 
@@ -370,35 +357,3 @@ void fun() {
   ExpensiveToCopyType E;
   NegativeUsingConstructor S(E);
 }
-
-template<typename T>
-void templateFunction(T) {
-}
-
-template<>
-void templateFunction<ExpensiveToCopyType>(ExpensiveToCopyType E) {
-  // CHECK-MESSAGES: [[@LINE-1]]:64: warning: the parameter 'E' is copied
-  // CHECK-FIXES: void templateFunction<ExpensiveToCopyType>(ExpensiveToCopyType E) {
-  E.constReference();
-}
-
-template <class T>
-T templateSpecializationFunction(ExpensiveToCopyType E) {
-  // CHECK-MESSAGES: [[@LINE-1]]:54: warning: the parameter 'E' is copied
-  // CHECK-FIXES-NOT: T templateSpecializationFunction(const ExpensiveToCopyType& E) {
-  return T();
-}
-
-template <>
-bool templateSpecializationFunction(ExpensiveToCopyType E) {
-  // CHECK-MESSAGES: [[@LINE-1]]:57: warning: the parameter 'E' is copied
-  // CHECK-FIXES-NOT: bool templateSpecializationFunction(const ExpensiveToCopyType& E) {
-  return true;
-}
-
-template <>
-int templateSpecializationFunction(ExpensiveToCopyType E) {
-  // CHECK-MESSAGES: [[@LINE-1]]:56: warning: the parameter 'E' is copied
-  // CHECK-FIXES-NOT: int templateSpecializationFunction(const ExpensiveToCopyType& E) {
-  return 0;
-}

@legrosbuffle legrosbuffle self-requested a review July 5, 2024 06:35
@legrosbuffle
Copy link
Contributor

There seems to be failing tests (see "buildkite" above).

Can you please update the release notes too (clang-tools-extra/docs/ReleaseNotes.rst) ?

@EugeneZelenko
Copy link
Contributor

Please mention changes in Release Notes.

void instantiatedTemplateSpecialization<ExpensiveToCopyType>(
ExpensiveToCopyType SpecS) {
// CHECK-MESSAGES: [[@LINE-1]]:25: warning: the parameter 'SpecS'
// When updating a template specialization, we also update the main template.
Copy link
Contributor

Choose a reason for hiding this comment

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

I don't think that we need to do that. The specialization can specialize for the specific type, and the base template can be const&-ed when an instantiation contains a type that is not cheap to copy. WDYT?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Note that it is template specialization and not an overload.

Template specialization must have exactly the same signature.
See an example https://gcc.godbolt.org/z/cqTzG5Wsn

Note that nothing special is done to update both versions.
When template specialization is updated, the main template and all other template specializations are updated automatically.

I personally prefer to use overloads, but this test is necessary to be sure that we are not proposing non compiling changes.

Copy link
Contributor

Choose a reason for hiding this comment

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

Note that it is template specialization and not an overload.
Template specialization must have exactly the same signature.

Whoops, I must have done something weird to think this works.

Then what I would have originally written applies:
When a specialization A is defined in another TU, applying a fix to specialization B from the analyzed TU or the underlying template, will make A no longer compile. The same goes for specializations in headers that are not included, and also specializations that are:

template <typename T> void instantiatedTemplateSpecialization(T NoSpecS) {}
template <>
void instantiatedTemplateSpecialization<ExpensiveToCopyType>(
    ExpensiveToCopyType SpecS) {
  // CHECK-MESSAGES: [[@LINE-1]]:25: warning: the parameter 'SpecS'
  // When updating a template specialization, we also update the main template.
  // CHECK-FIXES: const T& NoSpecS
  // CHECK-FIXES: const ExpensiveToCopyType& SpecS
  // CHECK-FIXES: const int& SpecS               <- fails, no fix generated it seems
}
template <>
void instantiatedTemplateSpecialization<int>(
    int SpecS) {
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That is unfortunately correct. I was aware that other TUs can be broken.

But it seems that other template instantiations are not fixed in the same file as well.

Do you know how to skip template specialization, but not all other template functions?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I have found a partial fix for this issue (and created fixup commit).

The changes are:

  1. No fixes are proposed for explicit specializations.
  2. Fixes are still proposed for the main template in case warning is issued during instantiation of the main template. I couldn't find the way to find that any instantiation is available. And in case they are defined in another translation unit, there is no way to do it.

Copy link
Member

@PiotrZSL PiotrZSL left a comment

Choose a reason for hiding this comment

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

On first glance, except few nits looks fine.

@PiotrZSL PiotrZSL merged commit 8e42e0d into llvm:main Jul 15, 2024
6 checks passed
Copy link

@goldvitaly 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!

yuxuanchen1997 pushed a commit that referenced this pull request Jul 25, 2024
…ns including lambdas with auto. (#97767)

Clang-Tidy unnecessary-value-param value param will be triggered for
templated functions if at least one instantiontion with expensive to
copy type is present in translation unit.

It is relatively common mistake to write lambda functions with auto
arguments for expensive to copy types.
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.

6 participants