blob: 9191958399b689aeea7a9c70eff47618442d9c12 [file] [log] [blame]
Ted Kremenek7296de92010-02-23 02:39:16 +00001//=- ReachableCodePathInsensitive.cpp ---------------------------*- 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//
10// This file implements a flow-sensitive, path-insensitive analysis of
11// determining reachable blocks within a CFG.
12//
13//===----------------------------------------------------------------------===//
14
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/Analysis/Analyses/ReachableCode.h"
Ted Kremenek552eeaa2010-02-23 05:59:20 +000016#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "clang/AST/ExprObjC.h"
Ted Kremenek552eeaa2010-02-23 05:59:20 +000019#include "clang/AST/StmtCXX.h"
Ted Kremenek552eeaa2010-02-23 05:59:20 +000020#include "clang/Analysis/AnalysisContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Analysis/CFG.h"
Ted Kremenek552eeaa2010-02-23 05:59:20 +000022#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "llvm/ADT/BitVector.h"
24#include "llvm/ADT/SmallVector.h"
Ted Kremenek7296de92010-02-23 02:39:16 +000025
26using namespace clang;
27
Ted Kremenek7d47cac2014-03-07 07:14:36 +000028//===----------------------------------------------------------------------===//
29// Core Reachability Analysis routines.
30//===----------------------------------------------------------------------===//
Ted Kremenek552eeaa2010-02-23 05:59:20 +000031
Ted Kremenekcc893382014-02-27 00:24:08 +000032static bool bodyEndsWithNoReturn(const CFGBlock *B) {
33 for (CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
34 I != E; ++I) {
35 if (Optional<CFGStmt> CS = I->getAs<CFGStmt>()) {
Ted Kremenekec2dc732014-03-06 06:50:46 +000036 const Stmt *S = CS->getStmt();
37 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(S))
38 S = EWC->getSubExpr();
39 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekcc893382014-02-27 00:24:08 +000040 QualType CalleeType = CE->getCallee()->getType();
41 if (getFunctionExtInfo(*CalleeType).getNoReturn())
42 return true;
43 }
44 break;
45 }
46 }
47 return false;
48}
49
Ted Kremenek5441c182014-02-27 06:32:32 +000050static bool bodyEndsWithNoReturn(const CFGBlock::AdjacentBlock &AB) {
Ted Kremenekeb862842014-03-04 21:41:38 +000051 // If the predecessor is a normal CFG edge, then by definition
52 // the predecessor did not end with a 'noreturn'.
53 if (AB.getReachableBlock())
54 return false;
55
Ted Kremenek5441c182014-02-27 06:32:32 +000056 const CFGBlock *Pred = AB.getPossiblyUnreachableBlock();
57 assert(!AB.isReachable() && Pred);
58 return bodyEndsWithNoReturn(Pred);
59}
60
Ted Kremenekcc893382014-02-27 00:24:08 +000061static bool isBreakPrecededByNoReturn(const CFGBlock *B,
62 const Stmt *S) {
63 if (!isa<BreakStmt>(S) || B->pred_empty())
64 return false;
65
66 assert(B->empty());
67 assert(B->pred_size() == 1);
Ted Kremenek5441c182014-02-27 06:32:32 +000068 return bodyEndsWithNoReturn(*B->pred_begin());
69}
70
71static bool isEnumConstant(const Expr *Ex) {
72 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex);
73 if (!DR)
74 return false;
75 return isa<EnumConstantDecl>(DR->getDecl());
76}
77
Ted Kremenekec2dc732014-03-06 06:50:46 +000078static const Expr *stripStdStringCtor(const Expr *Ex) {
79 // Go crazy pattern matching an implicit construction of std::string("").
80 const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex);
81 if (!EWC)
82 return 0;
83 const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(EWC->getSubExpr());
84 if (!CCE)
85 return 0;
86 QualType Ty = CCE->getType();
87 if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Ty))
88 Ty = ET->getNamedType();
89 const TypedefType *TT = dyn_cast<TypedefType>(Ty);
90 StringRef Name = TT->getDecl()->getName();
91 if (Name != "string")
92 return 0;
93 if (CCE->getNumArgs() != 1)
94 return 0;
95 const MaterializeTemporaryExpr *MTE =
96 dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0));
97 if (!MTE)
98 return 0;
99 CXXBindTemporaryExpr *CBT =
100 dyn_cast<CXXBindTemporaryExpr>(MTE->GetTemporaryExpr()->IgnoreParenCasts());
101 if (!CBT)
102 return 0;
103 Ex = CBT->getSubExpr()->IgnoreParenCasts();
104 CCE = dyn_cast<CXXConstructExpr>(Ex);
105 if (!CCE)
106 return 0;
107 if (CCE->getNumArgs() != 1)
108 return 0;
109 return dyn_cast<StringLiteral>(CCE->getArg(0)->IgnoreParenCasts());
110}
111
112/// Strip away "sugar" around trivial expressions that are for the
113/// purpose of this analysis considered uninteresting for dead code warnings.
114static const Expr *stripExprSugar(const Expr *Ex) {
115 Ex = Ex->IgnoreParenCasts();
116 // If 'Ex' is a constructor for a std::string, strip that
117 // away. We can only get here if the trivial expression was
118 // something like a C string literal, with the std::string
119 // just wrapping that value.
120 if (const Expr *StdStringVal = stripStdStringCtor(Ex))
121 return StdStringVal;
122 return Ex;
123}
124
Ted Kremenek5441c182014-02-27 06:32:32 +0000125static bool isTrivialExpression(const Expr *Ex) {
Ted Kremenek0a69cab2014-03-05 23:46:07 +0000126 Ex = Ex->IgnoreParenCasts();
Ted Kremenek5441c182014-02-27 06:32:32 +0000127 return isa<IntegerLiteral>(Ex) || isa<StringLiteral>(Ex) ||
Ted Kremenekc10830b2014-03-07 02:25:50 +0000128 isa<CXXBoolLiteralExpr>(Ex) || isa<ObjCBoolLiteralExpr>(Ex) ||
129 isa<CharacterLiteral>(Ex) ||
Ted Kremenek5441c182014-02-27 06:32:32 +0000130 isEnumConstant(Ex);
131}
132
Ted Kremenek1de2e142014-03-06 00:17:44 +0000133static bool isTrivialReturnOrDoWhile(const CFGBlock *B, const Stmt *S) {
Ted Kremenek5441c182014-02-27 06:32:32 +0000134 const Expr *Ex = dyn_cast<Expr>(S);
Ted Kremenek5441c182014-02-27 06:32:32 +0000135
Ted Kremenek04bfbee2014-03-08 02:22:23 +0000136 if (Ex && !isTrivialExpression(Ex))
Ted Kremenek5441c182014-02-27 06:32:32 +0000137 return false;
138
Ted Kremenek1de2e142014-03-06 00:17:44 +0000139 // Check if the block ends with a do...while() and see if 'S' is the
140 // condition.
141 if (const Stmt *Term = B->getTerminator()) {
142 if (const DoStmt *DS = dyn_cast<DoStmt>(Term))
143 if (DS->getCond() == S)
144 return true;
145 }
146
Ted Kremenek7549f0f2014-03-06 01:09:45 +0000147 if (B->pred_size() != 1)
148 return false;
Ted Kremenek1de2e142014-03-06 00:17:44 +0000149
Ted Kremenek5441c182014-02-27 06:32:32 +0000150 // Look to see if the block ends with a 'return', and see if 'S'
151 // is a substatement. The 'return' may not be the last element in
152 // the block because of destructors.
Ted Kremenek5441c182014-02-27 06:32:32 +0000153 for (CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
154 I != E; ++I) {
155 if (Optional<CFGStmt> CS = I->getAs<CFGStmt>()) {
156 if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(CS->getStmt())) {
Ted Kremenek04bfbee2014-03-08 02:22:23 +0000157 bool LookAtBody = false;
158 if (RS == S)
159 LookAtBody = true;
160 else {
161 const Expr *RE = RS->getRetValue();
162 if (RE && stripExprSugar(RE->IgnoreParenCasts()) == Ex)
163 LookAtBody = true;
164 }
165
166 if (LookAtBody)
Ted Kremenek7549f0f2014-03-06 01:09:45 +0000167 return bodyEndsWithNoReturn(*B->pred_begin());
Ted Kremenek5441c182014-02-27 06:32:32 +0000168 }
Ted Kremenek7549f0f2014-03-06 01:09:45 +0000169 break;
Ted Kremenek5441c182014-02-27 06:32:32 +0000170 }
171 }
Ted Kremenek0a69cab2014-03-05 23:46:07 +0000172 return false;
Ted Kremenekcc893382014-02-27 00:24:08 +0000173}
174
Ted Kremenek6d9bb562014-03-05 00:01:17 +0000175/// Returns true if the statement is expanded from a configuration macro.
176static bool isExpandedFromConfigurationMacro(const Stmt *S) {
177 // FIXME: This is not very precise. Here we just check to see if the
178 // value comes from a macro, but we can do much better. This is likely
179 // to be over conservative. This logic is factored into a separate function
180 // so that we can refine it later.
181 SourceLocation L = S->getLocStart();
182 return L.isMacroID();
183}
184
185/// Returns true if the statement represents a configuration value.
186///
187/// A configuration value is something usually determined at compile-time
188/// to conditionally always execute some branch. Such guards are for
189/// "sometimes unreachable" code. Such code is usually not interesting
190/// to report as unreachable, and may mask truly unreachable code within
191/// those blocks.
192static bool isConfigurationValue(const Stmt *S) {
193 if (!S)
194 return false;
195
196 if (const Expr *Ex = dyn_cast<Expr>(S))
197 S = Ex->IgnoreParenCasts();
198
199 switch (S->getStmtClass()) {
Ted Kremenek01a39b62014-03-05 23:38:41 +0000200 case Stmt::DeclRefExprClass: {
201 const DeclRefExpr *DR = cast<DeclRefExpr>(S);
Ted Kremenek94d16172014-03-07 20:51:13 +0000202 const ValueDecl *D = DR->getDecl();
203 if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D))
204 return ED ? isConfigurationValue(ED->getInitExpr()) : false;
205 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
206 // As a heuristic, treat globals as configuration values. Note
207 // that we only will get here if Sema evaluated this
208 // condition to a constant expression, which means the global
209 // had to be declared in a way to be a truly constant value.
210 // We could generalize this to local variables, but it isn't
211 // clear if those truly represent configuration values that
212 // gate unreachable code.
213 return !VD->hasLocalStorage();
214 }
215 return false;
Ted Kremenek01a39b62014-03-05 23:38:41 +0000216 }
Ted Kremenek6d9bb562014-03-05 00:01:17 +0000217 case Stmt::IntegerLiteralClass:
218 return isExpandedFromConfigurationMacro(S);
219 case Stmt::UnaryExprOrTypeTraitExprClass:
220 return true;
221 case Stmt::BinaryOperatorClass: {
222 const BinaryOperator *B = cast<BinaryOperator>(S);
Ted Kremenek3cdbc392014-03-05 22:32:39 +0000223 return (B->isLogicalOp() || B->isComparisonOp()) &&
Ted Kremenek6d9bb562014-03-05 00:01:17 +0000224 (isConfigurationValue(B->getLHS()) ||
225 isConfigurationValue(B->getRHS()));
226 }
227 case Stmt::UnaryOperatorClass: {
228 const UnaryOperator *UO = cast<UnaryOperator>(S);
229 return UO->getOpcode() == UO_LNot &&
230 isConfigurationValue(UO->getSubExpr());
231 }
232 default:
233 return false;
234 }
235}
236
237/// Returns true if we should always explore all successors of a block.
238static bool shouldTreatSuccessorsAsReachable(const CFGBlock *B) {
Ted Kremenek782f0032014-03-07 02:25:53 +0000239 if (const Stmt *Term = B->getTerminator()) {
Ted Kremenek6999d022014-03-06 08:09:00 +0000240 if (isa<SwitchStmt>(Term))
241 return true;
Ted Kremenek782f0032014-03-07 02:25:53 +0000242 // Specially handle '||' and '&&'.
243 if (isa<BinaryOperator>(Term))
244 return isConfigurationValue(Term);
245 }
Ted Kremenek6999d022014-03-06 08:09:00 +0000246
Ted Kremenek6d9bb562014-03-05 00:01:17 +0000247 return isConfigurationValue(B->getTerminatorCondition());
248}
249
Ted Kremenek7d47cac2014-03-07 07:14:36 +0000250static unsigned scanFromBlock(const CFGBlock *Start,
251 llvm::BitVector &Reachable,
252 bool IncludeSometimesUnreachableEdges) {
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000253 unsigned count = 0;
Ted Kremenekbd913712011-08-23 23:05:11 +0000254
Nico Webercc2b8712011-04-02 19:45:15 +0000255 // Prep work queue
Ted Kremenekbd913712011-08-23 23:05:11 +0000256 SmallVector<const CFGBlock*, 32> WL;
257
258 // The entry block may have already been marked reachable
259 // by the caller.
260 if (!Reachable[Start->getBlockID()]) {
261 ++count;
262 Reachable[Start->getBlockID()] = true;
263 }
264
265 WL.push_back(Start);
266
Ted Kremenekf2b0a1b2010-09-09 00:06:10 +0000267 // Find the reachable blocks from 'Start'.
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000268 while (!WL.empty()) {
Ted Kremenekbd913712011-08-23 23:05:11 +0000269 const CFGBlock *item = WL.pop_back_val();
Ted Kremenek6d9bb562014-03-05 00:01:17 +0000270
271 // There are cases where we want to treat all successors as reachable.
272 // The idea is that some "sometimes unreachable" code is not interesting,
273 // and that we should forge ahead and explore those branches anyway.
274 // This allows us to potentially uncover some "always unreachable" code
275 // within the "sometimes unreachable" code.
Ted Kremenekbd913712011-08-23 23:05:11 +0000276 // Look at the successors and mark then reachable.
Ted Kremenek782f0032014-03-07 02:25:53 +0000277 Optional<bool> TreatAllSuccessorsAsReachable;
Ted Kremenek7d47cac2014-03-07 07:14:36 +0000278 if (!IncludeSometimesUnreachableEdges)
279 TreatAllSuccessorsAsReachable = false;
Ted Kremenek782f0032014-03-07 02:25:53 +0000280
Ted Kremenekbd913712011-08-23 23:05:11 +0000281 for (CFGBlock::const_succ_iterator I = item->succ_begin(),
Ted Kremenek08da9782014-02-27 21:56:47 +0000282 E = item->succ_end(); I != E; ++I) {
283 const CFGBlock *B = *I;
Ted Kremenek6d9bb562014-03-05 00:01:17 +0000284 if (!B) do {
285 const CFGBlock *UB = I->getPossiblyUnreachableBlock();
286 if (!UB)
287 break;
288
Ted Kremenek782f0032014-03-07 02:25:53 +0000289 if (!TreatAllSuccessorsAsReachable.hasValue())
290 TreatAllSuccessorsAsReachable =
291 shouldTreatSuccessorsAsReachable(item);
292
293 if (TreatAllSuccessorsAsReachable.getValue()) {
Ted Kremenek6d9bb562014-03-05 00:01:17 +0000294 B = UB;
295 break;
296 }
Ted Kremenek08da9782014-02-27 21:56:47 +0000297 }
Ted Kremenek6d9bb562014-03-05 00:01:17 +0000298 while (false);
299
Ted Kremenek08da9782014-02-27 21:56:47 +0000300 if (B) {
Ted Kremenek7296de92010-02-23 02:39:16 +0000301 unsigned blockID = B->getBlockID();
302 if (!Reachable[blockID]) {
303 Reachable.set(blockID);
Ted Kremenek7296de92010-02-23 02:39:16 +0000304 WL.push_back(B);
Ted Kremenekbd913712011-08-23 23:05:11 +0000305 ++count;
Ted Kremenek7296de92010-02-23 02:39:16 +0000306 }
307 }
Ted Kremenek08da9782014-02-27 21:56:47 +0000308 }
Ted Kremenek7296de92010-02-23 02:39:16 +0000309 }
310 return count;
311}
Ted Kremenek7d47cac2014-03-07 07:14:36 +0000312
313static unsigned scanMaybeReachableFromBlock(const CFGBlock *Start,
314 llvm::BitVector &Reachable) {
315 return scanFromBlock(Start, Reachable, true);
316}
317
318//===----------------------------------------------------------------------===//
319// Dead Code Scanner.
320//===----------------------------------------------------------------------===//
321
322namespace {
323 class DeadCodeScan {
324 llvm::BitVector Visited;
325 llvm::BitVector &Reachable;
326 SmallVector<const CFGBlock *, 10> WorkList;
327
328 typedef SmallVector<std::pair<const CFGBlock *, const Stmt *>, 12>
329 DeferredLocsTy;
330
331 DeferredLocsTy DeferredLocs;
332
333 public:
334 DeadCodeScan(llvm::BitVector &reachable)
335 : Visited(reachable.size()),
336 Reachable(reachable) {}
337
338 void enqueue(const CFGBlock *block);
339 unsigned scanBackwards(const CFGBlock *Start,
340 clang::reachable_code::Callback &CB);
341
342 bool isDeadCodeRoot(const CFGBlock *Block);
343
344 const Stmt *findDeadCode(const CFGBlock *Block);
345
346 void reportDeadCode(const CFGBlock *B,
347 const Stmt *S,
348 clang::reachable_code::Callback &CB);
349 };
350}
351
352void DeadCodeScan::enqueue(const CFGBlock *block) {
353 unsigned blockID = block->getBlockID();
354 if (Reachable[blockID] || Visited[blockID])
355 return;
356 Visited[blockID] = true;
357 WorkList.push_back(block);
358}
359
360bool DeadCodeScan::isDeadCodeRoot(const clang::CFGBlock *Block) {
361 bool isDeadRoot = true;
362
363 for (CFGBlock::const_pred_iterator I = Block->pred_begin(),
364 E = Block->pred_end(); I != E; ++I) {
365 if (const CFGBlock *PredBlock = *I) {
366 unsigned blockID = PredBlock->getBlockID();
367 if (Visited[blockID]) {
368 isDeadRoot = false;
369 continue;
370 }
371 if (!Reachable[blockID]) {
372 isDeadRoot = false;
373 Visited[blockID] = true;
374 WorkList.push_back(PredBlock);
375 continue;
376 }
377 }
378 }
379
380 return isDeadRoot;
381}
382
383static bool isValidDeadStmt(const Stmt *S) {
384 if (S->getLocStart().isInvalid())
385 return false;
386 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(S))
387 return BO->getOpcode() != BO_Comma;
388 return true;
389}
390
391const Stmt *DeadCodeScan::findDeadCode(const clang::CFGBlock *Block) {
392 for (CFGBlock::const_iterator I = Block->begin(), E = Block->end(); I!=E; ++I)
393 if (Optional<CFGStmt> CS = I->getAs<CFGStmt>()) {
394 const Stmt *S = CS->getStmt();
395 if (isValidDeadStmt(S))
396 return S;
397 }
398
399 if (CFGTerminator T = Block->getTerminator()) {
Ted Kremenekefea6342014-03-08 02:22:32 +0000400 if (!T.isTemporaryDtorsBranch()) {
401 const Stmt *S = T.getStmt();
402 if (isValidDeadStmt(S))
403 return S;
404 }
Ted Kremenek7d47cac2014-03-07 07:14:36 +0000405 }
406
407 return 0;
408}
409
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000410static int SrcCmp(const std::pair<const CFGBlock *, const Stmt *> *p1,
411 const std::pair<const CFGBlock *, const Stmt *> *p2) {
412 if (p1->second->getLocStart() < p2->second->getLocStart())
413 return -1;
414 if (p2->second->getLocStart() < p1->second->getLocStart())
415 return 1;
416 return 0;
417}
418
Ted Kremenek7d47cac2014-03-07 07:14:36 +0000419unsigned DeadCodeScan::scanBackwards(const clang::CFGBlock *Start,
420 clang::reachable_code::Callback &CB) {
421
422 unsigned count = 0;
423 enqueue(Start);
424
425 while (!WorkList.empty()) {
426 const CFGBlock *Block = WorkList.pop_back_val();
427
428 // It is possible that this block has been marked reachable after
429 // it was enqueued.
430 if (Reachable[Block->getBlockID()])
431 continue;
432
433 // Look for any dead code within the block.
434 const Stmt *S = findDeadCode(Block);
435
436 if (!S) {
437 // No dead code. Possibly an empty block. Look at dead predecessors.
438 for (CFGBlock::const_pred_iterator I = Block->pred_begin(),
439 E = Block->pred_end(); I != E; ++I) {
440 if (const CFGBlock *predBlock = *I)
441 enqueue(predBlock);
442 }
443 continue;
444 }
445
446 // Specially handle macro-expanded code.
447 if (S->getLocStart().isMacroID()) {
448 count += scanMaybeReachableFromBlock(Block, Reachable);
449 continue;
450 }
451
452 if (isDeadCodeRoot(Block)) {
453 reportDeadCode(Block, S, CB);
454 count += scanMaybeReachableFromBlock(Block, Reachable);
455 }
456 else {
457 // Record this statement as the possibly best location in a
458 // strongly-connected component of dead code for emitting a
459 // warning.
460 DeferredLocs.push_back(std::make_pair(Block, S));
461 }
462 }
463
464 // If we didn't find a dead root, then report the dead code with the
465 // earliest location.
466 if (!DeferredLocs.empty()) {
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000467 llvm::array_pod_sort(DeferredLocs.begin(), DeferredLocs.end(), SrcCmp);
Ted Kremenek7d47cac2014-03-07 07:14:36 +0000468 for (DeferredLocsTy::iterator I = DeferredLocs.begin(),
469 E = DeferredLocs.end(); I != E; ++I) {
470 const CFGBlock *Block = I->first;
471 if (Reachable[Block->getBlockID()])
472 continue;
473 reportDeadCode(Block, I->second, CB);
474 count += scanMaybeReachableFromBlock(Block, Reachable);
475 }
476 }
477
478 return count;
479}
480
481static SourceLocation GetUnreachableLoc(const Stmt *S,
482 SourceRange &R1,
483 SourceRange &R2) {
484 R1 = R2 = SourceRange();
485
486 if (const Expr *Ex = dyn_cast<Expr>(S))
487 S = Ex->IgnoreParenImpCasts();
488
489 switch (S->getStmtClass()) {
490 case Expr::BinaryOperatorClass: {
491 const BinaryOperator *BO = cast<BinaryOperator>(S);
492 return BO->getOperatorLoc();
493 }
494 case Expr::UnaryOperatorClass: {
495 const UnaryOperator *UO = cast<UnaryOperator>(S);
496 R1 = UO->getSubExpr()->getSourceRange();
497 return UO->getOperatorLoc();
498 }
499 case Expr::CompoundAssignOperatorClass: {
500 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(S);
501 R1 = CAO->getLHS()->getSourceRange();
502 R2 = CAO->getRHS()->getSourceRange();
503 return CAO->getOperatorLoc();
504 }
505 case Expr::BinaryConditionalOperatorClass:
506 case Expr::ConditionalOperatorClass: {
507 const AbstractConditionalOperator *CO =
508 cast<AbstractConditionalOperator>(S);
509 return CO->getQuestionLoc();
510 }
511 case Expr::MemberExprClass: {
512 const MemberExpr *ME = cast<MemberExpr>(S);
513 R1 = ME->getSourceRange();
514 return ME->getMemberLoc();
515 }
516 case Expr::ArraySubscriptExprClass: {
517 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(S);
518 R1 = ASE->getLHS()->getSourceRange();
519 R2 = ASE->getRHS()->getSourceRange();
520 return ASE->getRBracketLoc();
521 }
522 case Expr::CStyleCastExprClass: {
523 const CStyleCastExpr *CSC = cast<CStyleCastExpr>(S);
524 R1 = CSC->getSubExpr()->getSourceRange();
525 return CSC->getLParenLoc();
526 }
527 case Expr::CXXFunctionalCastExprClass: {
528 const CXXFunctionalCastExpr *CE = cast <CXXFunctionalCastExpr>(S);
529 R1 = CE->getSubExpr()->getSourceRange();
530 return CE->getLocStart();
531 }
532 case Stmt::CXXTryStmtClass: {
533 return cast<CXXTryStmt>(S)->getHandler(0)->getCatchLoc();
534 }
535 case Expr::ObjCBridgedCastExprClass: {
536 const ObjCBridgedCastExpr *CSC = cast<ObjCBridgedCastExpr>(S);
537 R1 = CSC->getSubExpr()->getSourceRange();
538 return CSC->getLParenLoc();
539 }
540 default: ;
541 }
542 R1 = S->getSourceRange();
543 return S->getLocStart();
544}
545
546void DeadCodeScan::reportDeadCode(const CFGBlock *B,
547 const Stmt *S,
548 clang::reachable_code::Callback &CB) {
549 // Suppress idiomatic cases of calling a noreturn function just
550 // before executing a 'break'. If there is other code after the 'break'
551 // in the block then don't suppress the warning.
552 if (isBreakPrecededByNoReturn(B, S))
553 return;
554
555 // Suppress trivial 'return' statements that are dead.
556 if (isTrivialReturnOrDoWhile(B, S))
557 return;
558
559 SourceRange R1, R2;
560 SourceLocation Loc = GetUnreachableLoc(S, R1, R2);
561 CB.HandleUnreachable(Loc, R1, R2);
562}
563
564//===----------------------------------------------------------------------===//
565// Reachability APIs.
566//===----------------------------------------------------------------------===//
567
568namespace clang { namespace reachable_code {
569
570void Callback::anchor() { }
571
572unsigned ScanReachableFromBlock(const CFGBlock *Start,
573 llvm::BitVector &Reachable) {
574 return scanFromBlock(Start, Reachable, false);
575}
576
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000577void FindUnreachableCode(AnalysisDeclContext &AC, Callback &CB) {
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000578 CFG *cfg = AC.getCFG();
579 if (!cfg)
580 return;
581
Ted Kremenekbd913712011-08-23 23:05:11 +0000582 // Scan for reachable blocks from the entrance of the CFG.
583 // If there are no unreachable blocks, we're done.
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000584 llvm::BitVector reachable(cfg->getNumBlockIDs());
Ted Kremenek7d47cac2014-03-07 07:14:36 +0000585 unsigned numReachable =
586 scanMaybeReachableFromBlock(&cfg->getEntry(), reachable);
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000587 if (numReachable == cfg->getNumBlockIDs())
588 return;
Ted Kremenekbd913712011-08-23 23:05:11 +0000589
590 // If there aren't explicit EH edges, we should include the 'try' dispatch
591 // blocks as roots.
592 if (!AC.getCFGBuildOptions().AddEHEdges) {
593 for (CFG::try_block_iterator I = cfg->try_blocks_begin(),
594 E = cfg->try_blocks_end() ; I != E; ++I) {
Ted Kremenek7d47cac2014-03-07 07:14:36 +0000595 numReachable += scanMaybeReachableFromBlock(*I, reachable);
Ted Kremenekbd913712011-08-23 23:05:11 +0000596 }
597 if (numReachable == cfg->getNumBlockIDs())
598 return;
599 }
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000600
Ted Kremenekbd913712011-08-23 23:05:11 +0000601 // There are some unreachable blocks. We need to find the root blocks that
602 // contain code that should be considered unreachable.
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000603 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
Ted Kremenekbd913712011-08-23 23:05:11 +0000604 const CFGBlock *block = *I;
605 // A block may have been marked reachable during this loop.
606 if (reachable[block->getBlockID()])
607 continue;
608
609 DeadCodeScan DS(reachable);
610 numReachable += DS.scanBackwards(block, CB);
611
612 if (numReachable == cfg->getNumBlockIDs())
613 return;
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000614 }
Ted Kremenek552eeaa2010-02-23 05:59:20 +0000615}
616
617}} // end namespace clang::reachable_code