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

Dan McArdle via cfe-commits cfe-commits at lists.llvm.org
Wed Jun 12 12:08:48 PDT 2024


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

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

Issue #92408

>From f717082e700645f1fa6ca738a540aef20c2ba015 Mon Sep 17 00:00:00 2001
From: Dan McArdle <dmcardle at google.com>
Date: Wed, 12 Jun 2024 14:57:49 -0400
Subject: [PATCH] [clang][ThreadSafety] Warn when constructor is trylock

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

Issue #92408
---
 clang/lib/Sema/SemaDeclAttr.cpp                   | 6 ++++++
 clang/test/SemaCXX/warn-thread-safety-parsing.cpp | 7 +++++++
 2 files changed, 13 insertions(+)

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 0c5b0cc85897b..e3e0bd31e8067 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}}
 };



More information about the cfe-commits mailing list