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