IdenticalExprChecker.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. //== IdenticalExprChecker.cpp - Identical expression checker----------------==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. ///
  10. /// \file
  11. /// \brief This defines IdenticalExprChecker, a check that warns about
  12. /// unintended use of identical expressions.
  13. ///
  14. /// It checks for use of identical expressions with comparison operators and
  15. /// inside conditional expressions.
  16. ///
  17. //===----------------------------------------------------------------------===//
  18. #include "ClangSACheckers.h"
  19. #include "clang/AST/RecursiveASTVisitor.h"
  20. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  21. #include "clang/StaticAnalyzer/Core/Checker.h"
  22. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  23. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  24. using namespace clang;
  25. using namespace ento;
  26. static bool isIdenticalStmt(const ASTContext &Ctx, const Stmt *Stmt1,
  27. const Stmt *Stmt2, bool IgnoreSideEffects = false);
  28. //===----------------------------------------------------------------------===//
  29. // FindIdenticalExprVisitor - Identify nodes using identical expressions.
  30. //===----------------------------------------------------------------------===//
  31. namespace {
  32. class FindIdenticalExprVisitor
  33. : public RecursiveASTVisitor<FindIdenticalExprVisitor> {
  34. BugReporter &BR;
  35. const CheckerBase *Checker;
  36. AnalysisDeclContext *AC;
  37. public:
  38. explicit FindIdenticalExprVisitor(BugReporter &B,
  39. const CheckerBase *Checker,
  40. AnalysisDeclContext *A)
  41. : BR(B), Checker(Checker), AC(A) {}
  42. // FindIdenticalExprVisitor only visits nodes
  43. // that are binary operators, if statements or
  44. // conditional operators.
  45. bool VisitBinaryOperator(const BinaryOperator *B);
  46. bool VisitIfStmt(const IfStmt *I);
  47. bool VisitConditionalOperator(const ConditionalOperator *C);
  48. private:
  49. void reportIdenticalExpr(const BinaryOperator *B, bool CheckBitwise,
  50. ArrayRef<SourceRange> Sr);
  51. void checkBitwiseOrLogicalOp(const BinaryOperator *B, bool CheckBitwise);
  52. void checkComparisonOp(const BinaryOperator *B);
  53. };
  54. } // end anonymous namespace
  55. void FindIdenticalExprVisitor::reportIdenticalExpr(const BinaryOperator *B,
  56. bool CheckBitwise,
  57. ArrayRef<SourceRange> Sr) {
  58. StringRef Message;
  59. if (CheckBitwise)
  60. Message = "identical expressions on both sides of bitwise operator";
  61. else
  62. Message = "identical expressions on both sides of logical operator";
  63. PathDiagnosticLocation ELoc =
  64. PathDiagnosticLocation::createOperatorLoc(B, BR.getSourceManager());
  65. BR.EmitBasicReport(AC->getDecl(), Checker,
  66. "Use of identical expressions",
  67. categories::LogicError,
  68. Message, ELoc, Sr);
  69. }
  70. void FindIdenticalExprVisitor::checkBitwiseOrLogicalOp(const BinaryOperator *B,
  71. bool CheckBitwise) {
  72. SourceRange Sr[2];
  73. const Expr *LHS = B->getLHS();
  74. const Expr *RHS = B->getRHS();
  75. // Split operators as long as we still have operators to split on. We will
  76. // get called for every binary operator in an expression so there is no need
  77. // to check every one against each other here, just the right most one with
  78. // the others.
  79. while (const BinaryOperator *B2 = dyn_cast<BinaryOperator>(LHS)) {
  80. if (B->getOpcode() != B2->getOpcode())
  81. break;
  82. if (isIdenticalStmt(AC->getASTContext(), RHS, B2->getRHS())) {
  83. Sr[0] = RHS->getSourceRange();
  84. Sr[1] = B2->getRHS()->getSourceRange();
  85. reportIdenticalExpr(B, CheckBitwise, Sr);
  86. }
  87. LHS = B2->getLHS();
  88. }
  89. if (isIdenticalStmt(AC->getASTContext(), RHS, LHS)) {
  90. Sr[0] = RHS->getSourceRange();
  91. Sr[1] = LHS->getSourceRange();
  92. reportIdenticalExpr(B, CheckBitwise, Sr);
  93. }
  94. }
  95. bool FindIdenticalExprVisitor::VisitIfStmt(const IfStmt *I) {
  96. const Stmt *Stmt1 = I->getThen();
  97. const Stmt *Stmt2 = I->getElse();
  98. // Check for identical conditions:
  99. //
  100. // if (b) {
  101. // foo1();
  102. // } else if (b) {
  103. // foo2();
  104. // }
  105. if (Stmt1 && Stmt2) {
  106. const Expr *Cond1 = I->getCond();
  107. const Stmt *Else = Stmt2;
  108. while (const IfStmt *I2 = dyn_cast_or_null<IfStmt>(Else)) {
  109. const Expr *Cond2 = I2->getCond();
  110. if (isIdenticalStmt(AC->getASTContext(), Cond1, Cond2, false)) {
  111. SourceRange Sr = Cond1->getSourceRange();
  112. PathDiagnosticLocation ELoc(Cond2, BR.getSourceManager(), AC);
  113. BR.EmitBasicReport(AC->getDecl(), Checker, "Identical conditions",
  114. categories::LogicError,
  115. "expression is identical to previous condition",
  116. ELoc, Sr);
  117. }
  118. Else = I2->getElse();
  119. }
  120. }
  121. if (!Stmt1 || !Stmt2)
  122. return true;
  123. // Special handling for code like:
  124. //
  125. // if (b) {
  126. // i = 1;
  127. // } else
  128. // i = 1;
  129. if (const CompoundStmt *CompStmt = dyn_cast<CompoundStmt>(Stmt1)) {
  130. if (CompStmt->size() == 1)
  131. Stmt1 = CompStmt->body_back();
  132. }
  133. if (const CompoundStmt *CompStmt = dyn_cast<CompoundStmt>(Stmt2)) {
  134. if (CompStmt->size() == 1)
  135. Stmt2 = CompStmt->body_back();
  136. }
  137. if (isIdenticalStmt(AC->getASTContext(), Stmt1, Stmt2, true)) {
  138. PathDiagnosticLocation ELoc =
  139. PathDiagnosticLocation::createBegin(I, BR.getSourceManager(), AC);
  140. BR.EmitBasicReport(AC->getDecl(), Checker,
  141. "Identical branches",
  142. categories::LogicError,
  143. "true and false branches are identical", ELoc);
  144. }
  145. return true;
  146. }
  147. bool FindIdenticalExprVisitor::VisitBinaryOperator(const BinaryOperator *B) {
  148. BinaryOperator::Opcode Op = B->getOpcode();
  149. if (BinaryOperator::isBitwiseOp(Op))
  150. checkBitwiseOrLogicalOp(B, true);
  151. if (BinaryOperator::isLogicalOp(Op))
  152. checkBitwiseOrLogicalOp(B, false);
  153. if (BinaryOperator::isComparisonOp(Op))
  154. checkComparisonOp(B);
  155. // We want to visit ALL nodes (subexpressions of binary comparison
  156. // expressions too) that contains comparison operators.
  157. // True is always returned to traverse ALL nodes.
  158. return true;
  159. }
  160. void FindIdenticalExprVisitor::checkComparisonOp(const BinaryOperator *B) {
  161. BinaryOperator::Opcode Op = B->getOpcode();
  162. //
  163. // Special case for floating-point representation.
  164. //
  165. // If expressions on both sides of comparison operator are of type float,
  166. // then for some comparison operators no warning shall be
  167. // reported even if the expressions are identical from a symbolic point of
  168. // view. Comparison between expressions, declared variables and literals
  169. // are treated differently.
  170. //
  171. // != and == between float literals that have the same value should NOT warn.
  172. // < > between float literals that have the same value SHOULD warn.
  173. //
  174. // != and == between the same float declaration should NOT warn.
  175. // < > between the same float declaration SHOULD warn.
  176. //
  177. // != and == between eq. expressions that evaluates into float
  178. // should NOT warn.
  179. // < > between eq. expressions that evaluates into float
  180. // should NOT warn.
  181. //
  182. const Expr *LHS = B->getLHS()->IgnoreParenImpCasts();
  183. const Expr *RHS = B->getRHS()->IgnoreParenImpCasts();
  184. const DeclRefExpr *DeclRef1 = dyn_cast<DeclRefExpr>(LHS);
  185. const DeclRefExpr *DeclRef2 = dyn_cast<DeclRefExpr>(RHS);
  186. const FloatingLiteral *FloatLit1 = dyn_cast<FloatingLiteral>(LHS);
  187. const FloatingLiteral *FloatLit2 = dyn_cast<FloatingLiteral>(RHS);
  188. if ((DeclRef1) && (DeclRef2)) {
  189. if ((DeclRef1->getType()->hasFloatingRepresentation()) &&
  190. (DeclRef2->getType()->hasFloatingRepresentation())) {
  191. if (DeclRef1->getDecl() == DeclRef2->getDecl()) {
  192. if ((Op == BO_EQ) || (Op == BO_NE)) {
  193. return;
  194. }
  195. }
  196. }
  197. } else if ((FloatLit1) && (FloatLit2)) {
  198. if (FloatLit1->getValue().bitwiseIsEqual(FloatLit2->getValue())) {
  199. if ((Op == BO_EQ) || (Op == BO_NE)) {
  200. return;
  201. }
  202. }
  203. } else if (LHS->getType()->hasFloatingRepresentation()) {
  204. // If any side of comparison operator still has floating-point
  205. // representation, then it's an expression. Don't warn.
  206. // Here only LHS is checked since RHS will be implicit casted to float.
  207. return;
  208. } else {
  209. // No special case with floating-point representation, report as usual.
  210. }
  211. if (isIdenticalStmt(AC->getASTContext(), B->getLHS(), B->getRHS())) {
  212. PathDiagnosticLocation ELoc =
  213. PathDiagnosticLocation::createOperatorLoc(B, BR.getSourceManager());
  214. StringRef Message;
  215. if (((Op == BO_EQ) || (Op == BO_LE) || (Op == BO_GE)))
  216. Message = "comparison of identical expressions always evaluates to true";
  217. else
  218. Message = "comparison of identical expressions always evaluates to false";
  219. BR.EmitBasicReport(AC->getDecl(), Checker,
  220. "Compare of identical expressions",
  221. categories::LogicError, Message, ELoc);
  222. }
  223. }
  224. bool FindIdenticalExprVisitor::VisitConditionalOperator(
  225. const ConditionalOperator *C) {
  226. // Check if expressions in conditional expression are identical
  227. // from a symbolic point of view.
  228. if (isIdenticalStmt(AC->getASTContext(), C->getTrueExpr(),
  229. C->getFalseExpr(), true)) {
  230. PathDiagnosticLocation ELoc =
  231. PathDiagnosticLocation::createConditionalColonLoc(
  232. C, BR.getSourceManager());
  233. SourceRange Sr[2];
  234. Sr[0] = C->getTrueExpr()->getSourceRange();
  235. Sr[1] = C->getFalseExpr()->getSourceRange();
  236. BR.EmitBasicReport(
  237. AC->getDecl(), Checker,
  238. "Identical expressions in conditional expression",
  239. categories::LogicError,
  240. "identical expressions on both sides of ':' in conditional expression",
  241. ELoc, Sr);
  242. }
  243. // We want to visit ALL nodes (expressions in conditional
  244. // expressions too) that contains conditional operators,
  245. // thus always return true to traverse ALL nodes.
  246. return true;
  247. }
  248. /// \brief Determines whether two statement trees are identical regarding
  249. /// operators and symbols.
  250. ///
  251. /// Exceptions: expressions containing macros or functions with possible side
  252. /// effects are never considered identical.
  253. /// Limitations: (t + u) and (u + t) are not considered identical.
  254. /// t*(u + t) and t*u + t*t are not considered identical.
  255. ///
  256. static bool isIdenticalStmt(const ASTContext &Ctx, const Stmt *Stmt1,
  257. const Stmt *Stmt2, bool IgnoreSideEffects) {
  258. if (!Stmt1 || !Stmt2) {
  259. if (!Stmt1 && !Stmt2)
  260. return true;
  261. return false;
  262. }
  263. // If Stmt1 & Stmt2 are of different class then they are not
  264. // identical statements.
  265. if (Stmt1->getStmtClass() != Stmt2->getStmtClass())
  266. return false;
  267. const Expr *Expr1 = dyn_cast<Expr>(Stmt1);
  268. const Expr *Expr2 = dyn_cast<Expr>(Stmt2);
  269. if (Expr1 && Expr2) {
  270. // If Stmt1 has side effects then don't warn even if expressions
  271. // are identical.
  272. if (!IgnoreSideEffects && Expr1->HasSideEffects(Ctx))
  273. return false;
  274. // If either expression comes from a macro then don't warn even if
  275. // the expressions are identical.
  276. if ((Expr1->getExprLoc().isMacroID()) || (Expr2->getExprLoc().isMacroID()))
  277. return false;
  278. // If all children of two expressions are identical, return true.
  279. Expr::const_child_iterator I1 = Expr1->child_begin();
  280. Expr::const_child_iterator I2 = Expr2->child_begin();
  281. while (I1 != Expr1->child_end() && I2 != Expr2->child_end()) {
  282. if (!*I1 || !*I2 || !isIdenticalStmt(Ctx, *I1, *I2, IgnoreSideEffects))
  283. return false;
  284. ++I1;
  285. ++I2;
  286. }
  287. // If there are different number of children in the statements, return
  288. // false.
  289. if (I1 != Expr1->child_end())
  290. return false;
  291. if (I2 != Expr2->child_end())
  292. return false;
  293. }
  294. switch (Stmt1->getStmtClass()) {
  295. default:
  296. return false;
  297. case Stmt::CallExprClass:
  298. case Stmt::ArraySubscriptExprClass:
  299. case Stmt::ImplicitCastExprClass:
  300. case Stmt::ParenExprClass:
  301. case Stmt::BreakStmtClass:
  302. case Stmt::ContinueStmtClass:
  303. case Stmt::NullStmtClass:
  304. return true;
  305. case Stmt::CStyleCastExprClass: {
  306. const CStyleCastExpr* CastExpr1 = cast<CStyleCastExpr>(Stmt1);
  307. const CStyleCastExpr* CastExpr2 = cast<CStyleCastExpr>(Stmt2);
  308. return CastExpr1->getTypeAsWritten() == CastExpr2->getTypeAsWritten();
  309. }
  310. case Stmt::ReturnStmtClass: {
  311. const ReturnStmt *ReturnStmt1 = cast<ReturnStmt>(Stmt1);
  312. const ReturnStmt *ReturnStmt2 = cast<ReturnStmt>(Stmt2);
  313. return isIdenticalStmt(Ctx, ReturnStmt1->getRetValue(),
  314. ReturnStmt2->getRetValue(), IgnoreSideEffects);
  315. }
  316. case Stmt::ForStmtClass: {
  317. const ForStmt *ForStmt1 = cast<ForStmt>(Stmt1);
  318. const ForStmt *ForStmt2 = cast<ForStmt>(Stmt2);
  319. if (!isIdenticalStmt(Ctx, ForStmt1->getInit(), ForStmt2->getInit(),
  320. IgnoreSideEffects))
  321. return false;
  322. if (!isIdenticalStmt(Ctx, ForStmt1->getCond(), ForStmt2->getCond(),
  323. IgnoreSideEffects))
  324. return false;
  325. if (!isIdenticalStmt(Ctx, ForStmt1->getInc(), ForStmt2->getInc(),
  326. IgnoreSideEffects))
  327. return false;
  328. if (!isIdenticalStmt(Ctx, ForStmt1->getBody(), ForStmt2->getBody(),
  329. IgnoreSideEffects))
  330. return false;
  331. return true;
  332. }
  333. case Stmt::DoStmtClass: {
  334. const DoStmt *DStmt1 = cast<DoStmt>(Stmt1);
  335. const DoStmt *DStmt2 = cast<DoStmt>(Stmt2);
  336. if (!isIdenticalStmt(Ctx, DStmt1->getCond(), DStmt2->getCond(),
  337. IgnoreSideEffects))
  338. return false;
  339. if (!isIdenticalStmt(Ctx, DStmt1->getBody(), DStmt2->getBody(),
  340. IgnoreSideEffects))
  341. return false;
  342. return true;
  343. }
  344. case Stmt::WhileStmtClass: {
  345. const WhileStmt *WStmt1 = cast<WhileStmt>(Stmt1);
  346. const WhileStmt *WStmt2 = cast<WhileStmt>(Stmt2);
  347. if (!isIdenticalStmt(Ctx, WStmt1->getCond(), WStmt2->getCond(),
  348. IgnoreSideEffects))
  349. return false;
  350. if (!isIdenticalStmt(Ctx, WStmt1->getBody(), WStmt2->getBody(),
  351. IgnoreSideEffects))
  352. return false;
  353. return true;
  354. }
  355. case Stmt::IfStmtClass: {
  356. const IfStmt *IStmt1 = cast<IfStmt>(Stmt1);
  357. const IfStmt *IStmt2 = cast<IfStmt>(Stmt2);
  358. if (!isIdenticalStmt(Ctx, IStmt1->getCond(), IStmt2->getCond(),
  359. IgnoreSideEffects))
  360. return false;
  361. if (!isIdenticalStmt(Ctx, IStmt1->getThen(), IStmt2->getThen(),
  362. IgnoreSideEffects))
  363. return false;
  364. if (!isIdenticalStmt(Ctx, IStmt1->getElse(), IStmt2->getElse(),
  365. IgnoreSideEffects))
  366. return false;
  367. return true;
  368. }
  369. case Stmt::CompoundStmtClass: {
  370. const CompoundStmt *CompStmt1 = cast<CompoundStmt>(Stmt1);
  371. const CompoundStmt *CompStmt2 = cast<CompoundStmt>(Stmt2);
  372. if (CompStmt1->size() != CompStmt2->size())
  373. return false;
  374. CompoundStmt::const_body_iterator I1 = CompStmt1->body_begin();
  375. CompoundStmt::const_body_iterator I2 = CompStmt2->body_begin();
  376. while (I1 != CompStmt1->body_end() && I2 != CompStmt2->body_end()) {
  377. if (!isIdenticalStmt(Ctx, *I1, *I2, IgnoreSideEffects))
  378. return false;
  379. ++I1;
  380. ++I2;
  381. }
  382. return true;
  383. }
  384. case Stmt::CompoundAssignOperatorClass:
  385. case Stmt::BinaryOperatorClass: {
  386. const BinaryOperator *BinOp1 = cast<BinaryOperator>(Stmt1);
  387. const BinaryOperator *BinOp2 = cast<BinaryOperator>(Stmt2);
  388. return BinOp1->getOpcode() == BinOp2->getOpcode();
  389. }
  390. case Stmt::CharacterLiteralClass: {
  391. const CharacterLiteral *CharLit1 = cast<CharacterLiteral>(Stmt1);
  392. const CharacterLiteral *CharLit2 = cast<CharacterLiteral>(Stmt2);
  393. return CharLit1->getValue() == CharLit2->getValue();
  394. }
  395. case Stmt::DeclRefExprClass: {
  396. const DeclRefExpr *DeclRef1 = cast<DeclRefExpr>(Stmt1);
  397. const DeclRefExpr *DeclRef2 = cast<DeclRefExpr>(Stmt2);
  398. return DeclRef1->getDecl() == DeclRef2->getDecl();
  399. }
  400. case Stmt::IntegerLiteralClass: {
  401. const IntegerLiteral *IntLit1 = cast<IntegerLiteral>(Stmt1);
  402. const IntegerLiteral *IntLit2 = cast<IntegerLiteral>(Stmt2);
  403. llvm::APInt I1 = IntLit1->getValue();
  404. llvm::APInt I2 = IntLit2->getValue();
  405. if (I1.getBitWidth() != I2.getBitWidth())
  406. return false;
  407. return I1 == I2;
  408. }
  409. case Stmt::FloatingLiteralClass: {
  410. const FloatingLiteral *FloatLit1 = cast<FloatingLiteral>(Stmt1);
  411. const FloatingLiteral *FloatLit2 = cast<FloatingLiteral>(Stmt2);
  412. return FloatLit1->getValue().bitwiseIsEqual(FloatLit2->getValue());
  413. }
  414. case Stmt::StringLiteralClass: {
  415. const StringLiteral *StringLit1 = cast<StringLiteral>(Stmt1);
  416. const StringLiteral *StringLit2 = cast<StringLiteral>(Stmt2);
  417. return StringLit1->getBytes() == StringLit2->getBytes();
  418. }
  419. case Stmt::MemberExprClass: {
  420. const MemberExpr *MemberStmt1 = cast<MemberExpr>(Stmt1);
  421. const MemberExpr *MemberStmt2 = cast<MemberExpr>(Stmt2);
  422. return MemberStmt1->getMemberDecl() == MemberStmt2->getMemberDecl();
  423. }
  424. case Stmt::UnaryOperatorClass: {
  425. const UnaryOperator *UnaryOp1 = cast<UnaryOperator>(Stmt1);
  426. const UnaryOperator *UnaryOp2 = cast<UnaryOperator>(Stmt2);
  427. return UnaryOp1->getOpcode() == UnaryOp2->getOpcode();
  428. }
  429. }
  430. }
  431. //===----------------------------------------------------------------------===//
  432. // FindIdenticalExprChecker
  433. //===----------------------------------------------------------------------===//
  434. namespace {
  435. class FindIdenticalExprChecker : public Checker<check::ASTCodeBody> {
  436. public:
  437. void checkASTCodeBody(const Decl *D, AnalysisManager &Mgr,
  438. BugReporter &BR) const {
  439. FindIdenticalExprVisitor Visitor(BR, this, Mgr.getAnalysisDeclContext(D));
  440. Visitor.TraverseDecl(const_cast<Decl *>(D));
  441. }
  442. };
  443. } // end anonymous namespace
  444. void ento::registerIdenticalExprChecker(CheckerManager &Mgr) {
  445. Mgr.registerChecker<FindIdenticalExprChecker>();
  446. }