[clang] [Clang] Honour [[maybe_unused]] on private fields (PR #187940)

via cfe-commits cfe-commits at lists.llvm.org
Sun Mar 22 08:56:23 PDT 2026


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang

Author: None (Jean-Christian-Cirstea)

<details>
<summary>Changes</summary>

Before this commit, [[maybe_unused]] on private fields was ignored. In conjunction with `-Wunused-private-field`, false warnings were emitted by clang. This commit fixes this by checking if an unused private field is annotated with [[maybe_unused]].

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


2 Files Affected:

- (modified) clang/lib/Sema/Sema.cpp (+1-1) 
- (added) clang/test/SemaCXX/warn-maybe-unused-private-field.cpp (+11) 


``````````diff
diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 3065b5e1e66d3..201a2714fd8a3 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1610,7 +1610,7 @@ void Sema::ActOnEndOfTranslationUnit() {
     RecordCompleteMap MNCComplete;
     for (const NamedDecl *D : UnusedPrivateFields) {
       const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
-      if (RD && !RD->isUnion() &&
+      if (RD && !RD->isUnion() && !RD->hasAttr<UnusedAttr>() &&
           IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
         Diag(D->getLocation(), diag::warn_unused_private_field)
               << D->getDeclName();
diff --git a/clang/test/SemaCXX/warn-maybe-unused-private-field.cpp b/clang/test/SemaCXX/warn-maybe-unused-private-field.cpp
new file mode 100644
index 0000000000000..505c950a9fb81
--- /dev/null
+++ b/clang/test/SemaCXX/warn-maybe-unused-private-field.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -fsyntax-only -Wunused-private-field -verify -std=c++17 %s
+// RUN: %clang_cc1 -fsyntax-only -Wunused-private-field -verify -std=c++20 %s
+// RUN: %clang_cc1 -fsyntax-only -Wunused-private-field -verify -std=c++23 %s
+
+class MyClass {
+	// Marking an unused field with [[maybe_unused]] shouldn't result in a
+	// warning
+	[[maybe_unused]]
+	unsigned field1;
+	signed field2; // expected-warning{{private field 'field2' is not used}}
+};

``````````

</details>


https://github.com/llvm/llvm-project/pull/187940


More information about the cfe-commits mailing list