llvm-project
772 строки · 26.6 Кб
1//===-- ReachableCode.cpp - Code Reachability Analysis --------------------===//
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//
9// This file implements a flow-sensitive, path-insensitive analysis of
10// determining reachable blocks within a CFG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Analysis/Analyses/ReachableCode.h"
15#include "clang/AST/Attr.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
19#include "clang/AST/ParentMap.h"
20#include "clang/AST/RecursiveASTVisitor.h"
21#include "clang/AST/StmtCXX.h"
22#include "clang/Analysis/AnalysisDeclContext.h"
23#include "clang/Analysis/CFG.h"
24#include "clang/Basic/Builtins.h"
25#include "clang/Basic/SourceManager.h"
26#include "clang/Lex/Preprocessor.h"
27#include "llvm/ADT/BitVector.h"
28#include "llvm/ADT/SmallVector.h"
29#include <optional>
30
31using namespace clang;
32
33//===----------------------------------------------------------------------===//
34// Core Reachability Analysis routines.
35//===----------------------------------------------------------------------===//
36
37static bool isEnumConstant(const Expr *Ex) {
38const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex);
39if (!DR)
40return false;
41return isa<EnumConstantDecl>(DR->getDecl());
42}
43
44static bool isTrivialExpression(const Expr *Ex) {
45Ex = Ex->IgnoreParenCasts();
46return isa<IntegerLiteral>(Ex) || isa<StringLiteral>(Ex) ||
47isa<CXXBoolLiteralExpr>(Ex) || isa<ObjCBoolLiteralExpr>(Ex) ||
48isa<CharacterLiteral>(Ex) ||
49isEnumConstant(Ex);
50}
51
52static bool isTrivialDoWhile(const CFGBlock *B, const Stmt *S) {
53// Check if the block ends with a do...while() and see if 'S' is the
54// condition.
55if (const Stmt *Term = B->getTerminatorStmt()) {
56if (const DoStmt *DS = dyn_cast<DoStmt>(Term)) {
57const Expr *Cond = DS->getCond()->IgnoreParenCasts();
58return Cond == S && isTrivialExpression(Cond);
59}
60}
61return false;
62}
63
64static bool isBuiltinUnreachable(const Stmt *S) {
65if (const auto *DRE = dyn_cast<DeclRefExpr>(S))
66if (const auto *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl()))
67return FDecl->getIdentifier() &&
68FDecl->getBuiltinID() == Builtin::BI__builtin_unreachable;
69return false;
70}
71
72static bool isBuiltinAssumeFalse(const CFGBlock *B, const Stmt *S,
73ASTContext &C) {
74if (B->empty()) {
75// Happens if S is B's terminator and B contains nothing else
76// (e.g. a CFGBlock containing only a goto).
77return false;
78}
79if (std::optional<CFGStmt> CS = B->back().getAs<CFGStmt>()) {
80if (const auto *CE = dyn_cast<CallExpr>(CS->getStmt())) {
81return CE->getCallee()->IgnoreCasts() == S && CE->isBuiltinAssumeFalse(C);
82}
83}
84return false;
85}
86
87static bool isDeadReturn(const CFGBlock *B, const Stmt *S) {
88// Look to see if the current control flow ends with a 'return', and see if
89// 'S' is a substatement. The 'return' may not be the last element in the
90// block, or may be in a subsequent block because of destructors.
91const CFGBlock *Current = B;
92while (true) {
93for (const CFGElement &CE : llvm::reverse(*Current)) {
94if (std::optional<CFGStmt> CS = CE.getAs<CFGStmt>()) {
95if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(CS->getStmt())) {
96if (RS == S)
97return true;
98if (const Expr *RE = RS->getRetValue()) {
99RE = RE->IgnoreParenCasts();
100if (RE == S)
101return true;
102ParentMap PM(const_cast<Expr *>(RE));
103// If 'S' is in the ParentMap, it is a subexpression of
104// the return statement.
105return PM.getParent(S);
106}
107}
108break;
109}
110}
111// Note also that we are restricting the search for the return statement
112// to stop at control-flow; only part of a return statement may be dead,
113// without the whole return statement being dead.
114if (Current->getTerminator().isTemporaryDtorsBranch()) {
115// Temporary destructors have a predictable control flow, thus we want to
116// look into the next block for the return statement.
117// We look into the false branch, as we know the true branch only contains
118// the call to the destructor.
119assert(Current->succ_size() == 2);
120Current = *(Current->succ_begin() + 1);
121} else if (!Current->getTerminatorStmt() && Current->succ_size() == 1) {
122// If there is only one successor, we're not dealing with outgoing control
123// flow. Thus, look into the next block.
124Current = *Current->succ_begin();
125if (Current->pred_size() > 1) {
126// If there is more than one predecessor, we're dealing with incoming
127// control flow - if the return statement is in that block, it might
128// well be reachable via a different control flow, thus it's not dead.
129return false;
130}
131} else {
132// We hit control flow or a dead end. Stop searching.
133return false;
134}
135}
136llvm_unreachable("Broke out of infinite loop.");
137}
138
139static SourceLocation getTopMostMacro(SourceLocation Loc, SourceManager &SM) {
140assert(Loc.isMacroID());
141SourceLocation Last;
142do {
143Last = Loc;
144Loc = SM.getImmediateMacroCallerLoc(Loc);
145} while (Loc.isMacroID());
146return Last;
147}
148
149/// Returns true if the statement is expanded from a configuration macro.
150static bool isExpandedFromConfigurationMacro(const Stmt *S,
151Preprocessor &PP,
152bool IgnoreYES_NO = false) {
153// FIXME: This is not very precise. Here we just check to see if the
154// value comes from a macro, but we can do much better. This is likely
155// to be over conservative. This logic is factored into a separate function
156// so that we can refine it later.
157SourceLocation L = S->getBeginLoc();
158if (L.isMacroID()) {
159SourceManager &SM = PP.getSourceManager();
160if (IgnoreYES_NO) {
161// The Objective-C constant 'YES' and 'NO'
162// are defined as macros. Do not treat them
163// as configuration values.
164SourceLocation TopL = getTopMostMacro(L, SM);
165StringRef MacroName = PP.getImmediateMacroName(TopL);
166if (MacroName == "YES" || MacroName == "NO")
167return false;
168} else if (!PP.getLangOpts().CPlusPlus) {
169// Do not treat C 'false' and 'true' macros as configuration values.
170SourceLocation TopL = getTopMostMacro(L, SM);
171StringRef MacroName = PP.getImmediateMacroName(TopL);
172if (MacroName == "false" || MacroName == "true")
173return false;
174}
175return true;
176}
177return false;
178}
179
180static bool isConfigurationValue(const ValueDecl *D, Preprocessor &PP);
181
182/// Returns true if the statement represents a configuration value.
183///
184/// A configuration value is something usually determined at compile-time
185/// to conditionally always execute some branch. Such guards are for
186/// "sometimes unreachable" code. Such code is usually not interesting
187/// to report as unreachable, and may mask truly unreachable code within
188/// those blocks.
189static bool isConfigurationValue(const Stmt *S,
190Preprocessor &PP,
191SourceRange *SilenceableCondVal = nullptr,
192bool IncludeIntegers = true,
193bool WrappedInParens = false) {
194if (!S)
195return false;
196
197if (const auto *Ex = dyn_cast<Expr>(S))
198S = Ex->IgnoreImplicit();
199
200if (const auto *Ex = dyn_cast<Expr>(S))
201S = Ex->IgnoreCasts();
202
203// Special case looking for the sigil '()' around an integer literal.
204if (const ParenExpr *PE = dyn_cast<ParenExpr>(S))
205if (!PE->getBeginLoc().isMacroID())
206return isConfigurationValue(PE->getSubExpr(), PP, SilenceableCondVal,
207IncludeIntegers, true);
208
209if (const Expr *Ex = dyn_cast<Expr>(S))
210S = Ex->IgnoreCasts();
211
212bool IgnoreYES_NO = false;
213
214switch (S->getStmtClass()) {
215case Stmt::CallExprClass: {
216const FunctionDecl *Callee =
217dyn_cast_or_null<FunctionDecl>(cast<CallExpr>(S)->getCalleeDecl());
218return Callee ? Callee->isConstexpr() : false;
219}
220case Stmt::DeclRefExprClass:
221return isConfigurationValue(cast<DeclRefExpr>(S)->getDecl(), PP);
222case Stmt::ObjCBoolLiteralExprClass:
223IgnoreYES_NO = true;
224[[fallthrough]];
225case Stmt::CXXBoolLiteralExprClass:
226case Stmt::IntegerLiteralClass: {
227const Expr *E = cast<Expr>(S);
228if (IncludeIntegers) {
229if (SilenceableCondVal && !SilenceableCondVal->getBegin().isValid())
230*SilenceableCondVal = E->getSourceRange();
231return WrappedInParens ||
232isExpandedFromConfigurationMacro(E, PP, IgnoreYES_NO);
233}
234return false;
235}
236case Stmt::MemberExprClass:
237return isConfigurationValue(cast<MemberExpr>(S)->getMemberDecl(), PP);
238case Stmt::UnaryExprOrTypeTraitExprClass:
239return true;
240case Stmt::BinaryOperatorClass: {
241const BinaryOperator *B = cast<BinaryOperator>(S);
242// Only include raw integers (not enums) as configuration
243// values if they are used in a logical or comparison operator
244// (not arithmetic).
245IncludeIntegers &= (B->isLogicalOp() || B->isComparisonOp());
246return isConfigurationValue(B->getLHS(), PP, SilenceableCondVal,
247IncludeIntegers) ||
248isConfigurationValue(B->getRHS(), PP, SilenceableCondVal,
249IncludeIntegers);
250}
251case Stmt::UnaryOperatorClass: {
252const UnaryOperator *UO = cast<UnaryOperator>(S);
253if (UO->getOpcode() != UO_LNot && UO->getOpcode() != UO_Minus)
254return false;
255bool SilenceableCondValNotSet =
256SilenceableCondVal && SilenceableCondVal->getBegin().isInvalid();
257bool IsSubExprConfigValue =
258isConfigurationValue(UO->getSubExpr(), PP, SilenceableCondVal,
259IncludeIntegers, WrappedInParens);
260// Update the silenceable condition value source range only if the range
261// was set directly by the child expression.
262if (SilenceableCondValNotSet &&
263SilenceableCondVal->getBegin().isValid() &&
264*SilenceableCondVal ==
265UO->getSubExpr()->IgnoreCasts()->getSourceRange())
266*SilenceableCondVal = UO->getSourceRange();
267return IsSubExprConfigValue;
268}
269default:
270return false;
271}
272}
273
274static bool isConfigurationValue(const ValueDecl *D, Preprocessor &PP) {
275if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D))
276return isConfigurationValue(ED->getInitExpr(), PP);
277if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
278// As a heuristic, treat globals as configuration values. Note
279// that we only will get here if Sema evaluated this
280// condition to a constant expression, which means the global
281// had to be declared in a way to be a truly constant value.
282// We could generalize this to local variables, but it isn't
283// clear if those truly represent configuration values that
284// gate unreachable code.
285if (!VD->hasLocalStorage())
286return true;
287
288// As a heuristic, locals that have been marked 'const' explicitly
289// can be treated as configuration values as well.
290return VD->getType().isLocalConstQualified();
291}
292return false;
293}
294
295/// Returns true if we should always explore all successors of a block.
296static bool shouldTreatSuccessorsAsReachable(const CFGBlock *B,
297Preprocessor &PP) {
298if (const Stmt *Term = B->getTerminatorStmt()) {
299if (isa<SwitchStmt>(Term))
300return true;
301// Specially handle '||' and '&&'.
302if (isa<BinaryOperator>(Term)) {
303return isConfigurationValue(Term, PP);
304}
305// Do not treat constexpr if statement successors as unreachable in warnings
306// since the point of these statements is to determine branches at compile
307// time.
308if (const auto *IS = dyn_cast<IfStmt>(Term);
309IS != nullptr && IS->isConstexpr())
310return true;
311}
312
313const Stmt *Cond = B->getTerminatorCondition(/* stripParens */ false);
314return isConfigurationValue(Cond, PP);
315}
316
317static unsigned scanFromBlock(const CFGBlock *Start,
318llvm::BitVector &Reachable,
319Preprocessor *PP,
320bool IncludeSometimesUnreachableEdges) {
321unsigned count = 0;
322
323// Prep work queue
324SmallVector<const CFGBlock*, 32> WL;
325
326// The entry block may have already been marked reachable
327// by the caller.
328if (!Reachable[Start->getBlockID()]) {
329++count;
330Reachable[Start->getBlockID()] = true;
331}
332
333WL.push_back(Start);
334
335// Find the reachable blocks from 'Start'.
336while (!WL.empty()) {
337const CFGBlock *item = WL.pop_back_val();
338
339// There are cases where we want to treat all successors as reachable.
340// The idea is that some "sometimes unreachable" code is not interesting,
341// and that we should forge ahead and explore those branches anyway.
342// This allows us to potentially uncover some "always unreachable" code
343// within the "sometimes unreachable" code.
344// Look at the successors and mark then reachable.
345std::optional<bool> TreatAllSuccessorsAsReachable;
346if (!IncludeSometimesUnreachableEdges)
347TreatAllSuccessorsAsReachable = false;
348
349for (CFGBlock::const_succ_iterator I = item->succ_begin(),
350E = item->succ_end(); I != E; ++I) {
351const CFGBlock *B = *I;
352if (!B) do {
353const CFGBlock *UB = I->getPossiblyUnreachableBlock();
354if (!UB)
355break;
356
357if (!TreatAllSuccessorsAsReachable) {
358assert(PP);
359TreatAllSuccessorsAsReachable =
360shouldTreatSuccessorsAsReachable(item, *PP);
361}
362
363if (*TreatAllSuccessorsAsReachable) {
364B = UB;
365break;
366}
367}
368while (false);
369
370if (B) {
371unsigned blockID = B->getBlockID();
372if (!Reachable[blockID]) {
373Reachable.set(blockID);
374WL.push_back(B);
375++count;
376}
377}
378}
379}
380return count;
381}
382
383static unsigned scanMaybeReachableFromBlock(const CFGBlock *Start,
384Preprocessor &PP,
385llvm::BitVector &Reachable) {
386return scanFromBlock(Start, Reachable, &PP, true);
387}
388
389//===----------------------------------------------------------------------===//
390// Dead Code Scanner.
391//===----------------------------------------------------------------------===//
392
393namespace {
394class DeadCodeScan {
395llvm::BitVector Visited;
396llvm::BitVector &Reachable;
397SmallVector<const CFGBlock *, 10> WorkList;
398Preprocessor &PP;
399ASTContext &C;
400
401typedef SmallVector<std::pair<const CFGBlock *, const Stmt *>, 12>
402DeferredLocsTy;
403
404DeferredLocsTy DeferredLocs;
405
406public:
407DeadCodeScan(llvm::BitVector &reachable, Preprocessor &PP, ASTContext &C)
408: Visited(reachable.size()),
409Reachable(reachable),
410PP(PP), C(C) {}
411
412void enqueue(const CFGBlock *block);
413unsigned scanBackwards(const CFGBlock *Start,
414clang::reachable_code::Callback &CB);
415
416bool isDeadCodeRoot(const CFGBlock *Block);
417
418const Stmt *findDeadCode(const CFGBlock *Block);
419
420void reportDeadCode(const CFGBlock *B,
421const Stmt *S,
422clang::reachable_code::Callback &CB);
423};
424}
425
426void DeadCodeScan::enqueue(const CFGBlock *block) {
427unsigned blockID = block->getBlockID();
428if (Reachable[blockID] || Visited[blockID])
429return;
430Visited[blockID] = true;
431WorkList.push_back(block);
432}
433
434bool DeadCodeScan::isDeadCodeRoot(const clang::CFGBlock *Block) {
435bool isDeadRoot = true;
436
437for (CFGBlock::const_pred_iterator I = Block->pred_begin(),
438E = Block->pred_end(); I != E; ++I) {
439if (const CFGBlock *PredBlock = *I) {
440unsigned blockID = PredBlock->getBlockID();
441if (Visited[blockID]) {
442isDeadRoot = false;
443continue;
444}
445if (!Reachable[blockID]) {
446isDeadRoot = false;
447Visited[blockID] = true;
448WorkList.push_back(PredBlock);
449continue;
450}
451}
452}
453
454return isDeadRoot;
455}
456
457// Check if the given `DeadStmt` is a coroutine statement and is a substmt of
458// the coroutine statement. `Block` is the CFGBlock containing the `DeadStmt`.
459static bool isInCoroutineStmt(const Stmt *DeadStmt, const CFGBlock *Block) {
460// The coroutine statement, co_return, co_await, or co_yield.
461const Stmt *CoroStmt = nullptr;
462// Find the first coroutine statement after the DeadStmt in the block.
463bool AfterDeadStmt = false;
464for (CFGBlock::const_iterator I = Block->begin(), E = Block->end(); I != E;
465++I)
466if (std::optional<CFGStmt> CS = I->getAs<CFGStmt>()) {
467const Stmt *S = CS->getStmt();
468if (S == DeadStmt)
469AfterDeadStmt = true;
470if (AfterDeadStmt &&
471// For simplicity, we only check simple coroutine statements.
472(llvm::isa<CoreturnStmt>(S) || llvm::isa<CoroutineSuspendExpr>(S))) {
473CoroStmt = S;
474break;
475}
476}
477if (!CoroStmt)
478return false;
479struct Checker : RecursiveASTVisitor<Checker> {
480const Stmt *DeadStmt;
481bool CoroutineSubStmt = false;
482Checker(const Stmt *S) : DeadStmt(S) {}
483bool VisitStmt(const Stmt *S) {
484if (S == DeadStmt)
485CoroutineSubStmt = true;
486return true;
487}
488// Statements captured in the CFG can be implicit.
489bool shouldVisitImplicitCode() const { return true; }
490};
491Checker checker(DeadStmt);
492checker.TraverseStmt(const_cast<Stmt *>(CoroStmt));
493return checker.CoroutineSubStmt;
494}
495
496static bool isValidDeadStmt(const Stmt *S, const clang::CFGBlock *Block) {
497if (S->getBeginLoc().isInvalid())
498return false;
499if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(S))
500return BO->getOpcode() != BO_Comma;
501// Coroutine statements are never considered dead statements, because removing
502// them may change the function semantic if it is the only coroutine statement
503// of the coroutine.
504return !isInCoroutineStmt(S, Block);
505}
506
507const Stmt *DeadCodeScan::findDeadCode(const clang::CFGBlock *Block) {
508for (CFGBlock::const_iterator I = Block->begin(), E = Block->end(); I!=E; ++I)
509if (std::optional<CFGStmt> CS = I->getAs<CFGStmt>()) {
510const Stmt *S = CS->getStmt();
511if (isValidDeadStmt(S, Block))
512return S;
513}
514
515CFGTerminator T = Block->getTerminator();
516if (T.isStmtBranch()) {
517const Stmt *S = T.getStmt();
518if (S && isValidDeadStmt(S, Block))
519return S;
520}
521
522return nullptr;
523}
524
525static int SrcCmp(const std::pair<const CFGBlock *, const Stmt *> *p1,
526const std::pair<const CFGBlock *, const Stmt *> *p2) {
527if (p1->second->getBeginLoc() < p2->second->getBeginLoc())
528return -1;
529if (p2->second->getBeginLoc() < p1->second->getBeginLoc())
530return 1;
531return 0;
532}
533
534unsigned DeadCodeScan::scanBackwards(const clang::CFGBlock *Start,
535clang::reachable_code::Callback &CB) {
536
537unsigned count = 0;
538enqueue(Start);
539
540while (!WorkList.empty()) {
541const CFGBlock *Block = WorkList.pop_back_val();
542
543// It is possible that this block has been marked reachable after
544// it was enqueued.
545if (Reachable[Block->getBlockID()])
546continue;
547
548// Look for any dead code within the block.
549const Stmt *S = findDeadCode(Block);
550
551if (!S) {
552// No dead code. Possibly an empty block. Look at dead predecessors.
553for (CFGBlock::const_pred_iterator I = Block->pred_begin(),
554E = Block->pred_end(); I != E; ++I) {
555if (const CFGBlock *predBlock = *I)
556enqueue(predBlock);
557}
558continue;
559}
560
561// Specially handle macro-expanded code.
562if (S->getBeginLoc().isMacroID()) {
563count += scanMaybeReachableFromBlock(Block, PP, Reachable);
564continue;
565}
566
567if (isDeadCodeRoot(Block)) {
568reportDeadCode(Block, S, CB);
569count += scanMaybeReachableFromBlock(Block, PP, Reachable);
570}
571else {
572// Record this statement as the possibly best location in a
573// strongly-connected component of dead code for emitting a
574// warning.
575DeferredLocs.push_back(std::make_pair(Block, S));
576}
577}
578
579// If we didn't find a dead root, then report the dead code with the
580// earliest location.
581if (!DeferredLocs.empty()) {
582llvm::array_pod_sort(DeferredLocs.begin(), DeferredLocs.end(), SrcCmp);
583for (const auto &I : DeferredLocs) {
584const CFGBlock *Block = I.first;
585if (Reachable[Block->getBlockID()])
586continue;
587reportDeadCode(Block, I.second, CB);
588count += scanMaybeReachableFromBlock(Block, PP, Reachable);
589}
590}
591
592return count;
593}
594
595static SourceLocation GetUnreachableLoc(const Stmt *S,
596SourceRange &R1,
597SourceRange &R2) {
598R1 = R2 = SourceRange();
599
600if (const Expr *Ex = dyn_cast<Expr>(S))
601S = Ex->IgnoreParenImpCasts();
602
603switch (S->getStmtClass()) {
604case Expr::BinaryOperatorClass: {
605const BinaryOperator *BO = cast<BinaryOperator>(S);
606return BO->getOperatorLoc();
607}
608case Expr::UnaryOperatorClass: {
609const UnaryOperator *UO = cast<UnaryOperator>(S);
610R1 = UO->getSubExpr()->getSourceRange();
611return UO->getOperatorLoc();
612}
613case Expr::CompoundAssignOperatorClass: {
614const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(S);
615R1 = CAO->getLHS()->getSourceRange();
616R2 = CAO->getRHS()->getSourceRange();
617return CAO->getOperatorLoc();
618}
619case Expr::BinaryConditionalOperatorClass:
620case Expr::ConditionalOperatorClass: {
621const AbstractConditionalOperator *CO =
622cast<AbstractConditionalOperator>(S);
623return CO->getQuestionLoc();
624}
625case Expr::MemberExprClass: {
626const MemberExpr *ME = cast<MemberExpr>(S);
627R1 = ME->getSourceRange();
628return ME->getMemberLoc();
629}
630case Expr::ArraySubscriptExprClass: {
631const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(S);
632R1 = ASE->getLHS()->getSourceRange();
633R2 = ASE->getRHS()->getSourceRange();
634return ASE->getRBracketLoc();
635}
636case Expr::CStyleCastExprClass: {
637const CStyleCastExpr *CSC = cast<CStyleCastExpr>(S);
638R1 = CSC->getSubExpr()->getSourceRange();
639return CSC->getLParenLoc();
640}
641case Expr::CXXFunctionalCastExprClass: {
642const CXXFunctionalCastExpr *CE = cast <CXXFunctionalCastExpr>(S);
643R1 = CE->getSubExpr()->getSourceRange();
644return CE->getBeginLoc();
645}
646case Stmt::CXXTryStmtClass: {
647return cast<CXXTryStmt>(S)->getHandler(0)->getCatchLoc();
648}
649case Expr::ObjCBridgedCastExprClass: {
650const ObjCBridgedCastExpr *CSC = cast<ObjCBridgedCastExpr>(S);
651R1 = CSC->getSubExpr()->getSourceRange();
652return CSC->getLParenLoc();
653}
654default: ;
655}
656R1 = S->getSourceRange();
657return S->getBeginLoc();
658}
659
660void DeadCodeScan::reportDeadCode(const CFGBlock *B,
661const Stmt *S,
662clang::reachable_code::Callback &CB) {
663// Classify the unreachable code found, or suppress it in some cases.
664reachable_code::UnreachableKind UK = reachable_code::UK_Other;
665
666if (isa<BreakStmt>(S)) {
667UK = reachable_code::UK_Break;
668} else if (isTrivialDoWhile(B, S) || isBuiltinUnreachable(S) ||
669isBuiltinAssumeFalse(B, S, C)) {
670return;
671}
672else if (isDeadReturn(B, S)) {
673UK = reachable_code::UK_Return;
674}
675
676const auto *AS = dyn_cast<AttributedStmt>(S);
677bool HasFallThroughAttr =
678AS && hasSpecificAttr<FallThroughAttr>(AS->getAttrs());
679
680SourceRange SilenceableCondVal;
681
682if (UK == reachable_code::UK_Other) {
683// Check if the dead code is part of the "loop target" of
684// a for/for-range loop. This is the block that contains
685// the increment code.
686if (const Stmt *LoopTarget = B->getLoopTarget()) {
687SourceLocation Loc = LoopTarget->getBeginLoc();
688SourceRange R1(Loc, Loc), R2;
689
690if (const ForStmt *FS = dyn_cast<ForStmt>(LoopTarget)) {
691const Expr *Inc = FS->getInc();
692Loc = Inc->getBeginLoc();
693R2 = Inc->getSourceRange();
694}
695
696CB.HandleUnreachable(reachable_code::UK_Loop_Increment, Loc,
697SourceRange(), SourceRange(Loc, Loc), R2,
698HasFallThroughAttr);
699return;
700}
701
702// Check if the dead block has a predecessor whose branch has
703// a configuration value that *could* be modified to
704// silence the warning.
705CFGBlock::const_pred_iterator PI = B->pred_begin();
706if (PI != B->pred_end()) {
707if (const CFGBlock *PredBlock = PI->getPossiblyUnreachableBlock()) {
708const Stmt *TermCond =
709PredBlock->getTerminatorCondition(/* strip parens */ false);
710isConfigurationValue(TermCond, PP, &SilenceableCondVal);
711}
712}
713}
714
715SourceRange R1, R2;
716SourceLocation Loc = GetUnreachableLoc(S, R1, R2);
717CB.HandleUnreachable(UK, Loc, SilenceableCondVal, R1, R2, HasFallThroughAttr);
718}
719
720//===----------------------------------------------------------------------===//
721// Reachability APIs.
722//===----------------------------------------------------------------------===//
723
724namespace clang { namespace reachable_code {
725
726void Callback::anchor() { }
727
728unsigned ScanReachableFromBlock(const CFGBlock *Start,
729llvm::BitVector &Reachable) {
730return scanFromBlock(Start, Reachable, /* SourceManager* */ nullptr, false);
731}
732
733void FindUnreachableCode(AnalysisDeclContext &AC, Preprocessor &PP,
734Callback &CB) {
735
736CFG *cfg = AC.getCFG();
737if (!cfg)
738return;
739
740// Scan for reachable blocks from the entrance of the CFG.
741// If there are no unreachable blocks, we're done.
742llvm::BitVector reachable(cfg->getNumBlockIDs());
743unsigned numReachable =
744scanMaybeReachableFromBlock(&cfg->getEntry(), PP, reachable);
745if (numReachable == cfg->getNumBlockIDs())
746return;
747
748// If there aren't explicit EH edges, we should include the 'try' dispatch
749// blocks as roots.
750if (!AC.getCFGBuildOptions().AddEHEdges) {
751for (const CFGBlock *B : cfg->try_blocks())
752numReachable += scanMaybeReachableFromBlock(B, PP, reachable);
753if (numReachable == cfg->getNumBlockIDs())
754return;
755}
756
757// There are some unreachable blocks. We need to find the root blocks that
758// contain code that should be considered unreachable.
759for (const CFGBlock *block : *cfg) {
760// A block may have been marked reachable during this loop.
761if (reachable[block->getBlockID()])
762continue;
763
764DeadCodeScan DS(reachable, PP, AC.getASTContext());
765numReachable += DS.scanBackwards(block, CB);
766
767if (numReachable == cfg->getNumBlockIDs())
768return;
769}
770}
771
772}} // end namespace clang::reachable_code
773