ReachableCode.cpp 25 KB

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