From eef8c44f96699ab841d07e4f193063779fc1739a Mon Sep 17 00:00:00 2001 From: David Bolvansky Date: Thu, 3 Oct 2019 15:17:59 +0000 Subject: [PATCH] [Diagnostics] Bitwise negation of a boolean expr always evaluates to true; warn with -Wbool-operation Requested here: http://lists.llvm.org/pipermail/cfe-dev/2019-October/063452.html git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@373614 91177308-0d34-0410-b5e6-96231b3b80d8 --- lib/Sema/SemaExpr.cpp | 4 +++- test/Sema/warn-bitwise-negation-bool.c | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 test/Sema/warn-bitwise-negation-bool.c diff --git a/lib/Sema/SemaExpr.cpp b/lib/Sema/SemaExpr.cpp index dceef81529..d75c8240a1 100644 --- a/lib/Sema/SemaExpr.cpp +++ b/lib/Sema/SemaExpr.cpp @@ -13470,7 +13470,6 @@ ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, if (Input.isInvalid()) return ExprError(); resultType = Input.get()->getType(); - if (resultType->isDependentType()) break; // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. @@ -13478,6 +13477,9 @@ ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, // C99 does not support '~' for complex conjugation. Diag(OpLoc, diag::ext_integer_complement_complex) << resultType << Input.get()->getSourceRange(); + else if (Input.get()->IgnoreParenImpCasts()->getType()->isBooleanType()) + Diag(OpLoc, diag::warn_bitwise_negation_bool) + << FixItHint::CreateReplacement(OpLoc, "!"); else if (resultType->hasIntegerRepresentation()) break; else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { diff --git a/test/Sema/warn-bitwise-negation-bool.c b/test/Sema/warn-bitwise-negation-bool.c new file mode 100644 index 0000000000..1d39f0c576 --- /dev/null +++ b/test/Sema/warn-bitwise-negation-bool.c @@ -0,0 +1,20 @@ +// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wbool-operation %s +// RUN: %clang_cc1 -x c -fsyntax-only -verify %s +// RUN: %clang_cc1 -x c -fsyntax-only -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s +// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wbool-operation %s +// RUN: %clang_cc1 -x c++ -fsyntax-only -verify %s +// RUN: %clang_cc1 -x c++ -fsyntax-only -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s + +#ifdef __cplusplus +typedef bool boolean; +#else +typedef _Bool boolean; +#endif + +void test(boolean b, int i) { + b = ~b; // expected-warning {{bitwise negation of a boolean expression always evaluates to 'true'}} + // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:7-[[@LINE-1]]:8}:"!" + b = ~(b); // expected-warning {{bitwise negation of a boolean expression always evaluates to 'true'}} + // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:7-[[@LINE-1]]:8}:"!" + b = ~i; +} -- 2.40.0