[clang] Warning for incorrect useof 'pure' attribute (PR #78200)

Aaron Ballman via cfe-commits cfe-commits at lists.llvm.org
Wed Jan 17 06:45:36 PST 2024


================
@@ -11792,6 +11792,32 @@ static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
                                          OldDecl, Previous);
 }
 
+static void CheckFunctionDeclarationAttributesUsage(Sema &S,
+                                                    FunctionDecl *NewFD) {
+  const bool is_pure = NewFD->hasAttr<PureAttr>();
+  const bool is_const = NewFD->hasAttr<ConstAttr>();
+
+  if (is_pure && is_const) {
+    S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
+    NewFD->dropAttr<PureAttr>();
+  }
+  if (is_pure || is_const) {
+    if (isa<CXXConstructorDecl>(NewFD)) {
----------------
AaronBallman wrote:

I don't see why constructors and destructors should be handled differently. Neither has a way to specify a return value. My mental model for this is: pure and const only make sense on functions that are called for their return value. So anything which does not return a value is suspect to have either of these attributes. For ctor and dtor, there's no possible return value and so there is only one possible remedy (remove the attribute). For functions returning void, there are two possible remedies, remove the attribute or give the function a non-void return type.

Another situation worth thinking about is a function marked `noreturn` but I think those functions are typically declared with a `void` return type anyway and so I'm not certain we need special logic to diagnose this case.

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


More information about the cfe-commits mailing list