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