Added a warning when referencing an if's condition variable in the
"else" clause, e.g.,
if (int X = foo()) {
} else {
if (X) { // warning: X is always zero in this context
}
}
Fixes rdar://6425550 and lets me think about something other than
DeclContext.
git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@60858 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/Sema/SemaExpr.cpp b/lib/Sema/SemaExpr.cpp
index 8cbbca3..3870f07 100644
--- a/lib/Sema/SemaExpr.cpp
+++ b/lib/Sema/SemaExpr.cpp
@@ -483,6 +483,27 @@
// check if referencing an identifier with __attribute__((deprecated)).
if (VD->getAttr<DeprecatedAttr>())
Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
+
+ if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
+ if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
+ Scope *CheckS = S;
+ while (CheckS) {
+ if (CheckS->isWithinElse() &&
+ CheckS->getControlParent()->isDeclScope(Var)) {
+ if (Var->getType()->isBooleanType())
+ Diag(Loc, diag::warn_value_always_false) << Var->getDeclName();
+ else
+ Diag(Loc, diag::warn_value_always_zero) << Var->getDeclName();
+ break;
+ }
+
+ // Move up one more control parent to check again.
+ CheckS = CheckS->getControlParent();
+ if (CheckS)
+ CheckS = CheckS->getParent();
+ }
+ }
+ }
// Only create DeclRefExpr's for valid Decl's.
if (VD->isInvalidDecl())