BugReporter.cpp revision a43df9539644bf1c258e12710cd69d79b0b078cd
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 void 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  // After constructing the full PathDiagnostic, do a pass over it to compact
760  // PathDiagnosticPieces that occur within a macro.
761  CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager());
762}
763
764//===----------------------------------------------------------------------===//
765// "Extensive" PathDiagnostic generation.
766//===----------------------------------------------------------------------===//
767
768static bool IsControlFlowExpr(const Stmt *S) {
769  const Expr *E = dyn_cast<Expr>(S);
770
771  if (!E)
772    return false;
773
774  E = E->IgnoreParenCasts();
775
776  if (isa<AbstractConditionalOperator>(E))
777    return true;
778
779  if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
780    if (B->isLogicalOp())
781      return true;
782
783  return false;
784}
785
786namespace {
787class ContextLocation : public PathDiagnosticLocation {
788  bool IsDead;
789public:
790  ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
791    : PathDiagnosticLocation(L), IsDead(isdead) {}
792
793  void markDead() { IsDead = true; }
794  bool isDead() const { return IsDead; }
795};
796
797class EdgeBuilder {
798  std::vector<ContextLocation> CLocs;
799  typedef std::vector<ContextLocation>::iterator iterator;
800  PathDiagnostic &PD;
801  PathDiagnosticBuilder &PDB;
802  PathDiagnosticLocation PrevLoc;
803
804  bool IsConsumedExpr(const PathDiagnosticLocation &L);
805
806  bool containsLocation(const PathDiagnosticLocation &Container,
807                        const PathDiagnosticLocation &Containee);
808
809  PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
810
811  PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
812                                         bool firstCharOnly = false) {
813    if (const Stmt *S = L.asStmt()) {
814      const Stmt *Original = S;
815      while (1) {
816        // Adjust the location for some expressions that are best referenced
817        // by one of their subexpressions.
818        switch (S->getStmtClass()) {
819          default:
820            break;
821          case Stmt::ParenExprClass:
822          case Stmt::GenericSelectionExprClass:
823            S = cast<Expr>(S)->IgnoreParens();
824            firstCharOnly = true;
825            continue;
826          case Stmt::BinaryConditionalOperatorClass:
827          case Stmt::ConditionalOperatorClass:
828            S = cast<AbstractConditionalOperator>(S)->getCond();
829            firstCharOnly = true;
830            continue;
831          case Stmt::ChooseExprClass:
832            S = cast<ChooseExpr>(S)->getCond();
833            firstCharOnly = true;
834            continue;
835          case Stmt::BinaryOperatorClass:
836            S = cast<BinaryOperator>(S)->getLHS();
837            firstCharOnly = true;
838            continue;
839        }
840
841        break;
842      }
843
844      if (S != Original)
845        L = PathDiagnosticLocation(S, L.getManager(), PDB.LC);
846    }
847
848    if (firstCharOnly)
849      L  = PathDiagnosticLocation::createSingleLocation(L);
850
851    return L;
852  }
853
854  void popLocation() {
855    if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
856      // For contexts, we only one the first character as the range.
857      rawAddEdge(cleanUpLocation(CLocs.back(), true));
858    }
859    CLocs.pop_back();
860  }
861
862public:
863  EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
864    : PD(pd), PDB(pdb) {
865
866      // If the PathDiagnostic already has pieces, add the enclosing statement
867      // of the first piece as a context as well.
868      if (!PD.path.empty()) {
869        PrevLoc = (*PD.path.begin())->getLocation();
870
871        if (const Stmt *S = PrevLoc.asStmt())
872          addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
873      }
874  }
875
876  ~EdgeBuilder() {
877    while (!CLocs.empty()) popLocation();
878
879    // Finally, add an initial edge from the start location of the first
880    // statement (if it doesn't already exist).
881    PathDiagnosticLocation L = PathDiagnosticLocation::createDeclBegin(
882                                                       PDB.LC,
883                                                       PDB.getSourceManager());
884    if (L.isValid())
885      rawAddEdge(L);
886  }
887
888  void flushLocations() {
889    while (!CLocs.empty())
890      popLocation();
891    PrevLoc = PathDiagnosticLocation();
892  }
893
894  void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false);
895
896  void rawAddEdge(PathDiagnosticLocation NewLoc);
897
898  void addContext(const Stmt *S);
899  void addContext(const PathDiagnosticLocation &L);
900  void addExtendedContext(const Stmt *S);
901};
902} // end anonymous namespace
903
904
905PathDiagnosticLocation
906EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
907  if (const Stmt *S = L.asStmt()) {
908    if (IsControlFlowExpr(S))
909      return L;
910
911    return PDB.getEnclosingStmtLocation(S);
912  }
913
914  return L;
915}
916
917bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
918                                   const PathDiagnosticLocation &Containee) {
919
920  if (Container == Containee)
921    return true;
922
923  if (Container.asDecl())
924    return true;
925
926  if (const Stmt *S = Containee.asStmt())
927    if (const Stmt *ContainerS = Container.asStmt()) {
928      while (S) {
929        if (S == ContainerS)
930          return true;
931        S = PDB.getParent(S);
932      }
933      return false;
934    }
935
936  // Less accurate: compare using source ranges.
937  SourceRange ContainerR = Container.asRange();
938  SourceRange ContaineeR = Containee.asRange();
939
940  SourceManager &SM = PDB.getSourceManager();
941  SourceLocation ContainerRBeg = SM.getExpansionLoc(ContainerR.getBegin());
942  SourceLocation ContainerREnd = SM.getExpansionLoc(ContainerR.getEnd());
943  SourceLocation ContaineeRBeg = SM.getExpansionLoc(ContaineeR.getBegin());
944  SourceLocation ContaineeREnd = SM.getExpansionLoc(ContaineeR.getEnd());
945
946  unsigned ContainerBegLine = SM.getExpansionLineNumber(ContainerRBeg);
947  unsigned ContainerEndLine = SM.getExpansionLineNumber(ContainerREnd);
948  unsigned ContaineeBegLine = SM.getExpansionLineNumber(ContaineeRBeg);
949  unsigned ContaineeEndLine = SM.getExpansionLineNumber(ContaineeREnd);
950
951  assert(ContainerBegLine <= ContainerEndLine);
952  assert(ContaineeBegLine <= ContaineeEndLine);
953
954  return (ContainerBegLine <= ContaineeBegLine &&
955          ContainerEndLine >= ContaineeEndLine &&
956          (ContainerBegLine != ContaineeBegLine ||
957           SM.getExpansionColumnNumber(ContainerRBeg) <=
958           SM.getExpansionColumnNumber(ContaineeRBeg)) &&
959          (ContainerEndLine != ContaineeEndLine ||
960           SM.getExpansionColumnNumber(ContainerREnd) >=
961           SM.getExpansionColumnNumber(ContaineeREnd)));
962}
963
964void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
965  if (!PrevLoc.isValid()) {
966    PrevLoc = NewLoc;
967    return;
968  }
969
970  const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc);
971  const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc);
972
973  if (PrevLocClean.asLocation().isInvalid()) {
974    PrevLoc = NewLoc;
975    return;
976  }
977
978  if (NewLocClean.asLocation() == PrevLocClean.asLocation())
979    return;
980
981  // FIXME: Ignore intra-macro edges for now.
982  if (NewLocClean.asLocation().getExpansionLoc() ==
983      PrevLocClean.asLocation().getExpansionLoc())
984    return;
985
986  PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
987  PrevLoc = NewLoc;
988}
989
990void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) {
991
992  if (!alwaysAdd && NewLoc.asLocation().isMacroID())
993    return;
994
995  const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
996
997  while (!CLocs.empty()) {
998    ContextLocation &TopContextLoc = CLocs.back();
999
1000    // Is the top location context the same as the one for the new location?
1001    if (TopContextLoc == CLoc) {
1002      if (alwaysAdd) {
1003        if (IsConsumedExpr(TopContextLoc) &&
1004            !IsControlFlowExpr(TopContextLoc.asStmt()))
1005            TopContextLoc.markDead();
1006
1007        rawAddEdge(NewLoc);
1008      }
1009
1010      return;
1011    }
1012
1013    if (containsLocation(TopContextLoc, CLoc)) {
1014      if (alwaysAdd) {
1015        rawAddEdge(NewLoc);
1016
1017        if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) {
1018          CLocs.push_back(ContextLocation(CLoc, true));
1019          return;
1020        }
1021      }
1022
1023      CLocs.push_back(CLoc);
1024      return;
1025    }
1026
1027    // Context does not contain the location.  Flush it.
1028    popLocation();
1029  }
1030
1031  // If we reach here, there is no enclosing context.  Just add the edge.
1032  rawAddEdge(NewLoc);
1033}
1034
1035bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
1036  if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
1037    return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
1038
1039  return false;
1040}
1041
1042void EdgeBuilder::addExtendedContext(const Stmt *S) {
1043  if (!S)
1044    return;
1045
1046  const Stmt *Parent = PDB.getParent(S);
1047  while (Parent) {
1048    if (isa<CompoundStmt>(Parent))
1049      Parent = PDB.getParent(Parent);
1050    else
1051      break;
1052  }
1053
1054  if (Parent) {
1055    switch (Parent->getStmtClass()) {
1056      case Stmt::DoStmtClass:
1057      case Stmt::ObjCAtSynchronizedStmtClass:
1058        addContext(Parent);
1059      default:
1060        break;
1061    }
1062  }
1063
1064  addContext(S);
1065}
1066
1067void EdgeBuilder::addContext(const Stmt *S) {
1068  if (!S)
1069    return;
1070
1071  PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.LC);
1072  addContext(L);
1073}
1074
1075void EdgeBuilder::addContext(const PathDiagnosticLocation &L) {
1076  while (!CLocs.empty()) {
1077    const PathDiagnosticLocation &TopContextLoc = CLocs.back();
1078
1079    // Is the top location context the same as the one for the new location?
1080    if (TopContextLoc == L)
1081      return;
1082
1083    if (containsLocation(TopContextLoc, L)) {
1084      CLocs.push_back(L);
1085      return;
1086    }
1087
1088    // Context does not contain the location.  Flush it.
1089    popLocation();
1090  }
1091
1092  CLocs.push_back(L);
1093}
1094
1095// Cone-of-influence: support the reverse propagation of "interesting" symbols
1096// and values by tracing interesting calculations backwards through evaluated
1097// expressions along a path.  This is probably overly complicated, but the idea
1098// is that if an expression computed an "interesting" value, the child
1099// expressions are are also likely to be "interesting" as well (which then
1100// propagates to the values they in turn compute).  This reverse propagation
1101// is needed to track interesting correlations across function call boundaries,
1102// where formal arguments bind to actual arguments, etc.  This is also needed
1103// because the constraint solver sometimes simplifies certain symbolic values
1104// into constants when appropriate, and this complicates reasoning about
1105// interesting values.
1106typedef llvm::DenseSet<const Expr *> InterestingExprs;
1107
1108static void reversePropagateIntererstingSymbols(BugReport &R,
1109                                                InterestingExprs &IE,
1110                                                const ProgramState *State,
1111                                                const Expr *Ex,
1112                                                const LocationContext *LCtx) {
1113  SVal V = State->getSVal(Ex, LCtx);
1114  if (!(R.isInteresting(V) || IE.count(Ex)))
1115    return;
1116
1117  switch (Ex->getStmtClass()) {
1118    default:
1119      if (!isa<CastExpr>(Ex))
1120        break;
1121      // Fall through.
1122    case Stmt::BinaryOperatorClass:
1123    case Stmt::UnaryOperatorClass: {
1124      for (Stmt::const_child_iterator CI = Ex->child_begin(),
1125            CE = Ex->child_end();
1126            CI != CE; ++CI) {
1127        if (const Expr *child = dyn_cast_or_null<Expr>(*CI)) {
1128          IE.insert(child);
1129          SVal ChildV = State->getSVal(child, LCtx);
1130          R.markInteresting(ChildV);
1131        }
1132        break;
1133      }
1134    }
1135  }
1136
1137  R.markInteresting(V);
1138}
1139
1140static void reversePropagateInterestingSymbols(BugReport &R,
1141                                               InterestingExprs &IE,
1142                                               const ProgramState *State,
1143                                               const LocationContext *CalleeCtx,
1144                                               const LocationContext *CallerCtx)
1145{
1146  // FIXME: Handle non-CallExpr-based CallEvents.
1147  const StackFrameContext *Callee = CalleeCtx->getCurrentStackFrame();
1148  const Stmt *CallSite = Callee->getCallSite();
1149  if (const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite)) {
1150    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeCtx->getDecl())) {
1151      FunctionDecl::param_const_iterator PI = FD->param_begin(),
1152                                         PE = FD->param_end();
1153      CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end();
1154      for (; AI != AE && PI != PE; ++AI, ++PI) {
1155        if (const Expr *ArgE = *AI) {
1156          if (const ParmVarDecl *PD = *PI) {
1157            Loc LV = State->getLValue(PD, CalleeCtx);
1158            if (R.isInteresting(LV) || R.isInteresting(State->getRawSVal(LV)))
1159              IE.insert(ArgE);
1160          }
1161        }
1162      }
1163    }
1164  }
1165}
1166
1167static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
1168                                            PathDiagnosticBuilder &PDB,
1169                                            const ExplodedNode *N,
1170                                      ArrayRef<BugReporterVisitor *> visitors) {
1171  EdgeBuilder EB(PD, PDB);
1172  const SourceManager& SM = PDB.getSourceManager();
1173  StackDiagVector CallStack;
1174  InterestingExprs IE;
1175
1176  const ExplodedNode *NextNode = N->pred_empty() ? NULL : *(N->pred_begin());
1177  while (NextNode) {
1178    N = NextNode;
1179    NextNode = GetPredecessorNode(N);
1180    ProgramPoint P = N->getLocation();
1181
1182    do {
1183      if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
1184        if (const Expr *Ex = PS->getStmtAs<Expr>())
1185          reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1186                                              N->getState().getPtr(), Ex,
1187                                              N->getLocationContext());
1188      }
1189
1190      if (const CallExitEnd *CE = dyn_cast<CallExitEnd>(&P)) {
1191        const Stmt *S = CE->getCalleeContext()->getCallSite();
1192        if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) {
1193            reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1194                                                N->getState().getPtr(), Ex,
1195                                                N->getLocationContext());
1196        }
1197
1198        PathDiagnosticCallPiece *C =
1199          PathDiagnosticCallPiece::construct(N, *CE, SM);
1200        GRBugReporter& BR = PDB.getBugReporter();
1201        BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
1202
1203        EB.addEdge(C->callReturn, true);
1204        EB.flushLocations();
1205
1206        PD.getActivePath().push_front(C);
1207        PD.pushActivePath(&C->path);
1208        CallStack.push_back(StackDiagPair(C, N));
1209        break;
1210      }
1211
1212      // Pop the call hierarchy if we are done walking the contents
1213      // of a function call.
1214      if (const CallEnter *CE = dyn_cast<CallEnter>(&P)) {
1215        // Add an edge to the start of the function.
1216        const Decl *D = CE->getCalleeContext()->getDecl();
1217        PathDiagnosticLocation pos =
1218          PathDiagnosticLocation::createBegin(D, SM);
1219        EB.addEdge(pos);
1220
1221        // Flush all locations, and pop the active path.
1222        bool VisitedEntireCall = PD.isWithinCall();
1223        EB.flushLocations();
1224        PD.popActivePath();
1225        PDB.LC = N->getLocationContext();
1226
1227        // Either we just added a bunch of stuff to the top-level path, or
1228        // we have a previous CallExitEnd.  If the former, it means that the
1229        // path terminated within a function call.  We must then take the
1230        // current contents of the active path and place it within
1231        // a new PathDiagnosticCallPiece.
1232        PathDiagnosticCallPiece *C;
1233        if (VisitedEntireCall) {
1234          C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
1235        } else {
1236          const Decl *Caller = CE->getLocationContext()->getDecl();
1237          C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
1238          GRBugReporter& BR = PDB.getBugReporter();
1239          BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
1240        }
1241
1242        C->setCallee(*CE, SM);
1243        EB.addContext(C->getLocation());
1244
1245        if (!CallStack.empty()) {
1246          assert(CallStack.back().first == C);
1247          CallStack.pop_back();
1248        }
1249        break;
1250      }
1251
1252      // Note that is important that we update the LocationContext
1253      // after looking at CallExits.  CallExit basically adds an
1254      // edge in the *caller*, so we don't want to update the LocationContext
1255      // too soon.
1256      PDB.LC = N->getLocationContext();
1257
1258      // Block edges.
1259      if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
1260        // Does this represent entering a call?  If so, look at propagating
1261        // interesting symbols across call boundaries.
1262        if (NextNode) {
1263          const LocationContext *CallerCtx = NextNode->getLocationContext();
1264          const LocationContext *CalleeCtx = PDB.LC;
1265          if (CallerCtx != CalleeCtx) {
1266            reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
1267                                               N->getState().getPtr(),
1268                                               CalleeCtx, CallerCtx);
1269          }
1270        }
1271
1272        // Are we jumping to the head of a loop?  Add a special diagnostic.
1273        if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
1274          PathDiagnosticLocation L(Loop, SM, PDB.LC);
1275          const CompoundStmt *CS = NULL;
1276
1277          if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1278            CS = dyn_cast<CompoundStmt>(FS->getBody());
1279          else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1280            CS = dyn_cast<CompoundStmt>(WS->getBody());
1281
1282          PathDiagnosticEventPiece *p =
1283            new PathDiagnosticEventPiece(L,
1284                                        "Looping back to the head of the loop");
1285          p->setPrunable(true);
1286
1287          EB.addEdge(p->getLocation(), true);
1288          PD.getActivePath().push_front(p);
1289
1290          if (CS) {
1291            PathDiagnosticLocation BL =
1292              PathDiagnosticLocation::createEndBrace(CS, SM);
1293            EB.addEdge(BL);
1294          }
1295        }
1296
1297        if (const Stmt *Term = BE->getSrc()->getTerminator())
1298          EB.addContext(Term);
1299
1300        break;
1301      }
1302
1303      if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
1304        CFGElement First = BE->getFirstElement();
1305        if (const CFGStmt *S = First.getAs<CFGStmt>()) {
1306          const Stmt *stmt = S->getStmt();
1307          if (IsControlFlowExpr(stmt)) {
1308            // Add the proper context for '&&', '||', and '?'.
1309            EB.addContext(stmt);
1310          }
1311          else
1312            EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt());
1313        }
1314
1315        break;
1316      }
1317
1318
1319    } while (0);
1320
1321    if (!NextNode)
1322      continue;
1323
1324    // Add pieces from custom visitors.
1325    BugReport *R = PDB.getBugReport();
1326    for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
1327                                                  E = visitors.end();
1328         I != E; ++I) {
1329      if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) {
1330        const PathDiagnosticLocation &Loc = p->getLocation();
1331        EB.addEdge(Loc, true);
1332        PD.getActivePath().push_front(p);
1333        updateStackPiecesWithMessage(p, CallStack);
1334
1335        if (const Stmt *S = Loc.asStmt())
1336          EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1337      }
1338    }
1339  }
1340}
1341
1342//===----------------------------------------------------------------------===//
1343// Methods for BugType and subclasses.
1344//===----------------------------------------------------------------------===//
1345BugType::~BugType() { }
1346
1347void BugType::FlushReports(BugReporter &BR) {}
1348
1349void BuiltinBug::anchor() {}
1350
1351//===----------------------------------------------------------------------===//
1352// Methods for BugReport and subclasses.
1353//===----------------------------------------------------------------------===//
1354
1355void BugReport::NodeResolver::anchor() {}
1356
1357void BugReport::addVisitor(BugReporterVisitor* visitor) {
1358  if (!visitor)
1359    return;
1360
1361  llvm::FoldingSetNodeID ID;
1362  visitor->Profile(ID);
1363  void *InsertPos;
1364
1365  if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
1366    delete visitor;
1367    return;
1368  }
1369
1370  CallbacksSet.InsertNode(visitor, InsertPos);
1371  Callbacks.push_back(visitor);
1372  ++ConfigurationChangeToken;
1373}
1374
1375BugReport::~BugReport() {
1376  for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I) {
1377    delete *I;
1378  }
1379  while (!interestingSymbols.empty()) {
1380    popInterestingSymbolsAndRegions();
1381  }
1382}
1383
1384const Decl *BugReport::getDeclWithIssue() const {
1385  if (DeclWithIssue)
1386    return DeclWithIssue;
1387
1388  const ExplodedNode *N = getErrorNode();
1389  if (!N)
1390    return 0;
1391
1392  const LocationContext *LC = N->getLocationContext();
1393  return LC->getCurrentStackFrame()->getDecl();
1394}
1395
1396void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
1397  hash.AddPointer(&BT);
1398  hash.AddString(Description);
1399  if (UniqueingLocation.isValid()) {
1400    UniqueingLocation.Profile(hash);
1401  } else if (Location.isValid()) {
1402    Location.Profile(hash);
1403  } else {
1404    assert(ErrorNode);
1405    hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
1406  }
1407
1408  for (SmallVectorImpl<SourceRange>::const_iterator I =
1409      Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1410    const SourceRange range = *I;
1411    if (!range.isValid())
1412      continue;
1413    hash.AddInteger(range.getBegin().getRawEncoding());
1414    hash.AddInteger(range.getEnd().getRawEncoding());
1415  }
1416}
1417
1418void BugReport::markInteresting(SymbolRef sym) {
1419  if (!sym)
1420    return;
1421
1422  // If the symbol wasn't already in our set, note a configuration change.
1423  if (getInterestingSymbols().insert(sym).second)
1424    ++ConfigurationChangeToken;
1425
1426  if (const SymbolMetadata *meta = dyn_cast<SymbolMetadata>(sym))
1427    getInterestingRegions().insert(meta->getRegion());
1428}
1429
1430void BugReport::markInteresting(const MemRegion *R) {
1431  if (!R)
1432    return;
1433
1434  // If the base region wasn't already in our set, note a configuration change.
1435  R = R->getBaseRegion();
1436  if (getInterestingRegions().insert(R).second)
1437    ++ConfigurationChangeToken;
1438
1439  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
1440    getInterestingSymbols().insert(SR->getSymbol());
1441}
1442
1443void BugReport::markInteresting(SVal V) {
1444  markInteresting(V.getAsRegion());
1445  markInteresting(V.getAsSymbol());
1446}
1447
1448void BugReport::markInteresting(const LocationContext *LC) {
1449  if (!LC)
1450    return;
1451  InterestingLocationContexts.insert(LC);
1452}
1453
1454bool BugReport::isInteresting(SVal V) {
1455  return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol());
1456}
1457
1458bool BugReport::isInteresting(SymbolRef sym) {
1459  if (!sym)
1460    return false;
1461  // We don't currently consider metadata symbols to be interesting
1462  // even if we know their region is interesting. Is that correct behavior?
1463  return getInterestingSymbols().count(sym);
1464}
1465
1466bool BugReport::isInteresting(const MemRegion *R) {
1467  if (!R)
1468    return false;
1469  R = R->getBaseRegion();
1470  bool b = getInterestingRegions().count(R);
1471  if (b)
1472    return true;
1473  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
1474    return getInterestingSymbols().count(SR->getSymbol());
1475  return false;
1476}
1477
1478bool BugReport::isInteresting(const LocationContext *LC) {
1479  if (!LC)
1480    return false;
1481  return InterestingLocationContexts.count(LC);
1482}
1483
1484void BugReport::lazyInitializeInterestingSets() {
1485  if (interestingSymbols.empty()) {
1486    interestingSymbols.push_back(new Symbols());
1487    interestingRegions.push_back(new Regions());
1488  }
1489}
1490
1491BugReport::Symbols &BugReport::getInterestingSymbols() {
1492  lazyInitializeInterestingSets();
1493  return *interestingSymbols.back();
1494}
1495
1496BugReport::Regions &BugReport::getInterestingRegions() {
1497  lazyInitializeInterestingSets();
1498  return *interestingRegions.back();
1499}
1500
1501void BugReport::pushInterestingSymbolsAndRegions() {
1502  interestingSymbols.push_back(new Symbols(getInterestingSymbols()));
1503  interestingRegions.push_back(new Regions(getInterestingRegions()));
1504}
1505
1506void BugReport::popInterestingSymbolsAndRegions() {
1507  delete interestingSymbols.back();
1508  interestingSymbols.pop_back();
1509  delete interestingRegions.back();
1510  interestingRegions.pop_back();
1511}
1512
1513const Stmt *BugReport::getStmt() const {
1514  if (!ErrorNode)
1515    return 0;
1516
1517  ProgramPoint ProgP = ErrorNode->getLocation();
1518  const Stmt *S = NULL;
1519
1520  if (BlockEntrance *BE = dyn_cast<BlockEntrance>(&ProgP)) {
1521    CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
1522    if (BE->getBlock() == &Exit)
1523      S = GetPreviousStmt(ErrorNode);
1524  }
1525  if (!S)
1526    S = GetStmt(ProgP);
1527
1528  return S;
1529}
1530
1531std::pair<BugReport::ranges_iterator, BugReport::ranges_iterator>
1532BugReport::getRanges() {
1533    // If no custom ranges, add the range of the statement corresponding to
1534    // the error node.
1535    if (Ranges.empty()) {
1536      if (const Expr *E = dyn_cast_or_null<Expr>(getStmt()))
1537        addRange(E->getSourceRange());
1538      else
1539        return std::make_pair(ranges_iterator(), ranges_iterator());
1540    }
1541
1542    // User-specified absence of range info.
1543    if (Ranges.size() == 1 && !Ranges.begin()->isValid())
1544      return std::make_pair(ranges_iterator(), ranges_iterator());
1545
1546    return std::make_pair(Ranges.begin(), Ranges.end());
1547}
1548
1549PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
1550  if (ErrorNode) {
1551    assert(!Location.isValid() &&
1552     "Either Location or ErrorNode should be specified but not both.");
1553
1554    if (const Stmt *S = GetCurrentOrPreviousStmt(ErrorNode)) {
1555      const LocationContext *LC = ErrorNode->getLocationContext();
1556
1557      // For member expressions, return the location of the '.' or '->'.
1558      if (const MemberExpr *ME = dyn_cast<MemberExpr>(S))
1559        return PathDiagnosticLocation::createMemberLoc(ME, SM);
1560      // For binary operators, return the location of the operator.
1561      if (const BinaryOperator *B = dyn_cast<BinaryOperator>(S))
1562        return PathDiagnosticLocation::createOperatorLoc(B, SM);
1563
1564      return PathDiagnosticLocation::createBegin(S, SM, LC);
1565    }
1566  } else {
1567    assert(Location.isValid());
1568    return Location;
1569  }
1570
1571  return PathDiagnosticLocation();
1572}
1573
1574//===----------------------------------------------------------------------===//
1575// Methods for BugReporter and subclasses.
1576//===----------------------------------------------------------------------===//
1577
1578BugReportEquivClass::~BugReportEquivClass() { }
1579GRBugReporter::~GRBugReporter() { }
1580BugReporterData::~BugReporterData() {}
1581
1582ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
1583
1584ProgramStateManager&
1585GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1586
1587BugReporter::~BugReporter() {
1588  FlushReports();
1589
1590  // Free the bug reports we are tracking.
1591  typedef std::vector<BugReportEquivClass *> ContTy;
1592  for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end();
1593       I != E; ++I) {
1594    delete *I;
1595  }
1596}
1597
1598void BugReporter::FlushReports() {
1599  if (BugTypes.isEmpty())
1600    return;
1601
1602  // First flush the warnings for each BugType.  This may end up creating new
1603  // warnings and new BugTypes.
1604  // FIXME: Only NSErrorChecker needs BugType's FlushReports.
1605  // Turn NSErrorChecker into a proper checker and remove this.
1606  SmallVector<const BugType*, 16> bugTypes;
1607  for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
1608    bugTypes.push_back(*I);
1609  for (SmallVector<const BugType*, 16>::iterator
1610         I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I)
1611    const_cast<BugType*>(*I)->FlushReports(*this);
1612
1613  // We need to flush reports in deterministic order to ensure the order
1614  // of the reports is consistent between runs.
1615  typedef std::vector<BugReportEquivClass *> ContVecTy;
1616  for (ContVecTy::iterator EI=EQClassesVector.begin(), EE=EQClassesVector.end();
1617       EI != EE; ++EI){
1618    BugReportEquivClass& EQ = **EI;
1619    FlushReport(EQ);
1620  }
1621
1622  // BugReporter owns and deletes only BugTypes created implicitly through
1623  // EmitBasicReport.
1624  // FIXME: There are leaks from checkers that assume that the BugTypes they
1625  // create will be destroyed by the BugReporter.
1626  for (llvm::StringMap<BugType*>::iterator
1627         I = StrBugTypes.begin(), E = StrBugTypes.end(); I != E; ++I)
1628    delete I->second;
1629
1630  // Remove all references to the BugType objects.
1631  BugTypes = F.getEmptySet();
1632}
1633
1634//===----------------------------------------------------------------------===//
1635// PathDiagnostics generation.
1636//===----------------------------------------------------------------------===//
1637
1638static std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
1639                 std::pair<ExplodedNode*, unsigned> >
1640MakeReportGraph(const ExplodedGraph* G,
1641                SmallVectorImpl<const ExplodedNode*> &nodes) {
1642
1643  // Create the trimmed graph.  It will contain the shortest paths from the
1644  // error nodes to the root.  In the new graph we should only have one
1645  // error node unless there are two or more error nodes with the same minimum
1646  // path length.
1647  ExplodedGraph* GTrim;
1648  InterExplodedGraphMap* NMap;
1649
1650  llvm::DenseMap<const void*, const void*> InverseMap;
1651  llvm::tie(GTrim, NMap) = G->Trim(nodes.data(), nodes.data() + nodes.size(),
1652                                   &InverseMap);
1653
1654  // Create owning pointers for GTrim and NMap just to ensure that they are
1655  // released when this function exists.
1656  OwningPtr<ExplodedGraph> AutoReleaseGTrim(GTrim);
1657  OwningPtr<InterExplodedGraphMap> AutoReleaseNMap(NMap);
1658
1659  // Find the (first) error node in the trimmed graph.  We just need to consult
1660  // the node map (NMap) which maps from nodes in the original graph to nodes
1661  // in the new graph.
1662
1663  std::queue<const ExplodedNode*> WS;
1664  typedef llvm::DenseMap<const ExplodedNode*, unsigned> IndexMapTy;
1665  IndexMapTy IndexMap;
1666
1667  for (unsigned nodeIndex = 0 ; nodeIndex < nodes.size(); ++nodeIndex) {
1668    const ExplodedNode *originalNode = nodes[nodeIndex];
1669    if (const ExplodedNode *N = NMap->getMappedNode(originalNode)) {
1670      WS.push(N);
1671      IndexMap[originalNode] = nodeIndex;
1672    }
1673  }
1674
1675  assert(!WS.empty() && "No error node found in the trimmed graph.");
1676
1677  // Create a new (third!) graph with a single path.  This is the graph
1678  // that will be returned to the caller.
1679  ExplodedGraph *GNew = new ExplodedGraph();
1680
1681  // Sometimes the trimmed graph can contain a cycle.  Perform a reverse BFS
1682  // to the root node, and then construct a new graph that contains only
1683  // a single path.
1684  llvm::DenseMap<const void*,unsigned> Visited;
1685
1686  unsigned cnt = 0;
1687  const ExplodedNode *Root = 0;
1688
1689  while (!WS.empty()) {
1690    const ExplodedNode *Node = WS.front();
1691    WS.pop();
1692
1693    if (Visited.find(Node) != Visited.end())
1694      continue;
1695
1696    Visited[Node] = cnt++;
1697
1698    if (Node->pred_empty()) {
1699      Root = Node;
1700      break;
1701    }
1702
1703    for (ExplodedNode::const_pred_iterator I=Node->pred_begin(),
1704         E=Node->pred_end(); I!=E; ++I)
1705      WS.push(*I);
1706  }
1707
1708  assert(Root);
1709
1710  // Now walk from the root down the BFS path, always taking the successor
1711  // with the lowest number.
1712  ExplodedNode *Last = 0, *First = 0;
1713  NodeBackMap *BM = new NodeBackMap();
1714  unsigned NodeIndex = 0;
1715
1716  for ( const ExplodedNode *N = Root ;;) {
1717    // Lookup the number associated with the current node.
1718    llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
1719    assert(I != Visited.end());
1720
1721    // Create the equivalent node in the new graph with the same state
1722    // and location.
1723    ExplodedNode *NewN = GNew->getNode(N->getLocation(), N->getState());
1724
1725    // Store the mapping to the original node.
1726    llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1727    assert(IMitr != InverseMap.end() && "No mapping to original node.");
1728    (*BM)[NewN] = (const ExplodedNode*) IMitr->second;
1729
1730    // Link up the new node with the previous node.
1731    if (Last)
1732      NewN->addPredecessor(Last, *GNew);
1733
1734    Last = NewN;
1735
1736    // Are we at the final node?
1737    IndexMapTy::iterator IMI =
1738      IndexMap.find((const ExplodedNode*)(IMitr->second));
1739    if (IMI != IndexMap.end()) {
1740      First = NewN;
1741      NodeIndex = IMI->second;
1742      break;
1743    }
1744
1745    // Find the next successor node.  We choose the node that is marked
1746    // with the lowest DFS number.
1747    ExplodedNode::const_succ_iterator SI = N->succ_begin();
1748    ExplodedNode::const_succ_iterator SE = N->succ_end();
1749    N = 0;
1750
1751    for (unsigned MinVal = 0; SI != SE; ++SI) {
1752
1753      I = Visited.find(*SI);
1754
1755      if (I == Visited.end())
1756        continue;
1757
1758      if (!N || I->second < MinVal) {
1759        N = *SI;
1760        MinVal = I->second;
1761      }
1762    }
1763
1764    assert(N);
1765  }
1766
1767  assert(First);
1768
1769  return std::make_pair(std::make_pair(GNew, BM),
1770                        std::make_pair(First, NodeIndex));
1771}
1772
1773/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
1774///  and collapses PathDiagosticPieces that are expanded by macros.
1775static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM) {
1776  typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiece>,
1777                                SourceLocation> > MacroStackTy;
1778
1779  typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> >
1780          PiecesTy;
1781
1782  MacroStackTy MacroStack;
1783  PiecesTy Pieces;
1784
1785  for (PathPieces::const_iterator I = path.begin(), E = path.end();
1786       I!=E; ++I) {
1787
1788    PathDiagnosticPiece *piece = I->getPtr();
1789
1790    // Recursively compact calls.
1791    if (PathDiagnosticCallPiece *call=dyn_cast<PathDiagnosticCallPiece>(piece)){
1792      CompactPathDiagnostic(call->path, SM);
1793    }
1794
1795    // Get the location of the PathDiagnosticPiece.
1796    const FullSourceLoc Loc = piece->getLocation().asLocation();
1797
1798    // Determine the instantiation location, which is the location we group
1799    // related PathDiagnosticPieces.
1800    SourceLocation InstantiationLoc = Loc.isMacroID() ?
1801                                      SM.getExpansionLoc(Loc) :
1802                                      SourceLocation();
1803
1804    if (Loc.isFileID()) {
1805      MacroStack.clear();
1806      Pieces.push_back(piece);
1807      continue;
1808    }
1809
1810    assert(Loc.isMacroID());
1811
1812    // Is the PathDiagnosticPiece within the same macro group?
1813    if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
1814      MacroStack.back().first->subPieces.push_back(piece);
1815      continue;
1816    }
1817
1818    // We aren't in the same group.  Are we descending into a new macro
1819    // or are part of an old one?
1820    IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup;
1821
1822    SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
1823                                          SM.getExpansionLoc(Loc) :
1824                                          SourceLocation();
1825
1826    // Walk the entire macro stack.
1827    while (!MacroStack.empty()) {
1828      if (InstantiationLoc == MacroStack.back().second) {
1829        MacroGroup = MacroStack.back().first;
1830        break;
1831      }
1832
1833      if (ParentInstantiationLoc == MacroStack.back().second) {
1834        MacroGroup = MacroStack.back().first;
1835        break;
1836      }
1837
1838      MacroStack.pop_back();
1839    }
1840
1841    if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
1842      // Create a new macro group and add it to the stack.
1843      PathDiagnosticMacroPiece *NewGroup =
1844        new PathDiagnosticMacroPiece(
1845          PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
1846
1847      if (MacroGroup)
1848        MacroGroup->subPieces.push_back(NewGroup);
1849      else {
1850        assert(InstantiationLoc.isFileID());
1851        Pieces.push_back(NewGroup);
1852      }
1853
1854      MacroGroup = NewGroup;
1855      MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
1856    }
1857
1858    // Finally, add the PathDiagnosticPiece to the group.
1859    MacroGroup->subPieces.push_back(piece);
1860  }
1861
1862  // Now take the pieces and construct a new PathDiagnostic.
1863  path.clear();
1864
1865  for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I)
1866    path.push_back(*I);
1867}
1868
1869void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
1870                                           PathDiagnosticConsumer &PC,
1871                                           ArrayRef<BugReport *> &bugReports) {
1872
1873  assert(!bugReports.empty());
1874  SmallVector<const ExplodedNode *, 10> errorNodes;
1875  for (ArrayRef<BugReport*>::iterator I = bugReports.begin(),
1876                                      E = bugReports.end(); I != E; ++I) {
1877      errorNodes.push_back((*I)->getErrorNode());
1878  }
1879
1880  // Construct a new graph that contains only a single path from the error
1881  // node to a root.
1882  const std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
1883  std::pair<ExplodedNode*, unsigned> >&
1884    GPair = MakeReportGraph(&getGraph(), errorNodes);
1885
1886  // Find the BugReport with the original location.
1887  assert(GPair.second.second < bugReports.size());
1888  BugReport *R = bugReports[GPair.second.second];
1889  assert(R && "No original report found for sliced graph.");
1890
1891  OwningPtr<ExplodedGraph> ReportGraph(GPair.first.first);
1892  OwningPtr<NodeBackMap> BackMap(GPair.first.second);
1893  const ExplodedNode *N = GPair.second.first;
1894
1895  // Start building the path diagnostic...
1896  PathDiagnosticBuilder PDB(*this, R, BackMap.get(), &PC);
1897
1898  // Register additional node visitors.
1899  R->addVisitor(new NilReceiverBRVisitor());
1900  R->addVisitor(new ConditionBRVisitor());
1901
1902  BugReport::VisitorList visitors;
1903  unsigned originalReportConfigToken, finalReportConfigToken;
1904
1905  // While generating diagnostics, it's possible the visitors will decide
1906  // new symbols and regions are interesting, or add other visitors based on
1907  // the information they find. If they do, we need to regenerate the path
1908  // based on our new report configuration.
1909  do {
1910    // Get a clean copy of all the visitors.
1911    for (BugReport::visitor_iterator I = R->visitor_begin(),
1912                                     E = R->visitor_end(); I != E; ++I)
1913       visitors.push_back((*I)->clone());
1914
1915    // Clear out the active path from any previous work.
1916    PD.resetPath();
1917    originalReportConfigToken = R->getConfigurationChangeToken();
1918
1919    // Generate the very last diagnostic piece - the piece is visible before
1920    // the trace is expanded.
1921    PathDiagnosticPiece *LastPiece = 0;
1922    for (BugReport::visitor_iterator I = visitors.begin(), E = visitors.end();
1923         I != E; ++I) {
1924      if (PathDiagnosticPiece *Piece = (*I)->getEndPath(PDB, N, *R)) {
1925        assert (!LastPiece &&
1926                "There can only be one final piece in a diagnostic.");
1927        LastPiece = Piece;
1928      }
1929    }
1930    if (!LastPiece)
1931      LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R);
1932    if (LastPiece)
1933      PD.setEndOfPath(LastPiece);
1934    else
1935      return;
1936
1937    switch (PDB.getGenerationScheme()) {
1938    case PathDiagnosticConsumer::Extensive:
1939      GenerateExtensivePathDiagnostic(PD, PDB, N, visitors);
1940      break;
1941    case PathDiagnosticConsumer::Minimal:
1942      GenerateMinimalPathDiagnostic(PD, PDB, N, visitors);
1943      break;
1944    case PathDiagnosticConsumer::None:
1945      llvm_unreachable("PathDiagnosticConsumer::None should never appear here");
1946    }
1947
1948    // Clean up the visitors we used.
1949    llvm::DeleteContainerPointers(visitors);
1950
1951    // Did anything change while generating this path?
1952    finalReportConfigToken = R->getConfigurationChangeToken();
1953  } while(finalReportConfigToken != originalReportConfigToken);
1954
1955  // Finally, prune the diagnostic path of uninteresting stuff.
1956  if (R->shouldPrunePath()) {
1957    bool hasSomethingInteresting = RemoveUneededCalls(PD.getMutablePieces(), R);
1958    assert(hasSomethingInteresting);
1959    (void) hasSomethingInteresting;
1960  }
1961}
1962
1963void BugReporter::Register(BugType *BT) {
1964  BugTypes = F.add(BugTypes, BT);
1965}
1966
1967void BugReporter::EmitReport(BugReport* R) {
1968  // Compute the bug report's hash to determine its equivalence class.
1969  llvm::FoldingSetNodeID ID;
1970  R->Profile(ID);
1971
1972  // Lookup the equivance class.  If there isn't one, create it.
1973  BugType& BT = R->getBugType();
1974  Register(&BT);
1975  void *InsertPos;
1976  BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
1977
1978  if (!EQ) {
1979    EQ = new BugReportEquivClass(R);
1980    EQClasses.InsertNode(EQ, InsertPos);
1981    EQClassesVector.push_back(EQ);
1982  }
1983  else
1984    EQ->AddReport(R);
1985}
1986
1987
1988//===----------------------------------------------------------------------===//
1989// Emitting reports in equivalence classes.
1990//===----------------------------------------------------------------------===//
1991
1992namespace {
1993struct FRIEC_WLItem {
1994  const ExplodedNode *N;
1995  ExplodedNode::const_succ_iterator I, E;
1996
1997  FRIEC_WLItem(const ExplodedNode *n)
1998  : N(n), I(N->succ_begin()), E(N->succ_end()) {}
1999};
2000}
2001
2002static BugReport *
2003FindReportInEquivalenceClass(BugReportEquivClass& EQ,
2004                             SmallVectorImpl<BugReport*> &bugReports) {
2005
2006  BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
2007  assert(I != E);
2008  BugType& BT = I->getBugType();
2009
2010  // If we don't need to suppress any of the nodes because they are
2011  // post-dominated by a sink, simply add all the nodes in the equivalence class
2012  // to 'Nodes'.  Any of the reports will serve as a "representative" report.
2013  if (!BT.isSuppressOnSink()) {
2014    BugReport *R = I;
2015    for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
2016      const ExplodedNode *N = I->getErrorNode();
2017      if (N) {
2018        R = I;
2019        bugReports.push_back(R);
2020      }
2021    }
2022    return R;
2023  }
2024
2025  // For bug reports that should be suppressed when all paths are post-dominated
2026  // by a sink node, iterate through the reports in the equivalence class
2027  // until we find one that isn't post-dominated (if one exists).  We use a
2028  // DFS traversal of the ExplodedGraph to find a non-sink node.  We could write
2029  // this as a recursive function, but we don't want to risk blowing out the
2030  // stack for very long paths.
2031  BugReport *exampleReport = 0;
2032
2033  for (; I != E; ++I) {
2034    const ExplodedNode *errorNode = I->getErrorNode();
2035
2036    if (!errorNode)
2037      continue;
2038    if (errorNode->isSink()) {
2039      llvm_unreachable(
2040           "BugType::isSuppressSink() should not be 'true' for sink end nodes");
2041    }
2042    // No successors?  By definition this nodes isn't post-dominated by a sink.
2043    if (errorNode->succ_empty()) {
2044      bugReports.push_back(I);
2045      if (!exampleReport)
2046        exampleReport = I;
2047      continue;
2048    }
2049
2050    // At this point we know that 'N' is not a sink and it has at least one
2051    // successor.  Use a DFS worklist to find a non-sink end-of-path node.
2052    typedef FRIEC_WLItem WLItem;
2053    typedef SmallVector<WLItem, 10> DFSWorkList;
2054    llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
2055
2056    DFSWorkList WL;
2057    WL.push_back(errorNode);
2058    Visited[errorNode] = 1;
2059
2060    while (!WL.empty()) {
2061      WLItem &WI = WL.back();
2062      assert(!WI.N->succ_empty());
2063
2064      for (; WI.I != WI.E; ++WI.I) {
2065        const ExplodedNode *Succ = *WI.I;
2066        // End-of-path node?
2067        if (Succ->succ_empty()) {
2068          // If we found an end-of-path node that is not a sink.
2069          if (!Succ->isSink()) {
2070            bugReports.push_back(I);
2071            if (!exampleReport)
2072              exampleReport = I;
2073            WL.clear();
2074            break;
2075          }
2076          // Found a sink?  Continue on to the next successor.
2077          continue;
2078        }
2079        // Mark the successor as visited.  If it hasn't been explored,
2080        // enqueue it to the DFS worklist.
2081        unsigned &mark = Visited[Succ];
2082        if (!mark) {
2083          mark = 1;
2084          WL.push_back(Succ);
2085          break;
2086        }
2087      }
2088
2089      // The worklist may have been cleared at this point.  First
2090      // check if it is empty before checking the last item.
2091      if (!WL.empty() && &WL.back() == &WI)
2092        WL.pop_back();
2093    }
2094  }
2095
2096  // ExampleReport will be NULL if all the nodes in the equivalence class
2097  // were post-dominated by sinks.
2098  return exampleReport;
2099}
2100
2101void BugReporter::FlushReport(BugReportEquivClass& EQ) {
2102  SmallVector<BugReport*, 10> bugReports;
2103  BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports);
2104  if (exampleReport) {
2105    const PathDiagnosticConsumers &C = getPathDiagnosticConsumers();
2106    for (PathDiagnosticConsumers::const_iterator I=C.begin(),
2107                                                 E=C.end(); I != E; ++I) {
2108      FlushReport(exampleReport, **I, bugReports);
2109    }
2110  }
2111}
2112
2113void BugReporter::FlushReport(BugReport *exampleReport,
2114                              PathDiagnosticConsumer &PD,
2115                              ArrayRef<BugReport*> bugReports) {
2116
2117  // FIXME: Make sure we use the 'R' for the path that was actually used.
2118  // Probably doesn't make a difference in practice.
2119  BugType& BT = exampleReport->getBugType();
2120
2121  OwningPtr<PathDiagnostic>
2122    D(new PathDiagnostic(exampleReport->getDeclWithIssue(),
2123                         exampleReport->getBugType().getName(),
2124                         exampleReport->getDescription(),
2125                         exampleReport->getShortDescription(/*Fallback=*/false),
2126                         BT.getCategory()));
2127
2128  // Generate the full path diagnostic, using the generation scheme
2129  // specified by the PathDiagnosticConsumer.
2130  if (PD.getGenerationScheme() != PathDiagnosticConsumer::None) {
2131    if (!bugReports.empty())
2132      GeneratePathDiagnostic(*D.get(), PD, bugReports);
2133  }
2134
2135  // If the path is empty, generate a single step path with the location
2136  // of the issue.
2137  if (D->path.empty()) {
2138    PathDiagnosticLocation L = exampleReport->getLocation(getSourceManager());
2139    PathDiagnosticPiece *piece =
2140      new PathDiagnosticEventPiece(L, exampleReport->getDescription());
2141    BugReport::ranges_iterator Beg, End;
2142    llvm::tie(Beg, End) = exampleReport->getRanges();
2143    for ( ; Beg != End; ++Beg)
2144      piece->addRange(*Beg);
2145    D->setEndOfPath(piece);
2146  }
2147
2148  // Get the meta data.
2149  const BugReport::ExtraTextList &Meta = exampleReport->getExtraText();
2150  for (BugReport::ExtraTextList::const_iterator i = Meta.begin(),
2151                                                e = Meta.end(); i != e; ++i) {
2152    D->addMeta(*i);
2153  }
2154
2155  PD.HandlePathDiagnostic(D.take());
2156}
2157
2158void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
2159                                  StringRef name,
2160                                  StringRef category,
2161                                  StringRef str, PathDiagnosticLocation Loc,
2162                                  SourceRange* RBeg, unsigned NumRanges) {
2163
2164  // 'BT' is owned by BugReporter.
2165  BugType *BT = getBugTypeForName(name, category);
2166  BugReport *R = new BugReport(*BT, str, Loc);
2167  R->setDeclWithIssue(DeclWithIssue);
2168  for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
2169  EmitReport(R);
2170}
2171
2172BugType *BugReporter::getBugTypeForName(StringRef name,
2173                                        StringRef category) {
2174  SmallString<136> fullDesc;
2175  llvm::raw_svector_ostream(fullDesc) << name << ":" << category;
2176  llvm::StringMapEntry<BugType *> &
2177      entry = StrBugTypes.GetOrCreateValue(fullDesc);
2178  BugType *BT = entry.getValue();
2179  if (!BT) {
2180    BT = new BugType(name, category);
2181    entry.setValue(BT);
2182  }
2183  return BT;
2184}
2185