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