]> granicus.if.org Git - clang/commitdiff
For non-floating point types, added check for expressions of the form
authorTed Kremenek <kremenek@apple.com>
Mon, 29 Oct 2007 16:58:49 +0000 (16:58 +0000)
committerTed Kremenek <kremenek@apple.com>
Mon, 29 Oct 2007 16:58:49 +0000 (16:58 +0000)
"x == x" and "x != x".  We emit a warning for these since they always evaluate
to a constant value and often indicate a logical error.

Added test case for this check.

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@43450 91177308-0d34-0410-b5e6-96231b3b80d8

Sema/SemaExpr.cpp
include/clang/Basic/DiagnosticKinds.def
test/Sema/self-comparison.c [new file with mode: 0644]

index 1156bd7d4d1788c824cfbf2831418809dccae8a8..13267eecec395892039ed39949eb15bfbe4c8e2d 100644 (file)
@@ -1218,6 +1218,13 @@ inline QualType Sema::CheckCompareOperands( // C99 6.5.8
   QualType lType = lex->getType();
   QualType rType = rex->getType();
   
+  if (!lType->isFloatingType()) {
+    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
+      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
+        if (DRL->getDecl() == DRR->getDecl())
+          Diag(loc, diag::warn_selfcomparison);      
+  }
+  
   if (isRelational) {
     if (lType->isRealType() && rType->isRealType())
       return Context.IntTy;
index 6581e5d7ed4bac3d2d8f8c13db65afda4ff210e3..bbdb6bc51730738031766dbdfcc5ae2b1797bf22 100644 (file)
@@ -824,6 +824,11 @@ DIAG(warn_ret_stack_ref, WARNING,
 DIAG(warn_floatingpoint_eq, WARNING,
   "comparing floating point with == or != is unsafe")
 
+// CHECK: for non-floating point, expressions of the form x == x or x != x
+// should result in a warning, since these always evaluate to a constant.
+DIAG(warn_selfcomparison,WARNING,
+     "self-comparison always results in a constant value.")
+
 // CHECK: stores to variables that are no longer live (dead stores)
 DIAG(warn_dead_store, WARNING, "value stored to variable is never used")
 
diff --git a/test/Sema/self-comparison.c b/test/Sema/self-comparison.c
new file mode 100644 (file)
index 0000000..450673c
--- /dev/null
@@ -0,0 +1,17 @@
+// RUN: clang -fsyntax-only -verify %s
+
+int foo(int x) {
+  return x == x; // expected-warning {{self-comparison always results}}
+}
+
+int foo2(int x) {
+  return (x) != (((x))); // expected-warning {{self-comparison always results}}
+}
+
+int bar(float x) {
+  return x == x; // no-warning
+}
+
+int bar2(float x) {
+  return x != x; // no-warning
+}
\ No newline at end of file