[clang] [Clang] warn on discarded [[nodiscard]] function results after casting in C (PR #104677)
Oleksandr T. via cfe-commits
cfe-commits at lists.llvm.org
Sat Aug 17 09:45:03 PDT 2024
https://github.com/a-tarasyuk created https://github.com/llvm/llvm-project/pull/104677
Fixes #104391
>From cd7ce740464c9c46ab231cf773fd1cf28e3495eb Mon Sep 17 00:00:00 2001
From: Oleksandr T <oleksandr.tarasiuk at outlook.com>
Date: Sat, 17 Aug 2024 19:43:45 +0300
Subject: [PATCH] [Clang] warn on discarded [[nodiscard]] function results
after casting in C
---
clang/docs/ReleaseNotes.rst | 2 ++
clang/lib/Sema/SemaStmt.cpp | 3 ++-
clang/test/Sema/c2x-nodiscard.c | 6 ++++++
3 files changed, 10 insertions(+), 1 deletion(-)
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ffdd063ec99037..c8c6a98264b3a2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -214,6 +214,8 @@ Improvements to Clang's diagnostics
- Clang now diagnoses the use of ``main`` in an ``extern`` context as invalid according to [basic.start.main] p3. Fixes #GH101512.
+- Clang now diagnoses when the result of a [[nodiscard]] function is discarded after being cast in C. Fixes #GH104391.
+
Improvements to Clang's time-trace
----------------------------------
diff --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index d283eaa511011b..ba681671eb3290 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -281,7 +281,8 @@ void Sema::DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID) {
E = WarnExpr;
if (const auto *Cast = dyn_cast<CastExpr>(E))
if (Cast->getCastKind() == CK_NoOp ||
- Cast->getCastKind() == CK_ConstructorConversion)
+ Cast->getCastKind() == CK_ConstructorConversion ||
+ Cast->getCastKind() == CK_IntegralCast)
E = Cast->getSubExpr()->IgnoreImpCasts();
if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
diff --git a/clang/test/Sema/c2x-nodiscard.c b/clang/test/Sema/c2x-nodiscard.c
index cb33c0c242e7db..8b48fe8118dfe7 100644
--- a/clang/test/Sema/c2x-nodiscard.c
+++ b/clang/test/Sema/c2x-nodiscard.c
@@ -54,3 +54,9 @@ void test_missiles(void) {
launch_missiles();
}
+[[nodiscard]] int f3();
+
+void f4() {
+#define M (unsigned int) f3()
+ M; // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}}
+}
More information about the cfe-commits
mailing list