[clang] f819dbf - Classify (small unsigned bitfield) < 0 comparisons under

Richard Smith via cfe-commits cfe-commits at lists.llvm.org
Mon Aug 31 23:17:05 PDT 2020


Author: Richard Smith
Date: 2020-08-31T23:16:48-07:00
New Revision: f819dbf012b3f624a836641f90dabff5f667b82e

URL: https://github.com/llvm/llvm-project/commit/f819dbf012b3f624a836641f90dabff5f667b82e
DIFF: https://github.com/llvm/llvm-project/commit/f819dbf012b3f624a836641f90dabff5f667b82e.diff

LOG: Classify (small unsigned bitfield) < 0 comparisons under
-Wtautological-unsigned-zero-compare not under
-Wtautological-value-range-compare.

Added: 
    

Modified: 
    clang/lib/Sema/SemaChecking.cpp
    clang/test/Sema/compare.c

Removed: 
    


################################################################################
diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 3a2f070e7e68..2e07c8f63b79 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -10944,6 +10944,12 @@ static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
   if (InRange && IsEnumConstOrFromMacro(S, Constant))
     return false;
 
+  // A comparison of an unsigned bit-field against 0 is really a type problem,
+  // even though at the type level the bit-field might promote to 'signed int'.
+  if (Other->refersToBitField() && InRange && Value == 0 &&
+      Other->getType()->isUnsignedIntegerOrEnumerationType())
+    TautologicalTypeCompare = true;
+
   // If this is a comparison to an enum constant, include that
   // constant in the diagnostic.
   const EnumConstantDecl *ED = nullptr;

diff  --git a/clang/test/Sema/compare.c b/clang/test/Sema/compare.c
index 25aa13f6ba38..85dcffc502fd 100644
--- a/clang/test/Sema/compare.c
+++ b/clang/test/Sema/compare.c
@@ -285,6 +285,20 @@ int test5(unsigned int x) {
     && (0 <= x); // expected-warning {{comparison of 0 <= unsigned expression is always true}}
 }
 
+struct bitfield {
+  int a : 3;
+  unsigned b : 3;
+  long c : 40;
+  unsigned long d : 40;
+};
+
+void test5a(struct bitfield a) {
+  if (a.a < 0) {}
+  if (a.b < 0) {} // expected-warning {{comparison of unsigned expression < 0 is always false}}
+  if (a.c < 0) {}
+  if (a.d < 0) {} // expected-warning {{comparison of unsigned expression < 0 is always false}}
+}
+
 int test6(unsigned i, unsigned power) {
   unsigned x = (i < (1 << power) ? i : 0);
   return x != 3 ? 1 << power : i;


        


More information about the cfe-commits mailing list