clang  mainline
BugReporter.cpp
Go to the documentation of this file.
00001 // BugReporter.cpp - Generate PathDiagnostics for Bugs ------------*- C++ -*--//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines BugReporter, a utility class for generating
00011 //  PathDiagnostics.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
00016 #include "clang/AST/ASTContext.h"
00017 #include "clang/AST/DeclObjC.h"
00018 #include "clang/AST/Expr.h"
00019 #include "clang/AST/ExprCXX.h"
00020 #include "clang/AST/ParentMap.h"
00021 #include "clang/AST/StmtCXX.h"
00022 #include "clang/AST/StmtObjC.h"
00023 #include "clang/Analysis/CFG.h"
00024 #include "clang/Analysis/ProgramPoint.h"
00025 #include "clang/Basic/SourceManager.h"
00026 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
00027 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
00028 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
00029 #include "llvm/ADT/DenseMap.h"
00030 #include "llvm/ADT/IntrusiveRefCntPtr.h"
00031 #include "llvm/ADT/STLExtras.h"
00032 #include "llvm/ADT/SmallString.h"
00033 #include "llvm/ADT/Statistic.h"
00034 #include "llvm/Support/raw_ostream.h"
00035 #include <memory>
00036 #include <queue>
00037 
00038 using namespace clang;
00039 using namespace ento;
00040 
00041 #define DEBUG_TYPE "BugReporter"
00042 
00043 STATISTIC(MaxBugClassSize,
00044           "The maximum number of bug reports in the same equivalence class");
00045 STATISTIC(MaxValidBugClassSize,
00046           "The maximum number of bug reports in the same equivalence class "
00047           "where at least one report is valid (not suppressed)");
00048 
00049 BugReporterVisitor::~BugReporterVisitor() {}
00050 
00051 void BugReporterContext::anchor() {}
00052 
00053 //===----------------------------------------------------------------------===//
00054 // Helper routines for walking the ExplodedGraph and fetching statements.
00055 //===----------------------------------------------------------------------===//
00056 
00057 static const Stmt *GetPreviousStmt(const ExplodedNode *N) {
00058   for (N = N->getFirstPred(); N; N = N->getFirstPred())
00059     if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
00060       return S;
00061 
00062   return nullptr;
00063 }
00064 
00065 static inline const Stmt*
00066 GetCurrentOrPreviousStmt(const ExplodedNode *N) {
00067   if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
00068     return S;
00069 
00070   return GetPreviousStmt(N);
00071 }
00072 
00073 //===----------------------------------------------------------------------===//
00074 // Diagnostic cleanup.
00075 //===----------------------------------------------------------------------===//
00076 
00077 static PathDiagnosticEventPiece *
00078 eventsDescribeSameCondition(PathDiagnosticEventPiece *X,
00079                             PathDiagnosticEventPiece *Y) {
00080   // Prefer diagnostics that come from ConditionBRVisitor over
00081   // those that came from TrackConstraintBRVisitor.
00082   const void *tagPreferred = ConditionBRVisitor::getTag();
00083   const void *tagLesser = TrackConstraintBRVisitor::getTag();
00084   
00085   if (X->getLocation() != Y->getLocation())
00086     return nullptr;
00087 
00088   if (X->getTag() == tagPreferred && Y->getTag() == tagLesser)
00089     return X;
00090   
00091   if (Y->getTag() == tagPreferred && X->getTag() == tagLesser)
00092     return Y;
00093 
00094   return nullptr;
00095 }
00096 
00097 /// An optimization pass over PathPieces that removes redundant diagnostics
00098 /// generated by both ConditionBRVisitor and TrackConstraintBRVisitor.  Both
00099 /// BugReporterVisitors use different methods to generate diagnostics, with
00100 /// one capable of emitting diagnostics in some cases but not in others.  This
00101 /// can lead to redundant diagnostic pieces at the same point in a path.
00102 static void removeRedundantMsgs(PathPieces &path) {
00103   unsigned N = path.size();
00104   if (N < 2)
00105     return;
00106   // NOTE: this loop intentionally is not using an iterator.  Instead, we
00107   // are streaming the path and modifying it in place.  This is done by
00108   // grabbing the front, processing it, and if we decide to keep it append
00109   // it to the end of the path.  The entire path is processed in this way.
00110   for (unsigned i = 0; i < N; ++i) {
00111     IntrusiveRefCntPtr<PathDiagnosticPiece> piece(path.front());
00112     path.pop_front();
00113     
00114     switch (piece->getKind()) {
00115       case clang::ento::PathDiagnosticPiece::Call:
00116         removeRedundantMsgs(cast<PathDiagnosticCallPiece>(piece)->path);
00117         break;
00118       case clang::ento::PathDiagnosticPiece::Macro:
00119         removeRedundantMsgs(cast<PathDiagnosticMacroPiece>(piece)->subPieces);
00120         break;
00121       case clang::ento::PathDiagnosticPiece::ControlFlow:
00122         break;
00123       case clang::ento::PathDiagnosticPiece::Event: {
00124         if (i == N-1)
00125           break;
00126         
00127         if (PathDiagnosticEventPiece *nextEvent =
00128             dyn_cast<PathDiagnosticEventPiece>(path.front().get())) {
00129           PathDiagnosticEventPiece *event =
00130             cast<PathDiagnosticEventPiece>(piece);
00131           // Check to see if we should keep one of the two pieces.  If we
00132           // come up with a preference, record which piece to keep, and consume
00133           // another piece from the path.
00134           if (PathDiagnosticEventPiece *pieceToKeep =
00135               eventsDescribeSameCondition(event, nextEvent)) {
00136             piece = pieceToKeep;
00137             path.pop_front();
00138             ++i;
00139           }
00140         }
00141         break;
00142       }
00143     }
00144     path.push_back(piece);
00145   }
00146 }
00147 
00148 /// A map from PathDiagnosticPiece to the LocationContext of the inlined
00149 /// function call it represents.
00150 typedef llvm::DenseMap<const PathPieces *, const LocationContext *>
00151         LocationContextMap;
00152 
00153 /// Recursively scan through a path and prune out calls and macros pieces
00154 /// that aren't needed.  Return true if afterwards the path contains
00155 /// "interesting stuff" which means it shouldn't be pruned from the parent path.
00156 static bool removeUnneededCalls(PathPieces &pieces, BugReport *R,
00157                                 LocationContextMap &LCM) {
00158   bool containsSomethingInteresting = false;
00159   const unsigned N = pieces.size();
00160   
00161   for (unsigned i = 0 ; i < N ; ++i) {
00162     // Remove the front piece from the path.  If it is still something we
00163     // want to keep once we are done, we will push it back on the end.
00164     IntrusiveRefCntPtr<PathDiagnosticPiece> piece(pieces.front());
00165     pieces.pop_front();
00166     
00167     switch (piece->getKind()) {
00168       case PathDiagnosticPiece::Call: {
00169         PathDiagnosticCallPiece *call = cast<PathDiagnosticCallPiece>(piece);
00170         // Check if the location context is interesting.
00171         assert(LCM.count(&call->path));
00172         if (R->isInteresting(LCM[&call->path])) {
00173           containsSomethingInteresting = true;
00174           break;
00175         }
00176 
00177         if (!removeUnneededCalls(call->path, R, LCM))
00178           continue;
00179         
00180         containsSomethingInteresting = true;
00181         break;
00182       }
00183       case PathDiagnosticPiece::Macro: {
00184         PathDiagnosticMacroPiece *macro = cast<PathDiagnosticMacroPiece>(piece);
00185         if (!removeUnneededCalls(macro->subPieces, R, LCM))
00186           continue;
00187         containsSomethingInteresting = true;
00188         break;
00189       }
00190       case PathDiagnosticPiece::Event: {
00191         PathDiagnosticEventPiece *event = cast<PathDiagnosticEventPiece>(piece);
00192         
00193         // We never throw away an event, but we do throw it away wholesale
00194         // as part of a path if we throw the entire path away.
00195         containsSomethingInteresting |= !event->isPrunable();
00196         break;
00197       }
00198       case PathDiagnosticPiece::ControlFlow:
00199         break;
00200     }
00201     
00202     pieces.push_back(piece);
00203   }
00204   
00205   return containsSomethingInteresting;
00206 }
00207 
00208 /// Returns true if the given decl has been implicitly given a body, either by
00209 /// the analyzer or by the compiler proper.
00210 static bool hasImplicitBody(const Decl *D) {
00211   assert(D);
00212   return D->isImplicit() || !D->hasBody();
00213 }
00214 
00215 /// Recursively scan through a path and make sure that all call pieces have
00216 /// valid locations. 
00217 static void
00218 adjustCallLocations(PathPieces &Pieces,
00219                     PathDiagnosticLocation *LastCallLocation = nullptr) {
00220   for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E; ++I) {
00221     PathDiagnosticCallPiece *Call = dyn_cast<PathDiagnosticCallPiece>(*I);
00222 
00223     if (!Call) {
00224       assert((*I)->getLocation().asLocation().isValid());
00225       continue;
00226     }
00227 
00228     if (LastCallLocation) {
00229       bool CallerIsImplicit = hasImplicitBody(Call->getCaller());
00230       if (CallerIsImplicit || !Call->callEnter.asLocation().isValid())
00231         Call->callEnter = *LastCallLocation;
00232       if (CallerIsImplicit || !Call->callReturn.asLocation().isValid())
00233         Call->callReturn = *LastCallLocation;
00234     }
00235 
00236     // Recursively clean out the subclass.  Keep this call around if
00237     // it contains any informative diagnostics.
00238     PathDiagnosticLocation *ThisCallLocation;
00239     if (Call->callEnterWithin.asLocation().isValid() &&
00240         !hasImplicitBody(Call->getCallee()))
00241       ThisCallLocation = &Call->callEnterWithin;
00242     else
00243       ThisCallLocation = &Call->callEnter;
00244 
00245     assert(ThisCallLocation && "Outermost call has an invalid location");
00246     adjustCallLocations(Call->path, ThisCallLocation);
00247   }
00248 }
00249 
00250 /// Remove edges in and out of C++ default initializer expressions. These are
00251 /// for fields that have in-class initializers, as opposed to being initialized
00252 /// explicitly in a constructor or braced list.
00253 static void removeEdgesToDefaultInitializers(PathPieces &Pieces) {
00254   for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
00255     if (PathDiagnosticCallPiece *C = dyn_cast<PathDiagnosticCallPiece>(*I))
00256       removeEdgesToDefaultInitializers(C->path);
00257 
00258     if (PathDiagnosticMacroPiece *M = dyn_cast<PathDiagnosticMacroPiece>(*I))
00259       removeEdgesToDefaultInitializers(M->subPieces);
00260 
00261     if (PathDiagnosticControlFlowPiece *CF =
00262           dyn_cast<PathDiagnosticControlFlowPiece>(*I)) {
00263       const Stmt *Start = CF->getStartLocation().asStmt();
00264       const Stmt *End = CF->getEndLocation().asStmt();
00265       if (Start && isa<CXXDefaultInitExpr>(Start)) {
00266         I = Pieces.erase(I);
00267         continue;
00268       } else if (End && isa<CXXDefaultInitExpr>(End)) {
00269         PathPieces::iterator Next = std::next(I);
00270         if (Next != E) {
00271           if (PathDiagnosticControlFlowPiece *NextCF =
00272                 dyn_cast<PathDiagnosticControlFlowPiece>(*Next)) {
00273             NextCF->setStartLocation(CF->getStartLocation());
00274           }
00275         }
00276         I = Pieces.erase(I);
00277         continue;
00278       }
00279     }
00280 
00281     I++;
00282   }
00283 }
00284 
00285 /// Remove all pieces with invalid locations as these cannot be serialized.
00286 /// We might have pieces with invalid locations as a result of inlining Body
00287 /// Farm generated functions.
00288 static void removePiecesWithInvalidLocations(PathPieces &Pieces) {
00289   for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
00290     if (PathDiagnosticCallPiece *C = dyn_cast<PathDiagnosticCallPiece>(*I))
00291       removePiecesWithInvalidLocations(C->path);
00292 
00293     if (PathDiagnosticMacroPiece *M = dyn_cast<PathDiagnosticMacroPiece>(*I))
00294       removePiecesWithInvalidLocations(M->subPieces);
00295 
00296     if (!(*I)->getLocation().isValid() ||
00297         !(*I)->getLocation().asLocation().isValid()) {
00298       I = Pieces.erase(I);
00299       continue;
00300     }
00301     I++;
00302   }
00303 }
00304 
00305 //===----------------------------------------------------------------------===//
00306 // PathDiagnosticBuilder and its associated routines and helper objects.
00307 //===----------------------------------------------------------------------===//
00308 
00309 namespace {
00310 class NodeMapClosure : public BugReport::NodeResolver {
00311   InterExplodedGraphMap &M;
00312 public:
00313   NodeMapClosure(InterExplodedGraphMap &m) : M(m) {}
00314 
00315   const ExplodedNode *getOriginalNode(const ExplodedNode *N) override {
00316     return M.lookup(N);
00317   }
00318 };
00319 
00320 class PathDiagnosticBuilder : public BugReporterContext {
00321   BugReport *R;
00322   PathDiagnosticConsumer *PDC;
00323   NodeMapClosure NMC;
00324 public:
00325   const LocationContext *LC;
00326   
00327   PathDiagnosticBuilder(GRBugReporter &br,
00328                         BugReport *r, InterExplodedGraphMap &Backmap,
00329                         PathDiagnosticConsumer *pdc)
00330     : BugReporterContext(br),
00331       R(r), PDC(pdc), NMC(Backmap), LC(r->getErrorNode()->getLocationContext())
00332   {}
00333 
00334   PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N);
00335 
00336   PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os,
00337                                             const ExplodedNode *N);
00338 
00339   BugReport *getBugReport() { return R; }
00340 
00341   Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); }
00342   
00343   ParentMap& getParentMap() { return LC->getParentMap(); }
00344 
00345   const Stmt *getParent(const Stmt *S) {
00346     return getParentMap().getParent(S);
00347   }
00348 
00349   NodeMapClosure& getNodeResolver() override { return NMC; }
00350 
00351   PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
00352 
00353   PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const {
00354     return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Extensive;
00355   }
00356 
00357   bool supportsLogicalOpControlFlow() const {
00358     return PDC ? PDC->supportsLogicalOpControlFlow() : true;
00359   }
00360 };
00361 } // end anonymous namespace
00362 
00363 PathDiagnosticLocation
00364 PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) {
00365   if (const Stmt *S = PathDiagnosticLocation::getNextStmt(N))
00366     return PathDiagnosticLocation(S, getSourceManager(), LC);
00367 
00368   return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(),
00369                                                getSourceManager());
00370 }
00371 
00372 PathDiagnosticLocation
00373 PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os,
00374                                           const ExplodedNode *N) {
00375 
00376   // Slow, but probably doesn't matter.
00377   if (os.str().empty())
00378     os << ' ';
00379 
00380   const PathDiagnosticLocation &Loc = ExecutionContinues(N);
00381 
00382   if (Loc.asStmt())
00383     os << "Execution continues on line "
00384        << getSourceManager().getExpansionLineNumber(Loc.asLocation())
00385        << '.';
00386   else {
00387     os << "Execution jumps to the end of the ";
00388     const Decl *D = N->getLocationContext()->getDecl();
00389     if (isa<ObjCMethodDecl>(D))
00390       os << "method";
00391     else if (isa<FunctionDecl>(D))
00392       os << "function";
00393     else {
00394       assert(isa<BlockDecl>(D));
00395       os << "anonymous block";
00396     }
00397     os << '.';
00398   }
00399 
00400   return Loc;
00401 }
00402 
00403 static const Stmt *getEnclosingParent(const Stmt *S, const ParentMap &PM) {
00404   if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
00405     return PM.getParentIgnoreParens(S);
00406 
00407   const Stmt *Parent = PM.getParentIgnoreParens(S);
00408   if (!Parent)
00409     return nullptr;
00410 
00411   switch (Parent->getStmtClass()) {
00412   case Stmt::ForStmtClass:
00413   case Stmt::DoStmtClass:
00414   case Stmt::WhileStmtClass:
00415   case Stmt::ObjCForCollectionStmtClass:
00416   case Stmt::CXXForRangeStmtClass:
00417     return Parent;
00418   default:
00419     break;
00420   }
00421 
00422   return nullptr;
00423 }
00424 
00425 static PathDiagnosticLocation
00426 getEnclosingStmtLocation(const Stmt *S, SourceManager &SMgr, const ParentMap &P,
00427                          const LocationContext *LC, bool allowNestedContexts) {
00428   if (!S)
00429     return PathDiagnosticLocation();
00430 
00431   while (const Stmt *Parent = getEnclosingParent(S, P)) {
00432     switch (Parent->getStmtClass()) {
00433       case Stmt::BinaryOperatorClass: {
00434         const BinaryOperator *B = cast<BinaryOperator>(Parent);
00435         if (B->isLogicalOp())
00436           return PathDiagnosticLocation(allowNestedContexts ? B : S, SMgr, LC);
00437         break;
00438       }
00439       case Stmt::CompoundStmtClass:
00440       case Stmt::StmtExprClass:
00441         return PathDiagnosticLocation(S, SMgr, LC);
00442       case Stmt::ChooseExprClass:
00443         // Similar to '?' if we are referring to condition, just have the edge
00444         // point to the entire choose expression.
00445         if (allowNestedContexts || cast<ChooseExpr>(Parent)->getCond() == S)
00446           return PathDiagnosticLocation(Parent, SMgr, LC);
00447         else
00448           return PathDiagnosticLocation(S, SMgr, LC);
00449       case Stmt::BinaryConditionalOperatorClass:
00450       case Stmt::ConditionalOperatorClass:
00451         // For '?', if we are referring to condition, just have the edge point
00452         // to the entire '?' expression.
00453         if (allowNestedContexts ||
00454             cast<AbstractConditionalOperator>(Parent)->getCond() == S)
00455           return PathDiagnosticLocation(Parent, SMgr, LC);
00456         else
00457           return PathDiagnosticLocation(S, SMgr, LC);
00458       case Stmt::CXXForRangeStmtClass:
00459         if (cast<CXXForRangeStmt>(Parent)->getBody() == S)
00460           return PathDiagnosticLocation(S, SMgr, LC);
00461         break;
00462       case Stmt::DoStmtClass:
00463           return PathDiagnosticLocation(S, SMgr, LC);
00464       case Stmt::ForStmtClass:
00465         if (cast<ForStmt>(Parent)->getBody() == S)
00466           return PathDiagnosticLocation(S, SMgr, LC);
00467         break;
00468       case Stmt::IfStmtClass:
00469         if (cast<IfStmt>(Parent)->getCond() != S)
00470           return PathDiagnosticLocation(S, SMgr, LC);
00471         break;
00472       case Stmt::ObjCForCollectionStmtClass:
00473         if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
00474           return PathDiagnosticLocation(S, SMgr, LC);
00475         break;
00476       case Stmt::WhileStmtClass:
00477         if (cast<WhileStmt>(Parent)->getCond() != S)
00478           return PathDiagnosticLocation(S, SMgr, LC);
00479         break;
00480       default:
00481         break;
00482     }
00483 
00484     S = Parent;
00485   }
00486 
00487   assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
00488 
00489   return PathDiagnosticLocation(S, SMgr, LC);
00490 }
00491 
00492 PathDiagnosticLocation
00493 PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
00494   assert(S && "Null Stmt passed to getEnclosingStmtLocation");
00495   return ::getEnclosingStmtLocation(S, getSourceManager(), getParentMap(), LC,
00496                                     /*allowNestedContexts=*/false);
00497 }
00498 
00499 //===----------------------------------------------------------------------===//
00500 // "Visitors only" path diagnostic generation algorithm.
00501 //===----------------------------------------------------------------------===//
00502 static bool GenerateVisitorsOnlyPathDiagnostic(
00503     PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
00504     ArrayRef<std::unique_ptr<BugReporterVisitor>> visitors) {
00505   // All path generation skips the very first node (the error node).
00506   // This is because there is special handling for the end-of-path note.
00507   N = N->getFirstPred();
00508   if (!N)
00509     return true;
00510 
00511   BugReport *R = PDB.getBugReport();
00512   while (const ExplodedNode *Pred = N->getFirstPred()) {
00513     for (auto &V : visitors) {
00514       // Visit all the node pairs, but throw the path pieces away.
00515       PathDiagnosticPiece *Piece = V->VisitNode(N, Pred, PDB, *R);
00516       delete Piece;
00517     }
00518 
00519     N = Pred;
00520   }
00521 
00522   return R->isValid();
00523 }
00524 
00525 //===----------------------------------------------------------------------===//
00526 // "Minimal" path diagnostic generation algorithm.
00527 //===----------------------------------------------------------------------===//
00528 typedef std::pair<PathDiagnosticCallPiece*, const ExplodedNode*> StackDiagPair;
00529 typedef SmallVector<StackDiagPair, 6> StackDiagVector;
00530 
00531 static void updateStackPiecesWithMessage(PathDiagnosticPiece *P,
00532                                          StackDiagVector &CallStack) {
00533   // If the piece contains a special message, add it to all the call
00534   // pieces on the active stack.
00535   if (PathDiagnosticEventPiece *ep =
00536         dyn_cast<PathDiagnosticEventPiece>(P)) {
00537 
00538     if (ep->hasCallStackHint())
00539       for (StackDiagVector::iterator I = CallStack.begin(),
00540                                      E = CallStack.end(); I != E; ++I) {
00541         PathDiagnosticCallPiece *CP = I->first;
00542         const ExplodedNode *N = I->second;
00543         std::string stackMsg = ep->getCallStackMessage(N);
00544 
00545         // The last message on the path to final bug is the most important
00546         // one. Since we traverse the path backwards, do not add the message
00547         // if one has been previously added.
00548         if  (!CP->hasCallStackMessage())
00549           CP->setCallStackMessage(stackMsg);
00550       }
00551   }
00552 }
00553 
00554 static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM);
00555 
00556 static bool GenerateMinimalPathDiagnostic(
00557     PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
00558     LocationContextMap &LCM,
00559     ArrayRef<std::unique_ptr<BugReporterVisitor>> visitors) {
00560 
00561   SourceManager& SMgr = PDB.getSourceManager();
00562   const LocationContext *LC = PDB.LC;
00563   const ExplodedNode *NextNode = N->pred_empty()
00564                                         ? nullptr : *(N->pred_begin());
00565 
00566   StackDiagVector CallStack;
00567 
00568   while (NextNode) {
00569     N = NextNode;
00570     PDB.LC = N->getLocationContext();
00571     NextNode = N->getFirstPred();
00572 
00573     ProgramPoint P = N->getLocation();
00574 
00575     do {
00576       if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
00577         PathDiagnosticCallPiece *C =
00578             PathDiagnosticCallPiece::construct(N, *CE, SMgr);
00579         // Record the mapping from call piece to LocationContext.
00580         LCM[&C->path] = CE->getCalleeContext();
00581         PD.getActivePath().push_front(C);
00582         PD.pushActivePath(&C->path);
00583         CallStack.push_back(StackDiagPair(C, N));
00584         break;
00585       }
00586 
00587       if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
00588         // Flush all locations, and pop the active path.
00589         bool VisitedEntireCall = PD.isWithinCall();
00590         PD.popActivePath();
00591 
00592         // Either we just added a bunch of stuff to the top-level path, or
00593         // we have a previous CallExitEnd.  If the former, it means that the
00594         // path terminated within a function call.  We must then take the
00595         // current contents of the active path and place it within
00596         // a new PathDiagnosticCallPiece.
00597         PathDiagnosticCallPiece *C;
00598         if (VisitedEntireCall) {
00599           C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
00600         } else {
00601           const Decl *Caller = CE->getLocationContext()->getDecl();
00602           C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
00603           // Record the mapping from call piece to LocationContext.
00604           LCM[&C->path] = CE->getCalleeContext();
00605         }
00606 
00607         C->setCallee(*CE, SMgr);
00608         if (!CallStack.empty()) {
00609           assert(CallStack.back().first == C);
00610           CallStack.pop_back();
00611         }
00612         break;
00613       }
00614 
00615       if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
00616         const CFGBlock *Src = BE->getSrc();
00617         const CFGBlock *Dst = BE->getDst();
00618         const Stmt *T = Src->getTerminator();
00619 
00620         if (!T)
00621           break;
00622 
00623         PathDiagnosticLocation Start =
00624             PathDiagnosticLocation::createBegin(T, SMgr,
00625                 N->getLocationContext());
00626 
00627         switch (T->getStmtClass()) {
00628         default:
00629           break;
00630 
00631         case Stmt::GotoStmtClass:
00632         case Stmt::IndirectGotoStmtClass: {
00633           const Stmt *S = PathDiagnosticLocation::getNextStmt(N);
00634 
00635           if (!S)
00636             break;
00637 
00638           std::string sbuf;
00639           llvm::raw_string_ostream os(sbuf);
00640           const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
00641 
00642           os << "Control jumps to line "
00643               << End.asLocation().getExpansionLineNumber();
00644           PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
00645               Start, End, os.str()));
00646           break;
00647         }
00648 
00649         case Stmt::SwitchStmtClass: {
00650           // Figure out what case arm we took.
00651           std::string sbuf;
00652           llvm::raw_string_ostream os(sbuf);
00653 
00654           if (const Stmt *S = Dst->getLabel()) {
00655             PathDiagnosticLocation End(S, SMgr, LC);
00656 
00657             switch (S->getStmtClass()) {
00658             default:
00659               os << "No cases match in the switch statement. "
00660               "Control jumps to line "
00661               << End.asLocation().getExpansionLineNumber();
00662               break;
00663             case Stmt::DefaultStmtClass:
00664               os << "Control jumps to the 'default' case at line "
00665               << End.asLocation().getExpansionLineNumber();
00666               break;
00667 
00668             case Stmt::CaseStmtClass: {
00669               os << "Control jumps to 'case ";
00670               const CaseStmt *Case = cast<CaseStmt>(S);
00671               const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
00672 
00673               // Determine if it is an enum.
00674               bool GetRawInt = true;
00675 
00676               if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
00677                 // FIXME: Maybe this should be an assertion.  Are there cases
00678                 // were it is not an EnumConstantDecl?
00679                 const EnumConstantDecl *D =
00680                     dyn_cast<EnumConstantDecl>(DR->getDecl());
00681 
00682                 if (D) {
00683                   GetRawInt = false;
00684                   os << *D;
00685                 }
00686               }
00687 
00688               if (GetRawInt)
00689                 os << LHS->EvaluateKnownConstInt(PDB.getASTContext());
00690 
00691               os << ":'  at line "
00692                   << End.asLocation().getExpansionLineNumber();
00693               break;
00694             }
00695             }
00696             PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
00697                 Start, End, os.str()));
00698           }
00699           else {
00700             os << "'Default' branch taken. ";
00701             const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
00702             PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
00703                 Start, End, os.str()));
00704           }
00705 
00706           break;
00707         }
00708 
00709         case Stmt::BreakStmtClass:
00710         case Stmt::ContinueStmtClass: {
00711           std::string sbuf;
00712           llvm::raw_string_ostream os(sbuf);
00713           PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
00714           PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
00715               Start, End, os.str()));
00716           break;
00717         }
00718 
00719         // Determine control-flow for ternary '?'.
00720         case Stmt::BinaryConditionalOperatorClass:
00721         case Stmt::ConditionalOperatorClass: {
00722           std::string sbuf;
00723           llvm::raw_string_ostream os(sbuf);
00724           os << "'?' condition is ";
00725 
00726           if (*(Src->succ_begin()+1) == Dst)
00727             os << "false";
00728           else
00729             os << "true";
00730 
00731           PathDiagnosticLocation End = PDB.ExecutionContinues(N);
00732 
00733           if (const Stmt *S = End.asStmt())
00734             End = PDB.getEnclosingStmtLocation(S);
00735 
00736           PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
00737               Start, End, os.str()));
00738           break;
00739         }
00740 
00741         // Determine control-flow for short-circuited '&&' and '||'.
00742         case Stmt::BinaryOperatorClass: {
00743           if (!PDB.supportsLogicalOpControlFlow())
00744             break;
00745 
00746           const BinaryOperator *B = cast<BinaryOperator>(T);
00747           std::string sbuf;
00748           llvm::raw_string_ostream os(sbuf);
00749           os << "Left side of '";
00750 
00751           if (B->getOpcode() == BO_LAnd) {
00752             os << "&&" << "' is ";
00753 
00754             if (*(Src->succ_begin()+1) == Dst) {
00755               os << "false";
00756               PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
00757               PathDiagnosticLocation Start =
00758                   PathDiagnosticLocation::createOperatorLoc(B, SMgr);
00759               PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
00760                   Start, End, os.str()));
00761             }
00762             else {
00763               os << "true";
00764               PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
00765               PathDiagnosticLocation End = PDB.ExecutionContinues(N);
00766               PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
00767                   Start, End, os.str()));
00768             }
00769           }
00770           else {
00771             assert(B->getOpcode() == BO_LOr);
00772             os << "||" << "' is ";
00773 
00774             if (*(Src->succ_begin()+1) == Dst) {
00775               os << "false";
00776               PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
00777               PathDiagnosticLocation End = PDB.ExecutionContinues(N);
00778               PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
00779                   Start, End, os.str()));
00780             }
00781             else {
00782               os << "true";
00783               PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
00784               PathDiagnosticLocation Start =
00785                   PathDiagnosticLocation::createOperatorLoc(B, SMgr);
00786               PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
00787                   Start, End, os.str()));
00788             }
00789           }
00790 
00791           break;
00792         }
00793 
00794         case Stmt::DoStmtClass:  {
00795           if (*(Src->succ_begin()) == Dst) {
00796             std::string sbuf;
00797             llvm::raw_string_ostream os(sbuf);
00798 
00799             os << "Loop condition is true. ";
00800             PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
00801 
00802             if (const Stmt *S = End.asStmt())
00803               End = PDB.getEnclosingStmtLocation(S);
00804 
00805             PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
00806                 Start, End, os.str()));
00807           }
00808           else {
00809             PathDiagnosticLocation End = PDB.ExecutionContinues(N);
00810 
00811             if (const Stmt *S = End.asStmt())
00812               End = PDB.getEnclosingStmtLocation(S);
00813 
00814             PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
00815                 Start, End, "Loop condition is false.  Exiting loop"));
00816           }
00817 
00818           break;
00819         }
00820 
00821         case Stmt::WhileStmtClass:
00822         case Stmt::ForStmtClass: {
00823           if (*(Src->succ_begin()+1) == Dst) {
00824             std::string sbuf;
00825             llvm::raw_string_ostream os(sbuf);
00826 
00827             os << "Loop condition is false. ";
00828             PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
00829             if (const Stmt *S = End.asStmt())
00830               End = PDB.getEnclosingStmtLocation(S);
00831 
00832             PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
00833                 Start, End, os.str()));
00834           }
00835           else {
00836             PathDiagnosticLocation End = PDB.ExecutionContinues(N);
00837             if (const Stmt *S = End.asStmt())
00838               End = PDB.getEnclosingStmtLocation(S);
00839 
00840             PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
00841                 Start, End, "Loop condition is true.  Entering loop body"));
00842           }
00843 
00844           break;
00845         }
00846 
00847         case Stmt::IfStmtClass: {
00848           PathDiagnosticLocation End = PDB.ExecutionContinues(N);
00849 
00850           if (const Stmt *S = End.asStmt())
00851             End = PDB.getEnclosingStmtLocation(S);
00852 
00853           if (*(Src->succ_begin()+1) == Dst)
00854             PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
00855                 Start, End, "Taking false branch"));
00856           else
00857             PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
00858                 Start, End, "Taking true branch"));
00859 
00860           break;
00861         }
00862         }
00863       }
00864     } while(0);
00865 
00866     if (NextNode) {
00867       // Add diagnostic pieces from custom visitors.
00868       BugReport *R = PDB.getBugReport();
00869       for (auto &V : visitors) {
00870         if (PathDiagnosticPiece *p = V->VisitNode(N, NextNode, PDB, *R)) {
00871           PD.getActivePath().push_front(p);
00872           updateStackPiecesWithMessage(p, CallStack);
00873         }
00874       }
00875     }
00876   }
00877 
00878   if (!PDB.getBugReport()->isValid())
00879     return false;
00880 
00881   // After constructing the full PathDiagnostic, do a pass over it to compact
00882   // PathDiagnosticPieces that occur within a macro.
00883   CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager());
00884   return true;
00885 }
00886 
00887 //===----------------------------------------------------------------------===//
00888 // "Extensive" PathDiagnostic generation.
00889 //===----------------------------------------------------------------------===//
00890 
00891 static bool IsControlFlowExpr(const Stmt *S) {
00892   const Expr *E = dyn_cast<Expr>(S);
00893 
00894   if (!E)
00895     return false;
00896 
00897   E = E->IgnoreParenCasts();
00898 
00899   if (isa<AbstractConditionalOperator>(E))
00900     return true;
00901 
00902   if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
00903     if (B->isLogicalOp())
00904       return true;
00905 
00906   return false;
00907 }
00908 
00909 namespace {
00910 class ContextLocation : public PathDiagnosticLocation {
00911   bool IsDead;
00912 public:
00913   ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
00914     : PathDiagnosticLocation(L), IsDead(isdead) {}
00915 
00916   void markDead() { IsDead = true; }
00917   bool isDead() const { return IsDead; }
00918 };
00919 
00920 static PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
00921                                               const LocationContext *LC,
00922                                               bool firstCharOnly = false) {
00923   if (const Stmt *S = L.asStmt()) {
00924     const Stmt *Original = S;
00925     while (1) {
00926       // Adjust the location for some expressions that are best referenced
00927       // by one of their subexpressions.
00928       switch (S->getStmtClass()) {
00929         default:
00930           break;
00931         case Stmt::ParenExprClass:
00932         case Stmt::GenericSelectionExprClass:
00933           S = cast<Expr>(S)->IgnoreParens();
00934           firstCharOnly = true;
00935           continue;
00936         case Stmt::BinaryConditionalOperatorClass:
00937         case Stmt::ConditionalOperatorClass:
00938           S = cast<AbstractConditionalOperator>(S)->getCond();
00939           firstCharOnly = true;
00940           continue;
00941         case Stmt::ChooseExprClass:
00942           S = cast<ChooseExpr>(S)->getCond();
00943           firstCharOnly = true;
00944           continue;
00945         case Stmt::BinaryOperatorClass:
00946           S = cast<BinaryOperator>(S)->getLHS();
00947           firstCharOnly = true;
00948           continue;
00949       }
00950 
00951       break;
00952     }
00953 
00954     if (S != Original)
00955       L = PathDiagnosticLocation(S, L.getManager(), LC);
00956   }
00957 
00958   if (firstCharOnly)
00959     L  = PathDiagnosticLocation::createSingleLocation(L);
00960   
00961   return L;
00962 }
00963 
00964 class EdgeBuilder {
00965   std::vector<ContextLocation> CLocs;
00966   typedef std::vector<ContextLocation>::iterator iterator;
00967   PathDiagnostic &PD;
00968   PathDiagnosticBuilder &PDB;
00969   PathDiagnosticLocation PrevLoc;
00970 
00971   bool IsConsumedExpr(const PathDiagnosticLocation &L);
00972 
00973   bool containsLocation(const PathDiagnosticLocation &Container,
00974                         const PathDiagnosticLocation &Containee);
00975 
00976   PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
00977 
00978 
00979 
00980   void popLocation() {
00981     if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
00982       // For contexts, we only one the first character as the range.
00983       rawAddEdge(cleanUpLocation(CLocs.back(), PDB.LC, true));
00984     }
00985     CLocs.pop_back();
00986   }
00987 
00988 public:
00989   EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
00990     : PD(pd), PDB(pdb) {
00991 
00992       // If the PathDiagnostic already has pieces, add the enclosing statement
00993       // of the first piece as a context as well.
00994       if (!PD.path.empty()) {
00995         PrevLoc = (*PD.path.begin())->getLocation();
00996 
00997         if (const Stmt *S = PrevLoc.asStmt())
00998           addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
00999       }
01000   }
01001 
01002   ~EdgeBuilder() {
01003     while (!CLocs.empty()) popLocation();
01004     
01005     // Finally, add an initial edge from the start location of the first
01006     // statement (if it doesn't already exist).
01007     PathDiagnosticLocation L = PathDiagnosticLocation::createDeclBegin(
01008                                                        PDB.LC,
01009                                                        PDB.getSourceManager());
01010     if (L.isValid())
01011       rawAddEdge(L);
01012   }
01013 
01014   void flushLocations() {
01015     while (!CLocs.empty())
01016       popLocation();
01017     PrevLoc = PathDiagnosticLocation();
01018   }
01019   
01020   void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false,
01021                bool IsPostJump = false);
01022 
01023   void rawAddEdge(PathDiagnosticLocation NewLoc);
01024 
01025   void addContext(const Stmt *S);
01026   void addContext(const PathDiagnosticLocation &L);
01027   void addExtendedContext(const Stmt *S);
01028 };
01029 } // end anonymous namespace
01030 
01031 
01032 PathDiagnosticLocation
01033 EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
01034   if (const Stmt *S = L.asStmt()) {
01035     if (IsControlFlowExpr(S))
01036       return L;
01037 
01038     return PDB.getEnclosingStmtLocation(S);
01039   }
01040 
01041   return L;
01042 }
01043 
01044 bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
01045                                    const PathDiagnosticLocation &Containee) {
01046 
01047   if (Container == Containee)
01048     return true;
01049 
01050   if (Container.asDecl())
01051     return true;
01052 
01053   if (const Stmt *S = Containee.asStmt())
01054     if (const Stmt *ContainerS = Container.asStmt()) {
01055       while (S) {
01056         if (S == ContainerS)
01057           return true;
01058         S = PDB.getParent(S);
01059       }
01060       return false;
01061     }
01062 
01063   // Less accurate: compare using source ranges.
01064   SourceRange ContainerR = Container.asRange();
01065   SourceRange ContaineeR = Containee.asRange();
01066 
01067   SourceManager &SM = PDB.getSourceManager();
01068   SourceLocation ContainerRBeg = SM.getExpansionLoc(ContainerR.getBegin());
01069   SourceLocation ContainerREnd = SM.getExpansionLoc(ContainerR.getEnd());
01070   SourceLocation ContaineeRBeg = SM.getExpansionLoc(ContaineeR.getBegin());
01071   SourceLocation ContaineeREnd = SM.getExpansionLoc(ContaineeR.getEnd());
01072 
01073   unsigned ContainerBegLine = SM.getExpansionLineNumber(ContainerRBeg);
01074   unsigned ContainerEndLine = SM.getExpansionLineNumber(ContainerREnd);
01075   unsigned ContaineeBegLine = SM.getExpansionLineNumber(ContaineeRBeg);
01076   unsigned ContaineeEndLine = SM.getExpansionLineNumber(ContaineeREnd);
01077 
01078   assert(ContainerBegLine <= ContainerEndLine);
01079   assert(ContaineeBegLine <= ContaineeEndLine);
01080 
01081   return (ContainerBegLine <= ContaineeBegLine &&
01082           ContainerEndLine >= ContaineeEndLine &&
01083           (ContainerBegLine != ContaineeBegLine ||
01084            SM.getExpansionColumnNumber(ContainerRBeg) <=
01085            SM.getExpansionColumnNumber(ContaineeRBeg)) &&
01086           (ContainerEndLine != ContaineeEndLine ||
01087            SM.getExpansionColumnNumber(ContainerREnd) >=
01088            SM.getExpansionColumnNumber(ContaineeREnd)));
01089 }
01090 
01091 void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
01092   if (!PrevLoc.isValid()) {
01093     PrevLoc = NewLoc;
01094     return;
01095   }
01096 
01097   const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc, PDB.LC);
01098   const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc, PDB.LC);
01099 
01100   if (PrevLocClean.asLocation().isInvalid()) {
01101     PrevLoc = NewLoc;
01102     return;
01103   }
01104   
01105   if (NewLocClean.asLocation() == PrevLocClean.asLocation())
01106     return;
01107 
01108   // FIXME: Ignore intra-macro edges for now.
01109   if (NewLocClean.asLocation().getExpansionLoc() ==
01110       PrevLocClean.asLocation().getExpansionLoc())
01111     return;
01112 
01113   PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
01114   PrevLoc = NewLoc;
01115 }
01116 
01117 void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd,
01118                           bool IsPostJump) {
01119 
01120   if (!alwaysAdd && NewLoc.asLocation().isMacroID())
01121     return;
01122 
01123   const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
01124 
01125   while (!CLocs.empty()) {
01126     ContextLocation &TopContextLoc = CLocs.back();
01127 
01128     // Is the top location context the same as the one for the new location?
01129     if (TopContextLoc == CLoc) {
01130       if (alwaysAdd) {
01131         if (IsConsumedExpr(TopContextLoc))
01132           TopContextLoc.markDead();
01133 
01134         rawAddEdge(NewLoc);
01135       }
01136 
01137       if (IsPostJump)
01138         TopContextLoc.markDead();
01139       return;
01140     }
01141 
01142     if (containsLocation(TopContextLoc, CLoc)) {
01143       if (alwaysAdd) {
01144         rawAddEdge(NewLoc);
01145 
01146         if (IsConsumedExpr(CLoc)) {
01147           CLocs.push_back(ContextLocation(CLoc, /*IsDead=*/true));
01148           return;
01149         }
01150       }
01151 
01152       CLocs.push_back(ContextLocation(CLoc, /*IsDead=*/IsPostJump));
01153       return;
01154     }
01155 
01156     // Context does not contain the location.  Flush it.
01157     popLocation();
01158   }
01159 
01160   // If we reach here, there is no enclosing context.  Just add the edge.
01161   rawAddEdge(NewLoc);
01162 }
01163 
01164 bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
01165   if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
01166     return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
01167 
01168   return false;
01169 }
01170 
01171 void EdgeBuilder::addExtendedContext(const Stmt *S) {
01172   if (!S)
01173     return;
01174 
01175   const Stmt *Parent = PDB.getParent(S);
01176   while (Parent) {
01177     if (isa<CompoundStmt>(Parent))
01178       Parent = PDB.getParent(Parent);
01179     else
01180       break;
01181   }
01182 
01183   if (Parent) {
01184     switch (Parent->getStmtClass()) {
01185       case Stmt::DoStmtClass:
01186       case Stmt::ObjCAtSynchronizedStmtClass:
01187         addContext(Parent);
01188       default:
01189         break;
01190     }
01191   }
01192 
01193   addContext(S);
01194 }
01195 
01196 void EdgeBuilder::addContext(const Stmt *S) {
01197   if (!S)
01198     return;
01199 
01200   PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.LC);
01201   addContext(L);
01202 }
01203 
01204 void EdgeBuilder::addContext(const PathDiagnosticLocation &L) {
01205   while (!CLocs.empty()) {
01206     const PathDiagnosticLocation &TopContextLoc = CLocs.back();
01207 
01208     // Is the top location context the same as the one for the new location?
01209     if (TopContextLoc == L)
01210       return;
01211 
01212     if (containsLocation(TopContextLoc, L)) {
01213       CLocs.push_back(L);
01214       return;
01215     }
01216 
01217     // Context does not contain the location.  Flush it.
01218     popLocation();
01219   }
01220 
01221   CLocs.push_back(L);
01222 }
01223 
01224 // Cone-of-influence: support the reverse propagation of "interesting" symbols
01225 // and values by tracing interesting calculations backwards through evaluated
01226 // expressions along a path.  This is probably overly complicated, but the idea
01227 // is that if an expression computed an "interesting" value, the child
01228 // expressions are are also likely to be "interesting" as well (which then
01229 // propagates to the values they in turn compute).  This reverse propagation
01230 // is needed to track interesting correlations across function call boundaries,
01231 // where formal arguments bind to actual arguments, etc.  This is also needed
01232 // because the constraint solver sometimes simplifies certain symbolic values
01233 // into constants when appropriate, and this complicates reasoning about
01234 // interesting values.
01235 typedef llvm::DenseSet<const Expr *> InterestingExprs;
01236 
01237 static void reversePropagateIntererstingSymbols(BugReport &R,
01238                                                 InterestingExprs &IE,
01239                                                 const ProgramState *State,
01240                                                 const Expr *Ex,
01241                                                 const LocationContext *LCtx) {
01242   SVal V = State->getSVal(Ex, LCtx);
01243   if (!(R.isInteresting(V) || IE.count(Ex)))
01244     return;
01245   
01246   switch (Ex->getStmtClass()) {
01247     default:
01248       if (!isa<CastExpr>(Ex))
01249         break;
01250       // Fall through.
01251     case Stmt::BinaryOperatorClass:
01252     case Stmt::UnaryOperatorClass: {
01253       for (const Stmt *SubStmt : Ex->children()) {
01254         if (const Expr *child = dyn_cast_or_null<Expr>(SubStmt)) {
01255           IE.insert(child);
01256           SVal ChildV = State->getSVal(child, LCtx);
01257           R.markInteresting(ChildV);
01258         }
01259       }
01260       break;
01261     }
01262   }
01263   
01264   R.markInteresting(V);
01265 }
01266 
01267 static void reversePropagateInterestingSymbols(BugReport &R,
01268                                                InterestingExprs &IE,
01269                                                const ProgramState *State,
01270                                                const LocationContext *CalleeCtx,
01271                                                const LocationContext *CallerCtx)
01272 {
01273   // FIXME: Handle non-CallExpr-based CallEvents.
01274   const StackFrameContext *Callee = CalleeCtx->getCurrentStackFrame();
01275   const Stmt *CallSite = Callee->getCallSite();
01276   if (const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite)) {
01277     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeCtx->getDecl())) {
01278       FunctionDecl::param_const_iterator PI = FD->param_begin(), 
01279                                          PE = FD->param_end();
01280       CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end();
01281       for (; AI != AE && PI != PE; ++AI, ++PI) {
01282         if (const Expr *ArgE = *AI) {
01283           if (const ParmVarDecl *PD = *PI) {
01284             Loc LV = State->getLValue(PD, CalleeCtx);
01285             if (R.isInteresting(LV) || R.isInteresting(State->getRawSVal(LV)))
01286               IE.insert(ArgE);
01287           }
01288         }
01289       }
01290     }
01291   }
01292 }
01293 
01294 //===----------------------------------------------------------------------===//
01295 // Functions for determining if a loop was executed 0 times.
01296 //===----------------------------------------------------------------------===//
01297 
01298 static bool isLoop(const Stmt *Term) {
01299   switch (Term->getStmtClass()) {
01300     case Stmt::ForStmtClass:
01301     case Stmt::WhileStmtClass:
01302     case Stmt::ObjCForCollectionStmtClass:
01303     case Stmt::CXXForRangeStmtClass:
01304       return true;
01305     default:
01306       // Note that we intentionally do not include do..while here.
01307       return false;
01308   }
01309 }
01310 
01311 static bool isJumpToFalseBranch(const BlockEdge *BE) {
01312   const CFGBlock *Src = BE->getSrc();
01313   assert(Src->succ_size() == 2);
01314   return (*(Src->succ_begin()+1) == BE->getDst());
01315 }
01316 
01317 /// Return true if the terminator is a loop and the destination is the
01318 /// false branch.
01319 static bool isLoopJumpPastBody(const Stmt *Term, const BlockEdge *BE) {
01320   if (!isLoop(Term))
01321     return false;
01322 
01323   // Did we take the false branch?
01324   return isJumpToFalseBranch(BE);
01325 }
01326 
01327 static bool isContainedByStmt(ParentMap &PM, const Stmt *S, const Stmt *SubS) {
01328   while (SubS) {
01329     if (SubS == S)
01330       return true;
01331     SubS = PM.getParent(SubS);
01332   }
01333   return false;
01334 }
01335 
01336 static const Stmt *getStmtBeforeCond(ParentMap &PM, const Stmt *Term,
01337                                      const ExplodedNode *N) {
01338   while (N) {
01339     Optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>();
01340     if (SP) {
01341       const Stmt *S = SP->getStmt();
01342       if (!isContainedByStmt(PM, Term, S))
01343         return S;
01344     }
01345     N = N->getFirstPred();
01346   }
01347   return nullptr;
01348 }
01349 
01350 static bool isInLoopBody(ParentMap &PM, const Stmt *S, const Stmt *Term) {
01351   const Stmt *LoopBody = nullptr;
01352   switch (Term->getStmtClass()) {
01353     case Stmt::CXXForRangeStmtClass: {
01354       const CXXForRangeStmt *FR = cast<CXXForRangeStmt>(Term);
01355       if (isContainedByStmt(PM, FR->getInc(), S))
01356         return true;
01357       if (isContainedByStmt(PM, FR->getLoopVarStmt(), S))
01358         return true;
01359       LoopBody = FR->getBody();
01360       break;
01361     }
01362     case Stmt::ForStmtClass: {
01363       const ForStmt *FS = cast<ForStmt>(Term);
01364       if (isContainedByStmt(PM, FS->getInc(), S))
01365         return true;
01366       LoopBody = FS->getBody();
01367       break;
01368     }
01369     case Stmt::ObjCForCollectionStmtClass: {
01370       const ObjCForCollectionStmt *FC = cast<ObjCForCollectionStmt>(Term);
01371       LoopBody = FC->getBody();
01372       break;
01373     }
01374     case Stmt::WhileStmtClass:
01375       LoopBody = cast<WhileStmt>(Term)->getBody();
01376       break;
01377     default:
01378       return false;
01379   }
01380   return isContainedByStmt(PM, LoopBody, S);
01381 }
01382 
01383 //===----------------------------------------------------------------------===//
01384 // Top-level logic for generating extensive path diagnostics.
01385 //===----------------------------------------------------------------------===//
01386 
01387 static bool GenerateExtensivePathDiagnostic(
01388     PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
01389     LocationContextMap &LCM,
01390     ArrayRef<std::unique_ptr<BugReporterVisitor>> visitors) {
01391   EdgeBuilder EB(PD, PDB);
01392   const SourceManager& SM = PDB.getSourceManager();
01393   StackDiagVector CallStack;
01394   InterestingExprs IE;
01395 
01396   const ExplodedNode *NextNode = N->pred_empty() ? nullptr : *(N->pred_begin());
01397   while (NextNode) {
01398     N = NextNode;
01399     NextNode = N->getFirstPred();
01400     ProgramPoint P = N->getLocation();
01401 
01402     do {
01403       if (Optional<PostStmt> PS = P.getAs<PostStmt>()) {
01404         if (const Expr *Ex = PS->getStmtAs<Expr>())
01405           reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
01406                                               N->getState().get(), Ex,
01407                                               N->getLocationContext());
01408       }
01409       
01410       if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
01411         const Stmt *S = CE->getCalleeContext()->getCallSite();
01412         if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) {
01413             reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
01414                                                 N->getState().get(), Ex,
01415                                                 N->getLocationContext());
01416         }
01417         
01418         PathDiagnosticCallPiece *C =
01419           PathDiagnosticCallPiece::construct(N, *CE, SM);
01420         LCM[&C->path] = CE->getCalleeContext();
01421 
01422         EB.addEdge(C->callReturn, /*AlwaysAdd=*/true, /*IsPostJump=*/true);
01423         EB.flushLocations();
01424 
01425         PD.getActivePath().push_front(C);
01426         PD.pushActivePath(&C->path);
01427         CallStack.push_back(StackDiagPair(C, N));
01428         break;
01429       }
01430       
01431       // Pop the call hierarchy if we are done walking the contents
01432       // of a function call.
01433       if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
01434         // Add an edge to the start of the function.
01435         const Decl *D = CE->getCalleeContext()->getDecl();
01436         PathDiagnosticLocation pos =
01437           PathDiagnosticLocation::createBegin(D, SM);
01438         EB.addEdge(pos);
01439         
01440         // Flush all locations, and pop the active path.
01441         bool VisitedEntireCall = PD.isWithinCall();
01442         EB.flushLocations();
01443         PD.popActivePath();
01444         PDB.LC = N->getLocationContext();
01445 
01446         // Either we just added a bunch of stuff to the top-level path, or
01447         // we have a previous CallExitEnd.  If the former, it means that the
01448         // path terminated within a function call.  We must then take the
01449         // current contents of the active path and place it within
01450         // a new PathDiagnosticCallPiece.
01451         PathDiagnosticCallPiece *C;
01452         if (VisitedEntireCall) {
01453           C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
01454         } else {
01455           const Decl *Caller = CE->getLocationContext()->getDecl();
01456           C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
01457           LCM[&C->path] = CE->getCalleeContext();
01458         }
01459 
01460         C->setCallee(*CE, SM);
01461         EB.addContext(C->getLocation());
01462 
01463         if (!CallStack.empty()) {
01464           assert(CallStack.back().first == C);
01465           CallStack.pop_back();
01466         }
01467         break;
01468       }
01469       
01470       // Note that is important that we update the LocationContext
01471       // after looking at CallExits.  CallExit basically adds an
01472       // edge in the *caller*, so we don't want to update the LocationContext
01473       // too soon.
01474       PDB.LC = N->getLocationContext();
01475 
01476       // Block edges.
01477       if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
01478         // Does this represent entering a call?  If so, look at propagating
01479         // interesting symbols across call boundaries.
01480         if (NextNode) {
01481           const LocationContext *CallerCtx = NextNode->getLocationContext();
01482           const LocationContext *CalleeCtx = PDB.LC;
01483           if (CallerCtx != CalleeCtx) {
01484             reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
01485                                                N->getState().get(),
01486                                                CalleeCtx, CallerCtx);
01487           }
01488         }
01489        
01490         // Are we jumping to the head of a loop?  Add a special diagnostic.
01491         if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
01492           PathDiagnosticLocation L(Loop, SM, PDB.LC);
01493           const CompoundStmt *CS = nullptr;
01494 
01495           if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
01496             CS = dyn_cast<CompoundStmt>(FS->getBody());
01497           else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
01498             CS = dyn_cast<CompoundStmt>(WS->getBody());
01499 
01500           PathDiagnosticEventPiece *p =
01501             new PathDiagnosticEventPiece(L,
01502                                         "Looping back to the head of the loop");
01503           p->setPrunable(true);
01504 
01505           EB.addEdge(p->getLocation(), true);
01506           PD.getActivePath().push_front(p);
01507 
01508           if (CS) {
01509             PathDiagnosticLocation BL =
01510               PathDiagnosticLocation::createEndBrace(CS, SM);
01511             EB.addEdge(BL);
01512           }
01513         }
01514 
01515         const CFGBlock *BSrc = BE->getSrc();
01516         ParentMap &PM = PDB.getParentMap();
01517 
01518         if (const Stmt *Term = BSrc->getTerminator()) {
01519           // Are we jumping past the loop body without ever executing the
01520           // loop (because the condition was false)?
01521           if (isLoopJumpPastBody(Term, &*BE) &&
01522               !isInLoopBody(PM,
01523                             getStmtBeforeCond(PM,
01524                                               BSrc->getTerminatorCondition(),
01525                                               N),
01526                             Term)) {
01527             PathDiagnosticLocation L(Term, SM, PDB.LC);
01528             PathDiagnosticEventPiece *PE =
01529                 new PathDiagnosticEventPiece(L, "Loop body executed 0 times");
01530             PE->setPrunable(true);
01531 
01532             EB.addEdge(PE->getLocation(), true);
01533             PD.getActivePath().push_front(PE);
01534           }
01535 
01536           // In any case, add the terminator as the current statement
01537           // context for control edges.
01538           EB.addContext(Term);
01539         }
01540 
01541         break;
01542       }
01543 
01544       if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) {
01545         Optional<CFGElement> First = BE->getFirstElement();
01546         if (Optional<CFGStmt> S = First ? First->getAs<CFGStmt>() : None) {
01547           const Stmt *stmt = S->getStmt();
01548           if (IsControlFlowExpr(stmt)) {
01549             // Add the proper context for '&&', '||', and '?'.
01550             EB.addContext(stmt);
01551           }
01552           else
01553             EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt());
01554         }
01555         
01556         break;
01557       }
01558       
01559       
01560     } while (0);
01561 
01562     if (!NextNode)
01563       continue;
01564 
01565     // Add pieces from custom visitors.
01566     BugReport *R = PDB.getBugReport();
01567     for (auto &V : visitors) {
01568       if (PathDiagnosticPiece *p = V->VisitNode(N, NextNode, PDB, *R)) {
01569         const PathDiagnosticLocation &Loc = p->getLocation();
01570         EB.addEdge(Loc, true);
01571         PD.getActivePath().push_front(p);
01572         updateStackPiecesWithMessage(p, CallStack);
01573 
01574         if (const Stmt *S = Loc.asStmt())
01575           EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
01576       }
01577     }
01578   }
01579 
01580   return PDB.getBugReport()->isValid();
01581 }
01582 
01583 /// \brief Adds a sanitized control-flow diagnostic edge to a path.
01584 static void addEdgeToPath(PathPieces &path,
01585                           PathDiagnosticLocation &PrevLoc,
01586                           PathDiagnosticLocation NewLoc,
01587                           const LocationContext *LC) {
01588   if (!NewLoc.isValid())
01589     return;
01590 
01591   SourceLocation NewLocL = NewLoc.asLocation();
01592   if (NewLocL.isInvalid())
01593     return;
01594 
01595   if (!PrevLoc.isValid() || !PrevLoc.asLocation().isValid()) {
01596     PrevLoc = NewLoc;
01597     return;
01598   }
01599 
01600   // Ignore self-edges, which occur when there are multiple nodes at the same
01601   // statement.
01602   if (NewLoc.asStmt() && NewLoc.asStmt() == PrevLoc.asStmt())
01603     return;
01604 
01605   path.push_front(new PathDiagnosticControlFlowPiece(NewLoc,
01606                                                      PrevLoc));
01607   PrevLoc = NewLoc;
01608 }
01609 
01610 /// A customized wrapper for CFGBlock::getTerminatorCondition()
01611 /// which returns the element for ObjCForCollectionStmts.
01612 static const Stmt *getTerminatorCondition(const CFGBlock *B) {
01613   const Stmt *S = B->getTerminatorCondition();
01614   if (const ObjCForCollectionStmt *FS =
01615       dyn_cast_or_null<ObjCForCollectionStmt>(S))
01616     return FS->getElement();
01617   return S;
01618 }
01619 
01620 static const char StrEnteringLoop[] = "Entering loop body";
01621 static const char StrLoopBodyZero[] = "Loop body executed 0 times";
01622 static const char StrLoopRangeEmpty[] =
01623   "Loop body skipped when range is empty";
01624 static const char StrLoopCollectionEmpty[] =
01625   "Loop body skipped when collection is empty";
01626 
01627 static bool GenerateAlternateExtensivePathDiagnostic(
01628     PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
01629     LocationContextMap &LCM,
01630     ArrayRef<std::unique_ptr<BugReporterVisitor>> visitors) {
01631 
01632   BugReport *report = PDB.getBugReport();
01633   const SourceManager& SM = PDB.getSourceManager();
01634   StackDiagVector CallStack;
01635   InterestingExprs IE;
01636 
01637   PathDiagnosticLocation PrevLoc = PD.getLocation();
01638 
01639   const ExplodedNode *NextNode = N->getFirstPred();
01640   while (NextNode) {
01641     N = NextNode;
01642     NextNode = N->getFirstPred();
01643     ProgramPoint P = N->getLocation();
01644 
01645     do {
01646       // Have we encountered an entrance to a call?  It may be
01647       // the case that we have not encountered a matching
01648       // call exit before this point.  This means that the path
01649       // terminated within the call itself.
01650       if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
01651         // Add an edge to the start of the function.
01652         const StackFrameContext *CalleeLC = CE->getCalleeContext();
01653         const Decl *D = CalleeLC->getDecl();
01654         addEdgeToPath(PD.getActivePath(), PrevLoc,
01655                       PathDiagnosticLocation::createBegin(D, SM),
01656                       CalleeLC);
01657 
01658         // Did we visit an entire call?
01659         bool VisitedEntireCall = PD.isWithinCall();
01660         PD.popActivePath();
01661 
01662         PathDiagnosticCallPiece *C;
01663         if (VisitedEntireCall) {
01664           PathDiagnosticPiece *P = PD.getActivePath().front().get();
01665           C = cast<PathDiagnosticCallPiece>(P);
01666         } else {
01667           const Decl *Caller = CE->getLocationContext()->getDecl();
01668           C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
01669 
01670           // Since we just transferred the path over to the call piece,
01671           // reset the mapping from active to location context.
01672           assert(PD.getActivePath().size() == 1 &&
01673                  PD.getActivePath().front() == C);
01674           LCM[&PD.getActivePath()] = nullptr;
01675 
01676           // Record the location context mapping for the path within
01677           // the call.
01678           assert(LCM[&C->path] == nullptr ||
01679                  LCM[&C->path] == CE->getCalleeContext());
01680           LCM[&C->path] = CE->getCalleeContext();
01681 
01682           // If this is the first item in the active path, record
01683           // the new mapping from active path to location context.
01684           const LocationContext *&NewLC = LCM[&PD.getActivePath()];
01685           if (!NewLC)
01686             NewLC = N->getLocationContext();
01687 
01688           PDB.LC = NewLC;
01689         }
01690         C->setCallee(*CE, SM);
01691 
01692         // Update the previous location in the active path.
01693         PrevLoc = C->getLocation();
01694 
01695         if (!CallStack.empty()) {
01696           assert(CallStack.back().first == C);
01697           CallStack.pop_back();
01698         }
01699         break;
01700       }
01701 
01702       // Query the location context here and the previous location
01703       // as processing CallEnter may change the active path.
01704       PDB.LC = N->getLocationContext();
01705 
01706       // Record the mapping from the active path to the location
01707       // context.
01708       assert(!LCM[&PD.getActivePath()] ||
01709              LCM[&PD.getActivePath()] == PDB.LC);
01710       LCM[&PD.getActivePath()] = PDB.LC;
01711 
01712       // Have we encountered an exit from a function call?
01713       if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
01714         const Stmt *S = CE->getCalleeContext()->getCallSite();
01715         // Propagate the interesting symbols accordingly.
01716         if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) {
01717           reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
01718                                               N->getState().get(), Ex,
01719                                               N->getLocationContext());
01720         }
01721 
01722         // We are descending into a call (backwards).  Construct
01723         // a new call piece to contain the path pieces for that call.
01724         PathDiagnosticCallPiece *C =
01725           PathDiagnosticCallPiece::construct(N, *CE, SM);
01726 
01727         // Record the location context for this call piece.
01728         LCM[&C->path] = CE->getCalleeContext();
01729 
01730         // Add the edge to the return site.
01731         addEdgeToPath(PD.getActivePath(), PrevLoc, C->callReturn, PDB.LC);
01732         PD.getActivePath().push_front(C);
01733         PrevLoc.invalidate();
01734 
01735         // Make the contents of the call the active path for now.
01736         PD.pushActivePath(&C->path);
01737         CallStack.push_back(StackDiagPair(C, N));
01738         break;
01739       }
01740 
01741       if (Optional<PostStmt> PS = P.getAs<PostStmt>()) {
01742         // For expressions, make sure we propagate the
01743         // interesting symbols correctly.
01744         if (const Expr *Ex = PS->getStmtAs<Expr>())
01745           reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
01746                                               N->getState().get(), Ex,
01747                                               N->getLocationContext());
01748 
01749         // Add an edge.  If this is an ObjCForCollectionStmt do
01750         // not add an edge here as it appears in the CFG both
01751         // as a terminator and as a terminator condition.
01752         if (!isa<ObjCForCollectionStmt>(PS->getStmt())) {
01753           PathDiagnosticLocation L =
01754             PathDiagnosticLocation(PS->getStmt(), SM, PDB.LC);
01755           addEdgeToPath(PD.getActivePath(), PrevLoc, L, PDB.LC);
01756         }
01757         break;
01758       }
01759 
01760       // Block edges.
01761       if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
01762         // Does this represent entering a call?  If so, look at propagating
01763         // interesting symbols across call boundaries.
01764         if (NextNode) {
01765           const LocationContext *CallerCtx = NextNode->getLocationContext();
01766           const LocationContext *CalleeCtx = PDB.LC;
01767           if (CallerCtx != CalleeCtx) {
01768             reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
01769                                                N->getState().get(),
01770                                                CalleeCtx, CallerCtx);
01771           }
01772         }
01773 
01774         // Are we jumping to the head of a loop?  Add a special diagnostic.
01775         if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
01776           PathDiagnosticLocation L(Loop, SM, PDB.LC);
01777           const Stmt *Body = nullptr;
01778 
01779           if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
01780             Body = FS->getBody();
01781           else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
01782             Body = WS->getBody();
01783           else if (const ObjCForCollectionStmt *OFS =
01784                      dyn_cast<ObjCForCollectionStmt>(Loop)) {
01785             Body = OFS->getBody();
01786           } else if (const CXXForRangeStmt *FRS =
01787                        dyn_cast<CXXForRangeStmt>(Loop)) {
01788             Body = FRS->getBody();
01789           }
01790           // do-while statements are explicitly excluded here
01791 
01792           PathDiagnosticEventPiece *p =
01793             new PathDiagnosticEventPiece(L, "Looping back to the head "
01794                                             "of the loop");
01795           p->setPrunable(true);
01796 
01797           addEdgeToPath(PD.getActivePath(), PrevLoc, p->getLocation(), PDB.LC);
01798           PD.getActivePath().push_front(p);
01799 
01800           if (const CompoundStmt *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
01801             addEdgeToPath(PD.getActivePath(), PrevLoc,
01802                           PathDiagnosticLocation::createEndBrace(CS, SM),
01803                           PDB.LC);
01804           }
01805         }
01806 
01807         const CFGBlock *BSrc = BE->getSrc();
01808         ParentMap &PM = PDB.getParentMap();
01809 
01810         if (const Stmt *Term = BSrc->getTerminator()) {
01811           // Are we jumping past the loop body without ever executing the
01812           // loop (because the condition was false)?
01813           if (isLoop(Term)) {
01814             const Stmt *TermCond = getTerminatorCondition(BSrc);
01815             bool IsInLoopBody =
01816               isInLoopBody(PM, getStmtBeforeCond(PM, TermCond, N), Term);
01817 
01818             const char *str = nullptr;
01819 
01820             if (isJumpToFalseBranch(&*BE)) {
01821               if (!IsInLoopBody) {
01822                 if (isa<ObjCForCollectionStmt>(Term)) {
01823                   str = StrLoopCollectionEmpty;
01824                 } else if (isa<CXXForRangeStmt>(Term)) {
01825                   str = StrLoopRangeEmpty;
01826                 } else {
01827                   str = StrLoopBodyZero;
01828                 }
01829               }
01830             } else {
01831               str = StrEnteringLoop;
01832             }
01833 
01834             if (str) {
01835               PathDiagnosticLocation L(TermCond ? TermCond : Term, SM, PDB.LC);
01836               PathDiagnosticEventPiece *PE =
01837                 new PathDiagnosticEventPiece(L, str);
01838               PE->setPrunable(true);
01839               addEdgeToPath(PD.getActivePath(), PrevLoc,
01840                             PE->getLocation(), PDB.LC);
01841               PD.getActivePath().push_front(PE);
01842             }
01843           } else if (isa<BreakStmt>(Term) || isa<ContinueStmt>(Term) ||
01844                      isa<GotoStmt>(Term)) {
01845             PathDiagnosticLocation L(Term, SM, PDB.LC);
01846             addEdgeToPath(PD.getActivePath(), PrevLoc, L, PDB.LC);
01847           }
01848         }
01849         break;
01850       }
01851     } while (0);
01852 
01853     if (!NextNode)
01854       continue;
01855 
01856     // Add pieces from custom visitors.
01857     for (auto &V : visitors) {
01858       if (PathDiagnosticPiece *p = V->VisitNode(N, NextNode, PDB, *report)) {
01859         addEdgeToPath(PD.getActivePath(), PrevLoc, p->getLocation(), PDB.LC);
01860         PD.getActivePath().push_front(p);
01861         updateStackPiecesWithMessage(p, CallStack);
01862       }
01863     }
01864   }
01865 
01866   // Add an edge to the start of the function.
01867   // We'll prune it out later, but it helps make diagnostics more uniform.
01868   const StackFrameContext *CalleeLC = PDB.LC->getCurrentStackFrame();
01869   const Decl *D = CalleeLC->getDecl();
01870   addEdgeToPath(PD.getActivePath(), PrevLoc,
01871                 PathDiagnosticLocation::createBegin(D, SM),
01872                 CalleeLC);
01873 
01874   return report->isValid();
01875 }
01876 
01877 static const Stmt *getLocStmt(PathDiagnosticLocation L) {
01878   if (!L.isValid())
01879     return nullptr;
01880   return L.asStmt();
01881 }
01882 
01883 static const Stmt *getStmtParent(const Stmt *S, const ParentMap &PM) {
01884   if (!S)
01885     return nullptr;
01886 
01887   while (true) {
01888     S = PM.getParentIgnoreParens(S);
01889 
01890     if (!S)
01891       break;
01892 
01893     if (isa<ExprWithCleanups>(S) ||
01894         isa<CXXBindTemporaryExpr>(S) ||
01895         isa<SubstNonTypeTemplateParmExpr>(S))
01896       continue;
01897 
01898     break;
01899   }
01900 
01901   return S;
01902 }
01903 
01904 static bool isConditionForTerminator(const Stmt *S, const Stmt *Cond) {
01905   switch (S->getStmtClass()) {
01906     case Stmt::BinaryOperatorClass: {
01907       const BinaryOperator *BO = cast<BinaryOperator>(S);
01908       if (!BO->isLogicalOp())
01909         return false;
01910       return BO->getLHS() == Cond || BO->getRHS() == Cond;
01911     }
01912     case Stmt::IfStmtClass:
01913       return cast<IfStmt>(S)->getCond() == Cond;
01914     case Stmt::ForStmtClass:
01915       return cast<ForStmt>(S)->getCond() == Cond;
01916     case Stmt::WhileStmtClass:
01917       return cast<WhileStmt>(S)->getCond() == Cond;
01918     case Stmt::DoStmtClass:
01919       return cast<DoStmt>(S)->getCond() == Cond;
01920     case Stmt::ChooseExprClass:
01921       return cast<ChooseExpr>(S)->getCond() == Cond;
01922     case Stmt::IndirectGotoStmtClass:
01923       return cast<IndirectGotoStmt>(S)->getTarget() == Cond;
01924     case Stmt::SwitchStmtClass:
01925       return cast<SwitchStmt>(S)->getCond() == Cond;
01926     case Stmt::BinaryConditionalOperatorClass:
01927       return cast<BinaryConditionalOperator>(S)->getCond() == Cond;
01928     case Stmt::ConditionalOperatorClass: {
01929       const ConditionalOperator *CO = cast<ConditionalOperator>(S);
01930       return CO->getCond() == Cond ||
01931              CO->getLHS() == Cond ||
01932              CO->getRHS() == Cond;
01933     }
01934     case Stmt::ObjCForCollectionStmtClass:
01935       return cast<ObjCForCollectionStmt>(S)->getElement() == Cond;
01936     case Stmt::CXXForRangeStmtClass: {
01937       const CXXForRangeStmt *FRS = cast<CXXForRangeStmt>(S);
01938       return FRS->getCond() == Cond || FRS->getRangeInit() == Cond;
01939     }
01940     default:
01941       return false;
01942   }
01943 }
01944 
01945 static bool isIncrementOrInitInForLoop(const Stmt *S, const Stmt *FL) {
01946   if (const ForStmt *FS = dyn_cast<ForStmt>(FL))
01947     return FS->getInc() == S || FS->getInit() == S;
01948   if (const CXXForRangeStmt *FRS = dyn_cast<CXXForRangeStmt>(FL))
01949     return FRS->getInc() == S || FRS->getRangeStmt() == S ||
01950            FRS->getLoopVarStmt() || FRS->getRangeInit() == S;
01951   return false;
01952 }
01953 
01954 typedef llvm::DenseSet<const PathDiagnosticCallPiece *>
01955         OptimizedCallsSet;
01956 
01957 /// Adds synthetic edges from top-level statements to their subexpressions.
01958 ///
01959 /// This avoids a "swoosh" effect, where an edge from a top-level statement A
01960 /// points to a sub-expression B.1 that's not at the start of B. In these cases,
01961 /// we'd like to see an edge from A to B, then another one from B to B.1.
01962 static void addContextEdges(PathPieces &pieces, SourceManager &SM,
01963                             const ParentMap &PM, const LocationContext *LCtx) {
01964   PathPieces::iterator Prev = pieces.end();
01965   for (PathPieces::iterator I = pieces.begin(), E = Prev; I != E;
01966        Prev = I, ++I) {
01967     PathDiagnosticControlFlowPiece *Piece =
01968       dyn_cast<PathDiagnosticControlFlowPiece>(*I);
01969 
01970     if (!Piece)
01971       continue;
01972 
01973     PathDiagnosticLocation SrcLoc = Piece->getStartLocation();
01974     SmallVector<PathDiagnosticLocation, 4> SrcContexts;
01975 
01976     PathDiagnosticLocation NextSrcContext = SrcLoc;
01977     const Stmt *InnerStmt = nullptr;
01978     while (NextSrcContext.isValid() && NextSrcContext.asStmt() != InnerStmt) {
01979       SrcContexts.push_back(NextSrcContext);
01980       InnerStmt = NextSrcContext.asStmt();
01981       NextSrcContext = getEnclosingStmtLocation(InnerStmt, SM, PM, LCtx,
01982                                                 /*allowNested=*/true);
01983     }
01984 
01985     // Repeatedly split the edge as necessary.
01986     // This is important for nested logical expressions (||, &&, ?:) where we
01987     // want to show all the levels of context.
01988     while (true) {
01989       const Stmt *Dst = getLocStmt(Piece->getEndLocation());
01990 
01991       // We are looking at an edge. Is the destination within a larger
01992       // expression?
01993       PathDiagnosticLocation DstContext =
01994         getEnclosingStmtLocation(Dst, SM, PM, LCtx, /*allowNested=*/true);
01995       if (!DstContext.isValid() || DstContext.asStmt() == Dst)
01996         break;
01997 
01998       // If the source is in the same context, we're already good.
01999       if (std::find(SrcContexts.begin(), SrcContexts.end(), DstContext) !=
02000           SrcContexts.end())
02001         break;
02002 
02003       // Update the subexpression node to point to the context edge.
02004       Piece->setStartLocation(DstContext);
02005 
02006       // Try to extend the previous edge if it's at the same level as the source
02007       // context.
02008       if (Prev != E) {
02009         PathDiagnosticControlFlowPiece *PrevPiece =
02010           dyn_cast<PathDiagnosticControlFlowPiece>(*Prev);
02011 
02012         if (PrevPiece) {
02013           if (const Stmt *PrevSrc = getLocStmt(PrevPiece->getStartLocation())) {
02014             const Stmt *PrevSrcParent = getStmtParent(PrevSrc, PM);
02015             if (PrevSrcParent == getStmtParent(getLocStmt(DstContext), PM)) {
02016               PrevPiece->setEndLocation(DstContext);
02017               break;
02018             }
02019           }
02020         }
02021       }
02022 
02023       // Otherwise, split the current edge into a context edge and a
02024       // subexpression edge. Note that the context statement may itself have
02025       // context.
02026       Piece = new PathDiagnosticControlFlowPiece(SrcLoc, DstContext);
02027       I = pieces.insert(I, Piece);
02028     }
02029   }
02030 }
02031 
02032 /// \brief Move edges from a branch condition to a branch target
02033 ///        when the condition is simple.
02034 ///
02035 /// This restructures some of the work of addContextEdges.  That function
02036 /// creates edges this may destroy, but they work together to create a more
02037 /// aesthetically set of edges around branches.  After the call to
02038 /// addContextEdges, we may have (1) an edge to the branch, (2) an edge from
02039 /// the branch to the branch condition, and (3) an edge from the branch
02040 /// condition to the branch target.  We keep (1), but may wish to remove (2)
02041 /// and move the source of (3) to the branch if the branch condition is simple.
02042 ///
02043 static void simplifySimpleBranches(PathPieces &pieces) {
02044   for (PathPieces::iterator I = pieces.begin(), E = pieces.end(); I != E; ++I) {
02045 
02046     PathDiagnosticControlFlowPiece *PieceI =
02047       dyn_cast<PathDiagnosticControlFlowPiece>(*I);
02048 
02049     if (!PieceI)
02050       continue;
02051 
02052     const Stmt *s1Start = getLocStmt(PieceI->getStartLocation());
02053     const Stmt *s1End   = getLocStmt(PieceI->getEndLocation());
02054 
02055     if (!s1Start || !s1End)
02056       continue;
02057 
02058     PathPieces::iterator NextI = I; ++NextI;
02059     if (NextI == E)
02060       break;
02061 
02062     PathDiagnosticControlFlowPiece *PieceNextI = nullptr;
02063 
02064     while (true) {
02065       if (NextI == E)
02066         break;
02067 
02068       PathDiagnosticEventPiece *EV = dyn_cast<PathDiagnosticEventPiece>(*NextI);
02069       if (EV) {
02070         StringRef S = EV->getString();
02071         if (S == StrEnteringLoop || S == StrLoopBodyZero ||
02072             S == StrLoopCollectionEmpty || S == StrLoopRangeEmpty) {
02073           ++NextI;
02074           continue;
02075         }
02076         break;
02077       }
02078 
02079       PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(*NextI);
02080       break;
02081     }
02082 
02083     if (!PieceNextI)
02084       continue;
02085 
02086     const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation());
02087     const Stmt *s2End   = getLocStmt(PieceNextI->getEndLocation());
02088 
02089     if (!s2Start || !s2End || s1End != s2Start)
02090       continue;
02091 
02092     // We only perform this transformation for specific branch kinds.
02093     // We don't want to do this for do..while, for example.
02094     if (!(isa<ForStmt>(s1Start) || isa<WhileStmt>(s1Start) ||
02095           isa<IfStmt>(s1Start) || isa<ObjCForCollectionStmt>(s1Start) ||
02096           isa<CXXForRangeStmt>(s1Start)))
02097       continue;
02098 
02099     // Is s1End the branch condition?
02100     if (!isConditionForTerminator(s1Start, s1End))
02101       continue;
02102 
02103     // Perform the hoisting by eliminating (2) and changing the start
02104     // location of (3).
02105     PieceNextI->setStartLocation(PieceI->getStartLocation());
02106     I = pieces.erase(I);
02107   }
02108 }
02109 
02110 /// Returns the number of bytes in the given (character-based) SourceRange.
02111 ///
02112 /// If the locations in the range are not on the same line, returns None.
02113 ///
02114 /// Note that this does not do a precise user-visible character or column count.
02115 static Optional<size_t> getLengthOnSingleLine(SourceManager &SM,
02116                                               SourceRange Range) {
02117   SourceRange ExpansionRange(SM.getExpansionLoc(Range.getBegin()),
02118                              SM.getExpansionRange(Range.getEnd()).second);
02119 
02120   FileID FID = SM.getFileID(ExpansionRange.getBegin());
02121   if (FID != SM.getFileID(ExpansionRange.getEnd()))
02122     return None;
02123 
02124   bool Invalid;
02125   const llvm::MemoryBuffer *Buffer = SM.getBuffer(FID, &Invalid);
02126   if (Invalid)
02127     return None;
02128 
02129   unsigned BeginOffset = SM.getFileOffset(ExpansionRange.getBegin());
02130   unsigned EndOffset = SM.getFileOffset(ExpansionRange.getEnd());
02131   StringRef Snippet = Buffer->getBuffer().slice(BeginOffset, EndOffset);
02132 
02133   // We're searching the raw bytes of the buffer here, which might include
02134   // escaped newlines and such. That's okay; we're trying to decide whether the
02135   // SourceRange is covering a large or small amount of space in the user's
02136   // editor.
02137   if (Snippet.find_first_of("\r\n") != StringRef::npos)
02138     return None;
02139 
02140   // This isn't Unicode-aware, but it doesn't need to be.
02141   return Snippet.size();
02142 }
02143 
02144 /// \sa getLengthOnSingleLine(SourceManager, SourceRange)
02145 static Optional<size_t> getLengthOnSingleLine(SourceManager &SM,
02146                                               const Stmt *S) {
02147   return getLengthOnSingleLine(SM, S->getSourceRange());
02148 }
02149 
02150 /// Eliminate two-edge cycles created by addContextEdges().
02151 ///
02152 /// Once all the context edges are in place, there are plenty of cases where
02153 /// there's a single edge from a top-level statement to a subexpression,
02154 /// followed by a single path note, and then a reverse edge to get back out to
02155 /// the top level. If the statement is simple enough, the subexpression edges
02156 /// just add noise and make it harder to understand what's going on.
02157 ///
02158 /// This function only removes edges in pairs, because removing only one edge
02159 /// might leave other edges dangling.
02160 ///
02161 /// This will not remove edges in more complicated situations:
02162 /// - if there is more than one "hop" leading to or from a subexpression.
02163 /// - if there is an inlined call between the edges instead of a single event.
02164 /// - if the whole statement is large enough that having subexpression arrows
02165 ///   might be helpful.
02166 static void removeContextCycles(PathPieces &Path, SourceManager &SM,
02167                                 ParentMap &PM) {
02168   for (PathPieces::iterator I = Path.begin(), E = Path.end(); I != E; ) {
02169     // Pattern match the current piece and its successor.
02170     PathDiagnosticControlFlowPiece *PieceI =
02171       dyn_cast<PathDiagnosticControlFlowPiece>(*I);
02172 
02173     if (!PieceI) {
02174       ++I;
02175       continue;
02176     }
02177 
02178     const Stmt *s1Start = getLocStmt(PieceI->getStartLocation());
02179     const Stmt *s1End   = getLocStmt(PieceI->getEndLocation());
02180 
02181     PathPieces::iterator NextI = I; ++NextI;
02182     if (NextI == E)
02183       break;
02184 
02185     PathDiagnosticControlFlowPiece *PieceNextI =
02186       dyn_cast<PathDiagnosticControlFlowPiece>(*NextI);
02187 
02188     if (!PieceNextI) {
02189       if (isa<PathDiagnosticEventPiece>(*NextI)) {
02190         ++NextI;
02191         if (NextI == E)
02192           break;
02193         PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(*NextI);
02194       }
02195 
02196       if (!PieceNextI) {
02197         ++I;
02198         continue;
02199       }
02200     }
02201 
02202     const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation());
02203     const Stmt *s2End   = getLocStmt(PieceNextI->getEndLocation());
02204 
02205     if (s1Start && s2Start && s1Start == s2End && s2Start == s1End) {
02206       const size_t MAX_SHORT_LINE_LENGTH = 80;
02207       Optional<size_t> s1Length = getLengthOnSingleLine(SM, s1Start);
02208       if (s1Length && *s1Length <= MAX_SHORT_LINE_LENGTH) {
02209         Optional<size_t> s2Length = getLengthOnSingleLine(SM, s2Start);
02210         if (s2Length && *s2Length <= MAX_SHORT_LINE_LENGTH) {
02211           Path.erase(I);
02212           I = Path.erase(NextI);
02213           continue;
02214         }
02215       }
02216     }
02217 
02218     ++I;
02219   }
02220 }
02221 
02222 /// \brief Return true if X is contained by Y.
02223 static bool lexicalContains(ParentMap &PM,
02224                             const Stmt *X,
02225                             const Stmt *Y) {
02226   while (X) {
02227     if (X == Y)
02228       return true;
02229     X = PM.getParent(X);
02230   }
02231   return false;
02232 }
02233 
02234 // Remove short edges on the same line less than 3 columns in difference.
02235 static void removePunyEdges(PathPieces &path,
02236                             SourceManager &SM,
02237                             ParentMap &PM) {
02238 
02239   bool erased = false;
02240 
02241   for (PathPieces::iterator I = path.begin(), E = path.end(); I != E;
02242        erased ? I : ++I) {
02243 
02244     erased = false;
02245 
02246     PathDiagnosticControlFlowPiece *PieceI =
02247       dyn_cast<PathDiagnosticControlFlowPiece>(*I);
02248 
02249     if (!PieceI)
02250       continue;
02251 
02252     const Stmt *start = getLocStmt(PieceI->getStartLocation());
02253     const Stmt *end   = getLocStmt(PieceI->getEndLocation());
02254 
02255     if (!start || !end)
02256       continue;
02257 
02258     const Stmt *endParent = PM.getParent(end);
02259     if (!endParent)
02260       continue;
02261 
02262     if (isConditionForTerminator(end, endParent))
02263       continue;
02264 
02265     SourceLocation FirstLoc = start->getLocStart();
02266     SourceLocation SecondLoc = end->getLocStart();
02267 
02268     if (!SM.isWrittenInSameFile(FirstLoc, SecondLoc))
02269       continue;
02270     if (SM.isBeforeInTranslationUnit(SecondLoc, FirstLoc))
02271       std::swap(SecondLoc, FirstLoc);
02272 
02273     SourceRange EdgeRange(FirstLoc, SecondLoc);
02274     Optional<size_t> ByteWidth = getLengthOnSingleLine(SM, EdgeRange);
02275 
02276     // If the statements are on different lines, continue.
02277     if (!ByteWidth)
02278       continue;
02279 
02280     const size_t MAX_PUNY_EDGE_LENGTH = 2;
02281     if (*ByteWidth <= MAX_PUNY_EDGE_LENGTH) {
02282       // FIXME: There are enough /bytes/ between the endpoints of the edge, but
02283       // there might not be enough /columns/. A proper user-visible column count
02284       // is probably too expensive, though.
02285       I = path.erase(I);
02286       erased = true;
02287       continue;
02288     }
02289   }
02290 }
02291 
02292 static void removeIdenticalEvents(PathPieces &path) {
02293   for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ++I) {
02294     PathDiagnosticEventPiece *PieceI =
02295       dyn_cast<PathDiagnosticEventPiece>(*I);
02296 
02297     if (!PieceI)
02298       continue;
02299 
02300     PathPieces::iterator NextI = I; ++NextI;
02301     if (NextI == E)
02302       return;
02303 
02304     PathDiagnosticEventPiece *PieceNextI =
02305       dyn_cast<PathDiagnosticEventPiece>(*NextI);
02306 
02307     if (!PieceNextI)
02308       continue;
02309 
02310     // Erase the second piece if it has the same exact message text.
02311     if (PieceI->getString() == PieceNextI->getString()) {
02312       path.erase(NextI);
02313     }
02314   }
02315 }
02316 
02317 static bool optimizeEdges(PathPieces &path, SourceManager &SM,
02318                           OptimizedCallsSet &OCS,
02319                           LocationContextMap &LCM) {
02320   bool hasChanges = false;
02321   const LocationContext *LC = LCM[&path];
02322   assert(LC);
02323   ParentMap &PM = LC->getParentMap();
02324 
02325   for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ) {
02326     // Optimize subpaths.
02327     if (PathDiagnosticCallPiece *CallI = dyn_cast<PathDiagnosticCallPiece>(*I)){
02328       // Record the fact that a call has been optimized so we only do the
02329       // effort once.
02330       if (!OCS.count(CallI)) {
02331         while (optimizeEdges(CallI->path, SM, OCS, LCM)) {}
02332         OCS.insert(CallI);
02333       }
02334       ++I;
02335       continue;
02336     }
02337 
02338     // Pattern match the current piece and its successor.
02339     PathDiagnosticControlFlowPiece *PieceI =
02340       dyn_cast<PathDiagnosticControlFlowPiece>(*I);
02341 
02342     if (!PieceI) {
02343       ++I;
02344       continue;
02345     }
02346 
02347     const Stmt *s1Start = getLocStmt(PieceI->getStartLocation());
02348     const Stmt *s1End   = getLocStmt(PieceI->getEndLocation());
02349     const Stmt *level1 = getStmtParent(s1Start, PM);
02350     const Stmt *level2 = getStmtParent(s1End, PM);
02351 
02352     PathPieces::iterator NextI = I; ++NextI;
02353     if (NextI == E)
02354       break;
02355 
02356     PathDiagnosticControlFlowPiece *PieceNextI =
02357       dyn_cast<PathDiagnosticControlFlowPiece>(*NextI);
02358 
02359     if (!PieceNextI) {
02360       ++I;
02361       continue;
02362     }
02363 
02364     const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation());
02365     const Stmt *s2End   = getLocStmt(PieceNextI->getEndLocation());
02366     const Stmt *level3 = getStmtParent(s2Start, PM);
02367     const Stmt *level4 = getStmtParent(s2End, PM);
02368 
02369     // Rule I.
02370     //
02371     // If we have two consecutive control edges whose end/begin locations
02372     // are at the same level (e.g. statements or top-level expressions within
02373     // a compound statement, or siblings share a single ancestor expression),
02374     // then merge them if they have no interesting intermediate event.
02375     //
02376     // For example:
02377     //
02378     // (1.1 -> 1.2) -> (1.2 -> 1.3) becomes (1.1 -> 1.3) because the common
02379     // parent is '1'.  Here 'x.y.z' represents the hierarchy of statements.
02380     //
02381     // NOTE: this will be limited later in cases where we add barriers
02382     // to prevent this optimization.
02383     //
02384     if (level1 && level1 == level2 && level1 == level3 && level1 == level4) {
02385       PieceI->setEndLocation(PieceNextI->getEndLocation());
02386       path.erase(NextI);
02387       hasChanges = true;
02388       continue;
02389     }
02390 
02391     // Rule II.
02392     //
02393     // Eliminate edges between subexpressions and parent expressions
02394     // when the subexpression is consumed.
02395     //
02396     // NOTE: this will be limited later in cases where we add barriers
02397     // to prevent this optimization.
02398     //
02399     if (s1End && s1End == s2Start && level2) {
02400       bool removeEdge = false;
02401       // Remove edges into the increment or initialization of a
02402       // loop that have no interleaving event.  This means that
02403       // they aren't interesting.
02404       if (isIncrementOrInitInForLoop(s1End, level2))
02405         removeEdge = true;
02406       // Next only consider edges that are not anchored on
02407       // the condition of a terminator.  This are intermediate edges
02408       // that we might want to trim.
02409       else if (!isConditionForTerminator(level2, s1End)) {
02410         // Trim edges on expressions that are consumed by
02411         // the parent expression.
02412         if (isa<Expr>(s1End) && PM.isConsumedExpr(cast<Expr>(s1End))) {
02413           removeEdge = true;          
02414         }
02415         // Trim edges where a lexical containment doesn't exist.
02416         // For example:
02417         //
02418         //  X -> Y -> Z
02419         //
02420         // If 'Z' lexically contains Y (it is an ancestor) and
02421         // 'X' does not lexically contain Y (it is a descendant OR
02422         // it has no lexical relationship at all) then trim.
02423         //
02424         // This can eliminate edges where we dive into a subexpression
02425         // and then pop back out, etc.
02426         else if (s1Start && s2End &&
02427                  lexicalContains(PM, s2Start, s2End) &&
02428                  !lexicalContains(PM, s1End, s1Start)) {
02429           removeEdge = true;
02430         }
02431         // Trim edges from a subexpression back to the top level if the
02432         // subexpression is on a different line.
02433         //
02434         // A.1 -> A -> B
02435         // becomes
02436         // A.1 -> B
02437         //
02438         // These edges just look ugly and don't usually add anything.
02439         else if (s1Start && s2End &&
02440                  lexicalContains(PM, s1Start, s1End)) {
02441           SourceRange EdgeRange(PieceI->getEndLocation().asLocation(),
02442                                 PieceI->getStartLocation().asLocation());
02443           if (!getLengthOnSingleLine(SM, EdgeRange).hasValue())
02444             removeEdge = true;
02445         }
02446       }
02447 
02448       if (removeEdge) {
02449         PieceI->setEndLocation(PieceNextI->getEndLocation());
02450         path.erase(NextI);
02451         hasChanges = true;
02452         continue;
02453       }
02454     }
02455 
02456     // Optimize edges for ObjC fast-enumeration loops.
02457     //
02458     // (X -> collection) -> (collection -> element)
02459     //
02460     // becomes:
02461     //
02462     // (X -> element)
02463     if (s1End == s2Start) {
02464       const ObjCForCollectionStmt *FS =
02465         dyn_cast_or_null<ObjCForCollectionStmt>(level3);
02466       if (FS && FS->getCollection()->IgnoreParens() == s2Start &&
02467           s2End == FS->getElement()) {
02468         PieceI->setEndLocation(PieceNextI->getEndLocation());
02469         path.erase(NextI);
02470         hasChanges = true;
02471         continue;
02472       }
02473     }
02474 
02475     // No changes at this index?  Move to the next one.
02476     ++I;
02477   }
02478 
02479   if (!hasChanges) {
02480     // Adjust edges into subexpressions to make them more uniform
02481     // and aesthetically pleasing.
02482     addContextEdges(path, SM, PM, LC);
02483     // Remove "cyclical" edges that include one or more context edges.
02484     removeContextCycles(path, SM, PM);
02485     // Hoist edges originating from branch conditions to branches
02486     // for simple branches.
02487     simplifySimpleBranches(path);
02488     // Remove any puny edges left over after primary optimization pass.
02489     removePunyEdges(path, SM, PM);
02490     // Remove identical events.
02491     removeIdenticalEvents(path);
02492   }
02493 
02494   return hasChanges;
02495 }
02496 
02497 /// Drop the very first edge in a path, which should be a function entry edge.
02498 ///
02499 /// If the first edge is not a function entry edge (say, because the first
02500 /// statement had an invalid source location), this function does nothing.
02501 // FIXME: We should just generate invalid edges anyway and have the optimizer
02502 // deal with them.
02503 static void dropFunctionEntryEdge(PathPieces &Path,
02504                                   LocationContextMap &LCM,
02505                                   SourceManager &SM) {
02506   const PathDiagnosticControlFlowPiece *FirstEdge =
02507     dyn_cast<PathDiagnosticControlFlowPiece>(Path.front());
02508   if (!FirstEdge)
02509     return;
02510 
02511   const Decl *D = LCM[&Path]->getDecl();
02512   PathDiagnosticLocation EntryLoc = PathDiagnosticLocation::createBegin(D, SM);
02513   if (FirstEdge->getStartLocation() != EntryLoc)
02514     return;
02515 
02516   Path.pop_front();
02517 }
02518 
02519 
02520 //===----------------------------------------------------------------------===//
02521 // Methods for BugType and subclasses.
02522 //===----------------------------------------------------------------------===//
02523 void BugType::anchor() { }
02524 
02525 void BugType::FlushReports(BugReporter &BR) {}
02526 
02527 void BuiltinBug::anchor() {}
02528 
02529 //===----------------------------------------------------------------------===//
02530 // Methods for BugReport and subclasses.
02531 //===----------------------------------------------------------------------===//
02532 
02533 void BugReport::NodeResolver::anchor() {}
02534 
02535 void BugReport::addVisitor(std::unique_ptr<BugReporterVisitor> visitor) {
02536   if (!visitor)
02537     return;
02538 
02539   llvm::FoldingSetNodeID ID;
02540   visitor->Profile(ID);
02541   void *InsertPos;
02542 
02543   if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos))
02544     return;
02545 
02546   CallbacksSet.InsertNode(visitor.get(), InsertPos);
02547   Callbacks.push_back(std::move(visitor));
02548   ++ConfigurationChangeToken;
02549 }
02550 
02551 BugReport::~BugReport() {
02552   while (!interestingSymbols.empty()) {
02553     popInterestingSymbolsAndRegions();
02554   }
02555 }
02556 
02557 const Decl *BugReport::getDeclWithIssue() const {
02558   if (DeclWithIssue)
02559     return DeclWithIssue;
02560   
02561   const ExplodedNode *N = getErrorNode();
02562   if (!N)
02563     return nullptr;
02564 
02565   const LocationContext *LC = N->getLocationContext();
02566   return LC->getCurrentStackFrame()->getDecl();
02567 }
02568 
02569 void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
02570   hash.AddPointer(&BT);
02571   hash.AddString(Description);
02572   PathDiagnosticLocation UL = getUniqueingLocation();
02573   if (UL.isValid()) {
02574     UL.Profile(hash);
02575   } else if (Location.isValid()) {
02576     Location.Profile(hash);
02577   } else {
02578     assert(ErrorNode);
02579     hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
02580   }
02581 
02582   for (SmallVectorImpl<SourceRange>::const_iterator I =
02583       Ranges.begin(), E = Ranges.end(); I != E; ++I) {
02584     const SourceRange range = *I;
02585     if (!range.isValid())
02586       continue;
02587     hash.AddInteger(range.getBegin().getRawEncoding());
02588     hash.AddInteger(range.getEnd().getRawEncoding());
02589   }
02590 }
02591 
02592 void BugReport::markInteresting(SymbolRef sym) {
02593   if (!sym)
02594     return;
02595 
02596   // If the symbol wasn't already in our set, note a configuration change.
02597   if (getInterestingSymbols().insert(sym).second)
02598     ++ConfigurationChangeToken;
02599 
02600   if (const SymbolMetadata *meta = dyn_cast<SymbolMetadata>(sym))
02601     getInterestingRegions().insert(meta->getRegion());
02602 }
02603 
02604 void BugReport::markInteresting(const MemRegion *R) {
02605   if (!R)
02606     return;
02607 
02608   // If the base region wasn't already in our set, note a configuration change.
02609   R = R->getBaseRegion();
02610   if (getInterestingRegions().insert(R).second)
02611     ++ConfigurationChangeToken;
02612 
02613   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
02614     getInterestingSymbols().insert(SR->getSymbol());
02615 }
02616 
02617 void BugReport::markInteresting(SVal V) {
02618   markInteresting(V.getAsRegion());
02619   markInteresting(V.getAsSymbol());
02620 }
02621 
02622 void BugReport::markInteresting(const LocationContext *LC) {
02623   if (!LC)
02624     return;
02625   InterestingLocationContexts.insert(LC);
02626 }
02627 
02628 bool BugReport::isInteresting(SVal V) {
02629   return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol());
02630 }
02631 
02632 bool BugReport::isInteresting(SymbolRef sym) {
02633   if (!sym)
02634     return false;
02635   // We don't currently consider metadata symbols to be interesting
02636   // even if we know their region is interesting. Is that correct behavior?
02637   return getInterestingSymbols().count(sym);
02638 }
02639 
02640 bool BugReport::isInteresting(const MemRegion *R) {
02641   if (!R)
02642     return false;
02643   R = R->getBaseRegion();
02644   bool b = getInterestingRegions().count(R);
02645   if (b)
02646     return true;
02647   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
02648     return getInterestingSymbols().count(SR->getSymbol());
02649   return false;
02650 }
02651 
02652 bool BugReport::isInteresting(const LocationContext *LC) {
02653   if (!LC)
02654     return false;
02655   return InterestingLocationContexts.count(LC);
02656 }
02657 
02658 void BugReport::lazyInitializeInterestingSets() {
02659   if (interestingSymbols.empty()) {
02660     interestingSymbols.push_back(new Symbols());
02661     interestingRegions.push_back(new Regions());
02662   }
02663 }
02664 
02665 BugReport::Symbols &BugReport::getInterestingSymbols() {
02666   lazyInitializeInterestingSets();
02667   return *interestingSymbols.back();
02668 }
02669 
02670 BugReport::Regions &BugReport::getInterestingRegions() {
02671   lazyInitializeInterestingSets();
02672   return *interestingRegions.back();
02673 }
02674 
02675 void BugReport::pushInterestingSymbolsAndRegions() {
02676   interestingSymbols.push_back(new Symbols(getInterestingSymbols()));
02677   interestingRegions.push_back(new Regions(getInterestingRegions()));
02678 }
02679 
02680 void BugReport::popInterestingSymbolsAndRegions() {
02681   delete interestingSymbols.pop_back_val();
02682   delete interestingRegions.pop_back_val();
02683 }
02684 
02685 const Stmt *BugReport::getStmt() const {
02686   if (!ErrorNode)
02687     return nullptr;
02688 
02689   ProgramPoint ProgP = ErrorNode->getLocation();
02690   const Stmt *S = nullptr;
02691 
02692   if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
02693     CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
02694     if (BE->getBlock() == &Exit)
02695       S = GetPreviousStmt(ErrorNode);
02696   }
02697   if (!S)
02698     S = PathDiagnosticLocation::getStmt(ErrorNode);
02699 
02700   return S;
02701 }
02702 
02703 llvm::iterator_range<BugReport::ranges_iterator> BugReport::getRanges() {
02704   // If no custom ranges, add the range of the statement corresponding to
02705   // the error node.
02706   if (Ranges.empty()) {
02707     if (const Expr *E = dyn_cast_or_null<Expr>(getStmt()))
02708       addRange(E->getSourceRange());
02709     else
02710       return llvm::make_range(ranges_iterator(), ranges_iterator());
02711   }
02712 
02713   // User-specified absence of range info.
02714   if (Ranges.size() == 1 && !Ranges.begin()->isValid())
02715     return llvm::make_range(ranges_iterator(), ranges_iterator());
02716 
02717   return llvm::iterator_range<BugReport::ranges_iterator>(Ranges.begin(),
02718                                                           Ranges.end());
02719 }
02720 
02721 PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
02722   if (ErrorNode) {
02723     assert(!Location.isValid() &&
02724      "Either Location or ErrorNode should be specified but not both.");
02725     return PathDiagnosticLocation::createEndOfPath(ErrorNode, SM);
02726   }
02727 
02728   assert(Location.isValid());
02729   return Location;
02730 }
02731 
02732 //===----------------------------------------------------------------------===//
02733 // Methods for BugReporter and subclasses.
02734 //===----------------------------------------------------------------------===//
02735 
02736 BugReportEquivClass::~BugReportEquivClass() { }
02737 GRBugReporter::~GRBugReporter() { }
02738 BugReporterData::~BugReporterData() {}
02739 
02740 ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
02741 
02742 ProgramStateManager&
02743 GRBugReporter::getStateManager() { return Eng.getStateManager(); }
02744 
02745 BugReporter::~BugReporter() {
02746   FlushReports();
02747 
02748   // Free the bug reports we are tracking.
02749   typedef std::vector<BugReportEquivClass *> ContTy;
02750   for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end();
02751        I != E; ++I) {
02752     delete *I;
02753   }
02754 }
02755 
02756 void BugReporter::FlushReports() {
02757   if (BugTypes.isEmpty())
02758     return;
02759 
02760   // First flush the warnings for each BugType.  This may end up creating new
02761   // warnings and new BugTypes.
02762   // FIXME: Only NSErrorChecker needs BugType's FlushReports.
02763   // Turn NSErrorChecker into a proper checker and remove this.
02764   SmallVector<const BugType *, 16> bugTypes(BugTypes.begin(), BugTypes.end());
02765   for (SmallVectorImpl<const BugType *>::iterator
02766          I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I)
02767     const_cast<BugType*>(*I)->FlushReports(*this);
02768 
02769   // We need to flush reports in deterministic order to ensure the order
02770   // of the reports is consistent between runs.
02771   typedef std::vector<BugReportEquivClass *> ContVecTy;
02772   for (ContVecTy::iterator EI=EQClassesVector.begin(), EE=EQClassesVector.end();
02773        EI != EE; ++EI){
02774     BugReportEquivClass& EQ = **EI;
02775     FlushReport(EQ);
02776   }
02777 
02778   // BugReporter owns and deletes only BugTypes created implicitly through
02779   // EmitBasicReport.
02780   // FIXME: There are leaks from checkers that assume that the BugTypes they
02781   // create will be destroyed by the BugReporter.
02782   llvm::DeleteContainerSeconds(StrBugTypes);
02783 
02784   // Remove all references to the BugType objects.
02785   BugTypes = F.getEmptySet();
02786 }
02787 
02788 //===----------------------------------------------------------------------===//
02789 // PathDiagnostics generation.
02790 //===----------------------------------------------------------------------===//
02791 
02792 namespace {
02793 /// A wrapper around a report graph, which contains only a single path, and its
02794 /// node maps.
02795 class ReportGraph {
02796 public:
02797   InterExplodedGraphMap BackMap;
02798   std::unique_ptr<ExplodedGraph> Graph;
02799   const ExplodedNode *ErrorNode;
02800   size_t Index;
02801 };
02802 
02803 /// A wrapper around a trimmed graph and its node maps.
02804 class TrimmedGraph {
02805   InterExplodedGraphMap InverseMap;
02806 
02807   typedef llvm::DenseMap<const ExplodedNode *, unsigned> PriorityMapTy;
02808   PriorityMapTy PriorityMap;
02809 
02810   typedef std::pair<const ExplodedNode *, size_t> NodeIndexPair;
02811   SmallVector<NodeIndexPair, 32> ReportNodes;
02812 
02813   std::unique_ptr<ExplodedGraph> G;
02814 
02815   /// A helper class for sorting ExplodedNodes by priority.
02816   template <bool Descending>
02817   class PriorityCompare {
02818     const PriorityMapTy &PriorityMap;
02819 
02820   public:
02821     PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
02822 
02823     bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
02824       PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
02825       PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
02826       PriorityMapTy::const_iterator E = PriorityMap.end();
02827 
02828       if (LI == E)
02829         return Descending;
02830       if (RI == E)
02831         return !Descending;
02832 
02833       return Descending ? LI->second > RI->second
02834                         : LI->second < RI->second;
02835     }
02836 
02837     bool operator()(const NodeIndexPair &LHS, const NodeIndexPair &RHS) const {
02838       return (*this)(LHS.first, RHS.first);
02839     }
02840   };
02841 
02842 public:
02843   TrimmedGraph(const ExplodedGraph *OriginalGraph,
02844                ArrayRef<const ExplodedNode *> Nodes);
02845 
02846   bool popNextReportGraph(ReportGraph &GraphWrapper);
02847 };
02848 }
02849 
02850 TrimmedGraph::TrimmedGraph(const ExplodedGraph *OriginalGraph,
02851                            ArrayRef<const ExplodedNode *> Nodes) {
02852   // The trimmed graph is created in the body of the constructor to ensure
02853   // that the DenseMaps have been initialized already.
02854   InterExplodedGraphMap ForwardMap;
02855   G = OriginalGraph->trim(Nodes, &ForwardMap, &InverseMap);
02856 
02857   // Find the (first) error node in the trimmed graph.  We just need to consult
02858   // the node map which maps from nodes in the original graph to nodes
02859   // in the new graph.
02860   llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes;
02861 
02862   for (unsigned i = 0, count = Nodes.size(); i < count; ++i) {
02863     if (const ExplodedNode *NewNode = ForwardMap.lookup(Nodes[i])) {
02864       ReportNodes.push_back(std::make_pair(NewNode, i));
02865       RemainingNodes.insert(NewNode);
02866     }
02867   }
02868 
02869   assert(!RemainingNodes.empty() && "No error node found in the trimmed graph");
02870 
02871   // Perform a forward BFS to find all the shortest paths.
02872   std::queue<const ExplodedNode *> WS;
02873 
02874   assert(G->num_roots() == 1);
02875   WS.push(*G->roots_begin());
02876   unsigned Priority = 0;
02877 
02878   while (!WS.empty()) {
02879     const ExplodedNode *Node = WS.front();
02880     WS.pop();
02881 
02882     PriorityMapTy::iterator PriorityEntry;
02883     bool IsNew;
02884     std::tie(PriorityEntry, IsNew) =
02885       PriorityMap.insert(std::make_pair(Node, Priority));
02886     ++Priority;
02887 
02888     if (!IsNew) {
02889       assert(PriorityEntry->second <= Priority);
02890       continue;
02891     }
02892 
02893     if (RemainingNodes.erase(Node))
02894       if (RemainingNodes.empty())
02895         break;
02896 
02897     for (ExplodedNode::const_pred_iterator I = Node->succ_begin(),
02898                                            E = Node->succ_end();
02899          I != E; ++I)
02900       WS.push(*I);
02901   }
02902 
02903   // Sort the error paths from longest to shortest.
02904   std::sort(ReportNodes.begin(), ReportNodes.end(),
02905             PriorityCompare<true>(PriorityMap));
02906 }
02907 
02908 bool TrimmedGraph::popNextReportGraph(ReportGraph &GraphWrapper) {
02909   if (ReportNodes.empty())
02910     return false;
02911 
02912   const ExplodedNode *OrigN;
02913   std::tie(OrigN, GraphWrapper.Index) = ReportNodes.pop_back_val();
02914   assert(PriorityMap.find(OrigN) != PriorityMap.end() &&
02915          "error node not accessible from root");
02916 
02917   // Create a new graph with a single path.  This is the graph
02918   // that will be returned to the caller.
02919   auto GNew = llvm::make_unique<ExplodedGraph>();
02920   GraphWrapper.BackMap.clear();
02921 
02922   // Now walk from the error node up the BFS path, always taking the
02923   // predeccessor with the lowest number.
02924   ExplodedNode *Succ = nullptr;
02925   while (true) {
02926     // Create the equivalent node in the new graph with the same state
02927     // and location.
02928     ExplodedNode *NewN = GNew->getNode(OrigN->getLocation(), OrigN->getState(),
02929                                        OrigN->isSink());
02930 
02931     // Store the mapping to the original node.
02932     InterExplodedGraphMap::const_iterator IMitr = InverseMap.find(OrigN);
02933     assert(IMitr != InverseMap.end() && "No mapping to original node.");
02934     GraphWrapper.BackMap[NewN] = IMitr->second;
02935 
02936     // Link up the new node with the previous node.
02937     if (Succ)
02938       Succ->addPredecessor(NewN, *GNew);
02939     else
02940       GraphWrapper.ErrorNode = NewN;
02941 
02942     Succ = NewN;
02943 
02944     // Are we at the final node?
02945     if (OrigN->pred_empty()) {
02946       GNew->addRoot(NewN);
02947       break;
02948     }
02949 
02950     // Find the next predeccessor node.  We choose the node that is marked
02951     // with the lowest BFS number.
02952     OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(),
02953                           PriorityCompare<false>(PriorityMap));
02954   }
02955 
02956   GraphWrapper.Graph = std::move(GNew);
02957 
02958   return true;
02959 }
02960 
02961 
02962 /// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
02963 ///  and collapses PathDiagosticPieces that are expanded by macros.
02964 static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM) {
02965   typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiece>,
02966                                 SourceLocation> > MacroStackTy;
02967 
02968   typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> >
02969           PiecesTy;
02970 
02971   MacroStackTy MacroStack;
02972   PiecesTy Pieces;
02973 
02974   for (PathPieces::const_iterator I = path.begin(), E = path.end();
02975        I!=E; ++I) {
02976     
02977     PathDiagnosticPiece *piece = I->get();
02978 
02979     // Recursively compact calls.
02980     if (PathDiagnosticCallPiece *call=dyn_cast<PathDiagnosticCallPiece>(piece)){
02981       CompactPathDiagnostic(call->path, SM);
02982     }
02983     
02984     // Get the location of the PathDiagnosticPiece.
02985     const FullSourceLoc Loc = piece->getLocation().asLocation();
02986 
02987     // Determine the instantiation location, which is the location we group
02988     // related PathDiagnosticPieces.
02989     SourceLocation InstantiationLoc = Loc.isMacroID() ?
02990                                       SM.getExpansionLoc(Loc) :
02991                                       SourceLocation();
02992 
02993     if (Loc.isFileID()) {
02994       MacroStack.clear();
02995       Pieces.push_back(piece);
02996       continue;
02997     }
02998 
02999     assert(Loc.isMacroID());
03000 
03001     // Is the PathDiagnosticPiece within the same macro group?
03002     if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
03003       MacroStack.back().first->subPieces.push_back(piece);
03004       continue;
03005     }
03006 
03007     // We aren't in the same group.  Are we descending into a new macro
03008     // or are part of an old one?
03009     IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup;
03010 
03011     SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
03012                                           SM.getExpansionLoc(Loc) :
03013                                           SourceLocation();
03014 
03015     // Walk the entire macro stack.
03016     while (!MacroStack.empty()) {
03017       if (InstantiationLoc == MacroStack.back().second) {
03018         MacroGroup = MacroStack.back().first;
03019         break;
03020       }
03021 
03022       if (ParentInstantiationLoc == MacroStack.back().second) {
03023         MacroGroup = MacroStack.back().first;
03024         break;
03025       }
03026 
03027       MacroStack.pop_back();
03028     }
03029 
03030     if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
03031       // Create a new macro group and add it to the stack.
03032       PathDiagnosticMacroPiece *NewGroup =
03033         new PathDiagnosticMacroPiece(
03034           PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
03035 
03036       if (MacroGroup)
03037         MacroGroup->subPieces.push_back(NewGroup);
03038       else {
03039         assert(InstantiationLoc.isFileID());
03040         Pieces.push_back(NewGroup);
03041       }
03042 
03043       MacroGroup = NewGroup;
03044       MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
03045     }
03046 
03047     // Finally, add the PathDiagnosticPiece to the group.
03048     MacroGroup->subPieces.push_back(piece);
03049   }
03050 
03051   // Now take the pieces and construct a new PathDiagnostic.
03052   path.clear();
03053 
03054   path.insert(path.end(), Pieces.begin(), Pieces.end());
03055 }
03056 
03057 bool GRBugReporter::generatePathDiagnostic(PathDiagnostic& PD,
03058                                            PathDiagnosticConsumer &PC,
03059                                            ArrayRef<BugReport *> &bugReports) {
03060   assert(!bugReports.empty());
03061 
03062   bool HasValid = false;
03063   bool HasInvalid = false;
03064   SmallVector<const ExplodedNode *, 32> errorNodes;
03065   for (ArrayRef<BugReport*>::iterator I = bugReports.begin(),
03066                                       E = bugReports.end(); I != E; ++I) {
03067     if ((*I)->isValid()) {
03068       HasValid = true;
03069       errorNodes.push_back((*I)->getErrorNode());
03070     } else {
03071       // Keep the errorNodes list in sync with the bugReports list.
03072       HasInvalid = true;
03073       errorNodes.push_back(nullptr);
03074     }
03075   }
03076 
03077   // If all the reports have been marked invalid by a previous path generation,
03078   // we're done.
03079   if (!HasValid)
03080     return false;
03081 
03082   typedef PathDiagnosticConsumer::PathGenerationScheme PathGenerationScheme;
03083   PathGenerationScheme ActiveScheme = PC.getGenerationScheme();
03084 
03085   if (ActiveScheme == PathDiagnosticConsumer::Extensive) {
03086     AnalyzerOptions &options = getAnalyzerOptions();
03087     if (options.getBooleanOption("path-diagnostics-alternate", true)) {
03088       ActiveScheme = PathDiagnosticConsumer::AlternateExtensive;
03089     }
03090   }
03091 
03092   TrimmedGraph TrimG(&getGraph(), errorNodes);
03093   ReportGraph ErrorGraph;
03094 
03095   while (TrimG.popNextReportGraph(ErrorGraph)) {
03096     // Find the BugReport with the original location.
03097     assert(ErrorGraph.Index < bugReports.size());
03098     BugReport *R = bugReports[ErrorGraph.Index];
03099     assert(R && "No original report found for sliced graph.");
03100     assert(R->isValid() && "Report selected by trimmed graph marked invalid.");
03101 
03102     // Start building the path diagnostic...
03103     PathDiagnosticBuilder PDB(*this, R, ErrorGraph.BackMap, &PC);
03104     const ExplodedNode *N = ErrorGraph.ErrorNode;
03105 
03106     // Register additional node visitors.
03107     R->addVisitor(llvm::make_unique<NilReceiverBRVisitor>());
03108     R->addVisitor(llvm::make_unique<ConditionBRVisitor>());
03109     R->addVisitor(llvm::make_unique<LikelyFalsePositiveSuppressionBRVisitor>());
03110 
03111     BugReport::VisitorList visitors;
03112     unsigned origReportConfigToken, finalReportConfigToken;
03113     LocationContextMap LCM;
03114 
03115     // While generating diagnostics, it's possible the visitors will decide
03116     // new symbols and regions are interesting, or add other visitors based on
03117     // the information they find. If they do, we need to regenerate the path
03118     // based on our new report configuration.
03119     do {
03120       // Get a clean copy of all the visitors.
03121       for (BugReport::visitor_iterator I = R->visitor_begin(),
03122                                        E = R->visitor_end(); I != E; ++I)
03123         visitors.push_back((*I)->clone());
03124 
03125       // Clear out the active path from any previous work.
03126       PD.resetPath();
03127       origReportConfigToken = R->getConfigurationChangeToken();
03128 
03129       // Generate the very last diagnostic piece - the piece is visible before 
03130       // the trace is expanded.
03131       std::unique_ptr<PathDiagnosticPiece> LastPiece;
03132       for (BugReport::visitor_iterator I = visitors.begin(), E = visitors.end();
03133           I != E; ++I) {
03134         if (std::unique_ptr<PathDiagnosticPiece> Piece =
03135                 (*I)->getEndPath(PDB, N, *R)) {
03136           assert (!LastPiece &&
03137               "There can only be one final piece in a diagnostic.");
03138           LastPiece = std::move(Piece);
03139         }
03140       }
03141 
03142       if (ActiveScheme != PathDiagnosticConsumer::None) {
03143         if (!LastPiece)
03144           LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R);
03145         assert(LastPiece);
03146         PD.setEndOfPath(std::move(LastPiece));
03147       }
03148 
03149       // Make sure we get a clean location context map so we don't
03150       // hold onto old mappings.
03151       LCM.clear();
03152 
03153       switch (ActiveScheme) {
03154       case PathDiagnosticConsumer::AlternateExtensive:
03155         GenerateAlternateExtensivePathDiagnostic(PD, PDB, N, LCM, visitors);
03156         break;
03157       case PathDiagnosticConsumer::Extensive:
03158         GenerateExtensivePathDiagnostic(PD, PDB, N, LCM, visitors);
03159         break;
03160       case PathDiagnosticConsumer::Minimal:
03161         GenerateMinimalPathDiagnostic(PD, PDB, N, LCM, visitors);
03162         break;
03163       case PathDiagnosticConsumer::None:
03164         GenerateVisitorsOnlyPathDiagnostic(PD, PDB, N, visitors);
03165         break;
03166       }
03167 
03168       // Clean up the visitors we used.
03169       visitors.clear();
03170 
03171       // Did anything change while generating this path?
03172       finalReportConfigToken = R->getConfigurationChangeToken();
03173     } while (finalReportConfigToken != origReportConfigToken);
03174 
03175     if (!R->isValid())
03176       continue;
03177 
03178     // Finally, prune the diagnostic path of uninteresting stuff.
03179     if (!PD.path.empty()) {
03180       if (R->shouldPrunePath() && getAnalyzerOptions().shouldPrunePaths()) {
03181         bool stillHasNotes = removeUnneededCalls(PD.getMutablePieces(), R, LCM);
03182         assert(stillHasNotes);
03183         (void)stillHasNotes;
03184       }
03185 
03186       // Redirect all call pieces to have valid locations.
03187       adjustCallLocations(PD.getMutablePieces());
03188       removePiecesWithInvalidLocations(PD.getMutablePieces());
03189 
03190       if (ActiveScheme == PathDiagnosticConsumer::AlternateExtensive) {
03191         SourceManager &SM = getSourceManager();
03192 
03193         // Reduce the number of edges from a very conservative set
03194         // to an aesthetically pleasing subset that conveys the
03195         // necessary information.
03196         OptimizedCallsSet OCS;
03197         while (optimizeEdges(PD.getMutablePieces(), SM, OCS, LCM)) {}
03198 
03199         // Drop the very first function-entry edge. It's not really necessary
03200         // for top-level functions.
03201         dropFunctionEntryEdge(PD.getMutablePieces(), LCM, SM);
03202       }
03203 
03204       // Remove messages that are basically the same, and edges that may not
03205       // make sense.
03206       // We have to do this after edge optimization in the Extensive mode.
03207       removeRedundantMsgs(PD.getMutablePieces());
03208       removeEdgesToDefaultInitializers(PD.getMutablePieces());
03209     }
03210 
03211     // We found a report and didn't suppress it.
03212     return true;
03213   }
03214 
03215   // We suppressed all the reports in this equivalence class.
03216   assert(!HasInvalid && "Inconsistent suppression");
03217   (void)HasInvalid;
03218   return false;
03219 }
03220 
03221 void BugReporter::Register(BugType *BT) {
03222   BugTypes = F.add(BugTypes, BT);
03223 }
03224 
03225 void BugReporter::emitReport(std::unique_ptr<BugReport> R) {
03226   if (const ExplodedNode *E = R->getErrorNode()) {
03227     const AnalysisDeclContext *DeclCtx =
03228         E->getLocationContext()->getAnalysisDeclContext();
03229     // The source of autosynthesized body can be handcrafted AST or a model
03230     // file. The locations from handcrafted ASTs have no valid source locations
03231     // and have to be discarded. Locations from model files should be preserved
03232     // for processing and reporting.
03233     if (DeclCtx->isBodyAutosynthesized() &&
03234         !DeclCtx->isBodyAutosynthesizedFromModelFile())
03235       return;
03236   }
03237   
03238   bool ValidSourceLoc = R->getLocation(getSourceManager()).isValid();
03239   assert(ValidSourceLoc);
03240   // If we mess up in a release build, we'd still prefer to just drop the bug
03241   // instead of trying to go on.
03242   if (!ValidSourceLoc)
03243     return;
03244 
03245   // Compute the bug report's hash to determine its equivalence class.
03246   llvm::FoldingSetNodeID ID;
03247   R->Profile(ID);
03248 
03249   // Lookup the equivance class.  If there isn't one, create it.
03250   BugType& BT = R->getBugType();
03251   Register(&BT);
03252   void *InsertPos;
03253   BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
03254 
03255   if (!EQ) {
03256     EQ = new BugReportEquivClass(std::move(R));
03257     EQClasses.InsertNode(EQ, InsertPos);
03258     EQClassesVector.push_back(EQ);
03259   } else
03260     EQ->AddReport(std::move(R));
03261 }
03262 
03263 
03264 //===----------------------------------------------------------------------===//
03265 // Emitting reports in equivalence classes.
03266 //===----------------------------------------------------------------------===//
03267 
03268 namespace {
03269 struct FRIEC_WLItem {
03270   const ExplodedNode *N;
03271   ExplodedNode::const_succ_iterator I, E;
03272   
03273   FRIEC_WLItem(const ExplodedNode *n)
03274   : N(n), I(N->succ_begin()), E(N->succ_end()) {}
03275 };  
03276 }
03277 
03278 static BugReport *
03279 FindReportInEquivalenceClass(BugReportEquivClass& EQ,
03280                              SmallVectorImpl<BugReport*> &bugReports) {
03281 
03282   BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
03283   assert(I != E);
03284   BugType& BT = I->getBugType();
03285 
03286   // If we don't need to suppress any of the nodes because they are
03287   // post-dominated by a sink, simply add all the nodes in the equivalence class
03288   // to 'Nodes'.  Any of the reports will serve as a "representative" report.
03289   if (!BT.isSuppressOnSink()) {
03290     BugReport *R = I;
03291     for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
03292       const ExplodedNode *N = I->getErrorNode();
03293       if (N) {
03294         R = I;
03295         bugReports.push_back(R);
03296       }
03297     }
03298     return R;
03299   }
03300 
03301   // For bug reports that should be suppressed when all paths are post-dominated
03302   // by a sink node, iterate through the reports in the equivalence class
03303   // until we find one that isn't post-dominated (if one exists).  We use a
03304   // DFS traversal of the ExplodedGraph to find a non-sink node.  We could write
03305   // this as a recursive function, but we don't want to risk blowing out the
03306   // stack for very long paths.
03307   BugReport *exampleReport = nullptr;
03308 
03309   for (; I != E; ++I) {
03310     const ExplodedNode *errorNode = I->getErrorNode();
03311 
03312     if (!errorNode)
03313       continue;
03314     if (errorNode->isSink()) {
03315       llvm_unreachable(
03316            "BugType::isSuppressSink() should not be 'true' for sink end nodes");
03317     }
03318     // No successors?  By definition this nodes isn't post-dominated by a sink.
03319     if (errorNode->succ_empty()) {
03320       bugReports.push_back(I);
03321       if (!exampleReport)
03322         exampleReport = I;
03323       continue;
03324     }
03325 
03326     // At this point we know that 'N' is not a sink and it has at least one
03327     // successor.  Use a DFS worklist to find a non-sink end-of-path node.    
03328     typedef FRIEC_WLItem WLItem;
03329     typedef SmallVector<WLItem, 10> DFSWorkList;
03330     llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
03331     
03332     DFSWorkList WL;
03333     WL.push_back(errorNode);
03334     Visited[errorNode] = 1;
03335     
03336     while (!WL.empty()) {
03337       WLItem &WI = WL.back();
03338       assert(!WI.N->succ_empty());
03339             
03340       for (; WI.I != WI.E; ++WI.I) {
03341         const ExplodedNode *Succ = *WI.I;        
03342         // End-of-path node?
03343         if (Succ->succ_empty()) {
03344           // If we found an end-of-path node that is not a sink.
03345           if (!Succ->isSink()) {
03346             bugReports.push_back(I);
03347             if (!exampleReport)
03348               exampleReport = I;
03349             WL.clear();
03350             break;
03351           }
03352           // Found a sink?  Continue on to the next successor.
03353           continue;
03354         }
03355         // Mark the successor as visited.  If it hasn't been explored,
03356         // enqueue it to the DFS worklist.
03357         unsigned &mark = Visited[Succ];
03358         if (!mark) {
03359           mark = 1;
03360           WL.push_back(Succ);
03361           break;
03362         }
03363       }
03364 
03365       // The worklist may have been cleared at this point.  First
03366       // check if it is empty before checking the last item.
03367       if (!WL.empty() && &WL.back() == &WI)
03368         WL.pop_back();
03369     }
03370   }
03371 
03372   // ExampleReport will be NULL if all the nodes in the equivalence class
03373   // were post-dominated by sinks.
03374   return exampleReport;
03375 }
03376 
03377 void BugReporter::FlushReport(BugReportEquivClass& EQ) {
03378   SmallVector<BugReport*, 10> bugReports;
03379   BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports);
03380   if (exampleReport) {
03381     for (PathDiagnosticConsumer *PDC : getPathDiagnosticConsumers()) {
03382       FlushReport(exampleReport, *PDC, bugReports);
03383     }
03384   }
03385 }
03386 
03387 void BugReporter::FlushReport(BugReport *exampleReport,
03388                               PathDiagnosticConsumer &PD,
03389                               ArrayRef<BugReport*> bugReports) {
03390 
03391   // FIXME: Make sure we use the 'R' for the path that was actually used.
03392   // Probably doesn't make a difference in practice.
03393   BugType& BT = exampleReport->getBugType();
03394 
03395   std::unique_ptr<PathDiagnostic> D(new PathDiagnostic(
03396       exampleReport->getBugType().getCheckName(),
03397       exampleReport->getDeclWithIssue(), exampleReport->getBugType().getName(),
03398       exampleReport->getDescription(),
03399       exampleReport->getShortDescription(/*Fallback=*/false), BT.getCategory(),
03400       exampleReport->getUniqueingLocation(),
03401       exampleReport->getUniqueingDecl()));
03402 
03403   MaxBugClassSize = std::max(bugReports.size(),
03404                              static_cast<size_t>(MaxBugClassSize));
03405 
03406   // Generate the full path diagnostic, using the generation scheme
03407   // specified by the PathDiagnosticConsumer. Note that we have to generate
03408   // path diagnostics even for consumers which do not support paths, because
03409   // the BugReporterVisitors may mark this bug as a false positive.
03410   if (!bugReports.empty())
03411     if (!generatePathDiagnostic(*D.get(), PD, bugReports))
03412       return;
03413 
03414   MaxValidBugClassSize = std::max(bugReports.size(),
03415                                   static_cast<size_t>(MaxValidBugClassSize));
03416 
03417   // Examine the report and see if the last piece is in a header. Reset the
03418   // report location to the last piece in the main source file.
03419   AnalyzerOptions& Opts = getAnalyzerOptions();
03420   if (Opts.shouldReportIssuesInMainSourceFile() && !Opts.AnalyzeAll)
03421     D->resetDiagnosticLocationToMainFile();
03422 
03423   // If the path is empty, generate a single step path with the location
03424   // of the issue.
03425   if (D->path.empty()) {
03426     PathDiagnosticLocation L = exampleReport->getLocation(getSourceManager());
03427     auto piece = llvm::make_unique<PathDiagnosticEventPiece>(
03428         L, exampleReport->getDescription());
03429     for (const SourceRange &Range : exampleReport->getRanges())
03430       piece->addRange(Range);
03431     D->setEndOfPath(std::move(piece));
03432   }
03433 
03434   // Get the meta data.
03435   const BugReport::ExtraTextList &Meta = exampleReport->getExtraText();
03436   for (BugReport::ExtraTextList::const_iterator i = Meta.begin(),
03437                                                 e = Meta.end(); i != e; ++i) {
03438     D->addMeta(*i);
03439   }
03440 
03441   PD.HandlePathDiagnostic(std::move(D));
03442 }
03443 
03444 void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
03445                                   const CheckerBase *Checker,
03446                                   StringRef Name, StringRef Category,
03447                                   StringRef Str, PathDiagnosticLocation Loc,
03448                                   ArrayRef<SourceRange> Ranges) {
03449   EmitBasicReport(DeclWithIssue, Checker->getCheckName(), Name, Category, Str,
03450                   Loc, Ranges);
03451 }
03452 void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
03453                                   CheckName CheckName,
03454                                   StringRef name, StringRef category,
03455                                   StringRef str, PathDiagnosticLocation Loc,
03456                                   ArrayRef<SourceRange> Ranges) {
03457 
03458   // 'BT' is owned by BugReporter.
03459   BugType *BT = getBugTypeForName(CheckName, name, category);
03460   auto R = llvm::make_unique<BugReport>(*BT, str, Loc);
03461   R->setDeclWithIssue(DeclWithIssue);
03462   for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
03463        I != E; ++I)
03464     R->addRange(*I);
03465   emitReport(std::move(R));
03466 }
03467 
03468 BugType *BugReporter::getBugTypeForName(CheckName CheckName, StringRef name,
03469                                         StringRef category) {
03470   SmallString<136> fullDesc;
03471   llvm::raw_svector_ostream(fullDesc) << CheckName.getName() << ":" << name
03472                                       << ":" << category;
03473   BugType *&BT = StrBugTypes[fullDesc];
03474   if (!BT)
03475     BT = new BugType(CheckName, name, category);
03476   return BT;
03477 }
03478 
03479 LLVM_DUMP_METHOD void PathPieces::dump() const {
03480   unsigned index = 0;
03481   for (PathPieces::const_iterator I = begin(), E = end(); I != E; ++I) {
03482     llvm::errs() << "[" << index++ << "]  ";
03483     (*I)->dump();
03484     llvm::errs() << "\n";
03485   }
03486 }
03487 
03488 void PathDiagnosticCallPiece::dump() const {
03489   llvm::errs() << "CALL\n--------------\n";
03490 
03491   if (const Stmt *SLoc = getLocStmt(getLocation()))
03492     SLoc->dump();
03493   else if (const NamedDecl *ND = dyn_cast<NamedDecl>(getCallee()))
03494     llvm::errs() << *ND << "\n";
03495   else
03496     getLocation().dump();
03497 }
03498 
03499 void PathDiagnosticEventPiece::dump() const {
03500   llvm::errs() << "EVENT\n--------------\n";
03501   llvm::errs() << getString() << "\n";
03502   llvm::errs() << " ---- at ----\n";
03503   getLocation().dump();
03504 }
03505 
03506 void PathDiagnosticControlFlowPiece::dump() const {
03507   llvm::errs() << "CONTROL\n--------------\n";
03508   getStartLocation().dump();
03509   llvm::errs() << " ---- to ----\n";
03510   getEndLocation().dump();
03511 }
03512 
03513 void PathDiagnosticMacroPiece::dump() const {
03514   llvm::errs() << "MACRO\n--------------\n";
03515   // FIXME: Print which macro is being invoked.
03516 }
03517 
03518 void PathDiagnosticLocation::dump() const {
03519   if (!isValid()) {
03520     llvm::errs() << "<INVALID>\n";
03521     return;
03522   }
03523 
03524   switch (K) {
03525   case RangeK:
03526     // FIXME: actually print the range.
03527     llvm::errs() << "<range>\n";
03528     break;
03529   case SingleLocK:
03530     asLocation().dump();
03531     llvm::errs() << "\n";
03532     break;
03533   case StmtK:
03534     if (S)
03535       S->dump();
03536     else
03537       llvm::errs() << "<NULL STMT>\n";
03538     break;
03539   case DeclK:
03540     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
03541       llvm::errs() << *ND << "\n";
03542     else if (isa<BlockDecl>(D))
03543       // FIXME: Make this nicer.
03544       llvm::errs() << "<block>\n";
03545     else if (D)
03546       llvm::errs() << "<unknown decl>\n";
03547     else
03548       llvm::errs() << "<NULL DECL>\n";
03549     break;
03550   }
03551 }