1 //==- UnreachableCodeChecker.cpp - Generalized dead code checker -*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
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.
13 // A similar flow-sensitive only check exists in Analysis/ReachableCode.cpp
14 //===----------------------------------------------------------------------===//
16 #include "ClangSACheckers.h"
17 #include "clang/AST/ParentMap.h"
18 #include "clang/Basic/Builtins.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
21 #include "clang/StaticAnalyzer/Core/Checker.h"
22 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
27 #include "llvm/ADT/SmallSet.h"
29 // The number of CFGBlock pointers we want to reserve memory for. This is used
30 // once for each function we analyze.
31 #define DEFAULT_CFGBLOCKS 256
33 using namespace clang;
37 class UnreachableCodeChecker : public Checker<check::EndAnalysis> {
39 void checkEndAnalysis(ExplodedGraph &G, BugReporter &B,
40 ExprEngine &Eng) const;
42 typedef llvm::SmallSet<unsigned, DEFAULT_CFGBLOCKS> CFGBlocksSet;
44 static inline const Stmt *getUnreachableStmt(const CFGBlock *CB);
45 static void FindUnreachableEntryPoints(const CFGBlock *CB,
46 CFGBlocksSet &reachable,
47 CFGBlocksSet &visited);
48 static bool isInvalidPath(const CFGBlock *CB, const ParentMap &PM);
49 static inline bool isEmptyCFGBlock(const CFGBlock *CB);
53 void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G,
55 ExprEngine &Eng) const {
56 CFGBlocksSet reachable, visited;
58 if (Eng.hasWorkRemaining())
64 const LocationContext *LC = 0;
65 // Iterate over ExplodedGraph
66 for (ExplodedGraph::node_iterator I = G.nodes_begin(), E = G.nodes_end();
68 const ProgramPoint &P = I->getLocation();
69 LC = P.getLocationContext();
72 D = LC->getAnalysisDeclContext()->getDecl();
73 // Save the CFG if we don't have it already
75 C = LC->getAnalysisDeclContext()->getUnoptimizedCFG();
77 PM = &LC->getParentMap();
79 if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) {
80 const CFGBlock *CB = BE->getBlock();
81 reachable.insert(CB->getBlockID());
85 // Bail out if we didn't get the CFG or the ParentMap.
89 // Don't do anything for template instantiations. Proving that code
90 // in a template instantiation is unreachable means proving that it is
91 // unreachable in all instantiations.
92 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
93 if (FD->isTemplateInstantiation())
96 // 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()))
103 // Check if the block is empty (an artificial block)
104 if (isEmptyCFGBlock(CB))
107 // Find the entry points for this block
108 if (!visited.count(CB->getBlockID()))
109 FindUnreachableEntryPoints(CB, reachable, visited);
111 // This block may have been pruned; check if we still want to report it
112 if (reachable.count(CB->getBlockID()))
115 // Check for false positives
116 if (CB->size() > 0 && isInvalidPath(CB, *PM))
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)
127 // Special case for __builtin_unreachable.
128 // FIXME: This should be extended to include other unreachable markers,
129 // such as llvm_unreachable.
131 bool foundUnreachable = false;
132 for (CFGBlock::const_iterator ci = CB->begin(), ce = CB->end();
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;
142 if (foundUnreachable)
146 // We found a block that wasn't covered - find the statement to report
148 PathDiagnosticLocation DL;
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())
160 // Check if the SourceLocation is in a system header
161 const SourceManager &SM = B.getSourceManager();
162 if (SM.isInSystemHeader(SL) || SM.isInExternCSystemHeader(SL))
165 B.EmitBasicReport(D, "Unreachable code", "Dead code",
166 "This statement is never executed", DL, SR);
170 // Recursively finds the entry point(s) for this dead CFGBlock.
171 void UnreachableCodeChecker::FindUnreachableEntryPoints(const CFGBlock *CB,
172 CFGBlocksSet &reachable,
173 CFGBlocksSet &visited) {
174 visited.insert(CB->getBlockID());
176 for (CFGBlock::const_pred_iterator I = CB->pred_begin(), E = CB->pred_end();
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);
189 // Find the Stmt* in a CFGBlock for reporting a warning
190 const 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>())
195 if (const Stmt *S = CB->getTerminator())
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.
206 bool 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)
214 // If there are no predecessors, then this block is trivially unreachable
215 if (CB->pred_size() == 0)
218 const CFGBlock *pred = *CB->pred_begin();
220 // Get the predecessor block's terminator conditon
221 const Stmt *cond = pred->getTerminatorCondition();
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.
229 // Run each of the checks on the conditions
230 if (containsMacro(cond) || containsEnum(cond)
231 || containsStaticLocal(cond) || containsBuiltinOffsetOf(cond)
232 || containsStmt<UnaryExprOrTypeTraitExpr>(cond))
238 // Returns true if the given CFGBlock is empty
239 bool UnreachableCodeChecker::isEmptyCFGBlock(const CFGBlock *CB) {
240 return CB->getLabel() == 0 // No labels
241 && CB->size() == 0 // No statements
242 && CB->getTerminator() == 0; // No terminator
245 void ento::registerUnreachableCodeChecker(CheckerManager &mgr) {
246 mgr.registerChecker<UnreachableCodeChecker>();