ReachableCode.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. //=- 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. #include "clang/Analysis/Analyses/ReachableCode.h"
  15. #include "clang/AST/Expr.h"
  16. #include "clang/AST/ExprCXX.h"
  17. #include "clang/AST/ExprObjC.h"
  18. #include "clang/AST/ParentMap.h"
  19. #include "clang/AST/StmtCXX.h"
  20. #include "clang/Analysis/AnalysisContext.h"
  21. #include "clang/Analysis/CFG.h"
  22. #include "clang/Basic/SourceManager.h"
  23. #include "clang/Lex/Preprocessor.h"
  24. #include "llvm/ADT/BitVector.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. using namespace clang;
  27. //===----------------------------------------------------------------------===//
  28. // Core Reachability Analysis routines.
  29. //===----------------------------------------------------------------------===//
  30. static bool isEnumConstant(const Expr *Ex) {
  31. const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex);
  32. if (!DR)
  33. return false;
  34. return isa<EnumConstantDecl>(DR->getDecl());
  35. }
  36. static bool isTrivialExpression(const Expr *Ex) {
  37. Ex = Ex->IgnoreParenCasts();
  38. return isa<IntegerLiteral>(Ex) || isa<StringLiteral>(Ex) ||
  39. isa<CXXBoolLiteralExpr>(Ex) || isa<ObjCBoolLiteralExpr>(Ex) ||
  40. isa<CharacterLiteral>(Ex) ||
  41. isEnumConstant(Ex);
  42. }
  43. static bool isTrivialDoWhile(const CFGBlock *B, const Stmt *S) {
  44. // Check if the block ends with a do...while() and see if 'S' is the
  45. // condition.
  46. if (const Stmt *Term = B->getTerminator()) {
  47. if (const DoStmt *DS = dyn_cast<DoStmt>(Term)) {
  48. const Expr *Cond = DS->getCond()->IgnoreParenCasts();
  49. return Cond == S && isTrivialExpression(Cond);
  50. }
  51. }
  52. return false;
  53. }
  54. static bool isDeadReturn(const CFGBlock *B, const Stmt *S) {
  55. // Look to see if the current control flow ends with a 'return', and see if
  56. // 'S' is a substatement. The 'return' may not be the last element in the
  57. // block, or may be in a subsequent block because of destructors.
  58. const CFGBlock *Current = B;
  59. while (true) {
  60. for (CFGBlock::const_reverse_iterator I = Current->rbegin(),
  61. E = Current->rend();
  62. I != E; ++I) {
  63. if (Optional<CFGStmt> CS = I->getAs<CFGStmt>()) {
  64. if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(CS->getStmt())) {
  65. if (RS == S)
  66. return true;
  67. if (const Expr *RE = RS->getRetValue()) {
  68. RE = RE->IgnoreParenCasts();
  69. if (RE == S)
  70. return true;
  71. ParentMap PM(const_cast<Expr *>(RE));
  72. // If 'S' is in the ParentMap, it is a subexpression of
  73. // the return statement.
  74. return PM.getParent(S);
  75. }
  76. }
  77. break;
  78. }
  79. }
  80. // Note also that we are restricting the search for the return statement
  81. // to stop at control-flow; only part of a return statement may be dead,
  82. // without the whole return statement being dead.
  83. if (Current->getTerminator().isTemporaryDtorsBranch()) {
  84. // Temporary destructors have a predictable control flow, thus we want to
  85. // look into the next block for the return statement.
  86. // We look into the false branch, as we know the true branch only contains
  87. // the call to the destructor.
  88. assert(Current->succ_size() == 2);
  89. Current = *(Current->succ_begin() + 1);
  90. } else if (!Current->getTerminator() && Current->succ_size() == 1) {
  91. // If there is only one successor, we're not dealing with outgoing control
  92. // flow. Thus, look into the next block.
  93. Current = *Current->succ_begin();
  94. if (Current->pred_size() > 1) {
  95. // If there is more than one predecessor, we're dealing with incoming
  96. // control flow - if the return statement is in that block, it might
  97. // well be reachable via a different control flow, thus it's not dead.
  98. return false;
  99. }
  100. } else {
  101. // We hit control flow or a dead end. Stop searching.
  102. return false;
  103. }
  104. }
  105. llvm_unreachable("Broke out of infinite loop.");
  106. }
  107. static SourceLocation getTopMostMacro(SourceLocation Loc, SourceManager &SM) {
  108. assert(Loc.isMacroID());
  109. SourceLocation Last;
  110. while (Loc.isMacroID()) {
  111. Last = Loc;
  112. Loc = SM.getImmediateMacroCallerLoc(Loc);
  113. }
  114. return Last;
  115. }
  116. /// Returns true if the statement is expanded from a configuration macro.
  117. static bool isExpandedFromConfigurationMacro(const Stmt *S,
  118. Preprocessor &PP,
  119. bool IgnoreYES_NO = false) {
  120. // FIXME: This is not very precise. Here we just check to see if the
  121. // value comes from a macro, but we can do much better. This is likely
  122. // to be over conservative. This logic is factored into a separate function
  123. // so that we can refine it later.
  124. SourceLocation L = S->getLocStart();
  125. if (L.isMacroID()) {
  126. if (IgnoreYES_NO) {
  127. // The Objective-C constant 'YES' and 'NO'
  128. // are defined as macros. Do not treat them
  129. // as configuration values.
  130. SourceManager &SM = PP.getSourceManager();
  131. SourceLocation TopL = getTopMostMacro(L, SM);
  132. StringRef MacroName = PP.getImmediateMacroName(TopL);
  133. if (MacroName == "YES" || MacroName == "NO")
  134. return false;
  135. }
  136. return true;
  137. }
  138. return false;
  139. }
  140. static bool isConfigurationValue(const ValueDecl *D, Preprocessor &PP);
  141. /// Returns true if the statement represents a configuration value.
  142. ///
  143. /// A configuration value is something usually determined at compile-time
  144. /// to conditionally always execute some branch. Such guards are for
  145. /// "sometimes unreachable" code. Such code is usually not interesting
  146. /// to report as unreachable, and may mask truly unreachable code within
  147. /// those blocks.
  148. static bool isConfigurationValue(const Stmt *S,
  149. Preprocessor &PP,
  150. SourceRange *SilenceableCondVal = nullptr,
  151. bool IncludeIntegers = true,
  152. bool WrappedInParens = false) {
  153. if (!S)
  154. return false;
  155. if (const Expr *Ex = dyn_cast<Expr>(S))
  156. S = Ex->IgnoreCasts();
  157. // Special case looking for the sigil '()' around an integer literal.
  158. if (const ParenExpr *PE = dyn_cast<ParenExpr>(S))
  159. if (!PE->getLocStart().isMacroID())
  160. return isConfigurationValue(PE->getSubExpr(), PP, SilenceableCondVal,
  161. IncludeIntegers, true);
  162. if (const Expr *Ex = dyn_cast<Expr>(S))
  163. S = Ex->IgnoreCasts();
  164. bool IgnoreYES_NO = false;
  165. switch (S->getStmtClass()) {
  166. case Stmt::CallExprClass: {
  167. const FunctionDecl *Callee =
  168. dyn_cast_or_null<FunctionDecl>(cast<CallExpr>(S)->getCalleeDecl());
  169. return Callee ? Callee->isConstexpr() : false;
  170. }
  171. case Stmt::DeclRefExprClass:
  172. return isConfigurationValue(cast<DeclRefExpr>(S)->getDecl(), PP);
  173. case Stmt::ObjCBoolLiteralExprClass:
  174. IgnoreYES_NO = true;
  175. // Fallthrough.
  176. case Stmt::CXXBoolLiteralExprClass:
  177. case Stmt::IntegerLiteralClass: {
  178. const Expr *E = cast<Expr>(S);
  179. if (IncludeIntegers) {
  180. if (SilenceableCondVal && !SilenceableCondVal->getBegin().isValid())
  181. *SilenceableCondVal = E->getSourceRange();
  182. return WrappedInParens || isExpandedFromConfigurationMacro(E, PP, IgnoreYES_NO);
  183. }
  184. return false;
  185. }
  186. case Stmt::MemberExprClass:
  187. return isConfigurationValue(cast<MemberExpr>(S)->getMemberDecl(), PP);
  188. case Stmt::UnaryExprOrTypeTraitExprClass:
  189. return true;
  190. case Stmt::BinaryOperatorClass: {
  191. const BinaryOperator *B = cast<BinaryOperator>(S);
  192. // Only include raw integers (not enums) as configuration
  193. // values if they are used in a logical or comparison operator
  194. // (not arithmetic).
  195. IncludeIntegers &= (B->isLogicalOp() || B->isComparisonOp());
  196. return isConfigurationValue(B->getLHS(), PP, SilenceableCondVal,
  197. IncludeIntegers) ||
  198. isConfigurationValue(B->getRHS(), PP, SilenceableCondVal,
  199. IncludeIntegers);
  200. }
  201. case Stmt::UnaryOperatorClass: {
  202. const UnaryOperator *UO = cast<UnaryOperator>(S);
  203. if (SilenceableCondVal)
  204. *SilenceableCondVal = UO->getSourceRange();
  205. return UO->getOpcode() == UO_LNot &&
  206. isConfigurationValue(UO->getSubExpr(), PP, SilenceableCondVal,
  207. IncludeIntegers, WrappedInParens);
  208. }
  209. default:
  210. return false;
  211. }
  212. }
  213. static bool isConfigurationValue(const ValueDecl *D, Preprocessor &PP) {
  214. if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D))
  215. return isConfigurationValue(ED->getInitExpr(), PP);
  216. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  217. // As a heuristic, treat globals as configuration values. Note
  218. // that we only will get here if Sema evaluated this
  219. // condition to a constant expression, which means the global
  220. // had to be declared in a way to be a truly constant value.
  221. // We could generalize this to local variables, but it isn't
  222. // clear if those truly represent configuration values that
  223. // gate unreachable code.
  224. if (!VD->hasLocalStorage())
  225. return true;
  226. // As a heuristic, locals that have been marked 'const' explicitly
  227. // can be treated as configuration values as well.
  228. return VD->getType().isLocalConstQualified();
  229. }
  230. return false;
  231. }
  232. /// Returns true if we should always explore all successors of a block.
  233. static bool shouldTreatSuccessorsAsReachable(const CFGBlock *B,
  234. Preprocessor &PP) {
  235. if (const Stmt *Term = B->getTerminator()) {
  236. if (isa<SwitchStmt>(Term))
  237. return true;
  238. // Specially handle '||' and '&&'.
  239. if (isa<BinaryOperator>(Term)) {
  240. return isConfigurationValue(Term, PP);
  241. }
  242. }
  243. const Stmt *Cond = B->getTerminatorCondition(/* stripParens */ false);
  244. return isConfigurationValue(Cond, PP);
  245. }
  246. static unsigned scanFromBlock(const CFGBlock *Start,
  247. llvm::BitVector &Reachable,
  248. Preprocessor *PP,
  249. bool IncludeSometimesUnreachableEdges) {
  250. unsigned count = 0;
  251. // Prep work queue
  252. SmallVector<const CFGBlock*, 32> WL;
  253. // The entry block may have already been marked reachable
  254. // by the caller.
  255. if (!Reachable[Start->getBlockID()]) {
  256. ++count;
  257. Reachable[Start->getBlockID()] = true;
  258. }
  259. WL.push_back(Start);
  260. // Find the reachable blocks from 'Start'.
  261. while (!WL.empty()) {
  262. const CFGBlock *item = WL.pop_back_val();
  263. // There are cases where we want to treat all successors as reachable.
  264. // The idea is that some "sometimes unreachable" code is not interesting,
  265. // and that we should forge ahead and explore those branches anyway.
  266. // This allows us to potentially uncover some "always unreachable" code
  267. // within the "sometimes unreachable" code.
  268. // Look at the successors and mark then reachable.
  269. Optional<bool> TreatAllSuccessorsAsReachable;
  270. if (!IncludeSometimesUnreachableEdges)
  271. TreatAllSuccessorsAsReachable = false;
  272. for (CFGBlock::const_succ_iterator I = item->succ_begin(),
  273. E = item->succ_end(); I != E; ++I) {
  274. const CFGBlock *B = *I;
  275. if (!B) do {
  276. const CFGBlock *UB = I->getPossiblyUnreachableBlock();
  277. if (!UB)
  278. break;
  279. if (!TreatAllSuccessorsAsReachable.hasValue()) {
  280. assert(PP);
  281. TreatAllSuccessorsAsReachable =
  282. shouldTreatSuccessorsAsReachable(item, *PP);
  283. }
  284. if (TreatAllSuccessorsAsReachable.getValue()) {
  285. B = UB;
  286. break;
  287. }
  288. }
  289. while (false);
  290. if (B) {
  291. unsigned blockID = B->getBlockID();
  292. if (!Reachable[blockID]) {
  293. Reachable.set(blockID);
  294. WL.push_back(B);
  295. ++count;
  296. }
  297. }
  298. }
  299. }
  300. return count;
  301. }
  302. static unsigned scanMaybeReachableFromBlock(const CFGBlock *Start,
  303. Preprocessor &PP,
  304. llvm::BitVector &Reachable) {
  305. return scanFromBlock(Start, Reachable, &PP, true);
  306. }
  307. //===----------------------------------------------------------------------===//
  308. // Dead Code Scanner.
  309. //===----------------------------------------------------------------------===//
  310. namespace {
  311. class DeadCodeScan {
  312. llvm::BitVector Visited;
  313. llvm::BitVector &Reachable;
  314. SmallVector<const CFGBlock *, 10> WorkList;
  315. Preprocessor &PP;
  316. typedef SmallVector<std::pair<const CFGBlock *, const Stmt *>, 12>
  317. DeferredLocsTy;
  318. DeferredLocsTy DeferredLocs;
  319. public:
  320. DeadCodeScan(llvm::BitVector &reachable, Preprocessor &PP)
  321. : Visited(reachable.size()),
  322. Reachable(reachable),
  323. PP(PP) {}
  324. void enqueue(const CFGBlock *block);
  325. unsigned scanBackwards(const CFGBlock *Start,
  326. clang::reachable_code::Callback &CB);
  327. bool isDeadCodeRoot(const CFGBlock *Block);
  328. const Stmt *findDeadCode(const CFGBlock *Block);
  329. void reportDeadCode(const CFGBlock *B,
  330. const Stmt *S,
  331. clang::reachable_code::Callback &CB);
  332. };
  333. }
  334. void DeadCodeScan::enqueue(const CFGBlock *block) {
  335. unsigned blockID = block->getBlockID();
  336. if (Reachable[blockID] || Visited[blockID])
  337. return;
  338. Visited[blockID] = true;
  339. WorkList.push_back(block);
  340. }
  341. bool DeadCodeScan::isDeadCodeRoot(const clang::CFGBlock *Block) {
  342. bool isDeadRoot = true;
  343. for (CFGBlock::const_pred_iterator I = Block->pred_begin(),
  344. E = Block->pred_end(); I != E; ++I) {
  345. if (const CFGBlock *PredBlock = *I) {
  346. unsigned blockID = PredBlock->getBlockID();
  347. if (Visited[blockID]) {
  348. isDeadRoot = false;
  349. continue;
  350. }
  351. if (!Reachable[blockID]) {
  352. isDeadRoot = false;
  353. Visited[blockID] = true;
  354. WorkList.push_back(PredBlock);
  355. continue;
  356. }
  357. }
  358. }
  359. return isDeadRoot;
  360. }
  361. static bool isValidDeadStmt(const Stmt *S) {
  362. if (S->getLocStart().isInvalid())
  363. return false;
  364. if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(S))
  365. return BO->getOpcode() != BO_Comma;
  366. return true;
  367. }
  368. const Stmt *DeadCodeScan::findDeadCode(const clang::CFGBlock *Block) {
  369. for (CFGBlock::const_iterator I = Block->begin(), E = Block->end(); I!=E; ++I)
  370. if (Optional<CFGStmt> CS = I->getAs<CFGStmt>()) {
  371. const Stmt *S = CS->getStmt();
  372. if (isValidDeadStmt(S))
  373. return S;
  374. }
  375. if (CFGTerminator T = Block->getTerminator()) {
  376. if (!T.isTemporaryDtorsBranch()) {
  377. const Stmt *S = T.getStmt();
  378. if (isValidDeadStmt(S))
  379. return S;
  380. }
  381. }
  382. return nullptr;
  383. }
  384. // HLSL Change: changed calling convention to __cdecl
  385. static int __cdecl SrcCmp(const std::pair<const CFGBlock *, const Stmt *> *p1,
  386. const std::pair<const CFGBlock *, const Stmt *> *p2) {
  387. if (p1->second->getLocStart() < p2->second->getLocStart())
  388. return -1;
  389. if (p2->second->getLocStart() < p1->second->getLocStart())
  390. return 1;
  391. return 0;
  392. }
  393. unsigned DeadCodeScan::scanBackwards(const clang::CFGBlock *Start,
  394. clang::reachable_code::Callback &CB) {
  395. unsigned count = 0;
  396. enqueue(Start);
  397. while (!WorkList.empty()) {
  398. const CFGBlock *Block = WorkList.pop_back_val();
  399. // It is possible that this block has been marked reachable after
  400. // it was enqueued.
  401. if (Reachable[Block->getBlockID()])
  402. continue;
  403. // Look for any dead code within the block.
  404. const Stmt *S = findDeadCode(Block);
  405. if (!S) {
  406. // No dead code. Possibly an empty block. Look at dead predecessors.
  407. for (CFGBlock::const_pred_iterator I = Block->pred_begin(),
  408. E = Block->pred_end(); I != E; ++I) {
  409. if (const CFGBlock *predBlock = *I)
  410. enqueue(predBlock);
  411. }
  412. continue;
  413. }
  414. // Specially handle macro-expanded code.
  415. if (S->getLocStart().isMacroID()) {
  416. count += scanMaybeReachableFromBlock(Block, PP, Reachable);
  417. continue;
  418. }
  419. if (isDeadCodeRoot(Block)) {
  420. reportDeadCode(Block, S, CB);
  421. count += scanMaybeReachableFromBlock(Block, PP, Reachable);
  422. }
  423. else {
  424. // Record this statement as the possibly best location in a
  425. // strongly-connected component of dead code for emitting a
  426. // warning.
  427. DeferredLocs.push_back(std::make_pair(Block, S));
  428. }
  429. }
  430. // If we didn't find a dead root, then report the dead code with the
  431. // earliest location.
  432. if (!DeferredLocs.empty()) {
  433. llvm::array_pod_sort(DeferredLocs.begin(), DeferredLocs.end(), SrcCmp);
  434. for (DeferredLocsTy::iterator I = DeferredLocs.begin(),
  435. E = DeferredLocs.end(); I != E; ++I) {
  436. const CFGBlock *Block = I->first;
  437. if (Reachable[Block->getBlockID()])
  438. continue;
  439. reportDeadCode(Block, I->second, CB);
  440. count += scanMaybeReachableFromBlock(Block, PP, Reachable);
  441. }
  442. }
  443. return count;
  444. }
  445. static SourceLocation GetUnreachableLoc(const Stmt *S,
  446. SourceRange &R1,
  447. SourceRange &R2) {
  448. R1 = R2 = SourceRange();
  449. if (const Expr *Ex = dyn_cast<Expr>(S))
  450. S = Ex->IgnoreParenImpCasts();
  451. switch (S->getStmtClass()) {
  452. case Expr::BinaryOperatorClass: {
  453. const BinaryOperator *BO = cast<BinaryOperator>(S);
  454. return BO->getOperatorLoc();
  455. }
  456. case Expr::UnaryOperatorClass: {
  457. const UnaryOperator *UO = cast<UnaryOperator>(S);
  458. R1 = UO->getSubExpr()->getSourceRange();
  459. return UO->getOperatorLoc();
  460. }
  461. case Expr::CompoundAssignOperatorClass: {
  462. const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(S);
  463. R1 = CAO->getLHS()->getSourceRange();
  464. R2 = CAO->getRHS()->getSourceRange();
  465. return CAO->getOperatorLoc();
  466. }
  467. case Expr::BinaryConditionalOperatorClass:
  468. case Expr::ConditionalOperatorClass: {
  469. const AbstractConditionalOperator *CO =
  470. cast<AbstractConditionalOperator>(S);
  471. return CO->getQuestionLoc();
  472. }
  473. case Expr::MemberExprClass: {
  474. const MemberExpr *ME = cast<MemberExpr>(S);
  475. R1 = ME->getSourceRange();
  476. return ME->getMemberLoc();
  477. }
  478. case Expr::ArraySubscriptExprClass: {
  479. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(S);
  480. R1 = ASE->getLHS()->getSourceRange();
  481. R2 = ASE->getRHS()->getSourceRange();
  482. return ASE->getRBracketLoc();
  483. }
  484. case Expr::CStyleCastExprClass: {
  485. const CStyleCastExpr *CSC = cast<CStyleCastExpr>(S);
  486. R1 = CSC->getSubExpr()->getSourceRange();
  487. return CSC->getLParenLoc();
  488. }
  489. case Expr::CXXFunctionalCastExprClass: {
  490. const CXXFunctionalCastExpr *CE = cast <CXXFunctionalCastExpr>(S);
  491. R1 = CE->getSubExpr()->getSourceRange();
  492. return CE->getLocStart();
  493. }
  494. case Stmt::CXXTryStmtClass: {
  495. return cast<CXXTryStmt>(S)->getHandler(0)->getCatchLoc();
  496. }
  497. case Expr::ObjCBridgedCastExprClass: {
  498. const ObjCBridgedCastExpr *CSC = cast<ObjCBridgedCastExpr>(S);
  499. R1 = CSC->getSubExpr()->getSourceRange();
  500. return CSC->getLParenLoc();
  501. }
  502. default: ;
  503. }
  504. R1 = S->getSourceRange();
  505. return S->getLocStart();
  506. }
  507. void DeadCodeScan::reportDeadCode(const CFGBlock *B,
  508. const Stmt *S,
  509. clang::reachable_code::Callback &CB) {
  510. // Classify the unreachable code found, or suppress it in some cases.
  511. reachable_code::UnreachableKind UK = reachable_code::UK_Other;
  512. if (isa<BreakStmt>(S)) {
  513. UK = reachable_code::UK_Break;
  514. }
  515. else if (isTrivialDoWhile(B, S)) {
  516. return;
  517. }
  518. else if (isDeadReturn(B, S)) {
  519. UK = reachable_code::UK_Return;
  520. }
  521. SourceRange SilenceableCondVal;
  522. if (UK == reachable_code::UK_Other) {
  523. // Check if the dead code is part of the "loop target" of
  524. // a for/for-range loop. This is the block that contains
  525. // the increment code.
  526. if (const Stmt *LoopTarget = B->getLoopTarget()) {
  527. SourceLocation Loc = LoopTarget->getLocStart();
  528. SourceRange R1(Loc, Loc), R2;
  529. if (const ForStmt *FS = dyn_cast<ForStmt>(LoopTarget)) {
  530. const Expr *Inc = FS->getInc();
  531. Loc = Inc->getLocStart();
  532. R2 = Inc->getSourceRange();
  533. }
  534. CB.HandleUnreachable(reachable_code::UK_Loop_Increment,
  535. Loc, SourceRange(), SourceRange(Loc, Loc), R2);
  536. return;
  537. }
  538. // Check if the dead block has a predecessor whose branch has
  539. // a configuration value that *could* be modified to
  540. // silence the warning.
  541. CFGBlock::const_pred_iterator PI = B->pred_begin();
  542. if (PI != B->pred_end()) {
  543. if (const CFGBlock *PredBlock = PI->getPossiblyUnreachableBlock()) {
  544. const Stmt *TermCond =
  545. PredBlock->getTerminatorCondition(/* strip parens */ false);
  546. isConfigurationValue(TermCond, PP, &SilenceableCondVal);
  547. }
  548. }
  549. }
  550. SourceRange R1, R2;
  551. SourceLocation Loc = GetUnreachableLoc(S, R1, R2);
  552. CB.HandleUnreachable(UK, Loc, SilenceableCondVal, R1, R2);
  553. }
  554. //===----------------------------------------------------------------------===//
  555. // Reachability APIs.
  556. //===----------------------------------------------------------------------===//
  557. namespace clang { namespace reachable_code {
  558. void Callback::anchor() { }
  559. unsigned ScanReachableFromBlock(const CFGBlock *Start,
  560. llvm::BitVector &Reachable) {
  561. return scanFromBlock(Start, Reachable, /* SourceManager* */ nullptr, false);
  562. }
  563. void FindUnreachableCode(AnalysisDeclContext &AC, Preprocessor &PP,
  564. Callback &CB) {
  565. CFG *cfg = AC.getCFG();
  566. if (!cfg)
  567. return;
  568. // Scan for reachable blocks from the entrance of the CFG.
  569. // If there are no unreachable blocks, we're done.
  570. llvm::BitVector reachable(cfg->getNumBlockIDs());
  571. unsigned numReachable =
  572. scanMaybeReachableFromBlock(&cfg->getEntry(), PP, reachable);
  573. if (numReachable == cfg->getNumBlockIDs())
  574. return;
  575. // If there aren't explicit EH edges, we should include the 'try' dispatch
  576. // blocks as roots.
  577. if (!AC.getCFGBuildOptions().AddEHEdges) {
  578. for (CFG::try_block_iterator I = cfg->try_blocks_begin(),
  579. E = cfg->try_blocks_end() ; I != E; ++I) {
  580. numReachable += scanMaybeReachableFromBlock(*I, PP, reachable);
  581. }
  582. if (numReachable == cfg->getNumBlockIDs())
  583. return;
  584. }
  585. // There are some unreachable blocks. We need to find the root blocks that
  586. // contain code that should be considered unreachable.
  587. for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
  588. const CFGBlock *block = *I;
  589. // A block may have been marked reachable during this loop.
  590. if (reachable[block->getBlockID()])
  591. continue;
  592. DeadCodeScan DS(reachable, PP);
  593. numReachable += DS.scanBackwards(block, CB);
  594. if (numReachable == cfg->getNumBlockIDs())
  595. return;
  596. }
  597. }
  598. }} // end namespace clang::reachable_code