UnreachableCodeChecker.cpp revision 256281
11573Srgrimes//==- UnreachableCodeChecker.cpp - Generalized dead code checker -*- C++ -*-==//
21573Srgrimes//
31573Srgrimes//                     The LLVM Compiler Infrastructure
41573Srgrimes//
51573Srgrimes// This file is distributed under the University of Illinois Open Source
61573Srgrimes// License. See LICENSE.TXT for details.
71573Srgrimes//
81573Srgrimes//===----------------------------------------------------------------------===//
91573Srgrimes// This file implements a generalized unreachable code checker using a
101573Srgrimes// path-sensitive analysis. We mark any path visited, and then walk the CFG as a
111573Srgrimes// post-analysis to determine what was never visited.
121573Srgrimes//
131573Srgrimes// A similar flow-sensitive only check exists in Analysis/ReachableCode.cpp
141573Srgrimes//===----------------------------------------------------------------------===//
151573Srgrimes
16249808Semaste#include "ClangSACheckers.h"
171573Srgrimes#include "clang/AST/ParentMap.h"
181573Srgrimes#include "clang/Basic/Builtins.h"
191573Srgrimes#include "clang/Basic/SourceManager.h"
201573Srgrimes#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
211573Srgrimes#include "clang/StaticAnalyzer/Core/Checker.h"
221573Srgrimes#include "clang/StaticAnalyzer/Core/CheckerManager.h"
231573Srgrimes#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
241573Srgrimes#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
251573Srgrimes#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
261573Srgrimes#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
271573Srgrimes#include "llvm/ADT/SmallSet.h"
281573Srgrimes
291573Srgrimes// The number of CFGBlock pointers we want to reserve memory for. This is used
301573Srgrimes// once for each function we analyze.
311573Srgrimes#define DEFAULT_CFGBLOCKS 256
321573Srgrimes
331573Srgrimesusing namespace clang;
341573Srgrimesusing namespace ento;
351573Srgrimes
3692986Sobriennamespace {
3792986Sobrienclass UnreachableCodeChecker : public Checker<check::EndAnalysis> {
381573Srgrimespublic:
3971579Sdeischen  void checkEndAnalysis(ExplodedGraph &G, BugReporter &B,
40201999Scperciva                        ExprEngine &Eng) const;
41201999Scpercivaprivate:
421573Srgrimes  typedef llvm::SmallSet<unsigned, DEFAULT_CFGBLOCKS> CFGBlocksSet;
4371579Sdeischen
441573Srgrimes  static inline const Stmt *getUnreachableStmt(const CFGBlock *CB);
451573Srgrimes  static void FindUnreachableEntryPoints(const CFGBlock *CB,
4635129Sjb                                         CFGBlocksSet &reachable,
471573Srgrimes                                         CFGBlocksSet &visited);
481573Srgrimes  static bool isInvalidPath(const CFGBlock *CB, const ParentMap &PM);
491573Srgrimes  static inline bool isEmptyCFGBlock(const CFGBlock *CB);
501573Srgrimes};
511573Srgrimes}
521573Srgrimes
53249810Semastevoid UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G,
541573Srgrimes                                              BugReporter &B,
551573Srgrimes                                              ExprEngine &Eng) const {
561573Srgrimes  CFGBlocksSet reachable, visited;
571573Srgrimes
581573Srgrimes  if (Eng.hasWorkRemaining())
59195637Sed    return;
60195637Sed
61195637Sed  const Decl *D = 0;
62201999Scperciva  CFG *C = 0;
63195637Sed  ParentMap *PM = 0;
64195637Sed  const LocationContext *LC = 0;
65201999Scperciva  // Iterate over ExplodedGraph
66201999Scperciva  for (ExplodedGraph::node_iterator I = G.nodes_begin(), E = G.nodes_end();
67201999Scperciva      I != E; ++I) {
68253277Sschweikh    const ProgramPoint &P = I->getLocation();
69201999Scperciva    LC = P.getLocationContext();
70201999Scperciva
71201999Scperciva    if (!D)
72201999Scperciva      D = LC->getAnalysisDeclContext()->getDecl();
73201999Scperciva    // Save the CFG if we don't have it already
74201999Scperciva    if (!C)
75201999Scperciva      C = LC->getAnalysisDeclContext()->getUnoptimizedCFG();
76201999Scperciva    if (!PM)
77201999Scperciva      PM = &LC->getParentMap();
78201999Scperciva
79201999Scperciva    if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) {
801573Srgrimes      const CFGBlock *CB = BE->getBlock();
81195637Sed      reachable.insert(CB->getBlockID());
821573Srgrimes    }
831573Srgrimes  }
841573Srgrimes
8535129Sjb  // Bail out if we didn't get the CFG or the ParentMap.
86101776Stjr  if (!D || !C || !PM)
871573Srgrimes    return;
881573Srgrimes
891573Srgrimes  // Don't do anything for template instantiations.  Proving that code
901573Srgrimes  // in a template instantiation is unreachable means proving that it is
911573Srgrimes  // unreachable in all instantiations.
9213545Sjulian  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9313545Sjulian    if (FD->isTemplateInstantiation())
9435129Sjb      return;
9513545Sjulian
961573Srgrimes  // Find CFGBlocks that were not covered by any node
97  for (CFG::const_iterator I = C->begin(), E = C->end(); I != E; ++I) {
98    const CFGBlock *CB = *I;
99    // Check if the block is unreachable
100    if (reachable.count(CB->getBlockID()))
101      continue;
102
103    // Check if the block is empty (an artificial block)
104    if (isEmptyCFGBlock(CB))
105      continue;
106
107    // Find the entry points for this block
108    if (!visited.count(CB->getBlockID()))
109      FindUnreachableEntryPoints(CB, reachable, visited);
110
111    // This block may have been pruned; check if we still want to report it
112    if (reachable.count(CB->getBlockID()))
113      continue;
114
115    // Check for false positives
116    if (CB->size() > 0 && isInvalidPath(CB, *PM))
117      continue;
118
119    // It is good practice to always have a "default" label in a "switch", even
120    // if we should never get there. It can be used to detect errors, for
121    // instance. Unreachable code directly under a "default" label is therefore
122    // likely to be a false positive.
123    if (const Stmt *label = CB->getLabel())
124      if (label->getStmtClass() == Stmt::DefaultStmtClass)
125        continue;
126
127    // Special case for __builtin_unreachable.
128    // FIXME: This should be extended to include other unreachable markers,
129    // such as llvm_unreachable.
130    if (!CB->empty()) {
131      bool foundUnreachable = false;
132      for (CFGBlock::const_iterator ci = CB->begin(), ce = CB->end();
133           ci != ce; ++ci) {
134        if (Optional<CFGStmt> S = (*ci).getAs<CFGStmt>())
135          if (const CallExpr *CE = dyn_cast<CallExpr>(S->getStmt())) {
136            if (CE->isBuiltinCall() == Builtin::BI__builtin_unreachable) {
137              foundUnreachable = true;
138              break;
139            }
140          }
141      }
142      if (foundUnreachable)
143        continue;
144    }
145
146    // We found a block that wasn't covered - find the statement to report
147    SourceRange SR;
148    PathDiagnosticLocation DL;
149    SourceLocation SL;
150    if (const Stmt *S = getUnreachableStmt(CB)) {
151      SR = S->getSourceRange();
152      DL = PathDiagnosticLocation::createBegin(S, B.getSourceManager(), LC);
153      SL = DL.asLocation();
154      if (SR.isInvalid() || !SL.isValid())
155        continue;
156    }
157    else
158      continue;
159
160    // Check if the SourceLocation is in a system header
161    const SourceManager &SM = B.getSourceManager();
162    if (SM.isInSystemHeader(SL) || SM.isInExternCSystemHeader(SL))
163      continue;
164
165    B.EmitBasicReport(D, "Unreachable code", "Dead code",
166                      "This statement is never executed", DL, SR);
167  }
168}
169
170// Recursively finds the entry point(s) for this dead CFGBlock.
171void UnreachableCodeChecker::FindUnreachableEntryPoints(const CFGBlock *CB,
172                                                        CFGBlocksSet &reachable,
173                                                        CFGBlocksSet &visited) {
174  visited.insert(CB->getBlockID());
175
176  for (CFGBlock::const_pred_iterator I = CB->pred_begin(), E = CB->pred_end();
177      I != E; ++I) {
178    if (!reachable.count((*I)->getBlockID())) {
179      // If we find an unreachable predecessor, mark this block as reachable so
180      // we don't report this block
181      reachable.insert(CB->getBlockID());
182      if (!visited.count((*I)->getBlockID()))
183        // If we haven't previously visited the unreachable predecessor, recurse
184        FindUnreachableEntryPoints(*I, reachable, visited);
185    }
186  }
187}
188
189// Find the Stmt* in a CFGBlock for reporting a warning
190const Stmt *UnreachableCodeChecker::getUnreachableStmt(const CFGBlock *CB) {
191  for (CFGBlock::const_iterator I = CB->begin(), E = CB->end(); I != E; ++I) {
192    if (Optional<CFGStmt> S = I->getAs<CFGStmt>())
193      return S->getStmt();
194  }
195  if (const Stmt *S = CB->getTerminator())
196    return S;
197  else
198    return 0;
199}
200
201// Determines if the path to this CFGBlock contained an element that infers this
202// block is a false positive. We assume that FindUnreachableEntryPoints has
203// already marked only the entry points to any dead code, so we need only to
204// find the condition that led to this block (the predecessor of this block.)
205// There will never be more than one predecessor.
206bool UnreachableCodeChecker::isInvalidPath(const CFGBlock *CB,
207                                           const ParentMap &PM) {
208  // We only expect a predecessor size of 0 or 1. If it is >1, then an external
209  // condition has broken our assumption (for example, a sink being placed by
210  // another check). In these cases, we choose not to report.
211  if (CB->pred_size() > 1)
212    return true;
213
214  // If there are no predecessors, then this block is trivially unreachable
215  if (CB->pred_size() == 0)
216    return false;
217
218  const CFGBlock *pred = *CB->pred_begin();
219
220  // Get the predecessor block's terminator conditon
221  const Stmt *cond = pred->getTerminatorCondition();
222
223  //assert(cond && "CFGBlock's predecessor has a terminator condition");
224  // The previous assertion is invalid in some cases (eg do/while). Leaving
225  // reporting of these situations on at the moment to help triage these cases.
226  if (!cond)
227    return false;
228
229  // Run each of the checks on the conditions
230  if (containsMacro(cond) || containsEnum(cond)
231      || containsStaticLocal(cond) || containsBuiltinOffsetOf(cond)
232      || containsStmt<UnaryExprOrTypeTraitExpr>(cond))
233    return true;
234
235  return false;
236}
237
238// Returns true if the given CFGBlock is empty
239bool UnreachableCodeChecker::isEmptyCFGBlock(const CFGBlock *CB) {
240  return CB->getLabel() == 0       // No labels
241      && CB->size() == 0           // No statements
242      && CB->getTerminator() == 0; // No terminator
243}
244
245void ento::registerUnreachableCodeChecker(CheckerManager &mgr) {
246  mgr.registerChecker<UnreachableCodeChecker>();
247}
248