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