From e451eae8d7bd87992b681105a1ea91714b7158c6 Mon Sep 17 00:00:00 2001 From: Ted Kremenek Date: Mon, 29 Oct 2007 16:58:49 +0000 Subject: [PATCH] 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. llvm-svn: 43450 --- clang/Sema/SemaExpr.cpp | 7 +++++++ clang/include/clang/Basic/DiagnosticKinds.def | 5 +++++ clang/test/Sema/self-comparison.c | 17 +++++++++++++++++ 3 files changed, 29 insertions(+) create mode 100644 clang/test/Sema/self-comparison.c diff --git a/clang/Sema/SemaExpr.cpp b/clang/Sema/SemaExpr.cpp index 1156bd7d4d17..13267eecec39 100644 --- a/clang/Sema/SemaExpr.cpp +++ b/clang/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/clang/include/clang/Basic/DiagnosticKinds.def b/clang/include/clang/Basic/DiagnosticKinds.def index 6581e5d7ed4b..bbdb6bc51730 100644 --- a/clang/include/clang/Basic/DiagnosticKinds.def +++ b/clang/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/clang/test/Sema/self-comparison.c b/clang/test/Sema/self-comparison.c new file mode 100644 index 000000000000..450673c69c32 --- /dev/null +++ b/clang/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