clang 24.0.0git
UnreachableCodeChecker.cpp
Go to the documentation of this file.
1//==- UnreachableCodeChecker.cpp - Generalized dead code checker -*- C++ -*-==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8// This file implements a generalized unreachable code checker using a
9// path-sensitive analysis. We mark any path visited, and then walk the CFG as a
10// post-analysis to determine what was never visited.
11//
12// A similar flow-sensitive only check exists in Analysis/ReachableCode.cpp
13//===----------------------------------------------------------------------===//
14
16#include "clang/AST/ParentMap.h"
26#include "llvm/ADT/SmallSet.h"
27#include <optional>
28
29using namespace clang;
30using namespace ento;
31
32namespace {
33class UnreachableCodeChecker : public Checker<check::EndAnalysis> {
34public:
35 void checkEndAnalysis(ExplodedGraph &G, BugReporter &B,
36 ExprEngine &Eng) const;
37private:
38 typedef llvm::SmallSet<unsigned, 32> CFGBlocksSet;
39
40 static inline const Stmt *getUnreachableStmt(const CFGBlock *CB);
41 static void FindUnreachableEntryPoints(const CFGBlock *CB,
42 CFGBlocksSet &reachable,
43 CFGBlocksSet &visited);
44 static bool isInvalidPath(const CFGBlock *CB, const ParentMap &PM);
45 static inline bool isEmptyCFGBlock(const CFGBlock *CB);
46};
47}
48
49void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G,
50 BugReporter &B,
51 ExprEngine &Eng) const {
52 CFGBlocksSet reachable, visited;
53
54 if (!Eng.hasExploredAllPaths())
55 return;
56
57 const Decl *D = nullptr;
58 CFG *C = nullptr;
59 const ParentMap *PM = nullptr;
60 const StackFrame *SF = nullptr;
61 // Iterate over ExplodedGraph
62 for (const ExplodedNode &N : G.nodes()) {
63 const ProgramPoint &P = N.getLocation();
64 SF = P.getStackFrame();
65 if (!SF->inTopFrame())
66 continue;
67
68 if (!D)
70
71 // Save the CFG if we don't have it already
72 if (!C)
74 if (!PM)
75 PM = &SF->getParentMap();
76
77 if (std::optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) {
78 const CFGBlock *CB = BE->getBlock();
79 reachable.insert(CB->getBlockID());
80 }
81 }
82
83 // Bail out if we didn't get the CFG or the ParentMap.
84 if (!D || !C || !PM)
85 return;
86
87 // Don't do anything for template instantiations. Proving that code
88 // in a template instantiation is unreachable means proving that it is
89 // unreachable in all instantiations.
90 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
91 if (FD->isTemplateInstantiation())
92 return;
93
94 // Find CFGBlocks that were not covered by any node
95 for (const CFGBlock *CB : *C) {
96 // Check if the block is unreachable
97 if (reachable.count(CB->getBlockID()))
98 continue;
99
100 // Check if the block is empty (an artificial block)
101 if (isEmptyCFGBlock(CB))
102 continue;
103
104 // Find the entry points for this block
105 if (!visited.count(CB->getBlockID()))
106 FindUnreachableEntryPoints(CB, reachable, visited);
107
108 // This block may have been pruned; check if we still want to report it
109 if (reachable.count(CB->getBlockID()))
110 continue;
111
112 // Check for false positives
113 if (isInvalidPath(CB, *PM))
114 continue;
115
116 // It is good practice to always have a "default" label in a "switch", even
117 // if we should never get there. It can be used to detect errors, for
118 // instance. Unreachable code directly under a "default" label is therefore
119 // likely to be a false positive.
120 if (const Stmt *label = CB->getLabel())
121 if (label->getStmtClass() == Stmt::DefaultStmtClass)
122 continue;
123
124 // Special case for __builtin_unreachable.
125 // FIXME: This should be extended to include other unreachable markers,
126 // such as llvm_unreachable.
127 if (!CB->empty()) {
128 auto IsUnreachableMarker = [&](const CFGElement &Elem) {
129 std::optional<CFGStmt> S = Elem.getAs<CFGStmt>();
130 if (!S)
131 return false;
132 const auto *CE = dyn_cast<CallExpr>(S->getStmt());
133 return CE &&
134 (CE->getBuiltinCallee() == Builtin::BI__builtin_unreachable ||
135 CE->isBuiltinAssumeFalse(Eng.getContext()));
136 };
137 if (llvm::any_of(*CB, IsUnreachableMarker))
138 continue;
139 }
140
141 // We found a block that wasn't covered - find the statement to report
142 SourceRange SR;
143 PathDiagnosticLocation DL;
144 SourceLocation SL;
145 if (const Stmt *S = getUnreachableStmt(CB)) {
146 // In macros, 'do {...} while (0)' is often used. Don't warn about the
147 // condition 0 when it is unreachable.
148 if (S->getBeginLoc().isMacroID())
149 if (const auto *I = dyn_cast<IntegerLiteral>(S))
150 if (I->getValue() == 0ULL)
151 if (const Stmt *Parent = PM->getParent(S))
152 if (isa<DoStmt>(Parent))
153 continue;
154 SR = S->getSourceRange();
156 SL = DL.asLocation();
157 if (SR.isInvalid() || !SL.isValid())
158 continue;
159 if (isa<CXXTryStmt>(S))
160 continue;
161 }
162 else
163 continue;
164
165 // Check if the SourceLocation is in a system header
166 const SourceManager &SM = B.getSourceManager();
167 if (SM.isInSystemHeader(SL) || SM.isInExternCSystemHeader(SL))
168 continue;
169
170 B.EmitBasicReport(D, this, "Unreachable code", categories::UnusedCode,
171 "This statement is never executed", DL, SR);
172 }
173}
174
175// Recursively finds the entry point(s) for this dead CFGBlock.
176void UnreachableCodeChecker::FindUnreachableEntryPoints(const CFGBlock *CB,
177 CFGBlocksSet &reachable,
178 CFGBlocksSet &visited) {
179 visited.insert(CB->getBlockID());
180
181 for (const CFGBlock *PredBlock : CB->preds()) {
182 if (!PredBlock)
183 continue;
184
185 if (!reachable.count(PredBlock->getBlockID())) {
186 // If we find an unreachable predecessor, mark this block as reachable so
187 // we don't report this block
188 reachable.insert(CB->getBlockID());
189 if (!visited.count(PredBlock->getBlockID()))
190 // If we haven't previously visited the unreachable predecessor, recurse
191 FindUnreachableEntryPoints(PredBlock, reachable, visited);
192 }
193 }
194}
195
196// Find the Stmt* in a CFGBlock for reporting a warning
197const Stmt *UnreachableCodeChecker::getUnreachableStmt(const CFGBlock *CB) {
198 for (const CFGElement &Elem : *CB) {
199 if (std::optional<CFGStmt> S = Elem.getAs<CFGStmt>()) {
200 if (!isa<DeclStmt>(S->getStmt()))
201 return S->getStmt();
202 }
203 }
204 return CB->getTerminatorStmt();
205}
206
207// Determines if the path to this CFGBlock contained an element that infers this
208// block is a false positive. We assume that FindUnreachableEntryPoints has
209// already marked only the entry points to any dead code, so we need only to
210// find the condition that led to this block (the predecessor of this block.)
211// There will never be more than one predecessor.
212bool UnreachableCodeChecker::isInvalidPath(const CFGBlock *CB,
213 const ParentMap &PM) {
214 // We only expect a predecessor size of 0 or 1. If it is >1, then an external
215 // condition has broken our assumption (for example, a sink being placed by
216 // another check). In these cases, we choose not to report.
217 if (CB->pred_size() > 1)
218 return true;
219
220 // If there are no predecessors, then this block is trivially unreachable
221 if (CB->pred_size() == 0)
222 return false;
223
224 const CFGBlock *pred = *CB->pred_begin();
225 if (!pred)
226 return false;
227
228 // Get the predecessor block's terminator condition
229 const Stmt *cond = pred->getTerminatorCondition();
230
231 //assert(cond && "CFGBlock's predecessor has a terminator condition");
232 // The previous assertion is invalid in some cases (eg do/while). Leaving
233 // reporting of these situations on at the moment to help triage these cases.
234 if (!cond)
235 return false;
236
237 // Run each of the checks on the conditions
238 return containsMacro(cond) || containsEnum(cond) ||
241}
242
243// Returns true if the given CFGBlock is empty
244bool UnreachableCodeChecker::isEmptyCFGBlock(const CFGBlock *CB) {
245 return CB->getLabel() == nullptr // No labels
246 && CB->size() == 0 // No statements
247 && !CB->getTerminatorStmt(); // No terminator
248}
249
250void ento::registerUnreachableCodeChecker(CheckerManager &mgr) {
251 mgr.registerChecker<UnreachableCodeChecker>();
252}
253
254bool ento::shouldRegisterUnreachableCodeChecker(const CheckerManager &mgr) {
255 return true;
256}
Defines enum values for all the target-independent builtin functions.
Defines the SourceManager interface.
unsigned size() const
Definition CFG.h:1007
bool empty() const
Definition CFG.h:1008
Stmt * getLabel()
Definition CFG.h:1162
Stmt * getTerminatorStmt()
Definition CFG.h:1147
unsigned pred_size() const
Definition CFG.h:1066
const Stmt * getTerminatorCondition(bool StripParens=true) const
Definition CFG.cpp:6505
pred_iterator pred_begin()
Definition CFG.h:1027
pred_range preds()
Definition CFG.h:1037
unsigned getBlockID() const
Definition CFG.h:1177
Stmt * getParent(Stmt *) const
const StackFrame * getStackFrame() const
std::optional< T > getAs() const
Convert to the specified ProgramPoint type, returning std::nullopt if this ProgramPoint is not of the...
bool isValid() const
Return true if this is a valid SourceLocation object.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isInExternCSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in an "extern C" system header.
bool isInvalid() const
const ParentMap & getParentMap() const
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
BugReporter is a utility class for generating PathDiagnostics for analysis.
const SourceManager & getSourceManager()
void EmitBasicReport(const Decl *DeclWithIssue, const CheckerFrontend *Checker, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef< SourceRange > Ranges={}, ArrayRef< FixItHint > Fixits={})
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
Simple checker classes that implement one frontend (i.e.
Definition Checker.h:565
llvm::iterator_range< node_iterator > nodes()
bool hasExploredAllPaths() const
Definition ExprEngine.h:484
ASTContext & getContext() const
getContext - Return the ASTContext associated with this analysis.
Definition ExprEngine.h:196
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
bool containsEnum(const Stmt *S)
bool containsStaticLocal(const Stmt *S)
bool containsBuiltinOffsetOf(const Stmt *S)
bool containsStmt(const Stmt *S)
bool containsMacro(const Stmt *S)
const Fact * ProgramPoint
A ProgramPoint identifies a location in the CFG by pointing to a specific Fact.
Definition Facts.h:158
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330