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
16 #include "ClangSACheckers.h"
17 #include "clang/StaticAnalyzer/Core/Checker.h"
18 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
23 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
24 #include "clang/AST/ParentMap.h"
25 #include "clang/Basic/Builtins.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28
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
32
33 using namespace clang;
34 using namespace ento;
35
36 namespace {
37 class UnreachableCodeChecker : public Checker<check::EndAnalysis> {
38 public:
39 void checkEndAnalysis(ExplodedGraph &G, BugReporter &B,
40 ExprEngine &Eng) const;
41 private:
42 typedef llvm::SmallSet<unsigned, DEFAULT_CFGBLOCKS> CFGBlocksSet;
43
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);
50 };
51 }
52
checkEndAnalysis(ExplodedGraph & G,BugReporter & B,ExprEngine & Eng) const53 void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G,
54 BugReporter &B,
55 ExprEngine &Eng) const {
56 CFGBlocksSet reachable, visited;
57
58 if (Eng.hasWorkRemaining())
59 return;
60
61 CFG *C = 0;
62 ParentMap *PM = 0;
63 // Iterate over ExplodedGraph
64 for (ExplodedGraph::node_iterator I = G.nodes_begin(), E = G.nodes_end();
65 I != E; ++I) {
66 const ProgramPoint &P = I->getLocation();
67 const LocationContext *LC = P.getLocationContext();
68
69 // Save the CFG if we don't have it already
70 if (!C)
71 C = LC->getAnalysisContext()->getUnoptimizedCFG();
72 if (!PM)
73 PM = &LC->getParentMap();
74
75 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
76 const CFGBlock *CB = BE->getBlock();
77 reachable.insert(CB->getBlockID());
78 }
79 }
80
81 // Bail out if we didn't get the CFG or the ParentMap.
82 if (!C || !PM)
83 return;
84
85 ASTContext &Ctx = B.getContext();
86
87 // Find CFGBlocks that were not covered by any node
88 for (CFG::const_iterator I = C->begin(), E = C->end(); I != E; ++I) {
89 const CFGBlock *CB = *I;
90 // Check if the block is unreachable
91 if (reachable.count(CB->getBlockID()))
92 continue;
93
94 // Check if the block is empty (an artificial block)
95 if (isEmptyCFGBlock(CB))
96 continue;
97
98 // Find the entry points for this block
99 if (!visited.count(CB->getBlockID()))
100 FindUnreachableEntryPoints(CB, reachable, visited);
101
102 // This block may have been pruned; check if we still want to report it
103 if (reachable.count(CB->getBlockID()))
104 continue;
105
106 // Check for false positives
107 if (CB->size() > 0 && isInvalidPath(CB, *PM))
108 continue;
109
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 CFGElement First = CB->front();
115 if (const CFGStmt *S = First.getAs<CFGStmt>()) {
116 if (const CallExpr *CE = dyn_cast<CallExpr>(S->getStmt())) {
117 if (CE->isBuiltinCall(Ctx) == Builtin::BI__builtin_unreachable)
118 continue;
119 }
120 }
121 }
122
123 // We found a block that wasn't covered - find the statement to report
124 SourceRange SR;
125 SourceLocation SL;
126 if (const Stmt *S = getUnreachableStmt(CB)) {
127 SR = S->getSourceRange();
128 SL = S->getLocStart();
129 if (SR.isInvalid() || SL.isInvalid())
130 continue;
131 }
132 else
133 continue;
134
135 // Check if the SourceLocation is in a system header
136 const SourceManager &SM = B.getSourceManager();
137 if (SM.isInSystemHeader(SL) || SM.isInExternCSystemHeader(SL))
138 continue;
139
140 B.EmitBasicReport("Unreachable code", "Dead code", "This statement is never"
141 " executed", SL, SR);
142 }
143 }
144
145 // Recursively finds the entry point(s) for this dead CFGBlock.
FindUnreachableEntryPoints(const CFGBlock * CB,CFGBlocksSet & reachable,CFGBlocksSet & visited)146 void UnreachableCodeChecker::FindUnreachableEntryPoints(const CFGBlock *CB,
147 CFGBlocksSet &reachable,
148 CFGBlocksSet &visited) {
149 visited.insert(CB->getBlockID());
150
151 for (CFGBlock::const_pred_iterator I = CB->pred_begin(), E = CB->pred_end();
152 I != E; ++I) {
153 if (!reachable.count((*I)->getBlockID())) {
154 // If we find an unreachable predecessor, mark this block as reachable so
155 // we don't report this block
156 reachable.insert(CB->getBlockID());
157 if (!visited.count((*I)->getBlockID()))
158 // If we haven't previously visited the unreachable predecessor, recurse
159 FindUnreachableEntryPoints(*I, reachable, visited);
160 }
161 }
162 }
163
164 // Find the Stmt* in a CFGBlock for reporting a warning
getUnreachableStmt(const CFGBlock * CB)165 const Stmt *UnreachableCodeChecker::getUnreachableStmt(const CFGBlock *CB) {
166 for (CFGBlock::const_iterator I = CB->begin(), E = CB->end(); I != E; ++I) {
167 if (const CFGStmt *S = I->getAs<CFGStmt>())
168 return S->getStmt();
169 }
170 if (const Stmt *S = CB->getTerminator())
171 return S;
172 else
173 return 0;
174 }
175
176 // Determines if the path to this CFGBlock contained an element that infers this
177 // block is a false positive. We assume that FindUnreachableEntryPoints has
178 // already marked only the entry points to any dead code, so we need only to
179 // find the condition that led to this block (the predecessor of this block.)
180 // There will never be more than one predecessor.
isInvalidPath(const CFGBlock * CB,const ParentMap & PM)181 bool UnreachableCodeChecker::isInvalidPath(const CFGBlock *CB,
182 const ParentMap &PM) {
183 // We only expect a predecessor size of 0 or 1. If it is >1, then an external
184 // condition has broken our assumption (for example, a sink being placed by
185 // another check). In these cases, we choose not to report.
186 if (CB->pred_size() > 1)
187 return true;
188
189 // If there are no predecessors, then this block is trivially unreachable
190 if (CB->pred_size() == 0)
191 return false;
192
193 const CFGBlock *pred = *CB->pred_begin();
194
195 // Get the predecessor block's terminator conditon
196 const Stmt *cond = pred->getTerminatorCondition();
197
198 //assert(cond && "CFGBlock's predecessor has a terminator condition");
199 // The previous assertion is invalid in some cases (eg do/while). Leaving
200 // reporting of these situations on at the moment to help triage these cases.
201 if (!cond)
202 return false;
203
204 // Run each of the checks on the conditions
205 if (containsMacro(cond) || containsEnum(cond)
206 || containsStaticLocal(cond) || containsBuiltinOffsetOf(cond)
207 || containsStmt<UnaryExprOrTypeTraitExpr>(cond))
208 return true;
209
210 return false;
211 }
212
213 // Returns true if the given CFGBlock is empty
isEmptyCFGBlock(const CFGBlock * CB)214 bool UnreachableCodeChecker::isEmptyCFGBlock(const CFGBlock *CB) {
215 return CB->getLabel() == 0 // No labels
216 && CB->size() == 0 // No statements
217 && CB->getTerminator() == 0; // No terminator
218 }
219
registerUnreachableCodeChecker(CheckerManager & mgr)220 void ento::registerUnreachableCodeChecker(CheckerManager &mgr) {
221 mgr.registerChecker<UnreachableCodeChecker>();
222 }
223