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