UnreachableCodeChecker.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. //==- UnreachableCodeChecker.cpp - Generalized dead code checker -*- C++ -*-==//
  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. // This file implements a generalized unreachable code checker using a
  10. // path-sensitive analysis. We mark any path visited, and then walk the CFG as a
  11. // post-analysis to determine what was never visited.
  12. //
  13. // A similar flow-sensitive only check exists in Analysis/ReachableCode.cpp
  14. //===----------------------------------------------------------------------===//
  15. #include "ClangSACheckers.h"
  16. #include "clang/AST/ParentMap.h"
  17. #include "clang/Basic/Builtins.h"
  18. #include "clang/Basic/SourceManager.h"
  19. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  20. #include "clang/StaticAnalyzer/Core/Checker.h"
  21. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  22. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  23. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
  24. #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
  25. #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
  26. #include "llvm/ADT/SmallSet.h"
  27. // The number of CFGBlock pointers we want to reserve memory for. This is used
  28. // once for each function we analyze.
  29. #define DEFAULT_CFGBLOCKS 256
  30. using namespace clang;
  31. using namespace ento;
  32. namespace {
  33. class UnreachableCodeChecker : public Checker<check::EndAnalysis> {
  34. public:
  35. void checkEndAnalysis(ExplodedGraph &G, BugReporter &B,
  36. ExprEngine &Eng) const;
  37. private:
  38. typedef llvm::SmallSet<unsigned, DEFAULT_CFGBLOCKS> CFGBlocksSet;
  39. static inline const Stmt *getUnreachableStmt(const CFGBlock *CB);
  40. static void FindUnreachableEntryPoints(const CFGBlock *CB,
  41. CFGBlocksSet &reachable,
  42. CFGBlocksSet &visited);
  43. static bool isInvalidPath(const CFGBlock *CB, const ParentMap &PM);
  44. static inline bool isEmptyCFGBlock(const CFGBlock *CB);
  45. };
  46. }
  47. void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G,
  48. BugReporter &B,
  49. ExprEngine &Eng) const {
  50. CFGBlocksSet reachable, visited;
  51. if (Eng.hasWorkRemaining())
  52. return;
  53. const Decl *D = 0;
  54. CFG *C = 0;
  55. ParentMap *PM = 0;
  56. const LocationContext *LC = 0;
  57. // Iterate over ExplodedGraph
  58. for (ExplodedGraph::node_iterator I = G.nodes_begin(), E = G.nodes_end();
  59. I != E; ++I) {
  60. const ProgramPoint &P = I->getLocation();
  61. LC = P.getLocationContext();
  62. if (!LC->inTopFrame())
  63. continue;
  64. if (!D)
  65. D = LC->getAnalysisDeclContext()->getDecl();
  66. // Save the CFG if we don't have it already
  67. if (!C)
  68. C = LC->getAnalysisDeclContext()->getUnoptimizedCFG();
  69. if (!PM)
  70. PM = &LC->getParentMap();
  71. if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) {
  72. const CFGBlock *CB = BE->getBlock();
  73. reachable.insert(CB->getBlockID());
  74. }
  75. }
  76. // Bail out if we didn't get the CFG or the ParentMap.
  77. if (!D || !C || !PM)
  78. return;
  79. // Don't do anything for template instantiations. Proving that code
  80. // in a template instantiation is unreachable means proving that it is
  81. // unreachable in all instantiations.
  82. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  83. if (FD->isTemplateInstantiation())
  84. return;
  85. // Find CFGBlocks that were not covered by any node
  86. for (CFG::const_iterator I = C->begin(), E = C->end(); I != E; ++I) {
  87. const CFGBlock *CB = *I;
  88. // Check if the block is unreachable
  89. if (reachable.count(CB->getBlockID()))
  90. continue;
  91. // Check if the block is empty (an artificial block)
  92. if (isEmptyCFGBlock(CB))
  93. continue;
  94. // Find the entry points for this block
  95. if (!visited.count(CB->getBlockID()))
  96. FindUnreachableEntryPoints(CB, reachable, visited);
  97. // This block may have been pruned; check if we still want to report it
  98. if (reachable.count(CB->getBlockID()))
  99. continue;
  100. // Check for false positives
  101. if (CB->size() > 0 && isInvalidPath(CB, *PM))
  102. continue;
  103. // It is good practice to always have a "default" label in a "switch", even
  104. // if we should never get there. It can be used to detect errors, for
  105. // instance. Unreachable code directly under a "default" label is therefore
  106. // likely to be a false positive.
  107. if (const Stmt *label = CB->getLabel())
  108. if (label->getStmtClass() == Stmt::DefaultStmtClass)
  109. continue;
  110. // Special case for __builtin_unreachable.
  111. // FIXME: This should be extended to include other unreachable markers,
  112. // such as llvm_unreachable.
  113. if (!CB->empty()) {
  114. bool foundUnreachable = false;
  115. for (CFGBlock::const_iterator ci = CB->begin(), ce = CB->end();
  116. ci != ce; ++ci) {
  117. if (Optional<CFGStmt> S = (*ci).getAs<CFGStmt>())
  118. if (const CallExpr *CE = dyn_cast<CallExpr>(S->getStmt())) {
  119. if (CE->getBuiltinCallee() == Builtin::BI__builtin_unreachable) {
  120. foundUnreachable = true;
  121. break;
  122. }
  123. }
  124. }
  125. if (foundUnreachable)
  126. continue;
  127. }
  128. // We found a block that wasn't covered - find the statement to report
  129. SourceRange SR;
  130. PathDiagnosticLocation DL;
  131. SourceLocation SL;
  132. if (const Stmt *S = getUnreachableStmt(CB)) {
  133. SR = S->getSourceRange();
  134. DL = PathDiagnosticLocation::createBegin(S, B.getSourceManager(), LC);
  135. SL = DL.asLocation();
  136. if (SR.isInvalid() || !SL.isValid())
  137. continue;
  138. }
  139. else
  140. continue;
  141. // Check if the SourceLocation is in a system header
  142. const SourceManager &SM = B.getSourceManager();
  143. if (SM.isInSystemHeader(SL) || SM.isInExternCSystemHeader(SL))
  144. continue;
  145. B.EmitBasicReport(D, "Unreachable code", "Dead code",
  146. "This statement is never executed", DL, SR);
  147. }
  148. }
  149. // Recursively finds the entry point(s) for this dead CFGBlock.
  150. void UnreachableCodeChecker::FindUnreachableEntryPoints(const CFGBlock *CB,
  151. CFGBlocksSet &reachable,
  152. CFGBlocksSet &visited) {
  153. visited.insert(CB->getBlockID());
  154. for (CFGBlock::const_pred_iterator I = CB->pred_begin(), E = CB->pred_end();
  155. I != E; ++I) {
  156. if (!reachable.count((*I)->getBlockID())) {
  157. // If we find an unreachable predecessor, mark this block as reachable so
  158. // we don't report this block
  159. reachable.insert(CB->getBlockID());
  160. if (!visited.count((*I)->getBlockID()))
  161. // If we haven't previously visited the unreachable predecessor, recurse
  162. FindUnreachableEntryPoints(*I, reachable, visited);
  163. }
  164. }
  165. }
  166. // Find the Stmt* in a CFGBlock for reporting a warning
  167. const Stmt *UnreachableCodeChecker::getUnreachableStmt(const CFGBlock *CB) {
  168. for (CFGBlock::const_iterator I = CB->begin(), E = CB->end(); I != E; ++I) {
  169. if (Optional<CFGStmt> S = I->getAs<CFGStmt>())
  170. return S->getStmt();
  171. }
  172. if (const Stmt *S = CB->getTerminator())
  173. return S;
  174. else
  175. return 0;
  176. }
  177. // Determines if the path to this CFGBlock contained an element that infers this
  178. // block is a false positive. We assume that FindUnreachableEntryPoints has
  179. // already marked only the entry points to any dead code, so we need only to
  180. // find the condition that led to this block (the predecessor of this block.)
  181. // There will never be more than one predecessor.
  182. bool UnreachableCodeChecker::isInvalidPath(const CFGBlock *CB,
  183. const ParentMap &PM) {
  184. // We only expect a predecessor size of 0 or 1. If it is >1, then an external
  185. // condition has broken our assumption (for example, a sink being placed by
  186. // another check). In these cases, we choose not to report.
  187. if (CB->pred_size() > 1)
  188. return true;
  189. // If there are no predecessors, then this block is trivially unreachable
  190. if (CB->pred_size() == 0)
  191. return false;
  192. const CFGBlock *pred = *CB->pred_begin();
  193. // Get the predecessor block's terminator conditon
  194. const Stmt *cond = pred->getTerminatorCondition();
  195. //assert(cond && "CFGBlock's predecessor has a terminator condition");
  196. // The previous assertion is invalid in some cases (eg do/while). Leaving
  197. // reporting of these situations on at the moment to help triage these cases.
  198. if (!cond)
  199. return false;
  200. // Run each of the checks on the conditions
  201. if (containsMacro(cond) || containsEnum(cond)
  202. || containsStaticLocal(cond) || containsBuiltinOffsetOf(cond)
  203. || containsStmt<UnaryExprOrTypeTraitExpr>(cond))
  204. return true;
  205. return false;
  206. }
  207. // Returns true if the given CFGBlock is empty
  208. bool UnreachableCodeChecker::isEmptyCFGBlock(const CFGBlock *CB) {
  209. return CB->getLabel() == 0 // No labels
  210. && CB->size() == 0 // No statements
  211. && !CB->getTerminator(); // No terminator
  212. }
  213. void ento::registerUnreachableCodeChecker(CheckerManager &mgr) {
  214. mgr.registerChecker<UnreachableCodeChecker>();
  215. }