BugReporter.cpp revision 49a246f4fad959888bb0164c624c3c2b03078e91
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#define DEBUG_TYPE "BugReporter" 16 17#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/DeclObjC.h" 20#include "clang/AST/Expr.h" 21#include "clang/AST/ParentMap.h" 22#include "clang/AST/StmtObjC.h" 23#include "clang/Analysis/CFG.h" 24#include "clang/Analysis/ProgramPoint.h" 25#include "clang/Basic/SourceManager.h" 26#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 27#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 28#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 29#include "llvm/ADT/DenseMap.h" 30#include "llvm/ADT/IntrusiveRefCntPtr.h" 31#include "llvm/ADT/OwningPtr.h" 32#include "llvm/ADT/STLExtras.h" 33#include "llvm/ADT/SmallString.h" 34#include "llvm/ADT/Statistic.h" 35#include "llvm/Support/raw_ostream.h" 36#include <queue> 37 38using namespace clang; 39using namespace ento; 40 41STATISTIC(MaxBugClassSize, 42 "The maximum number of bug reports in the same equivalence class"); 43STATISTIC(MaxValidBugClassSize, 44 "The maximum number of bug reports in the same equivalence class " 45 "where at least one report is valid (not suppressed)"); 46 47BugReporterVisitor::~BugReporterVisitor() {} 48 49void BugReporterContext::anchor() {} 50 51//===----------------------------------------------------------------------===// 52// Helper routines for walking the ExplodedGraph and fetching statements. 53//===----------------------------------------------------------------------===// 54 55static const Stmt *GetPreviousStmt(const ExplodedNode *N) { 56 for (N = N->getFirstPred(); N; N = N->getFirstPred()) 57 if (const Stmt *S = PathDiagnosticLocation::getStmt(N)) 58 return S; 59 60 return 0; 61} 62 63static inline const Stmt* 64GetCurrentOrPreviousStmt(const ExplodedNode *N) { 65 if (const Stmt *S = PathDiagnosticLocation::getStmt(N)) 66 return S; 67 68 return GetPreviousStmt(N); 69} 70 71//===----------------------------------------------------------------------===// 72// Diagnostic cleanup. 73//===----------------------------------------------------------------------===// 74 75static PathDiagnosticEventPiece * 76eventsDescribeSameCondition(PathDiagnosticEventPiece *X, 77 PathDiagnosticEventPiece *Y) { 78 // Prefer diagnostics that come from ConditionBRVisitor over 79 // those that came from TrackConstraintBRVisitor. 80 const void *tagPreferred = ConditionBRVisitor::getTag(); 81 const void *tagLesser = TrackConstraintBRVisitor::getTag(); 82 83 if (X->getLocation() != Y->getLocation()) 84 return 0; 85 86 if (X->getTag() == tagPreferred && Y->getTag() == tagLesser) 87 return X; 88 89 if (Y->getTag() == tagPreferred && X->getTag() == tagLesser) 90 return Y; 91 92 return 0; 93} 94 95/// An optimization pass over PathPieces that removes redundant diagnostics 96/// generated by both ConditionBRVisitor and TrackConstraintBRVisitor. Both 97/// BugReporterVisitors use different methods to generate diagnostics, with 98/// one capable of emitting diagnostics in some cases but not in others. This 99/// can lead to redundant diagnostic pieces at the same point in a path. 100static void removeRedundantMsgs(PathPieces &path) { 101 unsigned N = path.size(); 102 if (N < 2) 103 return; 104 // NOTE: this loop intentionally is not using an iterator. Instead, we 105 // are streaming the path and modifying it in place. This is done by 106 // grabbing the front, processing it, and if we decide to keep it append 107 // it to the end of the path. The entire path is processed in this way. 108 for (unsigned i = 0; i < N; ++i) { 109 IntrusiveRefCntPtr<PathDiagnosticPiece> piece(path.front()); 110 path.pop_front(); 111 112 switch (piece->getKind()) { 113 case clang::ento::PathDiagnosticPiece::Call: 114 removeRedundantMsgs(cast<PathDiagnosticCallPiece>(piece)->path); 115 break; 116 case clang::ento::PathDiagnosticPiece::Macro: 117 removeRedundantMsgs(cast<PathDiagnosticMacroPiece>(piece)->subPieces); 118 break; 119 case clang::ento::PathDiagnosticPiece::ControlFlow: 120 break; 121 case clang::ento::PathDiagnosticPiece::Event: { 122 if (i == N-1) 123 break; 124 125 if (PathDiagnosticEventPiece *nextEvent = 126 dyn_cast<PathDiagnosticEventPiece>(path.front().getPtr())) { 127 PathDiagnosticEventPiece *event = 128 cast<PathDiagnosticEventPiece>(piece); 129 // Check to see if we should keep one of the two pieces. If we 130 // come up with a preference, record which piece to keep, and consume 131 // another piece from the path. 132 if (PathDiagnosticEventPiece *pieceToKeep = 133 eventsDescribeSameCondition(event, nextEvent)) { 134 piece = pieceToKeep; 135 path.pop_front(); 136 ++i; 137 } 138 } 139 break; 140 } 141 } 142 path.push_back(piece); 143 } 144} 145 146/// A map from PathDiagnosticPiece to the LocationContext of the inlined 147/// function call it represents. 148typedef llvm::DenseMap<const PathPieces *, const LocationContext *> 149 LocationContextMap; 150 151/// Recursively scan through a path and prune out calls and macros pieces 152/// that aren't needed. Return true if afterwards the path contains 153/// "interesting stuff" which means it shouldn't be pruned from the parent path. 154static bool removeUnneededCalls(PathPieces &pieces, BugReport *R, 155 LocationContextMap &LCM) { 156 bool containsSomethingInteresting = false; 157 const unsigned N = pieces.size(); 158 159 for (unsigned i = 0 ; i < N ; ++i) { 160 // Remove the front piece from the path. If it is still something we 161 // want to keep once we are done, we will push it back on the end. 162 IntrusiveRefCntPtr<PathDiagnosticPiece> piece(pieces.front()); 163 pieces.pop_front(); 164 165 // Throw away pieces with invalid locations. Note that we can't throw away 166 // calls just yet because they might have something interesting inside them. 167 // If so, their locations will be adjusted as necessary later. 168 if (piece->getKind() != PathDiagnosticPiece::Call && 169 piece->getLocation().asLocation().isInvalid()) 170 continue; 171 172 switch (piece->getKind()) { 173 case PathDiagnosticPiece::Call: { 174 PathDiagnosticCallPiece *call = cast<PathDiagnosticCallPiece>(piece); 175 // Check if the location context is interesting. 176 assert(LCM.count(&call->path)); 177 if (R->isInteresting(LCM[&call->path])) { 178 containsSomethingInteresting = true; 179 break; 180 } 181 182 if (!removeUnneededCalls(call->path, R, LCM)) 183 continue; 184 185 containsSomethingInteresting = true; 186 break; 187 } 188 case PathDiagnosticPiece::Macro: { 189 PathDiagnosticMacroPiece *macro = cast<PathDiagnosticMacroPiece>(piece); 190 if (!removeUnneededCalls(macro->subPieces, R, LCM)) 191 continue; 192 containsSomethingInteresting = true; 193 break; 194 } 195 case PathDiagnosticPiece::Event: { 196 PathDiagnosticEventPiece *event = cast<PathDiagnosticEventPiece>(piece); 197 198 // We never throw away an event, but we do throw it away wholesale 199 // as part of a path if we throw the entire path away. 200 containsSomethingInteresting |= !event->isPrunable(); 201 break; 202 } 203 case PathDiagnosticPiece::ControlFlow: 204 break; 205 } 206 207 pieces.push_back(piece); 208 } 209 210 return containsSomethingInteresting; 211} 212 213/// Returns true if the given decl has been implicitly given a body, either by 214/// the analyzer or by the compiler proper. 215static bool hasImplicitBody(const Decl *D) { 216 assert(D); 217 return D->isImplicit() || !D->hasBody(); 218} 219 220/// Recursively scan through a path and make sure that all call pieces have 221/// valid locations. Note that all other pieces with invalid locations should 222/// have already been pruned out. 223static void adjustCallLocations(PathPieces &Pieces, 224 PathDiagnosticLocation *LastCallLocation = 0) { 225 for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E; ++I) { 226 PathDiagnosticCallPiece *Call = dyn_cast<PathDiagnosticCallPiece>(*I); 227 228 if (!Call) { 229 assert((*I)->getLocation().asLocation().isValid()); 230 continue; 231 } 232 233 if (LastCallLocation) { 234 bool CallerIsImplicit = hasImplicitBody(Call->getCaller()); 235 if (CallerIsImplicit || !Call->callEnter.asLocation().isValid()) 236 Call->callEnter = *LastCallLocation; 237 if (CallerIsImplicit || !Call->callReturn.asLocation().isValid()) 238 Call->callReturn = *LastCallLocation; 239 } 240 241 // Recursively clean out the subclass. Keep this call around if 242 // it contains any informative diagnostics. 243 PathDiagnosticLocation *ThisCallLocation; 244 if (Call->callEnterWithin.asLocation().isValid() && 245 !hasImplicitBody(Call->getCallee())) 246 ThisCallLocation = &Call->callEnterWithin; 247 else 248 ThisCallLocation = &Call->callEnter; 249 250 assert(ThisCallLocation && "Outermost call has an invalid location"); 251 adjustCallLocations(Call->path, ThisCallLocation); 252 } 253} 254 255//===----------------------------------------------------------------------===// 256// PathDiagnosticBuilder and its associated routines and helper objects. 257//===----------------------------------------------------------------------===// 258 259namespace { 260class NodeMapClosure : public BugReport::NodeResolver { 261 InterExplodedGraphMap &M; 262public: 263 NodeMapClosure(InterExplodedGraphMap &m) : M(m) {} 264 265 const ExplodedNode *getOriginalNode(const ExplodedNode *N) { 266 return M.lookup(N); 267 } 268}; 269 270class PathDiagnosticBuilder : public BugReporterContext { 271 BugReport *R; 272 PathDiagnosticConsumer *PDC; 273 NodeMapClosure NMC; 274public: 275 const LocationContext *LC; 276 277 PathDiagnosticBuilder(GRBugReporter &br, 278 BugReport *r, InterExplodedGraphMap &Backmap, 279 PathDiagnosticConsumer *pdc) 280 : BugReporterContext(br), 281 R(r), PDC(pdc), NMC(Backmap), LC(r->getErrorNode()->getLocationContext()) 282 {} 283 284 PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N); 285 286 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os, 287 const ExplodedNode *N); 288 289 BugReport *getBugReport() { return R; } 290 291 Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); } 292 293 ParentMap& getParentMap() { return LC->getParentMap(); } 294 295 const Stmt *getParent(const Stmt *S) { 296 return getParentMap().getParent(S); 297 } 298 299 virtual NodeMapClosure& getNodeResolver() { return NMC; } 300 301 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S); 302 303 PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const { 304 return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Extensive; 305 } 306 307 bool supportsLogicalOpControlFlow() const { 308 return PDC ? PDC->supportsLogicalOpControlFlow() : true; 309 } 310}; 311} // end anonymous namespace 312 313PathDiagnosticLocation 314PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) { 315 if (const Stmt *S = PathDiagnosticLocation::getNextStmt(N)) 316 return PathDiagnosticLocation(S, getSourceManager(), LC); 317 318 return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(), 319 getSourceManager()); 320} 321 322PathDiagnosticLocation 323PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os, 324 const ExplodedNode *N) { 325 326 // Slow, but probably doesn't matter. 327 if (os.str().empty()) 328 os << ' '; 329 330 const PathDiagnosticLocation &Loc = ExecutionContinues(N); 331 332 if (Loc.asStmt()) 333 os << "Execution continues on line " 334 << getSourceManager().getExpansionLineNumber(Loc.asLocation()) 335 << '.'; 336 else { 337 os << "Execution jumps to the end of the "; 338 const Decl *D = N->getLocationContext()->getDecl(); 339 if (isa<ObjCMethodDecl>(D)) 340 os << "method"; 341 else if (isa<FunctionDecl>(D)) 342 os << "function"; 343 else { 344 assert(isa<BlockDecl>(D)); 345 os << "anonymous block"; 346 } 347 os << '.'; 348 } 349 350 return Loc; 351} 352 353static const Stmt *getEnclosingParent(const Stmt *S, const ParentMap &PM) { 354 if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S))) 355 return PM.getParentIgnoreParens(S); 356 357 const Stmt *Parent = PM.getParentIgnoreParens(S); 358 if (!Parent) 359 return 0; 360 361 switch (Parent->getStmtClass()) { 362 case Stmt::ForStmtClass: 363 case Stmt::DoStmtClass: 364 case Stmt::WhileStmtClass: 365 case Stmt::ObjCForCollectionStmtClass: 366 case Stmt::CXXForRangeStmtClass: 367 return Parent; 368 default: 369 break; 370 } 371 372 return 0; 373} 374 375static PathDiagnosticLocation 376getEnclosingStmtLocation(const Stmt *S, SourceManager &SMgr, const ParentMap &P, 377 const LocationContext *LC, bool allowNestedContexts) { 378 if (!S) 379 return PathDiagnosticLocation(); 380 381 while (const Stmt *Parent = getEnclosingParent(S, P)) { 382 switch (Parent->getStmtClass()) { 383 case Stmt::BinaryOperatorClass: { 384 const BinaryOperator *B = cast<BinaryOperator>(Parent); 385 if (B->isLogicalOp()) 386 return PathDiagnosticLocation(allowNestedContexts ? B : S, SMgr, LC); 387 break; 388 } 389 case Stmt::CompoundStmtClass: 390 case Stmt::StmtExprClass: 391 return PathDiagnosticLocation(S, SMgr, LC); 392 case Stmt::ChooseExprClass: 393 // Similar to '?' if we are referring to condition, just have the edge 394 // point to the entire choose expression. 395 if (allowNestedContexts || cast<ChooseExpr>(Parent)->getCond() == S) 396 return PathDiagnosticLocation(Parent, SMgr, LC); 397 else 398 return PathDiagnosticLocation(S, SMgr, LC); 399 case Stmt::BinaryConditionalOperatorClass: 400 case Stmt::ConditionalOperatorClass: 401 // For '?', if we are referring to condition, just have the edge point 402 // to the entire '?' expression. 403 if (allowNestedContexts || 404 cast<AbstractConditionalOperator>(Parent)->getCond() == S) 405 return PathDiagnosticLocation(Parent, SMgr, LC); 406 else 407 return PathDiagnosticLocation(S, SMgr, LC); 408 case Stmt::CXXForRangeStmtClass: 409 if (cast<CXXForRangeStmt>(Parent)->getBody() == S) 410 return PathDiagnosticLocation(S, SMgr, LC); 411 break; 412 case Stmt::DoStmtClass: 413 return PathDiagnosticLocation(S, SMgr, LC); 414 case Stmt::ForStmtClass: 415 if (cast<ForStmt>(Parent)->getBody() == S) 416 return PathDiagnosticLocation(S, SMgr, LC); 417 break; 418 case Stmt::IfStmtClass: 419 if (cast<IfStmt>(Parent)->getCond() != S) 420 return PathDiagnosticLocation(S, SMgr, LC); 421 break; 422 case Stmt::ObjCForCollectionStmtClass: 423 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S) 424 return PathDiagnosticLocation(S, SMgr, LC); 425 break; 426 case Stmt::WhileStmtClass: 427 if (cast<WhileStmt>(Parent)->getCond() != S) 428 return PathDiagnosticLocation(S, SMgr, LC); 429 break; 430 default: 431 break; 432 } 433 434 S = Parent; 435 } 436 437 assert(S && "Cannot have null Stmt for PathDiagnosticLocation"); 438 439 return PathDiagnosticLocation(S, SMgr, LC); 440} 441 442PathDiagnosticLocation 443PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) { 444 assert(S && "Null Stmt passed to getEnclosingStmtLocation"); 445 return ::getEnclosingStmtLocation(S, getSourceManager(), getParentMap(), LC, 446 /*allowNestedContexts=*/false); 447} 448 449//===----------------------------------------------------------------------===// 450// "Visitors only" path diagnostic generation algorithm. 451//===----------------------------------------------------------------------===// 452static bool GenerateVisitorsOnlyPathDiagnostic(PathDiagnostic &PD, 453 PathDiagnosticBuilder &PDB, 454 const ExplodedNode *N, 455 ArrayRef<BugReporterVisitor *> visitors) { 456 // All path generation skips the very first node (the error node). 457 // This is because there is special handling for the end-of-path note. 458 N = N->getFirstPred(); 459 if (!N) 460 return true; 461 462 BugReport *R = PDB.getBugReport(); 463 while (const ExplodedNode *Pred = N->getFirstPred()) { 464 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(), 465 E = visitors.end(); 466 I != E; ++I) { 467 // Visit all the node pairs, but throw the path pieces away. 468 PathDiagnosticPiece *Piece = (*I)->VisitNode(N, Pred, PDB, *R); 469 delete Piece; 470 } 471 472 N = Pred; 473 } 474 475 return R->isValid(); 476} 477 478//===----------------------------------------------------------------------===// 479// "Minimal" path diagnostic generation algorithm. 480//===----------------------------------------------------------------------===// 481typedef std::pair<PathDiagnosticCallPiece*, const ExplodedNode*> StackDiagPair; 482typedef SmallVector<StackDiagPair, 6> StackDiagVector; 483 484static void updateStackPiecesWithMessage(PathDiagnosticPiece *P, 485 StackDiagVector &CallStack) { 486 // If the piece contains a special message, add it to all the call 487 // pieces on the active stack. 488 if (PathDiagnosticEventPiece *ep = 489 dyn_cast<PathDiagnosticEventPiece>(P)) { 490 491 if (ep->hasCallStackHint()) 492 for (StackDiagVector::iterator I = CallStack.begin(), 493 E = CallStack.end(); I != E; ++I) { 494 PathDiagnosticCallPiece *CP = I->first; 495 const ExplodedNode *N = I->second; 496 std::string stackMsg = ep->getCallStackMessage(N); 497 498 // The last message on the path to final bug is the most important 499 // one. Since we traverse the path backwards, do not add the message 500 // if one has been previously added. 501 if (!CP->hasCallStackMessage()) 502 CP->setCallStackMessage(stackMsg); 503 } 504 } 505} 506 507static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM); 508 509static bool GenerateMinimalPathDiagnostic(PathDiagnostic& PD, 510 PathDiagnosticBuilder &PDB, 511 const ExplodedNode *N, 512 LocationContextMap &LCM, 513 ArrayRef<BugReporterVisitor *> visitors) { 514 515 SourceManager& SMgr = PDB.getSourceManager(); 516 const LocationContext *LC = PDB.LC; 517 const ExplodedNode *NextNode = N->pred_empty() 518 ? NULL : *(N->pred_begin()); 519 520 StackDiagVector CallStack; 521 522 while (NextNode) { 523 N = NextNode; 524 PDB.LC = N->getLocationContext(); 525 NextNode = N->getFirstPred(); 526 527 ProgramPoint P = N->getLocation(); 528 529 do { 530 if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) { 531 PathDiagnosticCallPiece *C = 532 PathDiagnosticCallPiece::construct(N, *CE, SMgr); 533 // Record the mapping from call piece to LocationContext. 534 LCM[&C->path] = CE->getCalleeContext(); 535 PD.getActivePath().push_front(C); 536 PD.pushActivePath(&C->path); 537 CallStack.push_back(StackDiagPair(C, N)); 538 break; 539 } 540 541 if (Optional<CallEnter> CE = P.getAs<CallEnter>()) { 542 // Flush all locations, and pop the active path. 543 bool VisitedEntireCall = PD.isWithinCall(); 544 PD.popActivePath(); 545 546 // Either we just added a bunch of stuff to the top-level path, or 547 // we have a previous CallExitEnd. If the former, it means that the 548 // path terminated within a function call. We must then take the 549 // current contents of the active path and place it within 550 // a new PathDiagnosticCallPiece. 551 PathDiagnosticCallPiece *C; 552 if (VisitedEntireCall) { 553 C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front()); 554 } else { 555 const Decl *Caller = CE->getLocationContext()->getDecl(); 556 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller); 557 // Record the mapping from call piece to LocationContext. 558 LCM[&C->path] = CE->getCalleeContext(); 559 } 560 561 C->setCallee(*CE, SMgr); 562 if (!CallStack.empty()) { 563 assert(CallStack.back().first == C); 564 CallStack.pop_back(); 565 } 566 break; 567 } 568 569 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) { 570 const CFGBlock *Src = BE->getSrc(); 571 const CFGBlock *Dst = BE->getDst(); 572 const Stmt *T = Src->getTerminator(); 573 574 if (!T) 575 break; 576 577 PathDiagnosticLocation Start = 578 PathDiagnosticLocation::createBegin(T, SMgr, 579 N->getLocationContext()); 580 581 switch (T->getStmtClass()) { 582 default: 583 break; 584 585 case Stmt::GotoStmtClass: 586 case Stmt::IndirectGotoStmtClass: { 587 const Stmt *S = PathDiagnosticLocation::getNextStmt(N); 588 589 if (!S) 590 break; 591 592 std::string sbuf; 593 llvm::raw_string_ostream os(sbuf); 594 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S); 595 596 os << "Control jumps to line " 597 << End.asLocation().getExpansionLineNumber(); 598 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 599 Start, End, os.str())); 600 break; 601 } 602 603 case Stmt::SwitchStmtClass: { 604 // Figure out what case arm we took. 605 std::string sbuf; 606 llvm::raw_string_ostream os(sbuf); 607 608 if (const Stmt *S = Dst->getLabel()) { 609 PathDiagnosticLocation End(S, SMgr, LC); 610 611 switch (S->getStmtClass()) { 612 default: 613 os << "No cases match in the switch statement. " 614 "Control jumps to line " 615 << End.asLocation().getExpansionLineNumber(); 616 break; 617 case Stmt::DefaultStmtClass: 618 os << "Control jumps to the 'default' case at line " 619 << End.asLocation().getExpansionLineNumber(); 620 break; 621 622 case Stmt::CaseStmtClass: { 623 os << "Control jumps to 'case "; 624 const CaseStmt *Case = cast<CaseStmt>(S); 625 const Expr *LHS = Case->getLHS()->IgnoreParenCasts(); 626 627 // Determine if it is an enum. 628 bool GetRawInt = true; 629 630 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) { 631 // FIXME: Maybe this should be an assertion. Are there cases 632 // were it is not an EnumConstantDecl? 633 const EnumConstantDecl *D = 634 dyn_cast<EnumConstantDecl>(DR->getDecl()); 635 636 if (D) { 637 GetRawInt = false; 638 os << *D; 639 } 640 } 641 642 if (GetRawInt) 643 os << LHS->EvaluateKnownConstInt(PDB.getASTContext()); 644 645 os << ":' at line " 646 << End.asLocation().getExpansionLineNumber(); 647 break; 648 } 649 } 650 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 651 Start, End, os.str())); 652 } 653 else { 654 os << "'Default' branch taken. "; 655 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N); 656 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 657 Start, End, os.str())); 658 } 659 660 break; 661 } 662 663 case Stmt::BreakStmtClass: 664 case Stmt::ContinueStmtClass: { 665 std::string sbuf; 666 llvm::raw_string_ostream os(sbuf); 667 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N); 668 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 669 Start, End, os.str())); 670 break; 671 } 672 673 // Determine control-flow for ternary '?'. 674 case Stmt::BinaryConditionalOperatorClass: 675 case Stmt::ConditionalOperatorClass: { 676 std::string sbuf; 677 llvm::raw_string_ostream os(sbuf); 678 os << "'?' condition is "; 679 680 if (*(Src->succ_begin()+1) == Dst) 681 os << "false"; 682 else 683 os << "true"; 684 685 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 686 687 if (const Stmt *S = End.asStmt()) 688 End = PDB.getEnclosingStmtLocation(S); 689 690 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 691 Start, End, os.str())); 692 break; 693 } 694 695 // Determine control-flow for short-circuited '&&' and '||'. 696 case Stmt::BinaryOperatorClass: { 697 if (!PDB.supportsLogicalOpControlFlow()) 698 break; 699 700 const BinaryOperator *B = cast<BinaryOperator>(T); 701 std::string sbuf; 702 llvm::raw_string_ostream os(sbuf); 703 os << "Left side of '"; 704 705 if (B->getOpcode() == BO_LAnd) { 706 os << "&&" << "' is "; 707 708 if (*(Src->succ_begin()+1) == Dst) { 709 os << "false"; 710 PathDiagnosticLocation End(B->getLHS(), SMgr, LC); 711 PathDiagnosticLocation Start = 712 PathDiagnosticLocation::createOperatorLoc(B, SMgr); 713 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 714 Start, End, os.str())); 715 } 716 else { 717 os << "true"; 718 PathDiagnosticLocation Start(B->getLHS(), SMgr, LC); 719 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 720 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 721 Start, End, os.str())); 722 } 723 } 724 else { 725 assert(B->getOpcode() == BO_LOr); 726 os << "||" << "' is "; 727 728 if (*(Src->succ_begin()+1) == Dst) { 729 os << "false"; 730 PathDiagnosticLocation Start(B->getLHS(), SMgr, LC); 731 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 732 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 733 Start, End, os.str())); 734 } 735 else { 736 os << "true"; 737 PathDiagnosticLocation End(B->getLHS(), SMgr, LC); 738 PathDiagnosticLocation Start = 739 PathDiagnosticLocation::createOperatorLoc(B, SMgr); 740 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 741 Start, End, os.str())); 742 } 743 } 744 745 break; 746 } 747 748 case Stmt::DoStmtClass: { 749 if (*(Src->succ_begin()) == Dst) { 750 std::string sbuf; 751 llvm::raw_string_ostream os(sbuf); 752 753 os << "Loop condition is true. "; 754 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N); 755 756 if (const Stmt *S = End.asStmt()) 757 End = PDB.getEnclosingStmtLocation(S); 758 759 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 760 Start, End, os.str())); 761 } 762 else { 763 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 764 765 if (const Stmt *S = End.asStmt()) 766 End = PDB.getEnclosingStmtLocation(S); 767 768 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 769 Start, End, "Loop condition is false. Exiting loop")); 770 } 771 772 break; 773 } 774 775 case Stmt::WhileStmtClass: 776 case Stmt::ForStmtClass: { 777 if (*(Src->succ_begin()+1) == Dst) { 778 std::string sbuf; 779 llvm::raw_string_ostream os(sbuf); 780 781 os << "Loop condition is false. "; 782 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N); 783 if (const Stmt *S = End.asStmt()) 784 End = PDB.getEnclosingStmtLocation(S); 785 786 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 787 Start, End, os.str())); 788 } 789 else { 790 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 791 if (const Stmt *S = End.asStmt()) 792 End = PDB.getEnclosingStmtLocation(S); 793 794 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 795 Start, End, "Loop condition is true. Entering loop body")); 796 } 797 798 break; 799 } 800 801 case Stmt::IfStmtClass: { 802 PathDiagnosticLocation End = PDB.ExecutionContinues(N); 803 804 if (const Stmt *S = End.asStmt()) 805 End = PDB.getEnclosingStmtLocation(S); 806 807 if (*(Src->succ_begin()+1) == Dst) 808 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 809 Start, End, "Taking false branch")); 810 else 811 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece( 812 Start, End, "Taking true branch")); 813 814 break; 815 } 816 } 817 } 818 } while(0); 819 820 if (NextNode) { 821 // Add diagnostic pieces from custom visitors. 822 BugReport *R = PDB.getBugReport(); 823 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(), 824 E = visitors.end(); 825 I != E; ++I) { 826 if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) { 827 PD.getActivePath().push_front(p); 828 updateStackPiecesWithMessage(p, CallStack); 829 } 830 } 831 } 832 } 833 834 if (!PDB.getBugReport()->isValid()) 835 return false; 836 837 // After constructing the full PathDiagnostic, do a pass over it to compact 838 // PathDiagnosticPieces that occur within a macro. 839 CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager()); 840 return true; 841} 842 843//===----------------------------------------------------------------------===// 844// "Extensive" PathDiagnostic generation. 845//===----------------------------------------------------------------------===// 846 847static bool IsControlFlowExpr(const Stmt *S) { 848 const Expr *E = dyn_cast<Expr>(S); 849 850 if (!E) 851 return false; 852 853 E = E->IgnoreParenCasts(); 854 855 if (isa<AbstractConditionalOperator>(E)) 856 return true; 857 858 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) 859 if (B->isLogicalOp()) 860 return true; 861 862 return false; 863} 864 865namespace { 866class ContextLocation : public PathDiagnosticLocation { 867 bool IsDead; 868public: 869 ContextLocation(const PathDiagnosticLocation &L, bool isdead = false) 870 : PathDiagnosticLocation(L), IsDead(isdead) {} 871 872 void markDead() { IsDead = true; } 873 bool isDead() const { return IsDead; } 874}; 875 876static PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L, 877 const LocationContext *LC, 878 bool firstCharOnly = false) { 879 if (const Stmt *S = L.asStmt()) { 880 const Stmt *Original = S; 881 while (1) { 882 // Adjust the location for some expressions that are best referenced 883 // by one of their subexpressions. 884 switch (S->getStmtClass()) { 885 default: 886 break; 887 case Stmt::ParenExprClass: 888 case Stmt::GenericSelectionExprClass: 889 S = cast<Expr>(S)->IgnoreParens(); 890 firstCharOnly = true; 891 continue; 892 case Stmt::BinaryConditionalOperatorClass: 893 case Stmt::ConditionalOperatorClass: 894 S = cast<AbstractConditionalOperator>(S)->getCond(); 895 firstCharOnly = true; 896 continue; 897 case Stmt::ChooseExprClass: 898 S = cast<ChooseExpr>(S)->getCond(); 899 firstCharOnly = true; 900 continue; 901 case Stmt::BinaryOperatorClass: 902 S = cast<BinaryOperator>(S)->getLHS(); 903 firstCharOnly = true; 904 continue; 905 } 906 907 break; 908 } 909 910 if (S != Original) 911 L = PathDiagnosticLocation(S, L.getManager(), LC); 912 } 913 914 if (firstCharOnly) 915 L = PathDiagnosticLocation::createSingleLocation(L); 916 917 return L; 918} 919 920class EdgeBuilder { 921 std::vector<ContextLocation> CLocs; 922 typedef std::vector<ContextLocation>::iterator iterator; 923 PathDiagnostic &PD; 924 PathDiagnosticBuilder &PDB; 925 PathDiagnosticLocation PrevLoc; 926 927 bool IsConsumedExpr(const PathDiagnosticLocation &L); 928 929 bool containsLocation(const PathDiagnosticLocation &Container, 930 const PathDiagnosticLocation &Containee); 931 932 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L); 933 934 935 936 void popLocation() { 937 if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) { 938 // For contexts, we only one the first character as the range. 939 rawAddEdge(cleanUpLocation(CLocs.back(), PDB.LC, true)); 940 } 941 CLocs.pop_back(); 942 } 943 944public: 945 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb) 946 : PD(pd), PDB(pdb) { 947 948 // If the PathDiagnostic already has pieces, add the enclosing statement 949 // of the first piece as a context as well. 950 if (!PD.path.empty()) { 951 PrevLoc = (*PD.path.begin())->getLocation(); 952 953 if (const Stmt *S = PrevLoc.asStmt()) 954 addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt()); 955 } 956 } 957 958 ~EdgeBuilder() { 959 while (!CLocs.empty()) popLocation(); 960 961 // Finally, add an initial edge from the start location of the first 962 // statement (if it doesn't already exist). 963 PathDiagnosticLocation L = PathDiagnosticLocation::createDeclBegin( 964 PDB.LC, 965 PDB.getSourceManager()); 966 if (L.isValid()) 967 rawAddEdge(L); 968 } 969 970 void flushLocations() { 971 while (!CLocs.empty()) 972 popLocation(); 973 PrevLoc = PathDiagnosticLocation(); 974 } 975 976 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false, 977 bool IsPostJump = false); 978 979 void rawAddEdge(PathDiagnosticLocation NewLoc); 980 981 void addContext(const Stmt *S); 982 void addContext(const PathDiagnosticLocation &L); 983 void addExtendedContext(const Stmt *S); 984}; 985} // end anonymous namespace 986 987 988PathDiagnosticLocation 989EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) { 990 if (const Stmt *S = L.asStmt()) { 991 if (IsControlFlowExpr(S)) 992 return L; 993 994 return PDB.getEnclosingStmtLocation(S); 995 } 996 997 return L; 998} 999 1000bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container, 1001 const PathDiagnosticLocation &Containee) { 1002 1003 if (Container == Containee) 1004 return true; 1005 1006 if (Container.asDecl()) 1007 return true; 1008 1009 if (const Stmt *S = Containee.asStmt()) 1010 if (const Stmt *ContainerS = Container.asStmt()) { 1011 while (S) { 1012 if (S == ContainerS) 1013 return true; 1014 S = PDB.getParent(S); 1015 } 1016 return false; 1017 } 1018 1019 // Less accurate: compare using source ranges. 1020 SourceRange ContainerR = Container.asRange(); 1021 SourceRange ContaineeR = Containee.asRange(); 1022 1023 SourceManager &SM = PDB.getSourceManager(); 1024 SourceLocation ContainerRBeg = SM.getExpansionLoc(ContainerR.getBegin()); 1025 SourceLocation ContainerREnd = SM.getExpansionLoc(ContainerR.getEnd()); 1026 SourceLocation ContaineeRBeg = SM.getExpansionLoc(ContaineeR.getBegin()); 1027 SourceLocation ContaineeREnd = SM.getExpansionLoc(ContaineeR.getEnd()); 1028 1029 unsigned ContainerBegLine = SM.getExpansionLineNumber(ContainerRBeg); 1030 unsigned ContainerEndLine = SM.getExpansionLineNumber(ContainerREnd); 1031 unsigned ContaineeBegLine = SM.getExpansionLineNumber(ContaineeRBeg); 1032 unsigned ContaineeEndLine = SM.getExpansionLineNumber(ContaineeREnd); 1033 1034 assert(ContainerBegLine <= ContainerEndLine); 1035 assert(ContaineeBegLine <= ContaineeEndLine); 1036 1037 return (ContainerBegLine <= ContaineeBegLine && 1038 ContainerEndLine >= ContaineeEndLine && 1039 (ContainerBegLine != ContaineeBegLine || 1040 SM.getExpansionColumnNumber(ContainerRBeg) <= 1041 SM.getExpansionColumnNumber(ContaineeRBeg)) && 1042 (ContainerEndLine != ContaineeEndLine || 1043 SM.getExpansionColumnNumber(ContainerREnd) >= 1044 SM.getExpansionColumnNumber(ContaineeREnd))); 1045} 1046 1047void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) { 1048 if (!PrevLoc.isValid()) { 1049 PrevLoc = NewLoc; 1050 return; 1051 } 1052 1053 const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc, PDB.LC); 1054 const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc, PDB.LC); 1055 1056 if (PrevLocClean.asLocation().isInvalid()) { 1057 PrevLoc = NewLoc; 1058 return; 1059 } 1060 1061 if (NewLocClean.asLocation() == PrevLocClean.asLocation()) 1062 return; 1063 1064 // FIXME: Ignore intra-macro edges for now. 1065 if (NewLocClean.asLocation().getExpansionLoc() == 1066 PrevLocClean.asLocation().getExpansionLoc()) 1067 return; 1068 1069 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean)); 1070 PrevLoc = NewLoc; 1071} 1072 1073void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd, 1074 bool IsPostJump) { 1075 1076 if (!alwaysAdd && NewLoc.asLocation().isMacroID()) 1077 return; 1078 1079 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc); 1080 1081 while (!CLocs.empty()) { 1082 ContextLocation &TopContextLoc = CLocs.back(); 1083 1084 // Is the top location context the same as the one for the new location? 1085 if (TopContextLoc == CLoc) { 1086 if (alwaysAdd) { 1087 if (IsConsumedExpr(TopContextLoc)) 1088 TopContextLoc.markDead(); 1089 1090 rawAddEdge(NewLoc); 1091 } 1092 1093 if (IsPostJump) 1094 TopContextLoc.markDead(); 1095 return; 1096 } 1097 1098 if (containsLocation(TopContextLoc, CLoc)) { 1099 if (alwaysAdd) { 1100 rawAddEdge(NewLoc); 1101 1102 if (IsConsumedExpr(CLoc)) { 1103 CLocs.push_back(ContextLocation(CLoc, /*IsDead=*/true)); 1104 return; 1105 } 1106 } 1107 1108 CLocs.push_back(ContextLocation(CLoc, /*IsDead=*/IsPostJump)); 1109 return; 1110 } 1111 1112 // Context does not contain the location. Flush it. 1113 popLocation(); 1114 } 1115 1116 // If we reach here, there is no enclosing context. Just add the edge. 1117 rawAddEdge(NewLoc); 1118} 1119 1120bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) { 1121 if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt())) 1122 return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X); 1123 1124 return false; 1125} 1126 1127void EdgeBuilder::addExtendedContext(const Stmt *S) { 1128 if (!S) 1129 return; 1130 1131 const Stmt *Parent = PDB.getParent(S); 1132 while (Parent) { 1133 if (isa<CompoundStmt>(Parent)) 1134 Parent = PDB.getParent(Parent); 1135 else 1136 break; 1137 } 1138 1139 if (Parent) { 1140 switch (Parent->getStmtClass()) { 1141 case Stmt::DoStmtClass: 1142 case Stmt::ObjCAtSynchronizedStmtClass: 1143 addContext(Parent); 1144 default: 1145 break; 1146 } 1147 } 1148 1149 addContext(S); 1150} 1151 1152void EdgeBuilder::addContext(const Stmt *S) { 1153 if (!S) 1154 return; 1155 1156 PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.LC); 1157 addContext(L); 1158} 1159 1160void EdgeBuilder::addContext(const PathDiagnosticLocation &L) { 1161 while (!CLocs.empty()) { 1162 const PathDiagnosticLocation &TopContextLoc = CLocs.back(); 1163 1164 // Is the top location context the same as the one for the new location? 1165 if (TopContextLoc == L) 1166 return; 1167 1168 if (containsLocation(TopContextLoc, L)) { 1169 CLocs.push_back(L); 1170 return; 1171 } 1172 1173 // Context does not contain the location. Flush it. 1174 popLocation(); 1175 } 1176 1177 CLocs.push_back(L); 1178} 1179 1180// Cone-of-influence: support the reverse propagation of "interesting" symbols 1181// and values by tracing interesting calculations backwards through evaluated 1182// expressions along a path. This is probably overly complicated, but the idea 1183// is that if an expression computed an "interesting" value, the child 1184// expressions are are also likely to be "interesting" as well (which then 1185// propagates to the values they in turn compute). This reverse propagation 1186// is needed to track interesting correlations across function call boundaries, 1187// where formal arguments bind to actual arguments, etc. This is also needed 1188// because the constraint solver sometimes simplifies certain symbolic values 1189// into constants when appropriate, and this complicates reasoning about 1190// interesting values. 1191typedef llvm::DenseSet<const Expr *> InterestingExprs; 1192 1193static void reversePropagateIntererstingSymbols(BugReport &R, 1194 InterestingExprs &IE, 1195 const ProgramState *State, 1196 const Expr *Ex, 1197 const LocationContext *LCtx) { 1198 SVal V = State->getSVal(Ex, LCtx); 1199 if (!(R.isInteresting(V) || IE.count(Ex))) 1200 return; 1201 1202 switch (Ex->getStmtClass()) { 1203 default: 1204 if (!isa<CastExpr>(Ex)) 1205 break; 1206 // Fall through. 1207 case Stmt::BinaryOperatorClass: 1208 case Stmt::UnaryOperatorClass: { 1209 for (Stmt::const_child_iterator CI = Ex->child_begin(), 1210 CE = Ex->child_end(); 1211 CI != CE; ++CI) { 1212 if (const Expr *child = dyn_cast_or_null<Expr>(*CI)) { 1213 IE.insert(child); 1214 SVal ChildV = State->getSVal(child, LCtx); 1215 R.markInteresting(ChildV); 1216 } 1217 break; 1218 } 1219 } 1220 } 1221 1222 R.markInteresting(V); 1223} 1224 1225static void reversePropagateInterestingSymbols(BugReport &R, 1226 InterestingExprs &IE, 1227 const ProgramState *State, 1228 const LocationContext *CalleeCtx, 1229 const LocationContext *CallerCtx) 1230{ 1231 // FIXME: Handle non-CallExpr-based CallEvents. 1232 const StackFrameContext *Callee = CalleeCtx->getCurrentStackFrame(); 1233 const Stmt *CallSite = Callee->getCallSite(); 1234 if (const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite)) { 1235 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeCtx->getDecl())) { 1236 FunctionDecl::param_const_iterator PI = FD->param_begin(), 1237 PE = FD->param_end(); 1238 CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end(); 1239 for (; AI != AE && PI != PE; ++AI, ++PI) { 1240 if (const Expr *ArgE = *AI) { 1241 if (const ParmVarDecl *PD = *PI) { 1242 Loc LV = State->getLValue(PD, CalleeCtx); 1243 if (R.isInteresting(LV) || R.isInteresting(State->getRawSVal(LV))) 1244 IE.insert(ArgE); 1245 } 1246 } 1247 } 1248 } 1249 } 1250} 1251 1252//===----------------------------------------------------------------------===// 1253// Functions for determining if a loop was executed 0 times. 1254//===----------------------------------------------------------------------===// 1255 1256static bool isLoop(const Stmt *Term) { 1257 switch (Term->getStmtClass()) { 1258 case Stmt::ForStmtClass: 1259 case Stmt::WhileStmtClass: 1260 case Stmt::ObjCForCollectionStmtClass: 1261 case Stmt::CXXForRangeStmtClass: 1262 return true; 1263 default: 1264 // Note that we intentionally do not include do..while here. 1265 return false; 1266 } 1267} 1268 1269static bool isJumpToFalseBranch(const BlockEdge *BE) { 1270 const CFGBlock *Src = BE->getSrc(); 1271 assert(Src->succ_size() == 2); 1272 return (*(Src->succ_begin()+1) == BE->getDst()); 1273} 1274 1275/// Return true if the terminator is a loop and the destination is the 1276/// false branch. 1277static bool isLoopJumpPastBody(const Stmt *Term, const BlockEdge *BE) { 1278 if (!isLoop(Term)) 1279 return false; 1280 1281 // Did we take the false branch? 1282 return isJumpToFalseBranch(BE); 1283} 1284 1285static bool isContainedByStmt(ParentMap &PM, const Stmt *S, const Stmt *SubS) { 1286 while (SubS) { 1287 if (SubS == S) 1288 return true; 1289 SubS = PM.getParent(SubS); 1290 } 1291 return false; 1292} 1293 1294static const Stmt *getStmtBeforeCond(ParentMap &PM, const Stmt *Term, 1295 const ExplodedNode *N) { 1296 while (N) { 1297 Optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>(); 1298 if (SP) { 1299 const Stmt *S = SP->getStmt(); 1300 if (!isContainedByStmt(PM, Term, S)) 1301 return S; 1302 } 1303 N = N->getFirstPred(); 1304 } 1305 return 0; 1306} 1307 1308static bool isInLoopBody(ParentMap &PM, const Stmt *S, const Stmt *Term) { 1309 const Stmt *LoopBody = 0; 1310 switch (Term->getStmtClass()) { 1311 case Stmt::CXXForRangeStmtClass: { 1312 const CXXForRangeStmt *FR = cast<CXXForRangeStmt>(Term); 1313 if (isContainedByStmt(PM, FR->getInc(), S)) 1314 return true; 1315 if (isContainedByStmt(PM, FR->getLoopVarStmt(), S)) 1316 return true; 1317 LoopBody = FR->getBody(); 1318 break; 1319 } 1320 case Stmt::ForStmtClass: { 1321 const ForStmt *FS = cast<ForStmt>(Term); 1322 if (isContainedByStmt(PM, FS->getInc(), S)) 1323 return true; 1324 LoopBody = FS->getBody(); 1325 break; 1326 } 1327 case Stmt::ObjCForCollectionStmtClass: { 1328 const ObjCForCollectionStmt *FC = cast<ObjCForCollectionStmt>(Term); 1329 LoopBody = FC->getBody(); 1330 break; 1331 } 1332 case Stmt::WhileStmtClass: 1333 LoopBody = cast<WhileStmt>(Term)->getBody(); 1334 break; 1335 default: 1336 return false; 1337 } 1338 return isContainedByStmt(PM, LoopBody, S); 1339} 1340 1341//===----------------------------------------------------------------------===// 1342// Top-level logic for generating extensive path diagnostics. 1343//===----------------------------------------------------------------------===// 1344 1345static bool GenerateExtensivePathDiagnostic(PathDiagnostic& PD, 1346 PathDiagnosticBuilder &PDB, 1347 const ExplodedNode *N, 1348 LocationContextMap &LCM, 1349 ArrayRef<BugReporterVisitor *> visitors) { 1350 EdgeBuilder EB(PD, PDB); 1351 const SourceManager& SM = PDB.getSourceManager(); 1352 StackDiagVector CallStack; 1353 InterestingExprs IE; 1354 1355 const ExplodedNode *NextNode = N->pred_empty() ? NULL : *(N->pred_begin()); 1356 while (NextNode) { 1357 N = NextNode; 1358 NextNode = N->getFirstPred(); 1359 ProgramPoint P = N->getLocation(); 1360 1361 do { 1362 if (Optional<PostStmt> PS = P.getAs<PostStmt>()) { 1363 if (const Expr *Ex = PS->getStmtAs<Expr>()) 1364 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE, 1365 N->getState().getPtr(), Ex, 1366 N->getLocationContext()); 1367 } 1368 1369 if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) { 1370 const Stmt *S = CE->getCalleeContext()->getCallSite(); 1371 if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) { 1372 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE, 1373 N->getState().getPtr(), Ex, 1374 N->getLocationContext()); 1375 } 1376 1377 PathDiagnosticCallPiece *C = 1378 PathDiagnosticCallPiece::construct(N, *CE, SM); 1379 LCM[&C->path] = CE->getCalleeContext(); 1380 1381 EB.addEdge(C->callReturn, /*AlwaysAdd=*/true, /*IsPostJump=*/true); 1382 EB.flushLocations(); 1383 1384 PD.getActivePath().push_front(C); 1385 PD.pushActivePath(&C->path); 1386 CallStack.push_back(StackDiagPair(C, N)); 1387 break; 1388 } 1389 1390 // Pop the call hierarchy if we are done walking the contents 1391 // of a function call. 1392 if (Optional<CallEnter> CE = P.getAs<CallEnter>()) { 1393 // Add an edge to the start of the function. 1394 const Decl *D = CE->getCalleeContext()->getDecl(); 1395 PathDiagnosticLocation pos = 1396 PathDiagnosticLocation::createBegin(D, SM); 1397 EB.addEdge(pos); 1398 1399 // Flush all locations, and pop the active path. 1400 bool VisitedEntireCall = PD.isWithinCall(); 1401 EB.flushLocations(); 1402 PD.popActivePath(); 1403 PDB.LC = N->getLocationContext(); 1404 1405 // Either we just added a bunch of stuff to the top-level path, or 1406 // we have a previous CallExitEnd. If the former, it means that the 1407 // path terminated within a function call. We must then take the 1408 // current contents of the active path and place it within 1409 // a new PathDiagnosticCallPiece. 1410 PathDiagnosticCallPiece *C; 1411 if (VisitedEntireCall) { 1412 C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front()); 1413 } else { 1414 const Decl *Caller = CE->getLocationContext()->getDecl(); 1415 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller); 1416 LCM[&C->path] = CE->getCalleeContext(); 1417 } 1418 1419 C->setCallee(*CE, SM); 1420 EB.addContext(C->getLocation()); 1421 1422 if (!CallStack.empty()) { 1423 assert(CallStack.back().first == C); 1424 CallStack.pop_back(); 1425 } 1426 break; 1427 } 1428 1429 // Note that is important that we update the LocationContext 1430 // after looking at CallExits. CallExit basically adds an 1431 // edge in the *caller*, so we don't want to update the LocationContext 1432 // too soon. 1433 PDB.LC = N->getLocationContext(); 1434 1435 // Block edges. 1436 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) { 1437 // Does this represent entering a call? If so, look at propagating 1438 // interesting symbols across call boundaries. 1439 if (NextNode) { 1440 const LocationContext *CallerCtx = NextNode->getLocationContext(); 1441 const LocationContext *CalleeCtx = PDB.LC; 1442 if (CallerCtx != CalleeCtx) { 1443 reversePropagateInterestingSymbols(*PDB.getBugReport(), IE, 1444 N->getState().getPtr(), 1445 CalleeCtx, CallerCtx); 1446 } 1447 } 1448 1449 // Are we jumping to the head of a loop? Add a special diagnostic. 1450 if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) { 1451 PathDiagnosticLocation L(Loop, SM, PDB.LC); 1452 const CompoundStmt *CS = NULL; 1453 1454 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop)) 1455 CS = dyn_cast<CompoundStmt>(FS->getBody()); 1456 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop)) 1457 CS = dyn_cast<CompoundStmt>(WS->getBody()); 1458 1459 PathDiagnosticEventPiece *p = 1460 new PathDiagnosticEventPiece(L, 1461 "Looping back to the head of the loop"); 1462 p->setPrunable(true); 1463 1464 EB.addEdge(p->getLocation(), true); 1465 PD.getActivePath().push_front(p); 1466 1467 if (CS) { 1468 PathDiagnosticLocation BL = 1469 PathDiagnosticLocation::createEndBrace(CS, SM); 1470 EB.addEdge(BL); 1471 } 1472 } 1473 1474 const CFGBlock *BSrc = BE->getSrc(); 1475 ParentMap &PM = PDB.getParentMap(); 1476 1477 if (const Stmt *Term = BSrc->getTerminator()) { 1478 // Are we jumping past the loop body without ever executing the 1479 // loop (because the condition was false)? 1480 if (isLoopJumpPastBody(Term, &*BE) && 1481 !isInLoopBody(PM, 1482 getStmtBeforeCond(PM, 1483 BSrc->getTerminatorCondition(), 1484 N), 1485 Term)) { 1486 PathDiagnosticLocation L(Term, SM, PDB.LC); 1487 PathDiagnosticEventPiece *PE = 1488 new PathDiagnosticEventPiece(L, "Loop body executed 0 times"); 1489 PE->setPrunable(true); 1490 1491 EB.addEdge(PE->getLocation(), true); 1492 PD.getActivePath().push_front(PE); 1493 } 1494 1495 // In any case, add the terminator as the current statement 1496 // context for control edges. 1497 EB.addContext(Term); 1498 } 1499 1500 break; 1501 } 1502 1503 if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) { 1504 Optional<CFGElement> First = BE->getFirstElement(); 1505 if (Optional<CFGStmt> S = First ? First->getAs<CFGStmt>() : None) { 1506 const Stmt *stmt = S->getStmt(); 1507 if (IsControlFlowExpr(stmt)) { 1508 // Add the proper context for '&&', '||', and '?'. 1509 EB.addContext(stmt); 1510 } 1511 else 1512 EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt()); 1513 } 1514 1515 break; 1516 } 1517 1518 1519 } while (0); 1520 1521 if (!NextNode) 1522 continue; 1523 1524 // Add pieces from custom visitors. 1525 BugReport *R = PDB.getBugReport(); 1526 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(), 1527 E = visitors.end(); 1528 I != E; ++I) { 1529 if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) { 1530 const PathDiagnosticLocation &Loc = p->getLocation(); 1531 EB.addEdge(Loc, true); 1532 PD.getActivePath().push_front(p); 1533 updateStackPiecesWithMessage(p, CallStack); 1534 1535 if (const Stmt *S = Loc.asStmt()) 1536 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt()); 1537 } 1538 } 1539 } 1540 1541 return PDB.getBugReport()->isValid(); 1542} 1543 1544/// \brief Adds a sanitized control-flow diagnostic edge to a path. 1545static void addEdgeToPath(PathPieces &path, 1546 PathDiagnosticLocation &PrevLoc, 1547 PathDiagnosticLocation NewLoc, 1548 const LocationContext *LC) { 1549 if (!NewLoc.isValid()) 1550 return; 1551 1552 SourceLocation NewLocL = NewLoc.asLocation(); 1553 if (NewLocL.isInvalid() || NewLocL.isMacroID()) 1554 return; 1555 1556 if (!PrevLoc.isValid() || !PrevLoc.asLocation().isValid()) { 1557 PrevLoc = NewLoc; 1558 return; 1559 } 1560 1561 // Ignore self-edges, which occur when there are multiple nodes at the same 1562 // statement. 1563 if (NewLoc.asStmt() && NewLoc.asStmt() == PrevLoc.asStmt()) 1564 return; 1565 1566 path.push_front(new PathDiagnosticControlFlowPiece(NewLoc, 1567 PrevLoc)); 1568 PrevLoc = NewLoc; 1569} 1570 1571/// A customized wrapper for CFGBlock::getTerminatorCondition() 1572/// which returns the element for ObjCForCollectionStmts. 1573static const Stmt *getTerminatorCondition(const CFGBlock *B) { 1574 const Stmt *S = B->getTerminatorCondition(); 1575 if (const ObjCForCollectionStmt *FS = 1576 dyn_cast_or_null<ObjCForCollectionStmt>(S)) 1577 return FS->getElement(); 1578 return S; 1579} 1580 1581static const char *StrEnteringLoop = "Entering loop body"; 1582static const char *StrLoopBodyZero = "Loop body executed 0 times"; 1583 1584static bool 1585GenerateAlternateExtensivePathDiagnostic(PathDiagnostic& PD, 1586 PathDiagnosticBuilder &PDB, 1587 const ExplodedNode *N, 1588 LocationContextMap &LCM, 1589 ArrayRef<BugReporterVisitor *> visitors) { 1590 1591 BugReport *report = PDB.getBugReport(); 1592 const SourceManager& SM = PDB.getSourceManager(); 1593 StackDiagVector CallStack; 1594 InterestingExprs IE; 1595 1596 PathDiagnosticLocation PrevLoc = PD.getLocation(); 1597 1598 const ExplodedNode *NextNode = N->getFirstPred(); 1599 while (NextNode) { 1600 N = NextNode; 1601 NextNode = N->getFirstPred(); 1602 ProgramPoint P = N->getLocation(); 1603 1604 do { 1605 // Have we encountered an entrance to a call? It may be 1606 // the case that we have not encountered a matching 1607 // call exit before this point. This means that the path 1608 // terminated within the call itself. 1609 if (Optional<CallEnter> CE = P.getAs<CallEnter>()) { 1610 // Add an edge to the start of the function. 1611 const StackFrameContext *CalleeLC = CE->getCalleeContext(); 1612 const Decl *D = CalleeLC->getDecl(); 1613 addEdgeToPath(PD.getActivePath(), PrevLoc, 1614 PathDiagnosticLocation::createBegin(D, SM), 1615 CalleeLC); 1616 1617 // Did we visit an entire call? 1618 bool VisitedEntireCall = PD.isWithinCall(); 1619 PD.popActivePath(); 1620 1621 PathDiagnosticCallPiece *C; 1622 if (VisitedEntireCall) { 1623 PathDiagnosticPiece *P = PD.getActivePath().front().getPtr(); 1624 C = cast<PathDiagnosticCallPiece>(P); 1625 } else { 1626 const Decl *Caller = CE->getLocationContext()->getDecl(); 1627 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller); 1628 1629 // Since we just transferred the path over to the call piece, 1630 // reset the mapping from active to location context. 1631 assert(PD.getActivePath().size() == 1 && 1632 PD.getActivePath().front() == C); 1633 LCM[&PD.getActivePath()] = 0; 1634 1635 // Record the location context mapping for the path within 1636 // the call. 1637 assert(LCM[&C->path] == 0 || 1638 LCM[&C->path] == CE->getCalleeContext()); 1639 LCM[&C->path] = CE->getCalleeContext(); 1640 1641 // If this is the first item in the active path, record 1642 // the new mapping from active path to location context. 1643 const LocationContext *&NewLC = LCM[&PD.getActivePath()]; 1644 if (!NewLC) 1645 NewLC = N->getLocationContext(); 1646 1647 PDB.LC = NewLC; 1648 } 1649 C->setCallee(*CE, SM); 1650 1651 // Update the previous location in the active path. 1652 PrevLoc = C->getLocation(); 1653 1654 if (!CallStack.empty()) { 1655 assert(CallStack.back().first == C); 1656 CallStack.pop_back(); 1657 } 1658 break; 1659 } 1660 1661 // Query the location context here and the previous location 1662 // as processing CallEnter may change the active path. 1663 PDB.LC = N->getLocationContext(); 1664 1665 // Record the mapping from the active path to the location 1666 // context. 1667 assert(!LCM[&PD.getActivePath()] || 1668 LCM[&PD.getActivePath()] == PDB.LC); 1669 LCM[&PD.getActivePath()] = PDB.LC; 1670 1671 // Have we encountered an exit from a function call? 1672 if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) { 1673 const Stmt *S = CE->getCalleeContext()->getCallSite(); 1674 // Propagate the interesting symbols accordingly. 1675 if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) { 1676 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE, 1677 N->getState().getPtr(), Ex, 1678 N->getLocationContext()); 1679 } 1680 1681 // We are descending into a call (backwards). Construct 1682 // a new call piece to contain the path pieces for that call. 1683 PathDiagnosticCallPiece *C = 1684 PathDiagnosticCallPiece::construct(N, *CE, SM); 1685 1686 // Record the location context for this call piece. 1687 LCM[&C->path] = CE->getCalleeContext(); 1688 1689 // Add the edge to the return site. 1690 addEdgeToPath(PD.getActivePath(), PrevLoc, C->callReturn, PDB.LC); 1691 PD.getActivePath().push_front(C); 1692 PrevLoc.invalidate(); 1693 1694 // Make the contents of the call the active path for now. 1695 PD.pushActivePath(&C->path); 1696 CallStack.push_back(StackDiagPair(C, N)); 1697 break; 1698 } 1699 1700 if (Optional<PostStmt> PS = P.getAs<PostStmt>()) { 1701 // For expressions, make sure we propagate the 1702 // interesting symbols correctly. 1703 if (const Expr *Ex = PS->getStmtAs<Expr>()) 1704 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE, 1705 N->getState().getPtr(), Ex, 1706 N->getLocationContext()); 1707 1708 // Add an edge. If this is an ObjCForCollectionStmt do 1709 // not add an edge here as it appears in the CFG both 1710 // as a terminator and as a terminator condition. 1711 if (!isa<ObjCForCollectionStmt>(PS->getStmt())) { 1712 PathDiagnosticLocation L = 1713 PathDiagnosticLocation(PS->getStmt(), SM, PDB.LC); 1714 addEdgeToPath(PD.getActivePath(), PrevLoc, L, PDB.LC); 1715 } 1716 break; 1717 } 1718 1719 // Block edges. 1720 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) { 1721 // Does this represent entering a call? If so, look at propagating 1722 // interesting symbols across call boundaries. 1723 if (NextNode) { 1724 const LocationContext *CallerCtx = NextNode->getLocationContext(); 1725 const LocationContext *CalleeCtx = PDB.LC; 1726 if (CallerCtx != CalleeCtx) { 1727 reversePropagateInterestingSymbols(*PDB.getBugReport(), IE, 1728 N->getState().getPtr(), 1729 CalleeCtx, CallerCtx); 1730 } 1731 } 1732 1733 // Are we jumping to the head of a loop? Add a special diagnostic. 1734 if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) { 1735 PathDiagnosticLocation L(Loop, SM, PDB.LC); 1736 const Stmt *Body = NULL; 1737 1738 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop)) 1739 Body = FS->getBody(); 1740 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop)) 1741 Body = WS->getBody(); 1742 else if (const ObjCForCollectionStmt *OFS = 1743 dyn_cast<ObjCForCollectionStmt>(Loop)) { 1744 Body = OFS->getBody(); 1745 } else if (const CXXForRangeStmt *FRS = 1746 dyn_cast<CXXForRangeStmt>(Loop)) { 1747 Body = FRS->getBody(); 1748 } 1749 // do-while statements are explicitly excluded here 1750 1751 PathDiagnosticEventPiece *p = 1752 new PathDiagnosticEventPiece(L, "Looping back to the head " 1753 "of the loop"); 1754 p->setPrunable(true); 1755 1756 addEdgeToPath(PD.getActivePath(), PrevLoc, p->getLocation(), PDB.LC); 1757 PD.getActivePath().push_front(p); 1758 1759 if (const CompoundStmt *CS = dyn_cast_or_null<CompoundStmt>(Body)) { 1760 addEdgeToPath(PD.getActivePath(), PrevLoc, 1761 PathDiagnosticLocation::createEndBrace(CS, SM), 1762 PDB.LC); 1763 } 1764 } 1765 1766 const CFGBlock *BSrc = BE->getSrc(); 1767 ParentMap &PM = PDB.getParentMap(); 1768 1769 if (const Stmt *Term = BSrc->getTerminator()) { 1770 // Are we jumping past the loop body without ever executing the 1771 // loop (because the condition was false)? 1772 if (isLoop(Term)) { 1773 const Stmt *TermCond = getTerminatorCondition(BSrc); 1774 bool IsInLoopBody = 1775 isInLoopBody(PM, getStmtBeforeCond(PM, TermCond, N), Term); 1776 1777 const char *str = 0; 1778 1779 if (isJumpToFalseBranch(&*BE)) { 1780 if (!IsInLoopBody) { 1781 str = StrLoopBodyZero; 1782 } 1783 } 1784 else { 1785 str = StrEnteringLoop; 1786 } 1787 1788 if (str) { 1789 PathDiagnosticLocation L(TermCond ? TermCond : Term, SM, PDB.LC); 1790 PathDiagnosticEventPiece *PE = 1791 new PathDiagnosticEventPiece(L, str); 1792 PE->setPrunable(true); 1793 addEdgeToPath(PD.getActivePath(), PrevLoc, 1794 PE->getLocation(), PDB.LC); 1795 PD.getActivePath().push_front(PE); 1796 } 1797 } 1798 else if (isa<BreakStmt>(Term) || isa<ContinueStmt>(Term) || 1799 isa<GotoStmt>(Term)) { 1800 PathDiagnosticLocation L(Term, SM, PDB.LC); 1801 addEdgeToPath(PD.getActivePath(), PrevLoc, L, PDB.LC); 1802 } 1803 } 1804 break; 1805 } 1806 } while (0); 1807 1808 if (!NextNode) 1809 continue; 1810 1811 // Add pieces from custom visitors. 1812 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(), 1813 E = visitors.end(); 1814 I != E; ++I) { 1815 if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *report)) { 1816 addEdgeToPath(PD.getActivePath(), PrevLoc, p->getLocation(), PDB.LC); 1817 PD.getActivePath().push_front(p); 1818 updateStackPiecesWithMessage(p, CallStack); 1819 } 1820 } 1821 } 1822 1823 // Add an edge to the start of the function. 1824 // We'll prune it out later, but it helps make diagnostics more uniform. 1825 const StackFrameContext *CalleeLC = PDB.LC->getCurrentStackFrame(); 1826 const Decl *D = CalleeLC->getDecl(); 1827 addEdgeToPath(PD.getActivePath(), PrevLoc, 1828 PathDiagnosticLocation::createBegin(D, SM), 1829 CalleeLC); 1830 1831 return report->isValid(); 1832} 1833 1834static const Stmt *getLocStmt(PathDiagnosticLocation L) { 1835 if (!L.isValid()) 1836 return 0; 1837 return L.asStmt(); 1838} 1839 1840static const Stmt *getStmtParent(const Stmt *S, const ParentMap &PM) { 1841 if (!S) 1842 return 0; 1843 1844 while (true) { 1845 S = PM.getParentIgnoreParens(S); 1846 1847 if (!S) 1848 break; 1849 1850 if (isa<ExprWithCleanups>(S) || 1851 isa<CXXBindTemporaryExpr>(S) || 1852 isa<SubstNonTypeTemplateParmExpr>(S)) 1853 continue; 1854 1855 break; 1856 } 1857 1858 return S; 1859} 1860 1861static bool isConditionForTerminator(const Stmt *S, const Stmt *Cond) { 1862 switch (S->getStmtClass()) { 1863 case Stmt::BinaryOperatorClass: { 1864 const BinaryOperator *BO = cast<BinaryOperator>(S); 1865 if (!BO->isLogicalOp()) 1866 return false; 1867 return BO->getLHS() == Cond || BO->getRHS() == Cond; 1868 } 1869 case Stmt::IfStmtClass: 1870 return cast<IfStmt>(S)->getCond() == Cond; 1871 case Stmt::ForStmtClass: 1872 return cast<ForStmt>(S)->getCond() == Cond; 1873 case Stmt::WhileStmtClass: 1874 return cast<WhileStmt>(S)->getCond() == Cond; 1875 case Stmt::DoStmtClass: 1876 return cast<DoStmt>(S)->getCond() == Cond; 1877 case Stmt::ChooseExprClass: 1878 return cast<ChooseExpr>(S)->getCond() == Cond; 1879 case Stmt::IndirectGotoStmtClass: 1880 return cast<IndirectGotoStmt>(S)->getTarget() == Cond; 1881 case Stmt::SwitchStmtClass: 1882 return cast<SwitchStmt>(S)->getCond() == Cond; 1883 case Stmt::BinaryConditionalOperatorClass: 1884 return cast<BinaryConditionalOperator>(S)->getCond() == Cond; 1885 case Stmt::ConditionalOperatorClass: { 1886 const ConditionalOperator *CO = cast<ConditionalOperator>(S); 1887 return CO->getCond() == Cond || 1888 CO->getLHS() == Cond || 1889 CO->getRHS() == Cond; 1890 } 1891 case Stmt::ObjCForCollectionStmtClass: 1892 return cast<ObjCForCollectionStmt>(S)->getElement() == Cond; 1893 case Stmt::CXXForRangeStmtClass: { 1894 const CXXForRangeStmt *FRS = cast<CXXForRangeStmt>(S); 1895 return FRS->getCond() == Cond || FRS->getRangeInit() == Cond; 1896 } 1897 default: 1898 return false; 1899 } 1900} 1901 1902static bool isIncrementOrInitInForLoop(const Stmt *S, const Stmt *FL) { 1903 if (const ForStmt *FS = dyn_cast<ForStmt>(FL)) 1904 return FS->getInc() == S || FS->getInit() == S; 1905 if (const CXXForRangeStmt *FRS = dyn_cast<CXXForRangeStmt>(FL)) 1906 return FRS->getInc() == S || FRS->getRangeStmt() == S || 1907 FRS->getLoopVarStmt() || FRS->getRangeInit() == S; 1908 return false; 1909} 1910 1911typedef llvm::DenseSet<const PathDiagnosticCallPiece *> 1912 OptimizedCallsSet; 1913 1914/// Adds synthetic edges from top-level statements to their subexpressions. 1915/// 1916/// This avoids a "swoosh" effect, where an edge from a top-level statement A 1917/// points to a sub-expression B.1 that's not at the start of B. In these cases, 1918/// we'd like to see an edge from A to B, then another one from B to B.1. 1919static void addContextEdges(PathPieces &pieces, SourceManager &SM, 1920 const ParentMap &PM, const LocationContext *LCtx) { 1921 PathPieces::iterator Prev = pieces.end(); 1922 for (PathPieces::iterator I = pieces.begin(), E = Prev; I != E; 1923 Prev = I, ++I) { 1924 PathDiagnosticControlFlowPiece *Piece = 1925 dyn_cast<PathDiagnosticControlFlowPiece>(*I); 1926 1927 if (!Piece) 1928 continue; 1929 1930 PathDiagnosticLocation SrcLoc = Piece->getStartLocation(); 1931 SmallVector<PathDiagnosticLocation, 4> SrcContexts; 1932 1933 PathDiagnosticLocation NextSrcContext = SrcLoc; 1934 const Stmt *InnerStmt = 0; 1935 while (NextSrcContext.isValid() && NextSrcContext.asStmt() != InnerStmt) { 1936 SrcContexts.push_back(NextSrcContext); 1937 InnerStmt = NextSrcContext.asStmt(); 1938 NextSrcContext = getEnclosingStmtLocation(InnerStmt, SM, PM, LCtx, 1939 /*allowNested=*/true); 1940 } 1941 1942 // Repeatedly split the edge as necessary. 1943 // This is important for nested logical expressions (||, &&, ?:) where we 1944 // want to show all the levels of context. 1945 while (true) { 1946 const Stmt *Dst = getLocStmt(Piece->getEndLocation()); 1947 1948 // We are looking at an edge. Is the destination within a larger 1949 // expression? 1950 PathDiagnosticLocation DstContext = 1951 getEnclosingStmtLocation(Dst, SM, PM, LCtx, /*allowNested=*/true); 1952 if (!DstContext.isValid() || DstContext.asStmt() == Dst) 1953 break; 1954 1955 // If the source is in the same context, we're already good. 1956 if (std::find(SrcContexts.begin(), SrcContexts.end(), DstContext) != 1957 SrcContexts.end()) 1958 break; 1959 1960 // Update the subexpression node to point to the context edge. 1961 Piece->setStartLocation(DstContext); 1962 1963 // Try to extend the previous edge if it's at the same level as the source 1964 // context. 1965 if (Prev != E) { 1966 PathDiagnosticControlFlowPiece *PrevPiece = 1967 dyn_cast<PathDiagnosticControlFlowPiece>(*Prev); 1968 1969 if (PrevPiece) { 1970 if (const Stmt *PrevSrc = getLocStmt(PrevPiece->getStartLocation())) { 1971 const Stmt *PrevSrcParent = getStmtParent(PrevSrc, PM); 1972 if (PrevSrcParent == getStmtParent(getLocStmt(DstContext), PM)) { 1973 PrevPiece->setEndLocation(DstContext); 1974 break; 1975 } 1976 } 1977 } 1978 } 1979 1980 // Otherwise, split the current edge into a context edge and a 1981 // subexpression edge. Note that the context statement may itself have 1982 // context. 1983 Piece = new PathDiagnosticControlFlowPiece(SrcLoc, DstContext); 1984 I = pieces.insert(I, Piece); 1985 } 1986 } 1987} 1988 1989/// \brief Move edges from a branch condition to a branch target 1990/// when the condition is simple. 1991/// 1992/// This restructures some of the work of addContextEdges. That function 1993/// creates edges this may destroy, but they work together to create a more 1994/// aesthetically set of edges around branches. After the call to 1995/// addContextEdges, we may have (1) an edge to the branch, (2) an edge from 1996/// the branch to the branch condition, and (3) an edge from the branch 1997/// condition to the branch target. We keep (1), but may wish to remove (2) 1998/// and move the source of (3) to the branch if the branch condition is simple. 1999/// 2000static void simplifySimpleBranches(PathPieces &pieces) { 2001 for (PathPieces::iterator I = pieces.begin(), E = pieces.end(); I != E; ++I) { 2002 2003 PathDiagnosticControlFlowPiece *PieceI = 2004 dyn_cast<PathDiagnosticControlFlowPiece>(*I); 2005 2006 if (!PieceI) 2007 continue; 2008 2009 const Stmt *s1Start = getLocStmt(PieceI->getStartLocation()); 2010 const Stmt *s1End = getLocStmt(PieceI->getEndLocation()); 2011 2012 if (!s1Start || !s1End) 2013 continue; 2014 2015 PathPieces::iterator NextI = I; ++NextI; 2016 if (NextI == E) 2017 break; 2018 2019 PathDiagnosticControlFlowPiece *PieceNextI = 0; 2020 2021 while (true) { 2022 if (NextI == E) 2023 break; 2024 2025 PathDiagnosticEventPiece *EV = dyn_cast<PathDiagnosticEventPiece>(*NextI); 2026 if (EV) { 2027 StringRef S = EV->getString(); 2028 if (S == StrEnteringLoop || S == StrLoopBodyZero) { 2029 ++NextI; 2030 continue; 2031 } 2032 break; 2033 } 2034 2035 PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(*NextI); 2036 break; 2037 } 2038 2039 if (!PieceNextI) 2040 continue; 2041 2042 const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation()); 2043 const Stmt *s2End = getLocStmt(PieceNextI->getEndLocation()); 2044 2045 if (!s2Start || !s2End || s1End != s2Start) 2046 continue; 2047 2048 // We only perform this transformation for specific branch kinds. 2049 // We don't want to do this for do..while, for example. 2050 if (!(isa<ForStmt>(s1Start) || isa<WhileStmt>(s1Start) || 2051 isa<IfStmt>(s1Start) || isa<ObjCForCollectionStmt>(s1Start) || 2052 isa<CXXForRangeStmt>(s1Start))) 2053 continue; 2054 2055 // Is s1End the branch condition? 2056 if (!isConditionForTerminator(s1Start, s1End)) 2057 continue; 2058 2059 // Perform the hoisting by eliminating (2) and changing the start 2060 // location of (3). 2061 PieceNextI->setStartLocation(PieceI->getStartLocation()); 2062 I = pieces.erase(I); 2063 } 2064} 2065 2066/// Returns the number of bytes in the given (character-based) SourceRange. 2067/// 2068/// If the locations in the range are not on the same line, returns None. 2069/// 2070/// Note that this does not do a precise user-visible character or column count. 2071static Optional<size_t> getLengthOnSingleLine(SourceManager &SM, 2072 SourceRange Range) { 2073 SourceRange ExpansionRange(SM.getExpansionLoc(Range.getBegin()), 2074 SM.getExpansionRange(Range.getEnd()).second); 2075 2076 FileID FID = SM.getFileID(ExpansionRange.getBegin()); 2077 if (FID != SM.getFileID(ExpansionRange.getEnd())) 2078 return None; 2079 2080 bool Invalid; 2081 const llvm::MemoryBuffer *Buffer = SM.getBuffer(FID, &Invalid); 2082 if (Invalid) 2083 return None; 2084 2085 unsigned BeginOffset = SM.getFileOffset(ExpansionRange.getBegin()); 2086 unsigned EndOffset = SM.getFileOffset(ExpansionRange.getEnd()); 2087 StringRef Snippet = Buffer->getBuffer().slice(BeginOffset, EndOffset); 2088 2089 // We're searching the raw bytes of the buffer here, which might include 2090 // escaped newlines and such. That's okay; we're trying to decide whether the 2091 // SourceRange is covering a large or small amount of space in the user's 2092 // editor. 2093 if (Snippet.find_first_of("\r\n") != StringRef::npos) 2094 return None; 2095 2096 // This isn't Unicode-aware, but it doesn't need to be. 2097 return Snippet.size(); 2098} 2099 2100/// \sa getLengthOnSingleLine(SourceManager, SourceRange) 2101static Optional<size_t> getLengthOnSingleLine(SourceManager &SM, 2102 const Stmt *S) { 2103 return getLengthOnSingleLine(SM, S->getSourceRange()); 2104} 2105 2106/// Eliminate two-edge cycles created by addContextEdges(). 2107/// 2108/// Once all the context edges are in place, there are plenty of cases where 2109/// there's a single edge from a top-level statement to a subexpression, 2110/// followed by a single path note, and then a reverse edge to get back out to 2111/// the top level. If the statement is simple enough, the subexpression edges 2112/// just add noise and make it harder to understand what's going on. 2113/// 2114/// This function only removes edges in pairs, because removing only one edge 2115/// might leave other edges dangling. 2116/// 2117/// This will not remove edges in more complicated situations: 2118/// - if there is more than one "hop" leading to or from a subexpression. 2119/// - if there is an inlined call between the edges instead of a single event. 2120/// - if the whole statement is large enough that having subexpression arrows 2121/// might be helpful. 2122static void removeContextCycles(PathPieces &Path, SourceManager &SM, 2123 ParentMap &PM) { 2124 for (PathPieces::iterator I = Path.begin(), E = Path.end(); I != E; ) { 2125 // Pattern match the current piece and its successor. 2126 PathDiagnosticControlFlowPiece *PieceI = 2127 dyn_cast<PathDiagnosticControlFlowPiece>(*I); 2128 2129 if (!PieceI) { 2130 ++I; 2131 continue; 2132 } 2133 2134 const Stmt *s1Start = getLocStmt(PieceI->getStartLocation()); 2135 const Stmt *s1End = getLocStmt(PieceI->getEndLocation()); 2136 2137 PathPieces::iterator NextI = I; ++NextI; 2138 if (NextI == E) 2139 break; 2140 2141 PathDiagnosticControlFlowPiece *PieceNextI = 2142 dyn_cast<PathDiagnosticControlFlowPiece>(*NextI); 2143 2144 if (!PieceNextI) { 2145 if (isa<PathDiagnosticEventPiece>(*NextI)) { 2146 ++NextI; 2147 if (NextI == E) 2148 break; 2149 PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(*NextI); 2150 } 2151 2152 if (!PieceNextI) { 2153 ++I; 2154 continue; 2155 } 2156 } 2157 2158 const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation()); 2159 const Stmt *s2End = getLocStmt(PieceNextI->getEndLocation()); 2160 2161 if (s1Start && s2Start && s1Start == s2End && s2Start == s1End) { 2162 const size_t MAX_SHORT_LINE_LENGTH = 80; 2163 Optional<size_t> s1Length = getLengthOnSingleLine(SM, s1Start); 2164 if (s1Length && *s1Length <= MAX_SHORT_LINE_LENGTH) { 2165 Optional<size_t> s2Length = getLengthOnSingleLine(SM, s2Start); 2166 if (s2Length && *s2Length <= MAX_SHORT_LINE_LENGTH) { 2167 Path.erase(I); 2168 I = Path.erase(NextI); 2169 continue; 2170 } 2171 } 2172 } 2173 2174 ++I; 2175 } 2176} 2177 2178/// \brief Return true if X is contained by Y. 2179static bool lexicalContains(ParentMap &PM, 2180 const Stmt *X, 2181 const Stmt *Y) { 2182 while (X) { 2183 if (X == Y) 2184 return true; 2185 X = PM.getParent(X); 2186 } 2187 return false; 2188} 2189 2190// Remove short edges on the same line less than 3 columns in difference. 2191static void removePunyEdges(PathPieces &path, 2192 SourceManager &SM, 2193 ParentMap &PM) { 2194 2195 bool erased = false; 2196 2197 for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; 2198 erased ? I : ++I) { 2199 2200 erased = false; 2201 2202 PathDiagnosticControlFlowPiece *PieceI = 2203 dyn_cast<PathDiagnosticControlFlowPiece>(*I); 2204 2205 if (!PieceI) 2206 continue; 2207 2208 const Stmt *start = getLocStmt(PieceI->getStartLocation()); 2209 const Stmt *end = getLocStmt(PieceI->getEndLocation()); 2210 2211 if (!start || !end) 2212 continue; 2213 2214 const Stmt *endParent = PM.getParent(end); 2215 if (!endParent) 2216 continue; 2217 2218 if (isConditionForTerminator(end, endParent)) 2219 continue; 2220 2221 SourceLocation FirstLoc = start->getLocStart(); 2222 SourceLocation SecondLoc = end->getLocStart(); 2223 2224 if (!SM.isFromSameFile(FirstLoc, SecondLoc)) 2225 continue; 2226 if (SM.isBeforeInTranslationUnit(SecondLoc, FirstLoc)) 2227 std::swap(SecondLoc, FirstLoc); 2228 2229 SourceRange EdgeRange(FirstLoc, SecondLoc); 2230 Optional<size_t> ByteWidth = getLengthOnSingleLine(SM, EdgeRange); 2231 2232 // If the statements are on different lines, continue. 2233 if (!ByteWidth) 2234 continue; 2235 2236 const size_t MAX_PUNY_EDGE_LENGTH = 2; 2237 if (*ByteWidth <= MAX_PUNY_EDGE_LENGTH) { 2238 // FIXME: There are enough /bytes/ between the endpoints of the edge, but 2239 // there might not be enough /columns/. A proper user-visible column count 2240 // is probably too expensive, though. 2241 I = path.erase(I); 2242 erased = true; 2243 continue; 2244 } 2245 } 2246} 2247 2248static void removeIdenticalEvents(PathPieces &path) { 2249 for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ++I) { 2250 PathDiagnosticEventPiece *PieceI = 2251 dyn_cast<PathDiagnosticEventPiece>(*I); 2252 2253 if (!PieceI) 2254 continue; 2255 2256 PathPieces::iterator NextI = I; ++NextI; 2257 if (NextI == E) 2258 return; 2259 2260 PathDiagnosticEventPiece *PieceNextI = 2261 dyn_cast<PathDiagnosticEventPiece>(*NextI); 2262 2263 if (!PieceNextI) 2264 continue; 2265 2266 // Erase the second piece if it has the same exact message text. 2267 if (PieceI->getString() == PieceNextI->getString()) { 2268 path.erase(NextI); 2269 } 2270 } 2271} 2272 2273static bool optimizeEdges(PathPieces &path, SourceManager &SM, 2274 OptimizedCallsSet &OCS, 2275 LocationContextMap &LCM) { 2276 bool hasChanges = false; 2277 const LocationContext *LC = LCM[&path]; 2278 assert(LC); 2279 ParentMap &PM = LC->getParentMap(); 2280 2281 for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ) { 2282 // Optimize subpaths. 2283 if (PathDiagnosticCallPiece *CallI = dyn_cast<PathDiagnosticCallPiece>(*I)){ 2284 // Record the fact that a call has been optimized so we only do the 2285 // effort once. 2286 if (!OCS.count(CallI)) { 2287 while (optimizeEdges(CallI->path, SM, OCS, LCM)) {} 2288 OCS.insert(CallI); 2289 } 2290 ++I; 2291 continue; 2292 } 2293 2294 // Pattern match the current piece and its successor. 2295 PathDiagnosticControlFlowPiece *PieceI = 2296 dyn_cast<PathDiagnosticControlFlowPiece>(*I); 2297 2298 if (!PieceI) { 2299 ++I; 2300 continue; 2301 } 2302 2303 const Stmt *s1Start = getLocStmt(PieceI->getStartLocation()); 2304 const Stmt *s1End = getLocStmt(PieceI->getEndLocation()); 2305 const Stmt *level1 = getStmtParent(s1Start, PM); 2306 const Stmt *level2 = getStmtParent(s1End, PM); 2307 2308 PathPieces::iterator NextI = I; ++NextI; 2309 if (NextI == E) 2310 break; 2311 2312 PathDiagnosticControlFlowPiece *PieceNextI = 2313 dyn_cast<PathDiagnosticControlFlowPiece>(*NextI); 2314 2315 if (!PieceNextI) { 2316 ++I; 2317 continue; 2318 } 2319 2320 const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation()); 2321 const Stmt *s2End = getLocStmt(PieceNextI->getEndLocation()); 2322 const Stmt *level3 = getStmtParent(s2Start, PM); 2323 const Stmt *level4 = getStmtParent(s2End, PM); 2324 2325 // Rule I. 2326 // 2327 // If we have two consecutive control edges whose end/begin locations 2328 // are at the same level (e.g. statements or top-level expressions within 2329 // a compound statement, or siblings share a single ancestor expression), 2330 // then merge them if they have no interesting intermediate event. 2331 // 2332 // For example: 2333 // 2334 // (1.1 -> 1.2) -> (1.2 -> 1.3) becomes (1.1 -> 1.3) because the common 2335 // parent is '1'. Here 'x.y.z' represents the hierarchy of statements. 2336 // 2337 // NOTE: this will be limited later in cases where we add barriers 2338 // to prevent this optimization. 2339 // 2340 if (level1 && level1 == level2 && level1 == level3 && level1 == level4) { 2341 PieceI->setEndLocation(PieceNextI->getEndLocation()); 2342 path.erase(NextI); 2343 hasChanges = true; 2344 continue; 2345 } 2346 2347 // Rule II. 2348 // 2349 // Eliminate edges between subexpressions and parent expressions 2350 // when the subexpression is consumed. 2351 // 2352 // NOTE: this will be limited later in cases where we add barriers 2353 // to prevent this optimization. 2354 // 2355 if (s1End && s1End == s2Start && level2) { 2356 bool removeEdge = false; 2357 // Remove edges into the increment or initialization of a 2358 // loop that have no interleaving event. This means that 2359 // they aren't interesting. 2360 if (isIncrementOrInitInForLoop(s1End, level2)) 2361 removeEdge = true; 2362 // Next only consider edges that are not anchored on 2363 // the condition of a terminator. This are intermediate edges 2364 // that we might want to trim. 2365 else if (!isConditionForTerminator(level2, s1End)) { 2366 // Trim edges on expressions that are consumed by 2367 // the parent expression. 2368 if (isa<Expr>(s1End) && PM.isConsumedExpr(cast<Expr>(s1End))) { 2369 removeEdge = true; 2370 } 2371 // Trim edges where a lexical containment doesn't exist. 2372 // For example: 2373 // 2374 // X -> Y -> Z 2375 // 2376 // If 'Z' lexically contains Y (it is an ancestor) and 2377 // 'X' does not lexically contain Y (it is a descendant OR 2378 // it has no lexical relationship at all) then trim. 2379 // 2380 // This can eliminate edges where we dive into a subexpression 2381 // and then pop back out, etc. 2382 else if (s1Start && s2End && 2383 lexicalContains(PM, s2Start, s2End) && 2384 !lexicalContains(PM, s1End, s1Start)) { 2385 removeEdge = true; 2386 } 2387 // Trim edges from a subexpression back to the top level if the 2388 // subexpression is on a different line. 2389 // 2390 // A.1 -> A -> B 2391 // becomes 2392 // A.1 -> B 2393 // 2394 // These edges just look ugly and don't usually add anything. 2395 else if (s1Start && s2End && 2396 lexicalContains(PM, s1Start, s1End)) { 2397 SourceRange EdgeRange(PieceI->getEndLocation().asLocation(), 2398 PieceI->getStartLocation().asLocation()); 2399 if (!getLengthOnSingleLine(SM, EdgeRange).hasValue()) 2400 removeEdge = true; 2401 } 2402 } 2403 2404 if (removeEdge) { 2405 PieceI->setEndLocation(PieceNextI->getEndLocation()); 2406 path.erase(NextI); 2407 hasChanges = true; 2408 continue; 2409 } 2410 } 2411 2412 // Optimize edges for ObjC fast-enumeration loops. 2413 // 2414 // (X -> collection) -> (collection -> element) 2415 // 2416 // becomes: 2417 // 2418 // (X -> element) 2419 if (s1End == s2Start) { 2420 const ObjCForCollectionStmt *FS = 2421 dyn_cast_or_null<ObjCForCollectionStmt>(level3); 2422 if (FS && FS->getCollection()->IgnoreParens() == s2Start && 2423 s2End == FS->getElement()) { 2424 PieceI->setEndLocation(PieceNextI->getEndLocation()); 2425 path.erase(NextI); 2426 hasChanges = true; 2427 continue; 2428 } 2429 } 2430 2431 // No changes at this index? Move to the next one. 2432 ++I; 2433 } 2434 2435 if (!hasChanges) { 2436 // Adjust edges into subexpressions to make them more uniform 2437 // and aesthetically pleasing. 2438 addContextEdges(path, SM, PM, LC); 2439 // Remove "cyclical" edges that include one or more context edges. 2440 removeContextCycles(path, SM, PM); 2441 // Hoist edges originating from branch conditions to branches 2442 // for simple branches. 2443 simplifySimpleBranches(path); 2444 // Remove any puny edges left over after primary optimization pass. 2445 removePunyEdges(path, SM, PM); 2446 // Remove identical events. 2447 removeIdenticalEvents(path); 2448 } 2449 2450 return hasChanges; 2451} 2452 2453/// Drop the very first edge in a path, which should be a function entry edge. 2454/// 2455/// If the first edge is not a function entry edge (say, because the first 2456/// statement had an invalid source location), this function does nothing. 2457// FIXME: We should just generate invalid edges anyway and have the optimizer 2458// deal with them. 2459static void dropFunctionEntryEdge(PathPieces &Path, 2460 LocationContextMap &LCM, 2461 SourceManager &SM) { 2462 const PathDiagnosticControlFlowPiece *FirstEdge = 2463 dyn_cast<PathDiagnosticControlFlowPiece>(Path.front()); 2464 if (!FirstEdge) 2465 return; 2466 2467 const Decl *D = LCM[&Path]->getDecl(); 2468 PathDiagnosticLocation EntryLoc = PathDiagnosticLocation::createBegin(D, SM); 2469 if (FirstEdge->getStartLocation() != EntryLoc) 2470 return; 2471 2472 Path.pop_front(); 2473} 2474 2475 2476//===----------------------------------------------------------------------===// 2477// Methods for BugType and subclasses. 2478//===----------------------------------------------------------------------===// 2479BugType::~BugType() { } 2480 2481void BugType::FlushReports(BugReporter &BR) {} 2482 2483void BuiltinBug::anchor() {} 2484 2485//===----------------------------------------------------------------------===// 2486// Methods for BugReport and subclasses. 2487//===----------------------------------------------------------------------===// 2488 2489void BugReport::NodeResolver::anchor() {} 2490 2491void BugReport::addVisitor(BugReporterVisitor* visitor) { 2492 if (!visitor) 2493 return; 2494 2495 llvm::FoldingSetNodeID ID; 2496 visitor->Profile(ID); 2497 void *InsertPos; 2498 2499 if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) { 2500 delete visitor; 2501 return; 2502 } 2503 2504 CallbacksSet.InsertNode(visitor, InsertPos); 2505 Callbacks.push_back(visitor); 2506 ++ConfigurationChangeToken; 2507} 2508 2509BugReport::~BugReport() { 2510 for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I) { 2511 delete *I; 2512 } 2513 while (!interestingSymbols.empty()) { 2514 popInterestingSymbolsAndRegions(); 2515 } 2516} 2517 2518const Decl *BugReport::getDeclWithIssue() const { 2519 if (DeclWithIssue) 2520 return DeclWithIssue; 2521 2522 const ExplodedNode *N = getErrorNode(); 2523 if (!N) 2524 return 0; 2525 2526 const LocationContext *LC = N->getLocationContext(); 2527 return LC->getCurrentStackFrame()->getDecl(); 2528} 2529 2530void BugReport::Profile(llvm::FoldingSetNodeID& hash) const { 2531 hash.AddPointer(&BT); 2532 hash.AddString(Description); 2533 PathDiagnosticLocation UL = getUniqueingLocation(); 2534 if (UL.isValid()) { 2535 UL.Profile(hash); 2536 } else if (Location.isValid()) { 2537 Location.Profile(hash); 2538 } else { 2539 assert(ErrorNode); 2540 hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode)); 2541 } 2542 2543 for (SmallVectorImpl<SourceRange>::const_iterator I = 2544 Ranges.begin(), E = Ranges.end(); I != E; ++I) { 2545 const SourceRange range = *I; 2546 if (!range.isValid()) 2547 continue; 2548 hash.AddInteger(range.getBegin().getRawEncoding()); 2549 hash.AddInteger(range.getEnd().getRawEncoding()); 2550 } 2551} 2552 2553void BugReport::markInteresting(SymbolRef sym) { 2554 if (!sym) 2555 return; 2556 2557 // If the symbol wasn't already in our set, note a configuration change. 2558 if (getInterestingSymbols().insert(sym).second) 2559 ++ConfigurationChangeToken; 2560 2561 if (const SymbolMetadata *meta = dyn_cast<SymbolMetadata>(sym)) 2562 getInterestingRegions().insert(meta->getRegion()); 2563} 2564 2565void BugReport::markInteresting(const MemRegion *R) { 2566 if (!R) 2567 return; 2568 2569 // If the base region wasn't already in our set, note a configuration change. 2570 R = R->getBaseRegion(); 2571 if (getInterestingRegions().insert(R).second) 2572 ++ConfigurationChangeToken; 2573 2574 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) 2575 getInterestingSymbols().insert(SR->getSymbol()); 2576} 2577 2578void BugReport::markInteresting(SVal V) { 2579 markInteresting(V.getAsRegion()); 2580 markInteresting(V.getAsSymbol()); 2581} 2582 2583void BugReport::markInteresting(const LocationContext *LC) { 2584 if (!LC) 2585 return; 2586 InterestingLocationContexts.insert(LC); 2587} 2588 2589bool BugReport::isInteresting(SVal V) { 2590 return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol()); 2591} 2592 2593bool BugReport::isInteresting(SymbolRef sym) { 2594 if (!sym) 2595 return false; 2596 // We don't currently consider metadata symbols to be interesting 2597 // even if we know their region is interesting. Is that correct behavior? 2598 return getInterestingSymbols().count(sym); 2599} 2600 2601bool BugReport::isInteresting(const MemRegion *R) { 2602 if (!R) 2603 return false; 2604 R = R->getBaseRegion(); 2605 bool b = getInterestingRegions().count(R); 2606 if (b) 2607 return true; 2608 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) 2609 return getInterestingSymbols().count(SR->getSymbol()); 2610 return false; 2611} 2612 2613bool BugReport::isInteresting(const LocationContext *LC) { 2614 if (!LC) 2615 return false; 2616 return InterestingLocationContexts.count(LC); 2617} 2618 2619void BugReport::lazyInitializeInterestingSets() { 2620 if (interestingSymbols.empty()) { 2621 interestingSymbols.push_back(new Symbols()); 2622 interestingRegions.push_back(new Regions()); 2623 } 2624} 2625 2626BugReport::Symbols &BugReport::getInterestingSymbols() { 2627 lazyInitializeInterestingSets(); 2628 return *interestingSymbols.back(); 2629} 2630 2631BugReport::Regions &BugReport::getInterestingRegions() { 2632 lazyInitializeInterestingSets(); 2633 return *interestingRegions.back(); 2634} 2635 2636void BugReport::pushInterestingSymbolsAndRegions() { 2637 interestingSymbols.push_back(new Symbols(getInterestingSymbols())); 2638 interestingRegions.push_back(new Regions(getInterestingRegions())); 2639} 2640 2641void BugReport::popInterestingSymbolsAndRegions() { 2642 delete interestingSymbols.back(); 2643 interestingSymbols.pop_back(); 2644 delete interestingRegions.back(); 2645 interestingRegions.pop_back(); 2646} 2647 2648const Stmt *BugReport::getStmt() const { 2649 if (!ErrorNode) 2650 return 0; 2651 2652 ProgramPoint ProgP = ErrorNode->getLocation(); 2653 const Stmt *S = NULL; 2654 2655 if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) { 2656 CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit(); 2657 if (BE->getBlock() == &Exit) 2658 S = GetPreviousStmt(ErrorNode); 2659 } 2660 if (!S) 2661 S = PathDiagnosticLocation::getStmt(ErrorNode); 2662 2663 return S; 2664} 2665 2666std::pair<BugReport::ranges_iterator, BugReport::ranges_iterator> 2667BugReport::getRanges() { 2668 // If no custom ranges, add the range of the statement corresponding to 2669 // the error node. 2670 if (Ranges.empty()) { 2671 if (const Expr *E = dyn_cast_or_null<Expr>(getStmt())) 2672 addRange(E->getSourceRange()); 2673 else 2674 return std::make_pair(ranges_iterator(), ranges_iterator()); 2675 } 2676 2677 // User-specified absence of range info. 2678 if (Ranges.size() == 1 && !Ranges.begin()->isValid()) 2679 return std::make_pair(ranges_iterator(), ranges_iterator()); 2680 2681 return std::make_pair(Ranges.begin(), Ranges.end()); 2682} 2683 2684PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const { 2685 if (ErrorNode) { 2686 assert(!Location.isValid() && 2687 "Either Location or ErrorNode should be specified but not both."); 2688 return PathDiagnosticLocation::createEndOfPath(ErrorNode, SM); 2689 } else { 2690 assert(Location.isValid()); 2691 return Location; 2692 } 2693 2694 return PathDiagnosticLocation(); 2695} 2696 2697//===----------------------------------------------------------------------===// 2698// Methods for BugReporter and subclasses. 2699//===----------------------------------------------------------------------===// 2700 2701BugReportEquivClass::~BugReportEquivClass() { } 2702GRBugReporter::~GRBugReporter() { } 2703BugReporterData::~BugReporterData() {} 2704 2705ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); } 2706 2707ProgramStateManager& 2708GRBugReporter::getStateManager() { return Eng.getStateManager(); } 2709 2710BugReporter::~BugReporter() { 2711 FlushReports(); 2712 2713 // Free the bug reports we are tracking. 2714 typedef std::vector<BugReportEquivClass *> ContTy; 2715 for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end(); 2716 I != E; ++I) { 2717 delete *I; 2718 } 2719} 2720 2721void BugReporter::FlushReports() { 2722 if (BugTypes.isEmpty()) 2723 return; 2724 2725 // First flush the warnings for each BugType. This may end up creating new 2726 // warnings and new BugTypes. 2727 // FIXME: Only NSErrorChecker needs BugType's FlushReports. 2728 // Turn NSErrorChecker into a proper checker and remove this. 2729 SmallVector<const BugType*, 16> bugTypes; 2730 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) 2731 bugTypes.push_back(*I); 2732 for (SmallVector<const BugType*, 16>::iterator 2733 I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I) 2734 const_cast<BugType*>(*I)->FlushReports(*this); 2735 2736 // We need to flush reports in deterministic order to ensure the order 2737 // of the reports is consistent between runs. 2738 typedef std::vector<BugReportEquivClass *> ContVecTy; 2739 for (ContVecTy::iterator EI=EQClassesVector.begin(), EE=EQClassesVector.end(); 2740 EI != EE; ++EI){ 2741 BugReportEquivClass& EQ = **EI; 2742 FlushReport(EQ); 2743 } 2744 2745 // BugReporter owns and deletes only BugTypes created implicitly through 2746 // EmitBasicReport. 2747 // FIXME: There are leaks from checkers that assume that the BugTypes they 2748 // create will be destroyed by the BugReporter. 2749 for (llvm::StringMap<BugType*>::iterator 2750 I = StrBugTypes.begin(), E = StrBugTypes.end(); I != E; ++I) 2751 delete I->second; 2752 2753 // Remove all references to the BugType objects. 2754 BugTypes = F.getEmptySet(); 2755} 2756 2757//===----------------------------------------------------------------------===// 2758// PathDiagnostics generation. 2759//===----------------------------------------------------------------------===// 2760 2761namespace { 2762/// A wrapper around a report graph, which contains only a single path, and its 2763/// node maps. 2764class ReportGraph { 2765public: 2766 InterExplodedGraphMap BackMap; 2767 OwningPtr<ExplodedGraph> Graph; 2768 const ExplodedNode *ErrorNode; 2769 size_t Index; 2770}; 2771 2772/// A wrapper around a trimmed graph and its node maps. 2773class TrimmedGraph { 2774 InterExplodedGraphMap InverseMap; 2775 2776 typedef llvm::DenseMap<const ExplodedNode *, unsigned> PriorityMapTy; 2777 PriorityMapTy PriorityMap; 2778 2779 typedef std::pair<const ExplodedNode *, size_t> NodeIndexPair; 2780 SmallVector<NodeIndexPair, 32> ReportNodes; 2781 2782 OwningPtr<ExplodedGraph> G; 2783 2784 /// A helper class for sorting ExplodedNodes by priority. 2785 template <bool Descending> 2786 class PriorityCompare { 2787 const PriorityMapTy &PriorityMap; 2788 2789 public: 2790 PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {} 2791 2792 bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const { 2793 PriorityMapTy::const_iterator LI = PriorityMap.find(LHS); 2794 PriorityMapTy::const_iterator RI = PriorityMap.find(RHS); 2795 PriorityMapTy::const_iterator E = PriorityMap.end(); 2796 2797 if (LI == E) 2798 return Descending; 2799 if (RI == E) 2800 return !Descending; 2801 2802 return Descending ? LI->second > RI->second 2803 : LI->second < RI->second; 2804 } 2805 2806 bool operator()(const NodeIndexPair &LHS, const NodeIndexPair &RHS) const { 2807 return (*this)(LHS.first, RHS.first); 2808 } 2809 }; 2810 2811public: 2812 TrimmedGraph(const ExplodedGraph *OriginalGraph, 2813 ArrayRef<const ExplodedNode *> Nodes); 2814 2815 bool popNextReportGraph(ReportGraph &GraphWrapper); 2816}; 2817} 2818 2819TrimmedGraph::TrimmedGraph(const ExplodedGraph *OriginalGraph, 2820 ArrayRef<const ExplodedNode *> Nodes) { 2821 // The trimmed graph is created in the body of the constructor to ensure 2822 // that the DenseMaps have been initialized already. 2823 InterExplodedGraphMap ForwardMap; 2824 G.reset(OriginalGraph->trim(Nodes, &ForwardMap, &InverseMap)); 2825 2826 // Find the (first) error node in the trimmed graph. We just need to consult 2827 // the node map which maps from nodes in the original graph to nodes 2828 // in the new graph. 2829 llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes; 2830 2831 for (unsigned i = 0, count = Nodes.size(); i < count; ++i) { 2832 if (const ExplodedNode *NewNode = ForwardMap.lookup(Nodes[i])) { 2833 ReportNodes.push_back(std::make_pair(NewNode, i)); 2834 RemainingNodes.insert(NewNode); 2835 } 2836 } 2837 2838 assert(!RemainingNodes.empty() && "No error node found in the trimmed graph"); 2839 2840 // Perform a forward BFS to find all the shortest paths. 2841 std::queue<const ExplodedNode *> WS; 2842 2843 assert(G->num_roots() == 1); 2844 WS.push(*G->roots_begin()); 2845 unsigned Priority = 0; 2846 2847 while (!WS.empty()) { 2848 const ExplodedNode *Node = WS.front(); 2849 WS.pop(); 2850 2851 PriorityMapTy::iterator PriorityEntry; 2852 bool IsNew; 2853 llvm::tie(PriorityEntry, IsNew) = 2854 PriorityMap.insert(std::make_pair(Node, Priority)); 2855 ++Priority; 2856 2857 if (!IsNew) { 2858 assert(PriorityEntry->second <= Priority); 2859 continue; 2860 } 2861 2862 if (RemainingNodes.erase(Node)) 2863 if (RemainingNodes.empty()) 2864 break; 2865 2866 for (ExplodedNode::const_pred_iterator I = Node->succ_begin(), 2867 E = Node->succ_end(); 2868 I != E; ++I) 2869 WS.push(*I); 2870 } 2871 2872 // Sort the error paths from longest to shortest. 2873 std::sort(ReportNodes.begin(), ReportNodes.end(), 2874 PriorityCompare<true>(PriorityMap)); 2875} 2876 2877bool TrimmedGraph::popNextReportGraph(ReportGraph &GraphWrapper) { 2878 if (ReportNodes.empty()) 2879 return false; 2880 2881 const ExplodedNode *OrigN; 2882 llvm::tie(OrigN, GraphWrapper.Index) = ReportNodes.pop_back_val(); 2883 assert(PriorityMap.find(OrigN) != PriorityMap.end() && 2884 "error node not accessible from root"); 2885 2886 // Create a new graph with a single path. This is the graph 2887 // that will be returned to the caller. 2888 ExplodedGraph *GNew = new ExplodedGraph(); 2889 GraphWrapper.Graph.reset(GNew); 2890 GraphWrapper.BackMap.clear(); 2891 2892 // Now walk from the error node up the BFS path, always taking the 2893 // predeccessor with the lowest number. 2894 ExplodedNode *Succ = 0; 2895 while (true) { 2896 // Create the equivalent node in the new graph with the same state 2897 // and location. 2898 ExplodedNode *NewN = GNew->getNode(OrigN->getLocation(), OrigN->getState(), 2899 OrigN->isSink()); 2900 2901 // Store the mapping to the original node. 2902 InterExplodedGraphMap::const_iterator IMitr = InverseMap.find(OrigN); 2903 assert(IMitr != InverseMap.end() && "No mapping to original node."); 2904 GraphWrapper.BackMap[NewN] = IMitr->second; 2905 2906 // Link up the new node with the previous node. 2907 if (Succ) 2908 Succ->addPredecessor(NewN, *GNew); 2909 else 2910 GraphWrapper.ErrorNode = NewN; 2911 2912 Succ = NewN; 2913 2914 // Are we at the final node? 2915 if (OrigN->pred_empty()) { 2916 GNew->addRoot(NewN); 2917 break; 2918 } 2919 2920 // Find the next predeccessor node. We choose the node that is marked 2921 // with the lowest BFS number. 2922 OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(), 2923 PriorityCompare<false>(PriorityMap)); 2924 } 2925 2926 return true; 2927} 2928 2929 2930/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object 2931/// and collapses PathDiagosticPieces that are expanded by macros. 2932static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM) { 2933 typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiece>, 2934 SourceLocation> > MacroStackTy; 2935 2936 typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> > 2937 PiecesTy; 2938 2939 MacroStackTy MacroStack; 2940 PiecesTy Pieces; 2941 2942 for (PathPieces::const_iterator I = path.begin(), E = path.end(); 2943 I!=E; ++I) { 2944 2945 PathDiagnosticPiece *piece = I->getPtr(); 2946 2947 // Recursively compact calls. 2948 if (PathDiagnosticCallPiece *call=dyn_cast<PathDiagnosticCallPiece>(piece)){ 2949 CompactPathDiagnostic(call->path, SM); 2950 } 2951 2952 // Get the location of the PathDiagnosticPiece. 2953 const FullSourceLoc Loc = piece->getLocation().asLocation(); 2954 2955 // Determine the instantiation location, which is the location we group 2956 // related PathDiagnosticPieces. 2957 SourceLocation InstantiationLoc = Loc.isMacroID() ? 2958 SM.getExpansionLoc(Loc) : 2959 SourceLocation(); 2960 2961 if (Loc.isFileID()) { 2962 MacroStack.clear(); 2963 Pieces.push_back(piece); 2964 continue; 2965 } 2966 2967 assert(Loc.isMacroID()); 2968 2969 // Is the PathDiagnosticPiece within the same macro group? 2970 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) { 2971 MacroStack.back().first->subPieces.push_back(piece); 2972 continue; 2973 } 2974 2975 // We aren't in the same group. Are we descending into a new macro 2976 // or are part of an old one? 2977 IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup; 2978 2979 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ? 2980 SM.getExpansionLoc(Loc) : 2981 SourceLocation(); 2982 2983 // Walk the entire macro stack. 2984 while (!MacroStack.empty()) { 2985 if (InstantiationLoc == MacroStack.back().second) { 2986 MacroGroup = MacroStack.back().first; 2987 break; 2988 } 2989 2990 if (ParentInstantiationLoc == MacroStack.back().second) { 2991 MacroGroup = MacroStack.back().first; 2992 break; 2993 } 2994 2995 MacroStack.pop_back(); 2996 } 2997 2998 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) { 2999 // Create a new macro group and add it to the stack. 3000 PathDiagnosticMacroPiece *NewGroup = 3001 new PathDiagnosticMacroPiece( 3002 PathDiagnosticLocation::createSingleLocation(piece->getLocation())); 3003 3004 if (MacroGroup) 3005 MacroGroup->subPieces.push_back(NewGroup); 3006 else { 3007 assert(InstantiationLoc.isFileID()); 3008 Pieces.push_back(NewGroup); 3009 } 3010 3011 MacroGroup = NewGroup; 3012 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc)); 3013 } 3014 3015 // Finally, add the PathDiagnosticPiece to the group. 3016 MacroGroup->subPieces.push_back(piece); 3017 } 3018 3019 // Now take the pieces and construct a new PathDiagnostic. 3020 path.clear(); 3021 3022 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) 3023 path.push_back(*I); 3024} 3025 3026bool GRBugReporter::generatePathDiagnostic(PathDiagnostic& PD, 3027 PathDiagnosticConsumer &PC, 3028 ArrayRef<BugReport *> &bugReports) { 3029 assert(!bugReports.empty()); 3030 3031 bool HasValid = false; 3032 bool HasInvalid = false; 3033 SmallVector<const ExplodedNode *, 32> errorNodes; 3034 for (ArrayRef<BugReport*>::iterator I = bugReports.begin(), 3035 E = bugReports.end(); I != E; ++I) { 3036 if ((*I)->isValid()) { 3037 HasValid = true; 3038 errorNodes.push_back((*I)->getErrorNode()); 3039 } else { 3040 // Keep the errorNodes list in sync with the bugReports list. 3041 HasInvalid = true; 3042 errorNodes.push_back(0); 3043 } 3044 } 3045 3046 // If all the reports have been marked invalid by a previous path generation, 3047 // we're done. 3048 if (!HasValid) 3049 return false; 3050 3051 typedef PathDiagnosticConsumer::PathGenerationScheme PathGenerationScheme; 3052 PathGenerationScheme ActiveScheme = PC.getGenerationScheme(); 3053 3054 if (ActiveScheme == PathDiagnosticConsumer::Extensive) { 3055 AnalyzerOptions &options = getAnalyzerOptions(); 3056 if (options.getBooleanOption("path-diagnostics-alternate", true)) { 3057 ActiveScheme = PathDiagnosticConsumer::AlternateExtensive; 3058 } 3059 } 3060 3061 TrimmedGraph TrimG(&getGraph(), errorNodes); 3062 ReportGraph ErrorGraph; 3063 3064 while (TrimG.popNextReportGraph(ErrorGraph)) { 3065 // Find the BugReport with the original location. 3066 assert(ErrorGraph.Index < bugReports.size()); 3067 BugReport *R = bugReports[ErrorGraph.Index]; 3068 assert(R && "No original report found for sliced graph."); 3069 assert(R->isValid() && "Report selected by trimmed graph marked invalid."); 3070 3071 // Start building the path diagnostic... 3072 PathDiagnosticBuilder PDB(*this, R, ErrorGraph.BackMap, &PC); 3073 const ExplodedNode *N = ErrorGraph.ErrorNode; 3074 3075 // Register additional node visitors. 3076 R->addVisitor(new NilReceiverBRVisitor()); 3077 R->addVisitor(new ConditionBRVisitor()); 3078 R->addVisitor(new LikelyFalsePositiveSuppressionBRVisitor()); 3079 3080 BugReport::VisitorList visitors; 3081 unsigned origReportConfigToken, finalReportConfigToken; 3082 LocationContextMap LCM; 3083 3084 // While generating diagnostics, it's possible the visitors will decide 3085 // new symbols and regions are interesting, or add other visitors based on 3086 // the information they find. If they do, we need to regenerate the path 3087 // based on our new report configuration. 3088 do { 3089 // Get a clean copy of all the visitors. 3090 for (BugReport::visitor_iterator I = R->visitor_begin(), 3091 E = R->visitor_end(); I != E; ++I) 3092 visitors.push_back((*I)->clone()); 3093 3094 // Clear out the active path from any previous work. 3095 PD.resetPath(); 3096 origReportConfigToken = R->getConfigurationChangeToken(); 3097 3098 // Generate the very last diagnostic piece - the piece is visible before 3099 // the trace is expanded. 3100 PathDiagnosticPiece *LastPiece = 0; 3101 for (BugReport::visitor_iterator I = visitors.begin(), E = visitors.end(); 3102 I != E; ++I) { 3103 if (PathDiagnosticPiece *Piece = (*I)->getEndPath(PDB, N, *R)) { 3104 assert (!LastPiece && 3105 "There can only be one final piece in a diagnostic."); 3106 LastPiece = Piece; 3107 } 3108 } 3109 3110 if (ActiveScheme != PathDiagnosticConsumer::None) { 3111 if (!LastPiece) 3112 LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R); 3113 assert(LastPiece); 3114 PD.setEndOfPath(LastPiece); 3115 } 3116 3117 // Make sure we get a clean location context map so we don't 3118 // hold onto old mappings. 3119 LCM.clear(); 3120 3121 switch (ActiveScheme) { 3122 case PathDiagnosticConsumer::AlternateExtensive: 3123 GenerateAlternateExtensivePathDiagnostic(PD, PDB, N, LCM, visitors); 3124 break; 3125 case PathDiagnosticConsumer::Extensive: 3126 GenerateExtensivePathDiagnostic(PD, PDB, N, LCM, visitors); 3127 break; 3128 case PathDiagnosticConsumer::Minimal: 3129 GenerateMinimalPathDiagnostic(PD, PDB, N, LCM, visitors); 3130 break; 3131 case PathDiagnosticConsumer::None: 3132 GenerateVisitorsOnlyPathDiagnostic(PD, PDB, N, visitors); 3133 break; 3134 } 3135 3136 // Clean up the visitors we used. 3137 llvm::DeleteContainerPointers(visitors); 3138 3139 // Did anything change while generating this path? 3140 finalReportConfigToken = R->getConfigurationChangeToken(); 3141 } while (finalReportConfigToken != origReportConfigToken); 3142 3143 if (!R->isValid()) 3144 continue; 3145 3146 // Finally, prune the diagnostic path of uninteresting stuff. 3147 if (!PD.path.empty()) { 3148 if (R->shouldPrunePath() && getAnalyzerOptions().shouldPrunePaths()) { 3149 bool stillHasNotes = removeUnneededCalls(PD.getMutablePieces(), R, LCM); 3150 assert(stillHasNotes); 3151 (void)stillHasNotes; 3152 } 3153 3154 adjustCallLocations(PD.getMutablePieces()); 3155 3156 if (ActiveScheme == PathDiagnosticConsumer::AlternateExtensive) { 3157 SourceManager &SM = getSourceManager(); 3158 3159 // Reduce the number of edges from a very conservative set 3160 // to an aesthetically pleasing subset that conveys the 3161 // necessary information. 3162 OptimizedCallsSet OCS; 3163 while (optimizeEdges(PD.getMutablePieces(), SM, OCS, LCM)) {} 3164 3165 // Drop the very first function-entry edge. It's not really necessary 3166 // for top-level functions. 3167 dropFunctionEntryEdge(PD.getMutablePieces(), LCM, SM); 3168 } 3169 3170 // Remove messages that are basically the same. 3171 // We have to do this after edge optimization in the Extensive mode. 3172 removeRedundantMsgs(PD.getMutablePieces()); 3173 } 3174 3175 // We found a report and didn't suppress it. 3176 return true; 3177 } 3178 3179 // We suppressed all the reports in this equivalence class. 3180 assert(!HasInvalid && "Inconsistent suppression"); 3181 (void)HasInvalid; 3182 return false; 3183} 3184 3185void BugReporter::Register(BugType *BT) { 3186 BugTypes = F.add(BugTypes, BT); 3187} 3188 3189void BugReporter::emitReport(BugReport* R) { 3190 // Compute the bug report's hash to determine its equivalence class. 3191 llvm::FoldingSetNodeID ID; 3192 R->Profile(ID); 3193 3194 // Lookup the equivance class. If there isn't one, create it. 3195 BugType& BT = R->getBugType(); 3196 Register(&BT); 3197 void *InsertPos; 3198 BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos); 3199 3200 if (!EQ) { 3201 EQ = new BugReportEquivClass(R); 3202 EQClasses.InsertNode(EQ, InsertPos); 3203 EQClassesVector.push_back(EQ); 3204 } 3205 else 3206 EQ->AddReport(R); 3207} 3208 3209 3210//===----------------------------------------------------------------------===// 3211// Emitting reports in equivalence classes. 3212//===----------------------------------------------------------------------===// 3213 3214namespace { 3215struct FRIEC_WLItem { 3216 const ExplodedNode *N; 3217 ExplodedNode::const_succ_iterator I, E; 3218 3219 FRIEC_WLItem(const ExplodedNode *n) 3220 : N(n), I(N->succ_begin()), E(N->succ_end()) {} 3221}; 3222} 3223 3224static BugReport * 3225FindReportInEquivalenceClass(BugReportEquivClass& EQ, 3226 SmallVectorImpl<BugReport*> &bugReports) { 3227 3228 BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end(); 3229 assert(I != E); 3230 BugType& BT = I->getBugType(); 3231 3232 // If we don't need to suppress any of the nodes because they are 3233 // post-dominated by a sink, simply add all the nodes in the equivalence class 3234 // to 'Nodes'. Any of the reports will serve as a "representative" report. 3235 if (!BT.isSuppressOnSink()) { 3236 BugReport *R = I; 3237 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) { 3238 const ExplodedNode *N = I->getErrorNode(); 3239 if (N) { 3240 R = I; 3241 bugReports.push_back(R); 3242 } 3243 } 3244 return R; 3245 } 3246 3247 // For bug reports that should be suppressed when all paths are post-dominated 3248 // by a sink node, iterate through the reports in the equivalence class 3249 // until we find one that isn't post-dominated (if one exists). We use a 3250 // DFS traversal of the ExplodedGraph to find a non-sink node. We could write 3251 // this as a recursive function, but we don't want to risk blowing out the 3252 // stack for very long paths. 3253 BugReport *exampleReport = 0; 3254 3255 for (; I != E; ++I) { 3256 const ExplodedNode *errorNode = I->getErrorNode(); 3257 3258 if (!errorNode) 3259 continue; 3260 if (errorNode->isSink()) { 3261 llvm_unreachable( 3262 "BugType::isSuppressSink() should not be 'true' for sink end nodes"); 3263 } 3264 // No successors? By definition this nodes isn't post-dominated by a sink. 3265 if (errorNode->succ_empty()) { 3266 bugReports.push_back(I); 3267 if (!exampleReport) 3268 exampleReport = I; 3269 continue; 3270 } 3271 3272 // At this point we know that 'N' is not a sink and it has at least one 3273 // successor. Use a DFS worklist to find a non-sink end-of-path node. 3274 typedef FRIEC_WLItem WLItem; 3275 typedef SmallVector<WLItem, 10> DFSWorkList; 3276 llvm::DenseMap<const ExplodedNode *, unsigned> Visited; 3277 3278 DFSWorkList WL; 3279 WL.push_back(errorNode); 3280 Visited[errorNode] = 1; 3281 3282 while (!WL.empty()) { 3283 WLItem &WI = WL.back(); 3284 assert(!WI.N->succ_empty()); 3285 3286 for (; WI.I != WI.E; ++WI.I) { 3287 const ExplodedNode *Succ = *WI.I; 3288 // End-of-path node? 3289 if (Succ->succ_empty()) { 3290 // If we found an end-of-path node that is not a sink. 3291 if (!Succ->isSink()) { 3292 bugReports.push_back(I); 3293 if (!exampleReport) 3294 exampleReport = I; 3295 WL.clear(); 3296 break; 3297 } 3298 // Found a sink? Continue on to the next successor. 3299 continue; 3300 } 3301 // Mark the successor as visited. If it hasn't been explored, 3302 // enqueue it to the DFS worklist. 3303 unsigned &mark = Visited[Succ]; 3304 if (!mark) { 3305 mark = 1; 3306 WL.push_back(Succ); 3307 break; 3308 } 3309 } 3310 3311 // The worklist may have been cleared at this point. First 3312 // check if it is empty before checking the last item. 3313 if (!WL.empty() && &WL.back() == &WI) 3314 WL.pop_back(); 3315 } 3316 } 3317 3318 // ExampleReport will be NULL if all the nodes in the equivalence class 3319 // were post-dominated by sinks. 3320 return exampleReport; 3321} 3322 3323void BugReporter::FlushReport(BugReportEquivClass& EQ) { 3324 SmallVector<BugReport*, 10> bugReports; 3325 BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports); 3326 if (exampleReport) { 3327 const PathDiagnosticConsumers &C = getPathDiagnosticConsumers(); 3328 for (PathDiagnosticConsumers::const_iterator I=C.begin(), 3329 E=C.end(); I != E; ++I) { 3330 FlushReport(exampleReport, **I, bugReports); 3331 } 3332 } 3333} 3334 3335void BugReporter::FlushReport(BugReport *exampleReport, 3336 PathDiagnosticConsumer &PD, 3337 ArrayRef<BugReport*> bugReports) { 3338 3339 // FIXME: Make sure we use the 'R' for the path that was actually used. 3340 // Probably doesn't make a difference in practice. 3341 BugType& BT = exampleReport->getBugType(); 3342 3343 OwningPtr<PathDiagnostic> 3344 D(new PathDiagnostic(exampleReport->getDeclWithIssue(), 3345 exampleReport->getBugType().getName(), 3346 exampleReport->getDescription(), 3347 exampleReport->getShortDescription(/*Fallback=*/false), 3348 BT.getCategory(), 3349 exampleReport->getUniqueingLocation(), 3350 exampleReport->getUniqueingDecl())); 3351 3352 MaxBugClassSize = std::max(bugReports.size(), 3353 static_cast<size_t>(MaxBugClassSize)); 3354 3355 // Generate the full path diagnostic, using the generation scheme 3356 // specified by the PathDiagnosticConsumer. Note that we have to generate 3357 // path diagnostics even for consumers which do not support paths, because 3358 // the BugReporterVisitors may mark this bug as a false positive. 3359 if (!bugReports.empty()) 3360 if (!generatePathDiagnostic(*D.get(), PD, bugReports)) 3361 return; 3362 3363 MaxValidBugClassSize = std::max(bugReports.size(), 3364 static_cast<size_t>(MaxValidBugClassSize)); 3365 3366 // Examine the report and see if the last piece is in a header. Reset the 3367 // report location to the last piece in the main source file. 3368 AnalyzerOptions& Opts = getAnalyzerOptions(); 3369 if (Opts.shouldReportIssuesInMainSourceFile() && !Opts.AnalyzeAll) 3370 D->resetDiagnosticLocationToMainFile(); 3371 3372 // If the path is empty, generate a single step path with the location 3373 // of the issue. 3374 if (D->path.empty()) { 3375 PathDiagnosticLocation L = exampleReport->getLocation(getSourceManager()); 3376 PathDiagnosticPiece *piece = 3377 new PathDiagnosticEventPiece(L, exampleReport->getDescription()); 3378 BugReport::ranges_iterator Beg, End; 3379 llvm::tie(Beg, End) = exampleReport->getRanges(); 3380 for ( ; Beg != End; ++Beg) 3381 piece->addRange(*Beg); 3382 D->setEndOfPath(piece); 3383 } 3384 3385 // Get the meta data. 3386 const BugReport::ExtraTextList &Meta = exampleReport->getExtraText(); 3387 for (BugReport::ExtraTextList::const_iterator i = Meta.begin(), 3388 e = Meta.end(); i != e; ++i) { 3389 D->addMeta(*i); 3390 } 3391 3392 PD.HandlePathDiagnostic(D.take()); 3393} 3394 3395void BugReporter::EmitBasicReport(const Decl *DeclWithIssue, 3396 StringRef name, 3397 StringRef category, 3398 StringRef str, PathDiagnosticLocation Loc, 3399 SourceRange* RBeg, unsigned NumRanges) { 3400 3401 // 'BT' is owned by BugReporter. 3402 BugType *BT = getBugTypeForName(name, category); 3403 BugReport *R = new BugReport(*BT, str, Loc); 3404 R->setDeclWithIssue(DeclWithIssue); 3405 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg); 3406 emitReport(R); 3407} 3408 3409BugType *BugReporter::getBugTypeForName(StringRef name, 3410 StringRef category) { 3411 SmallString<136> fullDesc; 3412 llvm::raw_svector_ostream(fullDesc) << name << ":" << category; 3413 llvm::StringMapEntry<BugType *> & 3414 entry = StrBugTypes.GetOrCreateValue(fullDesc); 3415 BugType *BT = entry.getValue(); 3416 if (!BT) { 3417 BT = new BugType(name, category); 3418 entry.setValue(BT); 3419 } 3420 return BT; 3421} 3422 3423 3424void PathPieces::dump() const { 3425 unsigned index = 0; 3426 for (PathPieces::const_iterator I = begin(), E = end(); I != E; ++I) { 3427 llvm::errs() << "[" << index++ << "] "; 3428 (*I)->dump(); 3429 llvm::errs() << "\n"; 3430 } 3431} 3432 3433void PathDiagnosticCallPiece::dump() const { 3434 llvm::errs() << "CALL\n--------------\n"; 3435 3436 if (const Stmt *SLoc = getLocStmt(getLocation())) 3437 SLoc->dump(); 3438 else if (const NamedDecl *ND = dyn_cast<NamedDecl>(getCallee())) 3439 llvm::errs() << *ND << "\n"; 3440 else 3441 getLocation().dump(); 3442} 3443 3444void PathDiagnosticEventPiece::dump() const { 3445 llvm::errs() << "EVENT\n--------------\n"; 3446 llvm::errs() << getString() << "\n"; 3447 llvm::errs() << " ---- at ----\n"; 3448 getLocation().dump(); 3449} 3450 3451void PathDiagnosticControlFlowPiece::dump() const { 3452 llvm::errs() << "CONTROL\n--------------\n"; 3453 getStartLocation().dump(); 3454 llvm::errs() << " ---- to ----\n"; 3455 getEndLocation().dump(); 3456} 3457 3458void PathDiagnosticMacroPiece::dump() const { 3459 llvm::errs() << "MACRO\n--------------\n"; 3460 // FIXME: Print which macro is being invoked. 3461} 3462 3463void PathDiagnosticLocation::dump() const { 3464 if (!isValid()) { 3465 llvm::errs() << "<INVALID>\n"; 3466 return; 3467 } 3468 3469 switch (K) { 3470 case RangeK: 3471 // FIXME: actually print the range. 3472 llvm::errs() << "<range>\n"; 3473 break; 3474 case SingleLocK: 3475 asLocation().dump(); 3476 llvm::errs() << "\n"; 3477 break; 3478 case StmtK: 3479 if (S) 3480 S->dump(); 3481 else 3482 llvm::errs() << "<NULL STMT>\n"; 3483 break; 3484 case DeclK: 3485 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 3486 llvm::errs() << *ND << "\n"; 3487 else if (isa<BlockDecl>(D)) 3488 // FIXME: Make this nicer. 3489 llvm::errs() << "<block>\n"; 3490 else if (D) 3491 llvm::errs() << "<unknown decl>\n"; 3492 else 3493 llvm::errs() << "<NULL DECL>\n"; 3494 break; 3495 } 3496} 3497