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