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