From: Ted Kremenek Date: Mon, 29 Oct 2007 16:58:49 +0000 (+0000) Subject: For non-floating point types, added check for expressions of the form X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=3ca0bf2a0ac27b1644ed73b8fc61077d2b9c6995;p=clang For non-floating point types, added check for expressions of the form "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 --- diff --git a/Sema/SemaExpr.cpp b/Sema/SemaExpr.cpp index 1156bd7d4d..13267eecec 100644 --- a/Sema/SemaExpr.cpp +++ b/Sema/SemaExpr.cpp @@ -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(IgnoreParen(lex))) + if (DeclRefExpr* DRR = dyn_cast(IgnoreParen(rex))) + if (DRL->getDecl() == DRR->getDecl()) + Diag(loc, diag::warn_selfcomparison); + } + if (isRelational) { if (lType->isRealType() && rType->isRealType()) return Context.IntTy; diff --git a/include/clang/Basic/DiagnosticKinds.def b/include/clang/Basic/DiagnosticKinds.def index 6581e5d7ed..bbdb6bc517 100644 --- a/include/clang/Basic/DiagnosticKinds.def +++ b/include/clang/Basic/DiagnosticKinds.def @@ -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 index 0000000000..450673c69c --- /dev/null +++ b/test/Sema/self-comparison.c @@ -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