[clang-tools-extra] [clang-tidy] Don't suggest removing [[maybe_unused]] variables in performance-unnecessary-copy-initialization (PR #244978)

David Meng via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 23 19:49:57 PST 2026


https://github.com/davidmenggx updated https://github.com/llvm/llvm-project/pull/244978

>From a97e2577953bef0eec3951eef808217b663366f2 Mon Sep 17 00:00:00 2001
From: David Meng <davidmenggx at gmail.com>
Date: Sat, 21 Nov 2026 17:43:14 -0800
Subject: [PATCH 1/2] [clang-tidy] Don't suggest removing [[maybe_unused]]
 variables in performance-unnecessary-copy-initialization

The check no longer treats variables marked [[maybe_unused]] as unused.
It suggests making them a const reference instead.

Fixes #244404.
---
 .../UnnecessaryCopyInitializationCheck.cpp        |  5 ++++-
 clang-tools-extra/docs/ReleaseNotes.md            |  5 +++++
 .../unnecessary-copy-initialization.cpp           | 15 +++++++++++++++
 3 files changed, 24 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitializationCheck.cpp b/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitializationCheck.cpp
index c8372a75fb4877..4dfb7be615f805 100644
--- a/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitializationCheck.cpp
+++ b/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitializationCheck.cpp
@@ -182,7 +182,10 @@ static bool isInitializingVariableImmutable(
 
 static bool isVariableUnused(const VarDecl &Var, const Stmt &BlockStmt,
                              ASTContext &Context) {
-  return allDeclRefExprs(Var, BlockStmt, Context).empty();
+  // A variable marked `[[maybe_unused]]` should not be treated as unused.
+  // Suggest a const reference instead.
+  return !Var.hasAttr<UnusedAttr>() &&
+         allDeclRefExprs(Var, BlockStmt, Context).empty();
 }
 
 static const SubstTemplateTypeParmType *
diff --git a/clang-tools-extra/docs/ReleaseNotes.md b/clang-tools-extra/docs/ReleaseNotes.md
index 30a58ae13a511d..cab821f08657a5 100644
--- a/clang-tools-extra/docs/ReleaseNotes.md
+++ b/clang-tools-extra/docs/ReleaseNotes.md
@@ -401,6 +401,11 @@ infrastructure are described first, followed by tool-specific sections.
   avoid offering fix-its for string literals originating from macro
   expansions.
 
+- Improved {doc}`performance-unnecessary-copy-initialization
+  <clang-tidy/checks/performance/unnecessary-copy-initialization>` check to
+  no longer suggest removing unused variables marked `[[maybe_unused]]`. It
+  suggests a const reference instead.
+
 - Improved {doc}`readability-convert-member-functions-to-static
   <clang-tidy/checks/readability/convert-member-functions-to-static>` check by
   fixing a crash when checking a const-qualified method declared with the
diff --git a/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-copy-initialization.cpp b/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-copy-initialization.cpp
index 4818e9ddfc86f7..0929b9ecc00653 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-copy-initialization.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-copy-initialization.cpp
@@ -771,6 +771,21 @@ void positiveUnusedReferenceIsRemoved() {
   // CHECK-FIXES: // Comments on a new line should not be deleted.
 }
 
+void positiveMaybeUnusedIsNotRemoved() {
+  [[maybe_unused]] auto FromCall = ExpensiveTypeReference();
+  // CHECK-MESSAGES: [[@LINE-1]]:25: warning: the variable 'FromCall' of type 'ExpensiveToCopyType' is copy-constructed from a const reference but is only used as const reference; consider making it a const reference [performance-unnecessary-copy-initialization]
+  // CHECK-FIXES: {{\[\[maybe_unused\]\]}} const auto& FromCall = ExpensiveTypeReference();
+
+  ExpensiveToCopyType Orig;
+  [[maybe_unused]] auto FromVar{Orig};
+  // CHECK-MESSAGES: [[@LINE-1]]:25: warning: local copy 'FromVar' of the variable 'Orig' of type 'ExpensiveToCopyType' is never modified; consider avoiding the copy [performance-unnecessary-copy-initialization]
+  // CHECK-FIXES: {{\[\[maybe_unused\]\]}} const auto& FromVar{Orig};
+
+  __attribute__((unused)) auto GnuSpelling = Orig;
+  // CHECK-MESSAGES: [[@LINE-1]]:32: warning: local copy 'GnuSpelling' of the variable 'Orig' of type 'ExpensiveToCopyType' is never modified; consider avoiding the copy [performance-unnecessary-copy-initialization]
+  // CHECK-FIXES: __attribute__((unused)) const auto& GnuSpelling = Orig;
+}
+
 void positiveLoopedOverObjectIsConst() {
   const Container<ExpensiveToCopyType> Orig;
   for (const auto &Element : Orig) {

>From 11f96f27d5c108f7b99fddead22dc1c34fa03a80 Mon Sep 17 00:00:00 2001
From: David Meng <davidmenggx at gmail.com>
Date: Mon, 23 Nov 2026 19:49:42 -0800
Subject: [PATCH 2/2] Address review comments

---
 .../UnnecessaryCopyInitializationCheck.cpp    | 25 +++++++++++--------
 .../UnnecessaryCopyInitializationCheck.h      |  1 +
 .../unnecessary-copy-initialization.cpp       |  6 ++++-
 3 files changed, 20 insertions(+), 12 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitializationCheck.cpp b/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitializationCheck.cpp
index 4dfb7be615f805..6ac44967bdde37 100644
--- a/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitializationCheck.cpp
+++ b/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitializationCheck.cpp
@@ -182,10 +182,7 @@ static bool isInitializingVariableImmutable(
 
 static bool isVariableUnused(const VarDecl &Var, const Stmt &BlockStmt,
                              ASTContext &Context) {
-  // A variable marked `[[maybe_unused]]` should not be treated as unused.
-  // Suggest a const reference instead.
-  return !Var.hasAttr<UnusedAttr>() &&
-         allDeclRefExprs(Var, BlockStmt, Context).empty();
+  return allDeclRefExprs(Var, BlockStmt, Context).empty();
 }
 
 static const SubstTemplateTypeParmType *
@@ -284,13 +281,16 @@ void UnnecessaryCopyInitializationCheck::check(
   const bool IssueFix =
       VarDeclStmt.isSingleDecl() && !NewVar.getLocation().isMacroID();
   const bool IsVarUnused = isVariableUnused(NewVar, BlockStmt, *Result.Context);
+  // A variable marked `[[maybe_unused]]` should not be removed. Suggest a const
+  // reference instead.
+  const bool ShouldRemoveVar = IsVarUnused && !NewVar.hasAttr<UnusedAttr>();
   const bool IsVarOnlyUsedAsConst =
       isOnlyUsedAsConst(NewVar, BlockStmt, *Result.Context,
                         // `NewVar` is always of non-pointer type.
                         0);
   const CheckContext Context{
-      NewVar,   BlockStmt,   VarDeclStmt,         *Result.Context,
-      IssueFix, IsVarUnused, IsVarOnlyUsedAsConst};
+      NewVar,   BlockStmt,   VarDeclStmt,     *Result.Context,
+      IssueFix, IsVarUnused, ShouldRemoveVar, IsVarOnlyUsedAsConst};
   const auto *OldVar = Result.Nodes.getNodeAs<VarDecl>(OldVarDeclId);
   const auto *ObjectArg = Result.Nodes.getNodeAs<VarDecl>(ObjectArgId);
   const auto *CtorCall = Result.Nodes.getNodeAs<CXXConstructExpr>("ctorCall");
@@ -346,15 +346,18 @@ void UnnecessaryCopyInitializationCheck::handleCopyFromLocalVar(
 
 void UnnecessaryCopyInitializationCheck::diagnoseCopyFromMethodReturn(
     const CheckContext &Ctx) {
+  const bool IsConstQualified = Ctx.Var.getType().isConstQualified();
+  // Only say that the variable is used as a const reference if it has uses.
+  const bool OmitUsageNote = IsConstQualified || Ctx.IsVarUnused;
   auto Diagnostic =
       diag(Ctx.Var.getLocation(),
            "the %select{|const qualified }0variable %1 of type %2 is "
            "copy-constructed "
            "from a const reference%select{%select{ but is only used as const "
-           "reference|}0| but is never used}3; consider "
+           "reference|}4| but is never used}3; consider "
            "%select{making it a const reference|removing the statement}3")
-      << Ctx.Var.getType().isConstQualified() << &Ctx.Var << Ctx.Var.getType()
-      << Ctx.IsVarUnused;
+      << IsConstQualified << &Ctx.Var << Ctx.Var.getType()
+      << Ctx.ShouldRemoveVar << OmitUsageNote;
   maybeIssueFixes(Ctx, Diagnostic);
 }
 
@@ -366,14 +369,14 @@ void UnnecessaryCopyInitializationCheck::diagnoseCopyFromLocalVar(
            "modified%select{"
            "| and never used}3; consider %select{avoiding the copy|removing "
            "the statement}3")
-      << &Ctx.Var << &OldVar << Ctx.Var.getType() << Ctx.IsVarUnused;
+      << &Ctx.Var << &OldVar << Ctx.Var.getType() << Ctx.ShouldRemoveVar;
   maybeIssueFixes(Ctx, Diagnostic);
 }
 
 void UnnecessaryCopyInitializationCheck::maybeIssueFixes(
     const CheckContext &Ctx, DiagnosticBuilder &Diagnostic) {
   if (Ctx.IssueFix) {
-    if (Ctx.IsVarUnused)
+    if (Ctx.ShouldRemoveVar)
       recordRemoval(Ctx.VarDeclStmt, Ctx.ASTCtx, Diagnostic);
     else
       recordFixes(Ctx.Var, Ctx.ASTCtx, Diagnostic);
diff --git a/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitializationCheck.h b/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitializationCheck.h
index 9395a1c01b44f7..3ae4aff0034dc1 100644
--- a/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitializationCheck.h
+++ b/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitializationCheck.h
@@ -45,6 +45,7 @@ class UnnecessaryCopyInitializationCheck : public ClangTidyCheck {
     ASTContext &ASTCtx;
     const bool IssueFix;
     const bool IsVarUnused;
+    const bool ShouldRemoveVar;
     const bool IsVarOnlyUsedAsConst;
   };
 
diff --git a/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-copy-initialization.cpp b/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-copy-initialization.cpp
index 0929b9ecc00653..7e9a99b51be2ca 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-copy-initialization.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-copy-initialization.cpp
@@ -773,9 +773,13 @@ void positiveUnusedReferenceIsRemoved() {
 
 void positiveMaybeUnusedIsNotRemoved() {
   [[maybe_unused]] auto FromCall = ExpensiveTypeReference();
-  // CHECK-MESSAGES: [[@LINE-1]]:25: warning: the variable 'FromCall' of type 'ExpensiveToCopyType' is copy-constructed from a const reference but is only used as const reference; consider making it a const reference [performance-unnecessary-copy-initialization]
+  // CHECK-MESSAGES: [[@LINE-1]]:25: warning: the variable 'FromCall' of type 'ExpensiveToCopyType' is copy-constructed from a const reference; consider making it a const reference [performance-unnecessary-copy-initialization]
   // CHECK-FIXES: {{\[\[maybe_unused\]\]}} const auto& FromCall = ExpensiveTypeReference();
 
+  [[maybe_unused]] const auto ConstFromCall = ExpensiveTypeReference();
+  // CHECK-MESSAGES: [[@LINE-1]]:31: warning: the const qualified variable 'ConstFromCall' of type 'const ExpensiveToCopyType' is copy-constructed from a const reference; consider making it a const reference [performance-unnecessary-copy-initialization]
+  // CHECK-FIXES: {{\[\[maybe_unused\]\]}} const auto& ConstFromCall = ExpensiveTypeReference();
+
   ExpensiveToCopyType Orig;
   [[maybe_unused]] auto FromVar{Orig};
   // CHECK-MESSAGES: [[@LINE-1]]:25: warning: local copy 'FromVar' of the variable 'Orig' of type 'ExpensiveToCopyType' is never modified; consider avoiding the copy [performance-unnecessary-copy-initialization]



More information about the cfe-commits mailing list