1 // BugReporter.cpp - Generate PathDiagnostics for Bugs ------------*- 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 defines BugReporter, a utility class for generating 11 // PathDiagnostics. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 16 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 17 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/Analysis/CFG.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ParentMap.h" 23 #include "clang/AST/StmtObjC.h" 24 #include "clang/Basic/SourceManager.h" 25 #include "clang/Analysis/ProgramPoint.h" 26 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 27 #include "llvm/Support/raw_ostream.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/SmallString.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/OwningPtr.h" 32 #include "llvm/ADT/IntrusiveRefCntPtr.h" 33 #include <queue> 34 35 using namespace clang; 36 using namespace ento; 37 38 BugReporterVisitor::~BugReporterVisitor() {} 39 40 void BugReporterContext::anchor() {} 41 42 //===----------------------------------------------------------------------===// 43 // Helper routines for walking the ExplodedGraph and fetching statements. 44 //===----------------------------------------------------------------------===// 45 46 static inline const Stmt *GetStmt(const ProgramPoint &P) { 47 if (const StmtPoint* SP = dyn_cast<StmtPoint>(&P)) 48 return SP->getStmt(); 49 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) 50 return BE->getSrc()->getTerminator(); 51 else if (const CallEnter *CE = dyn_cast<CallEnter>(&P)) 52 return CE->getCallExpr(); 53 else if (const CallExitEnd *CEE = dyn_cast<CallExitEnd>(&P)) 54 return CEE->getCalleeContext()->getCallSite(); 55 56 return 0; 57 } 58 59 static inline const ExplodedNode* 60 GetPredecessorNode(const ExplodedNode *N) { 61 return N->pred_empty() ? NULL : *(N->pred_begin()); 62 } 63 64 static inline const ExplodedNode* 65 GetSuccessorNode(const ExplodedNode *N) { 66 return N->succ_empty() ? NULL : *(N->succ_begin()); 67 } 68 69 static const Stmt *GetPreviousStmt(const ExplodedNode *N) { 70 for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N)) 71 if (const Stmt *S = GetStmt(N->getLocation())) 72 return S; 73 74 return 0; 75 } 76 77 static const Stmt *GetNextStmt(const ExplodedNode *N) { 78 for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N)) 79 if (const Stmt *S = GetStmt(N->getLocation())) { 80 // Check if the statement is '?' or '&&'/'||'. These are "merges", 81 // not actual statement points. 82 switch (S->getStmtClass()) { 83 case Stmt::ChooseExprClass: 84 case Stmt::BinaryConditionalOperatorClass: continue; 85 case Stmt::ConditionalOperatorClass: continue; 86 case Stmt::BinaryOperatorClass: { 87 BinaryOperatorKind Op = cast<BinaryOperator>(S)->getOpcode(); 88 if (Op == BO_LAnd || Op == BO_LOr) 89 continue; 90 break; 91 } 92 default: 93 break; 94 } 95 return S; 96 } 97 98 return 0; 99 } 100 101 static inline const Stmt* 102 GetCurrentOrPreviousStmt(const ExplodedNode *N) { 103 if (const Stmt *S = GetStmt(N->getLocation())) 104 return S; 105 106 return GetPreviousStmt(N); 107 } 108 109 static inline const Stmt* 110 GetCurrentOrNextStmt(const ExplodedNode *N) { 111 if (const Stmt *S = GetStmt(N->getLocation())) 112 return S; 113 114 return GetNextStmt(N); 115 } 116 117 //===----------------------------------------------------------------------===// 118 // Diagnostic cleanup. 119 //===----------------------------------------------------------------------===// 120 121 /// Recursively scan through a path and prune out calls and macros pieces 122 /// that aren't needed. Return true if afterwards the path contains 123 /// "interesting stuff" which means it should be pruned from the parent path. 124 bool BugReporter::RemoveUneededCalls(PathPieces &pieces, BugReport *R) { 125 bool containsSomethingInteresting = false; 126 const unsigned N = pieces.size(); 127 128 for (unsigned i = 0 ; i < N ; ++i) { 129 // Remove the front piece from the path. If it is still something we 130 // want to keep once we are done, we will push it back on the end. 131 IntrusiveRefCntPtr<PathDiagnosticPiece> piece(pieces.front()); 132 pieces.pop_front(); 133 134 switch (piece->getKind()) { 135 case PathDiagnosticPiece::Call: { 136 PathDiagnosticCallPiece *call = cast<PathDiagnosticCallPiece>(piece); 137 // Check if the location context is interesting. 138 assert(LocationContextMap.count(call)); 139 if (R->isInteresting(LocationContextMap[call])) { 140 containsSomethingInteresting = true; 141 break; 142 } 143 // Recursively clean out the subclass. Keep this call around if 144 // it contains any informative diagnostics. 145 if (!RemoveUneededCalls(call->path, R)) 146 continue; 147 containsSomethingInteresting = true; 148 break; 149 } 150 case PathDiagnosticPiece::Macro: { 151 PathDiagnosticMacroPiece *macro = cast<PathDiagnosticMacroPiece>(piece); 152 if (!RemoveUneededCalls(macro->subPieces, R)) 153 continue; 154 containsSomethingInteresting = true; 155 break; 156 } 157 case PathDiagnosticPiece::Event: { 158 PathDiagnosticEventPiece *event = cast<PathDiagnosticEventPiece>(piece); 159 // We never throw away an event, but we do throw it away wholesale 160 // as part of a path if we throw the entire path away. 161 containsSomethingInteresting |= !event->isPrunable(); 162 break; 163 } 164 case PathDiagnosticPiece::ControlFlow: 165 break; 166 } 167 168 pieces.push_back(piece); 169 } 170 171 return containsSomethingInteresting; 172 } 173 174 //===----------------------------------------------------------------------===// 175 // PathDiagnosticBuilder and its associated routines and helper objects. 176 //===----------------------------------------------------------------------===// 177 178 typedef llvm::DenseMap<const ExplodedNode*, 179 const ExplodedNode*> NodeBackMap; 180 181 namespace { 182 class NodeMapClosure : public BugReport::NodeResolver { 183 NodeBackMap& M; 184 public: 185 NodeMapClosure(NodeBackMap *m) : M(*m) {} 186 ~NodeMapClosure() {} 187 188 const ExplodedNode *getOriginalNode(const ExplodedNode *N) { 189 NodeBackMap::iterator I = M.find(N); 190 return I == M.end() ? 0 : I->second; 191 } 192 }; 193 194 class PathDiagnosticBuilder : public BugReporterContext { 195 BugReport *R; 196 PathDiagnosticConsumer *PDC; 197 OwningPtr<ParentMap> PM; 198 NodeMapClosure NMC; 199 public: 200 const LocationContext *LC; 201 202 PathDiagnosticBuilder(GRBugReporter &br, 203 BugReport *r, NodeBackMap *Backmap, 204 PathDiagnosticConsumer *pdc) 205 : BugReporterContext(br), 206 R(r), PDC(pdc), NMC(Backmap), LC(r->getErrorNode()->getLocationContext()) 207 {} 208 209 PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N); 210 211 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os, 212 const ExplodedNode *N); 213 214 BugReport *getBugReport() { return R; } 215 216 Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); } 217 218 ParentMap& getParentMap() { return LC->getParentMap(); } 219 220 const Stmt *getParent(const Stmt *S) { 221 return getParentMap().getParent(S); 222 } 223 224 virtual NodeMapClosure& getNodeResolver() { return NMC; } 225 226 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S); 227 228 PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const { 229 return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Extensive; 230 } 231 232 bool supportsLogicalOpControlFlow() const { 233 return PDC ? PDC->supportsLogicalOpControlFlow() : true; 234 } 235 }; 236 } // end anonymous namespace 237 238 PathDiagnosticLocation 239 PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) { 240 if (const Stmt *S = GetNextStmt(N)) 241 return PathDiagnosticLocation(S, getSourceManager(), LC); 242 243 return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(), 244 getSourceManager()); 245 } 246 247 PathDiagnosticLocation 248 PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os, 249 const ExplodedNode *N) { 250 251 // Slow, but probably doesn't matter. 252 if (os.str().empty()) 253 os << ' '; 254 255 const PathDiagnosticLocation &Loc = ExecutionContinues(N); 256 257 if (Loc.asStmt()) 258 os << "Execution continues on line " 259 << getSourceManager().getExpansionLineNumber(Loc.asLocation()) 260 << '.'; 261 else { 262 os << "Execution jumps to the end of the "; 263 const Decl *D = N->getLocationContext()->getDecl(); 264 if (isa<ObjCMethodDecl>(D)) 265 os << "method"; 266 else if (isa<FunctionDecl>(D)) 267 os << "function"; 268 else { 269 assert(isa<BlockDecl>(D)); 270 os << "anonymous block"; 271 } 272 os << '.'; 273 } 274 275 return Loc; 276 } 277 278 static bool IsNested(const Stmt *S, ParentMap &PM) { 279 if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S))) 280 return true; 281 282 const Stmt *Parent = PM.getParentIgnoreParens(S); 283 284 if (Parent) 285 switch (Parent->getStmtClass()) { 286 case Stmt::ForStmtClass: 287 case Stmt::DoStmtClass: 288 case Stmt::WhileStmtClass: 289 return true; 290 default: 291 break; 292 } 293 294 return false; 295 } 296 297 PathDiagnosticLocation 298 PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) { 299 assert(S && "Null Stmt *passed to getEnclosingStmtLocation"); 300 ParentMap &P = getParentMap(); 301 SourceManager &SMgr = getSourceManager(); 302 303 while (IsNested(S, P)) { 304 const Stmt *Parent = P.getParentIgnoreParens(S); 305 306 if (!Parent) 307 break; 308 309 switch (Parent->getStmtClass()) { 310 case Stmt::BinaryOperatorClass: { 311 const BinaryOperator *B = cast<BinaryOperator>(Parent); 312 if (B->isLogicalOp()) 313 return PathDiagnosticLocation(S, SMgr, LC); 314 break; 315 } 316 case Stmt::CompoundStmtClass: 317 case Stmt::StmtExprClass: 318 return PathDiagnosticLocation(S, SMgr, LC); 319 case Stmt::ChooseExprClass: 320 // Similar to '?' if we are referring to condition, just have the edge 321 // point to the entire choose expression. 322 if (cast<ChooseExpr>(Parent)->getCond() == S) 323 return PathDiagnosticLocation(Parent, SMgr, LC); 324 else 325 return PathDiagnosticLocation(S, SMgr, LC); 326 case Stmt::BinaryConditionalOperatorClass: 327 case Stmt::ConditionalOperatorClass: 328 // For '?', if we are referring to condition, just have the edge point 329 // to the entire '?' expression. 330 if (cast<AbstractConditionalOperator>(Parent)->getCond() == S) 331 return PathDiagnosticLocation(Parent, SMgr, LC); 332 else 333 return PathDiagnosticLocation(S, SMgr, LC); 334 case Stmt::DoStmtClass: 335 return PathDiagnosticLocation(S, SMgr, LC); 336 case Stmt::ForStmtClass: 337 if (cast<ForStmt>(Parent)->getBody() == S) 338 return PathDiagnosticLocation(S, SMgr, LC); 339 break; 340 case Stmt::IfStmtClass: 341 if (cast<IfStmt>(Parent)->getCond() != S) 342 return PathDiagnosticLocation(S, SMgr, LC); 343 break; 344 case Stmt::ObjCForCollectionStmtClass: 345 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S) 346 return PathDiagnosticLocation(S, SMgr, LC); 347 break; 348 case Stmt::WhileStmtClass: 349 if (cast<WhileStmt>(Parent)->getCond() != S) 350 return PathDiagnosticLocation(S, SMgr, LC); 351 break; 352 default: 353 break; 354 } 355 356 S = Parent; 357 } 358 359 assert(S && "Cannot have null Stmt for PathDiagnosticLocation"); 360 361 // Special case: DeclStmts can appear in for statement declarations, in which 362 // case the ForStmt is the context. 363 if (isa<DeclStmt>(S)) { 364 if (const Stmt *Parent = P.getParent(S)) { 365 switch (Parent->getStmtClass()) { 366 case Stmt::ForStmtClass: 367 case Stmt::ObjCForCollectionStmtClass: 368 return PathDiagnosticLocation(Parent, SMgr, LC); 369 default: 370 break; 371 } 372 } 373 } 374 else if (isa<BinaryOperator>(S)) { 375 // Special case: the binary operator represents the initialization 376 // code in a for statement (this can happen when the variable being 377 // initialized is an old variable. 378 if (const ForStmt *FS = 379 dyn_cast_or_null<ForStmt>(P.getParentIgnoreParens(S))) { 380 if (FS->getInit() == S) 381 return PathDiagnosticLocation(FS, SMgr, LC); 382 } 383 } 384 385 return PathDiagnosticLocation(S, SMgr, LC); 386 } 387 388 //===----------------------------------------------------------------------===// 389 // "Minimal" path diagnostic generation algorithm. 390 //===----------------------------------------------------------------------===// 391 typedef std::pair<PathDiagnosticCallPiece*, const ExplodedNode*> StackDiagPair; 392 typedef SmallVector<StackDiagPair, 6> StackDiagVector; 393 394 static void updateStackPiecesWithMessage(PathDiagnosticPiece *P, 395 StackDiagVector &CallStack) { 396 // If the piece contains a special message, add it to all the call 397 // pieces on the active stack. 398 if (PathDiagnosticEventPiece *ep = 399 dyn_cast<PathDiagnosticEventPiece>(P)) { 400 401 if (ep->hasCallStackHint()) 402 for (StackDiagVector::iterator I = CallStack.begin(), 403 E = CallStack.end(); I != E; ++I) { 404 PathDiagnosticCallPiece *CP = I->first; 405 const ExplodedNode *N = I->second; 406 std::string stackMsg = ep->getCallStackMessage(N); 407 408 // The last message on the path to final bug is the most important 409 // one. Since we traverse the path backwards, do not add the message 410 // if one has been previously added. 411 if (!CP->hasCallStackMessage()) 412 CP->setCallStackMessage(stackMsg); 413 } 414 } 415 } 416 417 static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM); 418 419 static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD, 420 PathDiagnosticBuilder &PDB, 421 const ExplodedNode *N, 422 ArrayRef<BugReporterVisitor *> visitors) { 423 424 SourceManager& SMgr = PDB.getSourceManager(); 425 const LocationContext *LC = PDB.LC; 426 const ExplodedNode *NextNode = N->pred_empty() 427 ? NULL : *(N->pred_begin()); 428 429 StackDiagVector CallStack; 430 431 while (NextNode) { 432 N = NextNode; 433 PDB.LC = N->getLocationContext(); 434 NextNode = GetPredecessorNode(N); 435 436 ProgramPoint P = N->getLocation(); 437 438 do { 439 if (const CallExitEnd *CE = dyn_cast<CallExitEnd>(&P)) { 440 PathDiagnosticCallPiece *C = 441 PathDiagnosticCallPiece::construct(N, *CE, SMgr); 442 GRBugReporter& BR = PDB.getBugReporter(); 443 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext()); 444 PD.getActivePath().push_front(C); 445 PD.pushActivePath(&C->path); 446 CallStack.push_back(StackDiagPair(C, N)); 447 break; 448 } 449 450 if (const CallEnter *CE = dyn_cast<CallEnter>(&P)) { 451 // Flush all locations, and pop the active path. 452 bool VisitedEntireCall = PD.isWithinCall(); 453 PD.popActivePath(); 454 455 // Either we just added a bunch of stuff to the top-level path, or 456 // we have a previous CallExitEnd. If the former, it means that the 457 // path terminated within a function call. We must then take the 458 // current contents of the active path and place it within 459 // a new PathDiagnosticCallPiece. 460 PathDiagnosticCallPiece *C; 461 if (VisitedEntireCall) { 462 C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front()); 463 } else { 464 const Decl *Caller = CE->getLocationContext()->getDecl(); 465 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller); 466 GRBugReporter& BR = PDB.getBugReporter(); 467 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext()); 468 } 469 470 C->setCallee(*CE, SMgr); 471 if (!CallStack.empty()) { 472 assert(CallStack.back().first == C); 473 CallStack.pop_back(); 474 } 475 break; 476 } 477 478 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) { 479 const CFGBlock *Src = BE->getSrc(); 480 const CFGBlock *Dst = BE->getDst(); 481 const Stmt *T = Src->getTerminator(); 482 483 if (!T) 484 break; 485 486 PathDiagnosticLocation Start = 487 PathDiagnosticLocation::createBegin(T, SMgr, 488 N->getLocationContext()); 489 490 switch (T->getStmtClass()) { 491 default: 492 break; 493 494 case Stmt::GotoStmtClass: 495 case Stmt::IndirectGotoStmtClass: { 496 const Stmt *S = GetNextStmt(N); 497 498 if (!S) 499 break; 500 501 std::string sbuf; 502 llvm::raw_string_ostream os(sbuf); 503 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S); 504 505 os << "Control jumps to line " 506 << End.asLocation().getExpansionLineNumber(); 507 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 508 Start, End, os.str())); 509 break; 510 } 511 512 case Stmt::SwitchStmtClass: { 513 // Figure out what case arm we took. 514 std::string sbuf; 515 llvm::raw_string_ostream os(sbuf); 516 517 if (const Stmt *S = Dst->getLabel()) { 518 PathDiagnosticLocation End(S, SMgr, LC); 519 520 switch (S->getStmtClass()) { 521 default: 522 os << "No cases match in the switch statement. " 523 "Control jumps to line " 524 << End.asLocation().getExpansionLineNumber(); 525 break; 526 case Stmt::DefaultStmtClass: 527 os << "Control jumps to the 'default' case at line " 528 << End.asLocation().getExpansionLineNumber(); 529 break; 530 531 case Stmt::CaseStmtClass: { 532 os << "Control jumps to 'case "; 533 const CaseStmt *Case = cast<CaseStmt>(S); 534 const Expr *LHS = Case->getLHS()->IgnoreParenCasts(); 535 536 // Determine if it is an enum. 537 bool GetRawInt = true; 538 539 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) { 540 // FIXME: Maybe this should be an assertion. Are there cases 541 // were it is not an EnumConstantDecl? 542 const EnumConstantDecl *D = 543 dyn_cast<EnumConstantDecl>(DR->getDecl()); 544 545 if (D) { 546 GetRawInt = false; 547 os << *D; 548 } 549 } 550 551 if (GetRawInt) 552 os << LHS->EvaluateKnownConstInt(PDB.getASTContext()); 553 554 os << ":' at line " 555 << End.asLocation().getExpansionLineNumber(); 556 break; 557 } 558 } 559 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 560 Start, End, os.str())); 561 } 562 else { 563 os << "'Default' branch taken. "; 564 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N); 565 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 566 Start, End, os.str())); 567 } 568 569 break; 570 } 571 572 case Stmt::BreakStmtClass: 573 case Stmt::ContinueStmtClass: { 574 std::string sbuf; 575 llvm::raw_string_ostream os(sbuf); 576 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N); 577 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 578 Start, End, os.str())); 579 break; 580 } 581 582 // Determine control-flow for ternary '?'. 583 case Stmt::BinaryConditionalOperatorClass: 584 case Stmt::ConditionalOperatorClass: { 585 std::string sbuf; 586 llvm::raw_string_ostream os(sbuf); 587 os << "'?' condition is "; 588 589 if (*(Src->succ_begin()+1) == Dst) 590 os << "false"; 591 else 592 os << "true"; 593 594 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 595 596 if (const Stmt *S = End.asStmt()) 597 End = PDB.getEnclosingStmtLocation(S); 598 599 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 600 Start, End, os.str())); 601 break; 602 } 603 604 // Determine control-flow for short-circuited '&&' and '||'. 605 case Stmt::BinaryOperatorClass: { 606 if (!PDB.supportsLogicalOpControlFlow()) 607 break; 608 609 const BinaryOperator *B = cast<BinaryOperator>(T); 610 std::string sbuf; 611 llvm::raw_string_ostream os(sbuf); 612 os << "Left side of '"; 613 614 if (B->getOpcode() == BO_LAnd) { 615 os << "&&" << "' is "; 616 617 if (*(Src->succ_begin()+1) == Dst) { 618 os << "false"; 619 PathDiagnosticLocation End(B->getLHS(), SMgr, LC); 620 PathDiagnosticLocation Start = 621 PathDiagnosticLocation::createOperatorLoc(B, SMgr); 622 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 623 Start, End, os.str())); 624 } 625 else { 626 os << "true"; 627 PathDiagnosticLocation Start(B->getLHS(), SMgr, LC); 628 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 629 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 630 Start, End, os.str())); 631 } 632 } 633 else { 634 assert(B->getOpcode() == BO_LOr); 635 os << "||" << "' is "; 636 637 if (*(Src->succ_begin()+1) == Dst) { 638 os << "false"; 639 PathDiagnosticLocation Start(B->getLHS(), SMgr, LC); 640 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 641 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 642 Start, End, os.str())); 643 } 644 else { 645 os << "true"; 646 PathDiagnosticLocation End(B->getLHS(), SMgr, LC); 647 PathDiagnosticLocation Start = 648 PathDiagnosticLocation::createOperatorLoc(B, SMgr); 649 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 650 Start, End, os.str())); 651 } 652 } 653 654 break; 655 } 656 657 case Stmt::DoStmtClass: { 658 if (*(Src->succ_begin()) == Dst) { 659 std::string sbuf; 660 llvm::raw_string_ostream os(sbuf); 661 662 os << "Loop condition is true. "; 663 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N); 664 665 if (const Stmt *S = End.asStmt()) 666 End = PDB.getEnclosingStmtLocation(S); 667 668 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 669 Start, End, os.str())); 670 } 671 else { 672 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 673 674 if (const Stmt *S = End.asStmt()) 675 End = PDB.getEnclosingStmtLocation(S); 676 677 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 678 Start, End, "Loop condition is false. Exiting loop")); 679 } 680 681 break; 682 } 683 684 case Stmt::WhileStmtClass: 685 case Stmt::ForStmtClass: { 686 if (*(Src->succ_begin()+1) == Dst) { 687 std::string sbuf; 688 llvm::raw_string_ostream os(sbuf); 689 690 os << "Loop condition is false. "; 691 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N); 692 if (const Stmt *S = End.asStmt()) 693 End = PDB.getEnclosingStmtLocation(S); 694 695 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 696 Start, End, os.str())); 697 } 698 else { 699 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 700 if (const Stmt *S = End.asStmt()) 701 End = PDB.getEnclosingStmtLocation(S); 702 703 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 704 Start, End, "Loop condition is true. Entering loop body")); 705 } 706 707 break; 708 } 709 710 case Stmt::IfStmtClass: { 711 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 712 713 if (const Stmt *S = End.asStmt()) 714 End = PDB.getEnclosingStmtLocation(S); 715 716 if (*(Src->succ_begin()+1) == Dst) 717 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 718 Start, End, "Taking false branch")); 719 else 720 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 721 Start, End, "Taking true branch")); 722 723 break; 724 } 725 } 726 } 727 } while(0); 728 729 if (NextNode) { 730 // Add diagnostic pieces from custom visitors. 731 BugReport *R = PDB.getBugReport(); 732 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(), 733 E = visitors.end(); 734 I != E; ++I) { 735 if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) { 736 PD.getActivePath().push_front(p); 737 updateStackPiecesWithMessage(p, CallStack); 738 } 739 } 740 } 741 } 742 743 // After constructing the full PathDiagnostic, do a pass over it to compact 744 // PathDiagnosticPieces that occur within a macro. 745 CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager()); 746 } 747 748 //===----------------------------------------------------------------------===// 749 // "Extensive" PathDiagnostic generation. 750 //===----------------------------------------------------------------------===// 751 752 static bool IsControlFlowExpr(const Stmt *S) { 753 const Expr *E = dyn_cast<Expr>(S); 754 755 if (!E) 756 return false; 757 758 E = E->IgnoreParenCasts(); 759 760 if (isa<AbstractConditionalOperator>(E)) 761 return true; 762 763 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) 764 if (B->isLogicalOp()) 765 return true; 766 767 return false; 768 } 769 770 namespace { 771 class ContextLocation : public PathDiagnosticLocation { 772 bool IsDead; 773 public: 774 ContextLocation(const PathDiagnosticLocation &L, bool isdead = false) 775 : PathDiagnosticLocation(L), IsDead(isdead) {} 776 777 void markDead() { IsDead = true; } 778 bool isDead() const { return IsDead; } 779 }; 780 781 class EdgeBuilder { 782 std::vector<ContextLocation> CLocs; 783 typedef std::vector<ContextLocation>::iterator iterator; 784 PathDiagnostic &PD; 785 PathDiagnosticBuilder &PDB; 786 PathDiagnosticLocation PrevLoc; 787 788 bool IsConsumedExpr(const PathDiagnosticLocation &L); 789 790 bool containsLocation(const PathDiagnosticLocation &Container, 791 const PathDiagnosticLocation &Containee); 792 793 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L); 794 795 PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L, 796 bool firstCharOnly = false) { 797 if (const Stmt *S = L.asStmt()) { 798 const Stmt *Original = S; 799 while (1) { 800 // Adjust the location for some expressions that are best referenced 801 // by one of their subexpressions. 802 switch (S->getStmtClass()) { 803 default: 804 break; 805 case Stmt::ParenExprClass: 806 case Stmt::GenericSelectionExprClass: 807 S = cast<Expr>(S)->IgnoreParens(); 808 firstCharOnly = true; 809 continue; 810 case Stmt::BinaryConditionalOperatorClass: 811 case Stmt::ConditionalOperatorClass: 812 S = cast<AbstractConditionalOperator>(S)->getCond(); 813 firstCharOnly = true; 814 continue; 815 case Stmt::ChooseExprClass: 816 S = cast<ChooseExpr>(S)->getCond(); 817 firstCharOnly = true; 818 continue; 819 case Stmt::BinaryOperatorClass: 820 S = cast<BinaryOperator>(S)->getLHS(); 821 firstCharOnly = true; 822 continue; 823 } 824 825 break; 826 } 827 828 if (S != Original) 829 L = PathDiagnosticLocation(S, L.getManager(), PDB.LC); 830 } 831 832 if (firstCharOnly) 833 L = PathDiagnosticLocation::createSingleLocation(L); 834 835 return L; 836 } 837 838 void popLocation() { 839 if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) { 840 // For contexts, we only one the first character as the range. 841 rawAddEdge(cleanUpLocation(CLocs.back(), true)); 842 } 843 CLocs.pop_back(); 844 } 845 846 public: 847 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb) 848 : PD(pd), PDB(pdb) { 849 850 // If the PathDiagnostic already has pieces, add the enclosing statement 851 // of the first piece as a context as well. 852 if (!PD.path.empty()) { 853 PrevLoc = (*PD.path.begin())->getLocation(); 854 855 if (const Stmt *S = PrevLoc.asStmt()) 856 addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt()); 857 } 858 } 859 860 ~EdgeBuilder() { 861 while (!CLocs.empty()) popLocation(); 862 863 // Finally, add an initial edge from the start location of the first 864 // statement (if it doesn't already exist). 865 PathDiagnosticLocation L = PathDiagnosticLocation::createDeclBegin( 866 PDB.LC, 867 PDB.getSourceManager()); 868 if (L.isValid()) 869 rawAddEdge(L); 870 } 871 872 void flushLocations() { 873 while (!CLocs.empty()) 874 popLocation(); 875 PrevLoc = PathDiagnosticLocation(); 876 } 877 878 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false); 879 880 void rawAddEdge(PathDiagnosticLocation NewLoc); 881 882 void addContext(const Stmt *S); 883 void addContext(const PathDiagnosticLocation &L); 884 void addExtendedContext(const Stmt *S); 885 }; 886 } // end anonymous namespace 887 888 889 PathDiagnosticLocation 890 EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) { 891 if (const Stmt *S = L.asStmt()) { 892 if (IsControlFlowExpr(S)) 893 return L; 894 895 return PDB.getEnclosingStmtLocation(S); 896 } 897 898 return L; 899 } 900 901 bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container, 902 const PathDiagnosticLocation &Containee) { 903 904 if (Container == Containee) 905 return true; 906 907 if (Container.asDecl()) 908 return true; 909 910 if (const Stmt *S = Containee.asStmt()) 911 if (const Stmt *ContainerS = Container.asStmt()) { 912 while (S) { 913 if (S == ContainerS) 914 return true; 915 S = PDB.getParent(S); 916 } 917 return false; 918 } 919 920 // Less accurate: compare using source ranges. 921 SourceRange ContainerR = Container.asRange(); 922 SourceRange ContaineeR = Containee.asRange(); 923 924 SourceManager &SM = PDB.getSourceManager(); 925 SourceLocation ContainerRBeg = SM.getExpansionLoc(ContainerR.getBegin()); 926 SourceLocation ContainerREnd = SM.getExpansionLoc(ContainerR.getEnd()); 927 SourceLocation ContaineeRBeg = SM.getExpansionLoc(ContaineeR.getBegin()); 928 SourceLocation ContaineeREnd = SM.getExpansionLoc(ContaineeR.getEnd()); 929 930 unsigned ContainerBegLine = SM.getExpansionLineNumber(ContainerRBeg); 931 unsigned ContainerEndLine = SM.getExpansionLineNumber(ContainerREnd); 932 unsigned ContaineeBegLine = SM.getExpansionLineNumber(ContaineeRBeg); 933 unsigned ContaineeEndLine = SM.getExpansionLineNumber(ContaineeREnd); 934 935 assert(ContainerBegLine <= ContainerEndLine); 936 assert(ContaineeBegLine <= ContaineeEndLine); 937 938 return (ContainerBegLine <= ContaineeBegLine && 939 ContainerEndLine >= ContaineeEndLine && 940 (ContainerBegLine != ContaineeBegLine || 941 SM.getExpansionColumnNumber(ContainerRBeg) <= 942 SM.getExpansionColumnNumber(ContaineeRBeg)) && 943 (ContainerEndLine != ContaineeEndLine || 944 SM.getExpansionColumnNumber(ContainerREnd) >= 945 SM.getExpansionColumnNumber(ContaineeREnd))); 946 } 947 948 void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) { 949 if (!PrevLoc.isValid()) { 950 PrevLoc = NewLoc; 951 return; 952 } 953 954 const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc); 955 const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc); 956 957 if (NewLocClean.asLocation() == PrevLocClean.asLocation()) 958 return; 959 960 // FIXME: Ignore intra-macro edges for now. 961 if (NewLocClean.asLocation().getExpansionLoc() == 962 PrevLocClean.asLocation().getExpansionLoc()) 963 return; 964 965 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean)); 966 PrevLoc = NewLoc; 967 } 968 969 void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) { 970 971 if (!alwaysAdd && NewLoc.asLocation().isMacroID()) 972 return; 973 974 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc); 975 976 while (!CLocs.empty()) { 977 ContextLocation &TopContextLoc = CLocs.back(); 978 979 // Is the top location context the same as the one for the new location? 980 if (TopContextLoc == CLoc) { 981 if (alwaysAdd) { 982 if (IsConsumedExpr(TopContextLoc) && 983 !IsControlFlowExpr(TopContextLoc.asStmt())) 984 TopContextLoc.markDead(); 985 986 rawAddEdge(NewLoc); 987 } 988 989 return; 990 } 991 992 if (containsLocation(TopContextLoc, CLoc)) { 993 if (alwaysAdd) { 994 rawAddEdge(NewLoc); 995 996 if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) { 997 CLocs.push_back(ContextLocation(CLoc, true)); 998 return; 999 } 1000 } 1001 1002 CLocs.push_back(CLoc); 1003 return; 1004 } 1005 1006 // Context does not contain the location. Flush it. 1007 popLocation(); 1008 } 1009 1010 // If we reach here, there is no enclosing context. Just add the edge. 1011 rawAddEdge(NewLoc); 1012 } 1013 1014 bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) { 1015 if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt())) 1016 return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X); 1017 1018 return false; 1019 } 1020 1021 void EdgeBuilder::addExtendedContext(const Stmt *S) { 1022 if (!S) 1023 return; 1024 1025 const Stmt *Parent = PDB.getParent(S); 1026 while (Parent) { 1027 if (isa<CompoundStmt>(Parent)) 1028 Parent = PDB.getParent(Parent); 1029 else 1030 break; 1031 } 1032 1033 if (Parent) { 1034 switch (Parent->getStmtClass()) { 1035 case Stmt::DoStmtClass: 1036 case Stmt::ObjCAtSynchronizedStmtClass: 1037 addContext(Parent); 1038 default: 1039 break; 1040 } 1041 } 1042 1043 addContext(S); 1044 } 1045 1046 void EdgeBuilder::addContext(const Stmt *S) { 1047 if (!S) 1048 return; 1049 1050 PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.LC); 1051 addContext(L); 1052 } 1053 1054 void EdgeBuilder::addContext(const PathDiagnosticLocation &L) { 1055 while (!CLocs.empty()) { 1056 const PathDiagnosticLocation &TopContextLoc = CLocs.back(); 1057 1058 // Is the top location context the same as the one for the new location? 1059 if (TopContextLoc == L) 1060 return; 1061 1062 if (containsLocation(TopContextLoc, L)) { 1063 CLocs.push_back(L); 1064 return; 1065 } 1066 1067 // Context does not contain the location. Flush it. 1068 popLocation(); 1069 } 1070 1071 CLocs.push_back(L); 1072 } 1073 1074 // Cone-of-influence: support the reverse propagation of "interesting" symbols 1075 // and values by tracing interesting calculations backwards through evaluated 1076 // expressions along a path. This is probably overly complicated, but the idea 1077 // is that if an expression computed an "interesting" value, the child 1078 // expressions are are also likely to be "interesting" as well (which then 1079 // propagates to the values they in turn compute). This reverse propagation 1080 // is needed to track interesting correlations across function call boundaries, 1081 // where formal arguments bind to actual arguments, etc. This is also needed 1082 // because the constraint solver sometimes simplifies certain symbolic values 1083 // into constants when appropriate, and this complicates reasoning about 1084 // interesting values. 1085 typedef llvm::DenseSet<const Expr *> InterestingExprs; 1086 1087 static void reversePropagateIntererstingSymbols(BugReport &R, 1088 InterestingExprs &IE, 1089 const ProgramState *State, 1090 const Expr *Ex, 1091 const LocationContext *LCtx) { 1092 SVal V = State->getSVal(Ex, LCtx); 1093 if (!(R.isInteresting(V) || IE.count(Ex))) 1094 return; 1095 1096 switch (Ex->getStmtClass()) { 1097 default: 1098 if (!isa<CastExpr>(Ex)) 1099 break; 1100 // Fall through. 1101 case Stmt::BinaryOperatorClass: 1102 case Stmt::UnaryOperatorClass: { 1103 for (Stmt::const_child_iterator CI = Ex->child_begin(), 1104 CE = Ex->child_end(); 1105 CI != CE; ++CI) { 1106 if (const Expr *child = dyn_cast_or_null<Expr>(*CI)) { 1107 IE.insert(child); 1108 SVal ChildV = State->getSVal(child, LCtx); 1109 R.markInteresting(ChildV); 1110 } 1111 break; 1112 } 1113 } 1114 } 1115 1116 R.markInteresting(V); 1117 } 1118 1119 static void reversePropagateInterestingSymbols(BugReport &R, 1120 InterestingExprs &IE, 1121 const ProgramState *State, 1122 const LocationContext *CalleeCtx, 1123 const LocationContext *CallerCtx) 1124 { 1125 // FIXME: Handle non-CallExpr-based CallEvents. 1126 const StackFrameContext *Callee = CalleeCtx->getCurrentStackFrame(); 1127 const Stmt *CallSite = Callee->getCallSite(); 1128 if (const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite)) { 1129 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeCtx->getDecl())) { 1130 FunctionDecl::param_const_iterator PI = FD->param_begin(), 1131 PE = FD->param_end(); 1132 CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end(); 1133 for (; AI != AE && PI != PE; ++AI, ++PI) { 1134 if (const Expr *ArgE = *AI) { 1135 if (const ParmVarDecl *PD = *PI) { 1136 Loc LV = State->getLValue(PD, CalleeCtx); 1137 if (R.isInteresting(LV) || R.isInteresting(State->getRawSVal(LV))) 1138 IE.insert(ArgE); 1139 } 1140 } 1141 } 1142 } 1143 } 1144 } 1145 1146 static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD, 1147 PathDiagnosticBuilder &PDB, 1148 const ExplodedNode *N, 1149 ArrayRef<BugReporterVisitor *> visitors) { 1150 EdgeBuilder EB(PD, PDB); 1151 const SourceManager& SM = PDB.getSourceManager(); 1152 StackDiagVector CallStack; 1153 InterestingExprs IE; 1154 1155 const ExplodedNode *NextNode = N->pred_empty() ? NULL : *(N->pred_begin()); 1156 while (NextNode) { 1157 N = NextNode; 1158 NextNode = GetPredecessorNode(N); 1159 ProgramPoint P = N->getLocation(); 1160 1161 do { 1162 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) { 1163 if (const Expr *Ex = PS->getStmtAs<Expr>()) 1164 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE, 1165 N->getState().getPtr(), Ex, 1166 N->getLocationContext()); 1167 } 1168 1169 if (const CallExitEnd *CE = dyn_cast<CallExitEnd>(&P)) { 1170 const Stmt *S = CE->getCalleeContext()->getCallSite(); 1171 if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) { 1172 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE, 1173 N->getState().getPtr(), Ex, 1174 N->getLocationContext()); 1175 } 1176 1177 PathDiagnosticCallPiece *C = 1178 PathDiagnosticCallPiece::construct(N, *CE, SM); 1179 GRBugReporter& BR = PDB.getBugReporter(); 1180 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext()); 1181 1182 EB.addEdge(C->callReturn, true); 1183 EB.flushLocations(); 1184 1185 PD.getActivePath().push_front(C); 1186 PD.pushActivePath(&C->path); 1187 CallStack.push_back(StackDiagPair(C, N)); 1188 break; 1189 } 1190 1191 // Pop the call hierarchy if we are done walking the contents 1192 // of a function call. 1193 if (const CallEnter *CE = dyn_cast<CallEnter>(&P)) { 1194 // Add an edge to the start of the function. 1195 const Decl *D = CE->getCalleeContext()->getDecl(); 1196 PathDiagnosticLocation pos = 1197 PathDiagnosticLocation::createBegin(D, SM); 1198 EB.addEdge(pos); 1199 1200 // Flush all locations, and pop the active path. 1201 bool VisitedEntireCall = PD.isWithinCall(); 1202 EB.flushLocations(); 1203 PD.popActivePath(); 1204 PDB.LC = N->getLocationContext(); 1205 1206 // Either we just added a bunch of stuff to the top-level path, or 1207 // we have a previous CallExitEnd. If the former, it means that the 1208 // path terminated within a function call. We must then take the 1209 // current contents of the active path and place it within 1210 // a new PathDiagnosticCallPiece. 1211 PathDiagnosticCallPiece *C; 1212 if (VisitedEntireCall) { 1213 C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front()); 1214 } else { 1215 const Decl *Caller = CE->getLocationContext()->getDecl(); 1216 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller); 1217 GRBugReporter& BR = PDB.getBugReporter(); 1218 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext()); 1219 } 1220 1221 C->setCallee(*CE, SM); 1222 EB.addContext(C->getLocation()); 1223 1224 if (!CallStack.empty()) { 1225 assert(CallStack.back().first == C); 1226 CallStack.pop_back(); 1227 } 1228 break; 1229 } 1230 1231 // Note that is important that we update the LocationContext 1232 // after looking at CallExits. CallExit basically adds an 1233 // edge in the *caller*, so we don't want to update the LocationContext 1234 // too soon. 1235 PDB.LC = N->getLocationContext(); 1236 1237 // Block edges. 1238 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) { 1239 // Does this represent entering a call? If so, look at propagating 1240 // interesting symbols across call boundaries. 1241 if (NextNode) { 1242 const LocationContext *CallerCtx = NextNode->getLocationContext(); 1243 const LocationContext *CalleeCtx = PDB.LC; 1244 if (CallerCtx != CalleeCtx) { 1245 reversePropagateInterestingSymbols(*PDB.getBugReport(), IE, 1246 N->getState().getPtr(), 1247 CalleeCtx, CallerCtx); 1248 } 1249 } 1250 1251 // Are we jumping to the head of a loop? Add a special diagnostic. 1252 if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) { 1253 PathDiagnosticLocation L(Loop, SM, PDB.LC); 1254 const CompoundStmt *CS = NULL; 1255 1256 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop)) 1257 CS = dyn_cast<CompoundStmt>(FS->getBody()); 1258 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop)) 1259 CS = dyn_cast<CompoundStmt>(WS->getBody()); 1260 1261 PathDiagnosticEventPiece *p = 1262 new PathDiagnosticEventPiece(L, 1263 "Looping back to the head of the loop"); 1264 p->setPrunable(true); 1265 1266 EB.addEdge(p->getLocation(), true); 1267 PD.getActivePath().push_front(p); 1268 1269 if (CS) { 1270 PathDiagnosticLocation BL = 1271 PathDiagnosticLocation::createEndBrace(CS, SM); 1272 EB.addEdge(BL); 1273 } 1274 } 1275 1276 if (const Stmt *Term = BE->getSrc()->getTerminator()) 1277 EB.addContext(Term); 1278 1279 break; 1280 } 1281 1282 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) { 1283 CFGElement First = BE->getFirstElement(); 1284 if (const CFGStmt *S = First.getAs<CFGStmt>()) { 1285 const Stmt *stmt = S->getStmt(); 1286 if (IsControlFlowExpr(stmt)) { 1287 // Add the proper context for '&&', '||', and '?'. 1288 EB.addContext(stmt); 1289 } 1290 else 1291 EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt()); 1292 } 1293 1294 break; 1295 } 1296 1297 1298 } while (0); 1299 1300 if (!NextNode) 1301 continue; 1302 1303 // Add pieces from custom visitors. 1304 BugReport *R = PDB.getBugReport(); 1305 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(), 1306 E = visitors.end(); 1307 I != E; ++I) { 1308 if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) { 1309 const PathDiagnosticLocation &Loc = p->getLocation(); 1310 EB.addEdge(Loc, true); 1311 PD.getActivePath().push_front(p); 1312 updateStackPiecesWithMessage(p, CallStack); 1313 1314 if (const Stmt *S = Loc.asStmt()) 1315 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt()); 1316 } 1317 } 1318 } 1319 } 1320 1321 //===----------------------------------------------------------------------===// 1322 // Methods for BugType and subclasses. 1323 //===----------------------------------------------------------------------===// 1324 BugType::~BugType() { } 1325 1326 void BugType::FlushReports(BugReporter &BR) {} 1327 1328 void BuiltinBug::anchor() {} 1329 1330 //===----------------------------------------------------------------------===// 1331 // Methods for BugReport and subclasses. 1332 //===----------------------------------------------------------------------===// 1333 1334 void BugReport::NodeResolver::anchor() {} 1335 1336 void BugReport::addVisitor(BugReporterVisitor* visitor) { 1337 if (!visitor) 1338 return; 1339 1340 llvm::FoldingSetNodeID ID; 1341 visitor->Profile(ID); 1342 void *InsertPos; 1343 1344 if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) { 1345 delete visitor; 1346 return; 1347 } 1348 1349 CallbacksSet.InsertNode(visitor, InsertPos); 1350 Callbacks.push_back(visitor); 1351 ++ConfigurationChangeToken; 1352 } 1353 1354 BugReport::~BugReport() { 1355 for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I) { 1356 delete *I; 1357 } 1358 while (!interestingSymbols.empty()) { 1359 popInterestingSymbolsAndRegions(); 1360 } 1361 } 1362 1363 const Decl *BugReport::getDeclWithIssue() const { 1364 if (DeclWithIssue) 1365 return DeclWithIssue; 1366 1367 const ExplodedNode *N = getErrorNode(); 1368 if (!N) 1369 return 0; 1370 1371 const LocationContext *LC = N->getLocationContext(); 1372 return LC->getCurrentStackFrame()->getDecl(); 1373 } 1374 1375 void BugReport::Profile(llvm::FoldingSetNodeID& hash) const { 1376 hash.AddPointer(&BT); 1377 hash.AddString(Description); 1378 if (UniqueingLocation.isValid()) { 1379 UniqueingLocation.Profile(hash); 1380 } else if (Location.isValid()) { 1381 Location.Profile(hash); 1382 } else { 1383 assert(ErrorNode); 1384 hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode)); 1385 } 1386 1387 for (SmallVectorImpl<SourceRange>::const_iterator I = 1388 Ranges.begin(), E = Ranges.end(); I != E; ++I) { 1389 const SourceRange range = *I; 1390 if (!range.isValid()) 1391 continue; 1392 hash.AddInteger(range.getBegin().getRawEncoding()); 1393 hash.AddInteger(range.getEnd().getRawEncoding()); 1394 } 1395 } 1396 1397 void BugReport::markInteresting(SymbolRef sym) { 1398 if (!sym) 1399 return; 1400 1401 // If the symbol wasn't already in our set, note a configuration change. 1402 if (getInterestingSymbols().insert(sym).second) 1403 ++ConfigurationChangeToken; 1404 1405 if (const SymbolMetadata *meta = dyn_cast<SymbolMetadata>(sym)) 1406 getInterestingRegions().insert(meta->getRegion()); 1407 } 1408 1409 void BugReport::markInteresting(const MemRegion *R) { 1410 if (!R) 1411 return; 1412 1413 // If the base region wasn't already in our set, note a configuration change. 1414 R = R->getBaseRegion(); 1415 if (getInterestingRegions().insert(R).second) 1416 ++ConfigurationChangeToken; 1417 1418 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) 1419 getInterestingSymbols().insert(SR->getSymbol()); 1420 } 1421 1422 void BugReport::markInteresting(SVal V) { 1423 markInteresting(V.getAsRegion()); 1424 markInteresting(V.getAsSymbol()); 1425 } 1426 1427 void BugReport::markInteresting(const LocationContext *LC) { 1428 if (!LC) 1429 return; 1430 InterestingLocationContexts.insert(LC); 1431 } 1432 1433 bool BugReport::isInteresting(SVal V) { 1434 return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol()); 1435 } 1436 1437 bool BugReport::isInteresting(SymbolRef sym) { 1438 if (!sym) 1439 return false; 1440 // We don't currently consider metadata symbols to be interesting 1441 // even if we know their region is interesting. Is that correct behavior? 1442 return getInterestingSymbols().count(sym); 1443 } 1444 1445 bool BugReport::isInteresting(const MemRegion *R) { 1446 if (!R) 1447 return false; 1448 R = R->getBaseRegion(); 1449 bool b = getInterestingRegions().count(R); 1450 if (b) 1451 return true; 1452 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) 1453 return getInterestingSymbols().count(SR->getSymbol()); 1454 return false; 1455 } 1456 1457 bool BugReport::isInteresting(const LocationContext *LC) { 1458 if (!LC) 1459 return false; 1460 return InterestingLocationContexts.count(LC); 1461 } 1462 1463 void BugReport::lazyInitializeInterestingSets() { 1464 if (interestingSymbols.empty()) { 1465 interestingSymbols.push_back(new Symbols()); 1466 interestingRegions.push_back(new Regions()); 1467 } 1468 } 1469 1470 BugReport::Symbols &BugReport::getInterestingSymbols() { 1471 lazyInitializeInterestingSets(); 1472 return *interestingSymbols.back(); 1473 } 1474 1475 BugReport::Regions &BugReport::getInterestingRegions() { 1476 lazyInitializeInterestingSets(); 1477 return *interestingRegions.back(); 1478 } 1479 1480 void BugReport::pushInterestingSymbolsAndRegions() { 1481 interestingSymbols.push_back(new Symbols(getInterestingSymbols())); 1482 interestingRegions.push_back(new Regions(getInterestingRegions())); 1483 } 1484 1485 void BugReport::popInterestingSymbolsAndRegions() { 1486 delete interestingSymbols.back(); 1487 interestingSymbols.pop_back(); 1488 delete interestingRegions.back(); 1489 interestingRegions.pop_back(); 1490 } 1491 1492 const Stmt *BugReport::getStmt() const { 1493 if (!ErrorNode) 1494 return 0; 1495 1496 ProgramPoint ProgP = ErrorNode->getLocation(); 1497 const Stmt *S = NULL; 1498 1499 if (BlockEntrance *BE = dyn_cast<BlockEntrance>(&ProgP)) { 1500 CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit(); 1501 if (BE->getBlock() == &Exit) 1502 S = GetPreviousStmt(ErrorNode); 1503 } 1504 if (!S) 1505 S = GetStmt(ProgP); 1506 1507 return S; 1508 } 1509 1510 std::pair<BugReport::ranges_iterator, BugReport::ranges_iterator> 1511 BugReport::getRanges() { 1512 // If no custom ranges, add the range of the statement corresponding to 1513 // the error node. 1514 if (Ranges.empty()) { 1515 if (const Expr *E = dyn_cast_or_null<Expr>(getStmt())) 1516 addRange(E->getSourceRange()); 1517 else 1518 return std::make_pair(ranges_iterator(), ranges_iterator()); 1519 } 1520 1521 // User-specified absence of range info. 1522 if (Ranges.size() == 1 && !Ranges.begin()->isValid()) 1523 return std::make_pair(ranges_iterator(), ranges_iterator()); 1524 1525 return std::make_pair(Ranges.begin(), Ranges.end()); 1526 } 1527 1528 PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const { 1529 if (ErrorNode) { 1530 assert(!Location.isValid() && 1531 "Either Location or ErrorNode should be specified but not both."); 1532 1533 if (const Stmt *S = GetCurrentOrPreviousStmt(ErrorNode)) { 1534 const LocationContext *LC = ErrorNode->getLocationContext(); 1535 1536 // For member expressions, return the location of the '.' or '->'. 1537 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) 1538 return PathDiagnosticLocation::createMemberLoc(ME, SM); 1539 // For binary operators, return the location of the operator. 1540 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(S)) 1541 return PathDiagnosticLocation::createOperatorLoc(B, SM); 1542 1543 return PathDiagnosticLocation::createBegin(S, SM, LC); 1544 } 1545 } else { 1546 assert(Location.isValid()); 1547 return Location; 1548 } 1549 1550 return PathDiagnosticLocation(); 1551 } 1552 1553 //===----------------------------------------------------------------------===// 1554 // Methods for BugReporter and subclasses. 1555 //===----------------------------------------------------------------------===// 1556 1557 BugReportEquivClass::~BugReportEquivClass() { } 1558 GRBugReporter::~GRBugReporter() { } 1559 BugReporterData::~BugReporterData() {} 1560 1561 ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); } 1562 1563 ProgramStateManager& 1564 GRBugReporter::getStateManager() { return Eng.getStateManager(); } 1565 1566 BugReporter::~BugReporter() { 1567 FlushReports(); 1568 1569 // Free the bug reports we are tracking. 1570 typedef std::vector<BugReportEquivClass *> ContTy; 1571 for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end(); 1572 I != E; ++I) { 1573 delete *I; 1574 } 1575 } 1576 1577 void BugReporter::FlushReports() { 1578 if (BugTypes.isEmpty()) 1579 return; 1580 1581 // First flush the warnings for each BugType. This may end up creating new 1582 // warnings and new BugTypes. 1583 // FIXME: Only NSErrorChecker needs BugType's FlushReports. 1584 // Turn NSErrorChecker into a proper checker and remove this. 1585 SmallVector<const BugType*, 16> bugTypes; 1586 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) 1587 bugTypes.push_back(*I); 1588 for (SmallVector<const BugType*, 16>::iterator 1589 I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I) 1590 const_cast<BugType*>(*I)->FlushReports(*this); 1591 1592 // We need to flush reports in deterministic order to ensure the order 1593 // of the reports is consistent between runs. 1594 typedef std::vector<BugReportEquivClass *> ContVecTy; 1595 for (ContVecTy::iterator EI=EQClassesVector.begin(), EE=EQClassesVector.end(); 1596 EI != EE; ++EI){ 1597 BugReportEquivClass& EQ = **EI; 1598 FlushReport(EQ); 1599 } 1600 1601 // BugReporter owns and deletes only BugTypes created implicitly through 1602 // EmitBasicReport. 1603 // FIXME: There are leaks from checkers that assume that the BugTypes they 1604 // create will be destroyed by the BugReporter. 1605 for (llvm::StringMap<BugType*>::iterator 1606 I = StrBugTypes.begin(), E = StrBugTypes.end(); I != E; ++I) 1607 delete I->second; 1608 1609 // Remove all references to the BugType objects. 1610 BugTypes = F.getEmptySet(); 1611 } 1612 1613 //===----------------------------------------------------------------------===// 1614 // PathDiagnostics generation. 1615 //===----------------------------------------------------------------------===// 1616 1617 static std::pair<std::pair<ExplodedGraph*, NodeBackMap*>, 1618 std::pair<ExplodedNode*, unsigned> > 1619 MakeReportGraph(const ExplodedGraph* G, 1620 SmallVectorImpl<const ExplodedNode*> &nodes) { 1621 1622 // Create the trimmed graph. It will contain the shortest paths from the 1623 // error nodes to the root. In the new graph we should only have one 1624 // error node unless there are two or more error nodes with the same minimum 1625 // path length. 1626 ExplodedGraph* GTrim; 1627 InterExplodedGraphMap* NMap; 1628 1629 llvm::DenseMap<const void*, const void*> InverseMap; 1630 llvm::tie(GTrim, NMap) = G->Trim(nodes.data(), nodes.data() + nodes.size(), 1631 &InverseMap); 1632 1633 // Create owning pointers for GTrim and NMap just to ensure that they are 1634 // released when this function exists. 1635 OwningPtr<ExplodedGraph> AutoReleaseGTrim(GTrim); 1636 OwningPtr<InterExplodedGraphMap> AutoReleaseNMap(NMap); 1637 1638 // Find the (first) error node in the trimmed graph. We just need to consult 1639 // the node map (NMap) which maps from nodes in the original graph to nodes 1640 // in the new graph. 1641 1642 std::queue<const ExplodedNode*> WS; 1643 typedef llvm::DenseMap<const ExplodedNode*, unsigned> IndexMapTy; 1644 IndexMapTy IndexMap; 1645 1646 for (unsigned nodeIndex = 0 ; nodeIndex < nodes.size(); ++nodeIndex) { 1647 const ExplodedNode *originalNode = nodes[nodeIndex]; 1648 if (const ExplodedNode *N = NMap->getMappedNode(originalNode)) { 1649 WS.push(N); 1650 IndexMap[originalNode] = nodeIndex; 1651 } 1652 } 1653 1654 assert(!WS.empty() && "No error node found in the trimmed graph."); 1655 1656 // Create a new (third!) graph with a single path. This is the graph 1657 // that will be returned to the caller. 1658 ExplodedGraph *GNew = new ExplodedGraph(); 1659 1660 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS 1661 // to the root node, and then construct a new graph that contains only 1662 // a single path. 1663 llvm::DenseMap<const void*,unsigned> Visited; 1664 1665 unsigned cnt = 0; 1666 const ExplodedNode *Root = 0; 1667 1668 while (!WS.empty()) { 1669 const ExplodedNode *Node = WS.front(); 1670 WS.pop(); 1671 1672 if (Visited.find(Node) != Visited.end()) 1673 continue; 1674 1675 Visited[Node] = cnt++; 1676 1677 if (Node->pred_empty()) { 1678 Root = Node; 1679 break; 1680 } 1681 1682 for (ExplodedNode::const_pred_iterator I=Node->pred_begin(), 1683 E=Node->pred_end(); I!=E; ++I) 1684 WS.push(*I); 1685 } 1686 1687 assert(Root); 1688 1689 // Now walk from the root down the BFS path, always taking the successor 1690 // with the lowest number. 1691 ExplodedNode *Last = 0, *First = 0; 1692 NodeBackMap *BM = new NodeBackMap(); 1693 unsigned NodeIndex = 0; 1694 1695 for ( const ExplodedNode *N = Root ;;) { 1696 // Lookup the number associated with the current node. 1697 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N); 1698 assert(I != Visited.end()); 1699 1700 // Create the equivalent node in the new graph with the same state 1701 // and location. 1702 ExplodedNode *NewN = GNew->getNode(N->getLocation(), N->getState()); 1703 1704 // Store the mapping to the original node. 1705 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N); 1706 assert(IMitr != InverseMap.end() && "No mapping to original node."); 1707 (*BM)[NewN] = (const ExplodedNode*) IMitr->second; 1708 1709 // Link up the new node with the previous node. 1710 if (Last) 1711 NewN->addPredecessor(Last, *GNew); 1712 1713 Last = NewN; 1714 1715 // Are we at the final node? 1716 IndexMapTy::iterator IMI = 1717 IndexMap.find((const ExplodedNode*)(IMitr->second)); 1718 if (IMI != IndexMap.end()) { 1719 First = NewN; 1720 NodeIndex = IMI->second; 1721 break; 1722 } 1723 1724 // Find the next successor node. We choose the node that is marked 1725 // with the lowest DFS number. 1726 ExplodedNode::const_succ_iterator SI = N->succ_begin(); 1727 ExplodedNode::const_succ_iterator SE = N->succ_end(); 1728 N = 0; 1729 1730 for (unsigned MinVal = 0; SI != SE; ++SI) { 1731 1732 I = Visited.find(*SI); 1733 1734 if (I == Visited.end()) 1735 continue; 1736 1737 if (!N || I->second < MinVal) { 1738 N = *SI; 1739 MinVal = I->second; 1740 } 1741 } 1742 1743 assert(N); 1744 } 1745 1746 assert(First); 1747 1748 return std::make_pair(std::make_pair(GNew, BM), 1749 std::make_pair(First, NodeIndex)); 1750 } 1751 1752 /// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object 1753 /// and collapses PathDiagosticPieces that are expanded by macros. 1754 static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM) { 1755 typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiece>, 1756 SourceLocation> > MacroStackTy; 1757 1758 typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> > 1759 PiecesTy; 1760 1761 MacroStackTy MacroStack; 1762 PiecesTy Pieces; 1763 1764 for (PathPieces::const_iterator I = path.begin(), E = path.end(); 1765 I!=E; ++I) { 1766 1767 PathDiagnosticPiece *piece = I->getPtr(); 1768 1769 // Recursively compact calls. 1770 if (PathDiagnosticCallPiece *call=dyn_cast<PathDiagnosticCallPiece>(piece)){ 1771 CompactPathDiagnostic(call->path, SM); 1772 } 1773 1774 // Get the location of the PathDiagnosticPiece. 1775 const FullSourceLoc Loc = piece->getLocation().asLocation(); 1776 1777 // Determine the instantiation location, which is the location we group 1778 // related PathDiagnosticPieces. 1779 SourceLocation InstantiationLoc = Loc.isMacroID() ? 1780 SM.getExpansionLoc(Loc) : 1781 SourceLocation(); 1782 1783 if (Loc.isFileID()) { 1784 MacroStack.clear(); 1785 Pieces.push_back(piece); 1786 continue; 1787 } 1788 1789 assert(Loc.isMacroID()); 1790 1791 // Is the PathDiagnosticPiece within the same macro group? 1792 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) { 1793 MacroStack.back().first->subPieces.push_back(piece); 1794 continue; 1795 } 1796 1797 // We aren't in the same group. Are we descending into a new macro 1798 // or are part of an old one? 1799 IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup; 1800 1801 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ? 1802 SM.getExpansionLoc(Loc) : 1803 SourceLocation(); 1804 1805 // Walk the entire macro stack. 1806 while (!MacroStack.empty()) { 1807 if (InstantiationLoc == MacroStack.back().second) { 1808 MacroGroup = MacroStack.back().first; 1809 break; 1810 } 1811 1812 if (ParentInstantiationLoc == MacroStack.back().second) { 1813 MacroGroup = MacroStack.back().first; 1814 break; 1815 } 1816 1817 MacroStack.pop_back(); 1818 } 1819 1820 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) { 1821 // Create a new macro group and add it to the stack. 1822 PathDiagnosticMacroPiece *NewGroup = 1823 new PathDiagnosticMacroPiece( 1824 PathDiagnosticLocation::createSingleLocation(piece->getLocation())); 1825 1826 if (MacroGroup) 1827 MacroGroup->subPieces.push_back(NewGroup); 1828 else { 1829 assert(InstantiationLoc.isFileID()); 1830 Pieces.push_back(NewGroup); 1831 } 1832 1833 MacroGroup = NewGroup; 1834 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc)); 1835 } 1836 1837 // Finally, add the PathDiagnosticPiece to the group. 1838 MacroGroup->subPieces.push_back(piece); 1839 } 1840 1841 // Now take the pieces and construct a new PathDiagnostic. 1842 path.clear(); 1843 1844 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) 1845 path.push_back(*I); 1846 } 1847 1848 void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD, 1849 PathDiagnosticConsumer &PC, 1850 ArrayRef<BugReport *> &bugReports) { 1851 1852 assert(!bugReports.empty()); 1853 SmallVector<const ExplodedNode *, 10> errorNodes; 1854 for (ArrayRef<BugReport*>::iterator I = bugReports.begin(), 1855 E = bugReports.end(); I != E; ++I) { 1856 errorNodes.push_back((*I)->getErrorNode()); 1857 } 1858 1859 // Construct a new graph that contains only a single path from the error 1860 // node to a root. 1861 const std::pair<std::pair<ExplodedGraph*, NodeBackMap*>, 1862 std::pair<ExplodedNode*, unsigned> >& 1863 GPair = MakeReportGraph(&getGraph(), errorNodes); 1864 1865 // Find the BugReport with the original location. 1866 assert(GPair.second.second < bugReports.size()); 1867 BugReport *R = bugReports[GPair.second.second]; 1868 assert(R && "No original report found for sliced graph."); 1869 1870 OwningPtr<ExplodedGraph> ReportGraph(GPair.first.first); 1871 OwningPtr<NodeBackMap> BackMap(GPair.first.second); 1872 const ExplodedNode *N = GPair.second.first; 1873 1874 // Start building the path diagnostic... 1875 PathDiagnosticBuilder PDB(*this, R, BackMap.get(), &PC); 1876 1877 // Register additional node visitors. 1878 R->addVisitor(new NilReceiverBRVisitor()); 1879 R->addVisitor(new ConditionBRVisitor()); 1880 1881 BugReport::VisitorList visitors; 1882 unsigned originalReportConfigToken, finalReportConfigToken; 1883 1884 // While generating diagnostics, it's possible the visitors will decide 1885 // new symbols and regions are interesting, or add other visitors based on 1886 // the information they find. If they do, we need to regenerate the path 1887 // based on our new report configuration. 1888 do { 1889 // Get a clean copy of all the visitors. 1890 for (BugReport::visitor_iterator I = R->visitor_begin(), 1891 E = R->visitor_end(); I != E; ++I) 1892 visitors.push_back((*I)->clone()); 1893 1894 // Clear out the active path from any previous work. 1895 PD.resetPath(); 1896 originalReportConfigToken = R->getConfigurationChangeToken(); 1897 1898 // Generate the very last diagnostic piece - the piece is visible before 1899 // the trace is expanded. 1900 PathDiagnosticPiece *LastPiece = 0; 1901 for (BugReport::visitor_iterator I = visitors.begin(), E = visitors.end(); 1902 I != E; ++I) { 1903 if (PathDiagnosticPiece *Piece = (*I)->getEndPath(PDB, N, *R)) { 1904 assert (!LastPiece && 1905 "There can only be one final piece in a diagnostic."); 1906 LastPiece = Piece; 1907 } 1908 } 1909 if (!LastPiece) 1910 LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R); 1911 if (LastPiece) 1912 PD.setEndOfPath(LastPiece); 1913 else 1914 return; 1915 1916 switch (PDB.getGenerationScheme()) { 1917 case PathDiagnosticConsumer::Extensive: 1918 GenerateExtensivePathDiagnostic(PD, PDB, N, visitors); 1919 break; 1920 case PathDiagnosticConsumer::Minimal: 1921 GenerateMinimalPathDiagnostic(PD, PDB, N, visitors); 1922 break; 1923 case PathDiagnosticConsumer::None: 1924 llvm_unreachable("PathDiagnosticConsumer::None should never appear here"); 1925 } 1926 1927 // Clean up the visitors we used. 1928 llvm::DeleteContainerPointers(visitors); 1929 1930 // Did anything change while generating this path? 1931 finalReportConfigToken = R->getConfigurationChangeToken(); 1932 } while(finalReportConfigToken != originalReportConfigToken); 1933 1934 // Finally, prune the diagnostic path of uninteresting stuff. 1935 if (R->shouldPrunePath()) { 1936 bool hasSomethingInteresting = RemoveUneededCalls(PD.getMutablePieces(), R); 1937 assert(hasSomethingInteresting); 1938 (void) hasSomethingInteresting; 1939 } 1940 } 1941 1942 void BugReporter::Register(BugType *BT) { 1943 BugTypes = F.add(BugTypes, BT); 1944 } 1945 1946 void BugReporter::EmitReport(BugReport* R) { 1947 // Compute the bug report's hash to determine its equivalence class. 1948 llvm::FoldingSetNodeID ID; 1949 R->Profile(ID); 1950 1951 // Lookup the equivance class. If there isn't one, create it. 1952 BugType& BT = R->getBugType(); 1953 Register(&BT); 1954 void *InsertPos; 1955 BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos); 1956 1957 if (!EQ) { 1958 EQ = new BugReportEquivClass(R); 1959 EQClasses.InsertNode(EQ, InsertPos); 1960 EQClassesVector.push_back(EQ); 1961 } 1962 else 1963 EQ->AddReport(R); 1964 } 1965 1966 1967 //===----------------------------------------------------------------------===// 1968 // Emitting reports in equivalence classes. 1969 //===----------------------------------------------------------------------===// 1970 1971 namespace { 1972 struct FRIEC_WLItem { 1973 const ExplodedNode *N; 1974 ExplodedNode::const_succ_iterator I, E; 1975 1976 FRIEC_WLItem(const ExplodedNode *n) 1977 : N(n), I(N->succ_begin()), E(N->succ_end()) {} 1978 }; 1979 } 1980 1981 static BugReport * 1982 FindReportInEquivalenceClass(BugReportEquivClass& EQ, 1983 SmallVectorImpl<BugReport*> &bugReports) { 1984 1985 BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end(); 1986 assert(I != E); 1987 BugType& BT = I->getBugType(); 1988 1989 // If we don't need to suppress any of the nodes because they are 1990 // post-dominated by a sink, simply add all the nodes in the equivalence class 1991 // to 'Nodes'. Any of the reports will serve as a "representative" report. 1992 if (!BT.isSuppressOnSink()) { 1993 BugReport *R = I; 1994 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) { 1995 const ExplodedNode *N = I->getErrorNode(); 1996 if (N) { 1997 R = I; 1998 bugReports.push_back(R); 1999 } 2000 } 2001 return R; 2002 } 2003 2004 // For bug reports that should be suppressed when all paths are post-dominated 2005 // by a sink node, iterate through the reports in the equivalence class 2006 // until we find one that isn't post-dominated (if one exists). We use a 2007 // DFS traversal of the ExplodedGraph to find a non-sink node. We could write 2008 // this as a recursive function, but we don't want to risk blowing out the 2009 // stack for very long paths. 2010 BugReport *exampleReport = 0; 2011 2012 for (; I != E; ++I) { 2013 const ExplodedNode *errorNode = I->getErrorNode(); 2014 2015 if (!errorNode) 2016 continue; 2017 if (errorNode->isSink()) { 2018 llvm_unreachable( 2019 "BugType::isSuppressSink() should not be 'true' for sink end nodes"); 2020 } 2021 // No successors? By definition this nodes isn't post-dominated by a sink. 2022 if (errorNode->succ_empty()) { 2023 bugReports.push_back(I); 2024 if (!exampleReport) 2025 exampleReport = I; 2026 continue; 2027 } 2028 2029 // At this point we know that 'N' is not a sink and it has at least one 2030 // successor. Use a DFS worklist to find a non-sink end-of-path node. 2031 typedef FRIEC_WLItem WLItem; 2032 typedef SmallVector<WLItem, 10> DFSWorkList; 2033 llvm::DenseMap<const ExplodedNode *, unsigned> Visited; 2034 2035 DFSWorkList WL; 2036 WL.push_back(errorNode); 2037 Visited[errorNode] = 1; 2038 2039 while (!WL.empty()) { 2040 WLItem &WI = WL.back(); 2041 assert(!WI.N->succ_empty()); 2042 2043 for (; WI.I != WI.E; ++WI.I) { 2044 const ExplodedNode *Succ = *WI.I; 2045 // End-of-path node? 2046 if (Succ->succ_empty()) { 2047 // If we found an end-of-path node that is not a sink. 2048 if (!Succ->isSink()) { 2049 bugReports.push_back(I); 2050 if (!exampleReport) 2051 exampleReport = I; 2052 WL.clear(); 2053 break; 2054 } 2055 // Found a sink? Continue on to the next successor. 2056 continue; 2057 } 2058 // Mark the successor as visited. If it hasn't been explored, 2059 // enqueue it to the DFS worklist. 2060 unsigned &mark = Visited[Succ]; 2061 if (!mark) { 2062 mark = 1; 2063 WL.push_back(Succ); 2064 break; 2065 } 2066 } 2067 2068 // The worklist may have been cleared at this point. First 2069 // check if it is empty before checking the last item. 2070 if (!WL.empty() && &WL.back() == &WI) 2071 WL.pop_back(); 2072 } 2073 } 2074 2075 // ExampleReport will be NULL if all the nodes in the equivalence class 2076 // were post-dominated by sinks. 2077 return exampleReport; 2078 } 2079 2080 void BugReporter::FlushReport(BugReportEquivClass& EQ) { 2081 SmallVector<BugReport*, 10> bugReports; 2082 BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports); 2083 if (exampleReport) { 2084 const PathDiagnosticConsumers &C = getPathDiagnosticConsumers(); 2085 for (PathDiagnosticConsumers::const_iterator I=C.begin(), 2086 E=C.end(); I != E; ++I) { 2087 FlushReport(exampleReport, **I, bugReports); 2088 } 2089 } 2090 } 2091 2092 void BugReporter::FlushReport(BugReport *exampleReport, 2093 PathDiagnosticConsumer &PD, 2094 ArrayRef<BugReport*> bugReports) { 2095 2096 // FIXME: Make sure we use the 'R' for the path that was actually used. 2097 // Probably doesn't make a difference in practice. 2098 BugType& BT = exampleReport->getBugType(); 2099 2100 OwningPtr<PathDiagnostic> 2101 D(new PathDiagnostic(exampleReport->getDeclWithIssue(), 2102 exampleReport->getBugType().getName(), 2103 exampleReport->getDescription(), 2104 exampleReport->getShortDescription(/*Fallback=*/false), 2105 BT.getCategory())); 2106 2107 // Generate the full path diagnostic, using the generation scheme 2108 // specified by the PathDiagnosticConsumer. 2109 if (PD.getGenerationScheme() != PathDiagnosticConsumer::None) { 2110 if (!bugReports.empty()) 2111 GeneratePathDiagnostic(*D.get(), PD, bugReports); 2112 } 2113 2114 // If the path is empty, generate a single step path with the location 2115 // of the issue. 2116 if (D->path.empty()) { 2117 PathDiagnosticLocation L = exampleReport->getLocation(getSourceManager()); 2118 PathDiagnosticPiece *piece = 2119 new PathDiagnosticEventPiece(L, exampleReport->getDescription()); 2120 BugReport::ranges_iterator Beg, End; 2121 llvm::tie(Beg, End) = exampleReport->getRanges(); 2122 for ( ; Beg != End; ++Beg) 2123 piece->addRange(*Beg); 2124 D->setEndOfPath(piece); 2125 } 2126 2127 // Get the meta data. 2128 const BugReport::ExtraTextList &Meta = exampleReport->getExtraText(); 2129 for (BugReport::ExtraTextList::const_iterator i = Meta.begin(), 2130 e = Meta.end(); i != e; ++i) { 2131 D->addMeta(*i); 2132 } 2133 2134 PD.HandlePathDiagnostic(D.take()); 2135 } 2136 2137 void BugReporter::EmitBasicReport(const Decl *DeclWithIssue, 2138 StringRef name, 2139 StringRef category, 2140 StringRef str, PathDiagnosticLocation Loc, 2141 SourceRange* RBeg, unsigned NumRanges) { 2142 2143 // 'BT' is owned by BugReporter. 2144 BugType *BT = getBugTypeForName(name, category); 2145 BugReport *R = new BugReport(*BT, str, Loc); 2146 R->setDeclWithIssue(DeclWithIssue); 2147 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg); 2148 EmitReport(R); 2149 } 2150 2151 BugType *BugReporter::getBugTypeForName(StringRef name, 2152 StringRef category) { 2153 SmallString<136> fullDesc; 2154 llvm::raw_svector_ostream(fullDesc) << name << ":" << category; 2155 llvm::StringMapEntry<BugType *> & 2156 entry = StrBugTypes.GetOrCreateValue(fullDesc); 2157 BugType *BT = entry.getValue(); 2158 if (!BT) { 2159 BT = new BugType(name, category); 2160 entry.setValue(BT); 2161 } 2162 return BT; 2163 } 2164