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