[clang] [clang][ThreadSafety] Warn when constructor is trylock (PR #95290)

via cfe-commits cfe-commits at lists.llvm.org
Wed Jun 12 12:22:06 PDT 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang

Author: Dan McArdle (dmcardle)

<details>
<summary>Changes</summary>

With this change, Clang will generate a warning when a constructor is annotated as a trylock function.

Issue #<!-- -->92408

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


2 Files Affected:

- (modified) clang/lib/Sema/SemaDeclAttr.cpp (+6) 
- (modified) clang/test/SemaCXX/warn-thread-safety-parsing.cpp (+7) 


``````````diff
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index ce6b5b1ff6f93..373f6a591fd09 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -605,6 +605,12 @@ static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
 
 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
                                       SmallVectorImpl<Expr *> &Args) {
+  if (isa<CXXConstructorDecl>(D)) {
+    S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
+        << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
+    return false;
+  }
+
   if (!AL.checkAtLeastNumArgs(S, 1))
     return false;
 
diff --git a/clang/test/SemaCXX/warn-thread-safety-parsing.cpp b/clang/test/SemaCXX/warn-thread-safety-parsing.cpp
index 1626e8375892a..c9a2ad498ff24 100644
--- a/clang/test/SemaCXX/warn-thread-safety-parsing.cpp
+++ b/clang/test/SemaCXX/warn-thread-safety-parsing.cpp
@@ -747,6 +747,13 @@ class EtfFoo {
     // expected-warning {{'exclusive_trylock_function' attribute without capability arguments refers to 'this', but 'EtfFoo' isn't annotated with 'capability' or 'scoped_lockable' attribute}}
 };
 
+// It does not make sense to annotate a constructor as an exclusive trylock
+// function. See <https://github.com/llvm/llvm-project/issues/92408>.
+class EtfConstructor {
+  EtfConstructor() EXCLUSIVE_TRYLOCK_FUNCTION(1); // \
+  // expected-warning {{'exclusive_trylock_function' attribute only applies to functions}}
+};
+
 class EXCLUSIVE_TRYLOCK_FUNCTION(1) EtfTestClass { // \
   // expected-warning {{'exclusive_trylock_function' attribute only applies to functions}}
 };

``````````

</details>


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


More information about the cfe-commits mailing list