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