1 //===- BugReporter.cpp - Generate PathDiagnostics for bugs ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines BugReporter, a utility class for generating
10 //  PathDiagnostics.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclBase.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ParentMap.h"
21 #include "clang/AST/Stmt.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtObjC.h"
24 #include "clang/Analysis/AnalysisDeclContext.h"
25 #include "clang/Analysis/CFG.h"
26 #include "clang/Analysis/CFGStmtMap.h"
27 #include "clang/Analysis/ProgramPoint.h"
28 #include "clang/Basic/LLVM.h"
29 #include "clang/Basic/SourceLocation.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
32 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
33 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
34 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
35 #include "clang/StaticAnalyzer/Core/Checker.h"
36 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
37 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
38 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
39 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
40 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
41 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
42 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
43 #include "llvm/ADT/ArrayRef.h"
44 #include "llvm/ADT/DenseMap.h"
45 #include "llvm/ADT/DenseSet.h"
46 #include "llvm/ADT/FoldingSet.h"
47 #include "llvm/ADT/None.h"
48 #include "llvm/ADT/Optional.h"
49 #include "llvm/ADT/STLExtras.h"
50 #include "llvm/ADT/SmallPtrSet.h"
51 #include "llvm/ADT/SmallString.h"
52 #include "llvm/ADT/SmallVector.h"
53 #include "llvm/ADT/Statistic.h"
54 #include "llvm/ADT/StringRef.h"
55 #include "llvm/ADT/iterator_range.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/ErrorHandling.h"
59 #include "llvm/Support/MemoryBuffer.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include <algorithm>
62 #include <cassert>
63 #include <cstddef>
64 #include <iterator>
65 #include <memory>
66 #include <queue>
67 #include <string>
68 #include <tuple>
69 #include <utility>
70 #include <vector>
71 
72 using namespace clang;
73 using namespace ento;
74 
75 #define DEBUG_TYPE "BugReporter"
76 
77 STATISTIC(MaxBugClassSize,
78           "The maximum number of bug reports in the same equivalence class");
79 STATISTIC(MaxValidBugClassSize,
80           "The maximum number of bug reports in the same equivalence class "
81           "where at least one report is valid (not suppressed)");
82 
83 BugReporterVisitor::~BugReporterVisitor() = default;
84 
85 void BugReporterContext::anchor() {}
86 
87 //===----------------------------------------------------------------------===//
88 // PathDiagnosticBuilder and its associated routines and helper objects.
89 //===----------------------------------------------------------------------===//
90 
91 namespace {
92 
93 /// A (CallPiece, node assiciated with its CallEnter) pair.
94 using CallWithEntry =
95     std::pair<PathDiagnosticCallPiece *, const ExplodedNode *>;
96 using CallWithEntryStack = SmallVector<CallWithEntry, 6>;
97 
98 /// Map from each node to the diagnostic pieces visitors emit for them.
99 using VisitorsDiagnosticsTy =
100     llvm::DenseMap<const ExplodedNode *, std::vector<PathDiagnosticPieceRef>>;
101 
102 /// A map from PathDiagnosticPiece to the LocationContext of the inlined
103 /// function call it represents.
104 using LocationContextMap =
105     llvm::DenseMap<const PathPieces *, const LocationContext *>;
106 
107 /// A helper class that contains everything needed to construct a
108 /// PathDiagnostic object. It does no much more then providing convenient
109 /// getters and some well placed asserts for extra security.
110 class PathDiagnosticConstruct {
111   /// The consumer we're constructing the bug report for.
112   const PathDiagnosticConsumer *Consumer;
113   /// Our current position in the bug path, which is owned by
114   /// PathDiagnosticBuilder.
115   const ExplodedNode *CurrentNode;
116   /// A mapping from parts of the bug path (for example, a function call, which
117   /// would span backwards from a CallExit to a CallEnter with the nodes in
118   /// between them) with the location contexts it is associated with.
119   LocationContextMap LCM;
120   const SourceManager &SM;
121 
122 public:
123   /// We keep stack of calls to functions as we're ascending the bug path.
124   /// TODO: PathDiagnostic has a stack doing the same thing, shouldn't we use
125   /// that instead?
126   CallWithEntryStack CallStack;
127   /// The bug report we're constructing. For ease of use, this field is kept
128   /// public, though some "shortcut" getters are provided for commonly used
129   /// methods of PathDiagnostic.
130   std::unique_ptr<PathDiagnostic> PD;
131 
132 public:
133   PathDiagnosticConstruct(const PathDiagnosticConsumer *PDC,
134                           const ExplodedNode *ErrorNode, const BugReport *R);
135 
136   /// \returns the location context associated with the current position in the
137   /// bug path.
138   const LocationContext *getCurrLocationContext() const {
139     assert(CurrentNode && "Already reached the root!");
140     return CurrentNode->getLocationContext();
141   }
142 
143   /// Same as getCurrLocationContext (they should always return the same
144   /// location context), but works after reaching the root of the bug path as
145   /// well.
146   const LocationContext *getLocationContextForActivePath() const {
147     return LCM.find(&PD->getActivePath())->getSecond();
148   }
149 
150   const ExplodedNode *getCurrentNode() const { return CurrentNode; }
151 
152   /// Steps the current node to its predecessor.
153   /// \returns whether we reached the root of the bug path.
154   bool ascendToPrevNode() {
155     CurrentNode = CurrentNode->getFirstPred();
156     return static_cast<bool>(CurrentNode);
157   }
158 
159   const ParentMap &getParentMap() const {
160     return getCurrLocationContext()->getParentMap();
161   }
162 
163   const SourceManager &getSourceManager() const { return SM; }
164 
165   const Stmt *getParent(const Stmt *S) const {
166     return getParentMap().getParent(S);
167   }
168 
169   void updateLocCtxMap(const PathPieces *Path, const LocationContext *LC) {
170     assert(Path && LC);
171     LCM[Path] = LC;
172   }
173 
174   const LocationContext *getLocationContextFor(const PathPieces *Path) const {
175     assert(LCM.count(Path) &&
176            "Failed to find the context associated with these pieces!");
177     return LCM.find(Path)->getSecond();
178   }
179 
180   bool isInLocCtxMap(const PathPieces *Path) const { return LCM.count(Path); }
181 
182   PathPieces &getActivePath() { return PD->getActivePath(); }
183   PathPieces &getMutablePieces() { return PD->getMutablePieces(); }
184 
185   bool shouldAddPathEdges() const { return Consumer->shouldAddPathEdges(); }
186   bool shouldGenerateDiagnostics() const {
187     return Consumer->shouldGenerateDiagnostics();
188   }
189   bool supportsLogicalOpControlFlow() const {
190     return Consumer->supportsLogicalOpControlFlow();
191   }
192 };
193 
194 /// Contains every contextual information needed for constructing a
195 /// PathDiagnostic object for a given bug report. This class and its fields are
196 /// immutable, and passes a BugReportConstruct object around during the
197 /// construction.
198 class PathDiagnosticBuilder : public BugReporterContext {
199   /// A linear path from the error node to the root.
200   std::unique_ptr<const ExplodedGraph> BugPath;
201   /// The bug report we're describing. Visitors create their diagnostics with
202   /// them being the last entities being able to modify it (for example,
203   /// changing interestingness here would cause inconsistencies as to how this
204   /// file and visitors construct diagnostics), hence its const.
205   const BugReport *R;
206   /// The leaf of the bug path. This isn't the same as the bug reports error
207   /// node, which refers to the *original* graph, not the bug path.
208   const ExplodedNode *const ErrorNode;
209   /// The diagnostic pieces visitors emitted, which is expected to be collected
210   /// by the time this builder is constructed.
211   std::unique_ptr<const VisitorsDiagnosticsTy> VisitorsDiagnostics;
212 
213 public:
214   /// Find a non-invalidated report for a given equivalence class,  and returns
215   /// a PathDiagnosticBuilder able to construct bug reports for different
216   /// consumers. Returns None if no valid report is found.
217   static Optional<PathDiagnosticBuilder>
218   findValidReport(ArrayRef<BugReport *> &bugReports,
219                   PathSensitiveBugReporter &Reporter);
220 
221   PathDiagnosticBuilder(
222       BugReporterContext BRC, std::unique_ptr<ExplodedGraph> BugPath,
223       BugReport *r, const ExplodedNode *ErrorNode,
224       std::unique_ptr<VisitorsDiagnosticsTy> VisitorsDiagnostics);
225 
226   /// This function is responsible for generating diagnostic pieces that are
227   /// *not* provided by bug report visitors.
228   /// These diagnostics may differ depending on the consumer's settings,
229   /// and are therefore constructed separately for each consumer.
230   ///
231   /// There are two path diagnostics generation modes: with adding edges (used
232   /// for plists) and without  (used for HTML and text). When edges are added,
233   /// the path is modified to insert artificially generated edges.
234   /// Otherwise, more detailed diagnostics is emitted for block edges,
235   /// explaining the transitions in words.
236   std::unique_ptr<PathDiagnostic>
237   generate(const PathDiagnosticConsumer *PDC) const;
238 
239 private:
240   void generatePathDiagnosticsForNode(PathDiagnosticConstruct &C,
241                                       PathDiagnosticLocation &PrevLoc) const;
242 
243   void generateMinimalDiagForBlockEdge(PathDiagnosticConstruct &C,
244                                        BlockEdge BE) const;
245 
246   PathDiagnosticPieceRef
247   generateDiagForGotoOP(const PathDiagnosticConstruct &C, const Stmt *S,
248                         PathDiagnosticLocation &Start) const;
249 
250   PathDiagnosticPieceRef
251   generateDiagForSwitchOP(const PathDiagnosticConstruct &C, const CFGBlock *Dst,
252                           PathDiagnosticLocation &Start) const;
253 
254   PathDiagnosticPieceRef
255   generateDiagForBinaryOP(const PathDiagnosticConstruct &C, const Stmt *T,
256                           const CFGBlock *Src, const CFGBlock *DstC) const;
257 
258   PathDiagnosticLocation
259   ExecutionContinues(const PathDiagnosticConstruct &C) const;
260 
261   PathDiagnosticLocation
262   ExecutionContinues(llvm::raw_string_ostream &os,
263                      const PathDiagnosticConstruct &C) const;
264 
265   const BugReport *getBugReport() const { return R; }
266 };
267 
268 } // namespace
269 
270 //===----------------------------------------------------------------------===//
271 // Helper routines for walking the ExplodedGraph and fetching statements.
272 //===----------------------------------------------------------------------===//
273 
274 static const Stmt *GetPreviousStmt(const ExplodedNode *N) {
275   for (N = N->getFirstPred(); N; N = N->getFirstPred())
276     if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
277       return S;
278 
279   return nullptr;
280 }
281 
282 static inline const Stmt*
283 GetCurrentOrPreviousStmt(const ExplodedNode *N) {
284   if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
285     return S;
286 
287   return GetPreviousStmt(N);
288 }
289 
290 //===----------------------------------------------------------------------===//
291 // Diagnostic cleanup.
292 //===----------------------------------------------------------------------===//
293 
294 static PathDiagnosticEventPiece *
295 eventsDescribeSameCondition(PathDiagnosticEventPiece *X,
296                             PathDiagnosticEventPiece *Y) {
297   // Prefer diagnostics that come from ConditionBRVisitor over
298   // those that came from TrackConstraintBRVisitor,
299   // unless the one from ConditionBRVisitor is
300   // its generic fallback diagnostic.
301   const void *tagPreferred = ConditionBRVisitor::getTag();
302   const void *tagLesser = TrackConstraintBRVisitor::getTag();
303 
304   if (X->getLocation() != Y->getLocation())
305     return nullptr;
306 
307   if (X->getTag() == tagPreferred && Y->getTag() == tagLesser)
308     return ConditionBRVisitor::isPieceMessageGeneric(X) ? Y : X;
309 
310   if (Y->getTag() == tagPreferred && X->getTag() == tagLesser)
311     return ConditionBRVisitor::isPieceMessageGeneric(Y) ? X : Y;
312 
313   return nullptr;
314 }
315 
316 /// An optimization pass over PathPieces that removes redundant diagnostics
317 /// generated by both ConditionBRVisitor and TrackConstraintBRVisitor.  Both
318 /// BugReporterVisitors use different methods to generate diagnostics, with
319 /// one capable of emitting diagnostics in some cases but not in others.  This
320 /// can lead to redundant diagnostic pieces at the same point in a path.
321 static void removeRedundantMsgs(PathPieces &path) {
322   unsigned N = path.size();
323   if (N < 2)
324     return;
325   // NOTE: this loop intentionally is not using an iterator.  Instead, we
326   // are streaming the path and modifying it in place.  This is done by
327   // grabbing the front, processing it, and if we decide to keep it append
328   // it to the end of the path.  The entire path is processed in this way.
329   for (unsigned i = 0; i < N; ++i) {
330     auto piece = std::move(path.front());
331     path.pop_front();
332 
333     switch (piece->getKind()) {
334       case PathDiagnosticPiece::Call:
335         removeRedundantMsgs(cast<PathDiagnosticCallPiece>(*piece).path);
336         break;
337       case PathDiagnosticPiece::Macro:
338         removeRedundantMsgs(cast<PathDiagnosticMacroPiece>(*piece).subPieces);
339         break;
340       case PathDiagnosticPiece::Event: {
341         if (i == N-1)
342           break;
343 
344         if (auto *nextEvent =
345             dyn_cast<PathDiagnosticEventPiece>(path.front().get())) {
346           auto *event = cast<PathDiagnosticEventPiece>(piece.get());
347           // Check to see if we should keep one of the two pieces.  If we
348           // come up with a preference, record which piece to keep, and consume
349           // another piece from the path.
350           if (auto *pieceToKeep =
351                   eventsDescribeSameCondition(event, nextEvent)) {
352             piece = std::move(pieceToKeep == event ? piece : path.front());
353             path.pop_front();
354             ++i;
355           }
356         }
357         break;
358       }
359       case PathDiagnosticPiece::ControlFlow:
360       case PathDiagnosticPiece::Note:
361       case PathDiagnosticPiece::PopUp:
362         break;
363     }
364     path.push_back(std::move(piece));
365   }
366 }
367 
368 /// Recursively scan through a path and prune out calls and macros pieces
369 /// that aren't needed.  Return true if afterwards the path contains
370 /// "interesting stuff" which means it shouldn't be pruned from the parent path.
371 static bool removeUnneededCalls(const PathDiagnosticConstruct &C,
372                                 PathPieces &pieces, const BugReport *R,
373                                 bool IsInteresting = false) {
374   bool containsSomethingInteresting = IsInteresting;
375   const unsigned N = pieces.size();
376 
377   for (unsigned i = 0 ; i < N ; ++i) {
378     // Remove the front piece from the path.  If it is still something we
379     // want to keep once we are done, we will push it back on the end.
380     auto piece = std::move(pieces.front());
381     pieces.pop_front();
382 
383     switch (piece->getKind()) {
384       case PathDiagnosticPiece::Call: {
385         auto &call = cast<PathDiagnosticCallPiece>(*piece);
386         // Check if the location context is interesting.
387         if (!removeUnneededCalls(
388                 C, call.path, R,
389                 R->isInteresting(C.getLocationContextFor(&call.path))))
390           continue;
391 
392         containsSomethingInteresting = true;
393         break;
394       }
395       case PathDiagnosticPiece::Macro: {
396         auto &macro = cast<PathDiagnosticMacroPiece>(*piece);
397         if (!removeUnneededCalls(C, macro.subPieces, R, IsInteresting))
398           continue;
399         containsSomethingInteresting = true;
400         break;
401       }
402       case PathDiagnosticPiece::Event: {
403         auto &event = cast<PathDiagnosticEventPiece>(*piece);
404 
405         // We never throw away an event, but we do throw it away wholesale
406         // as part of a path if we throw the entire path away.
407         containsSomethingInteresting |= !event.isPrunable();
408         break;
409       }
410       case PathDiagnosticPiece::ControlFlow:
411       case PathDiagnosticPiece::Note:
412       case PathDiagnosticPiece::PopUp:
413         break;
414     }
415 
416     pieces.push_back(std::move(piece));
417   }
418 
419   return containsSomethingInteresting;
420 }
421 
422 /// Same logic as above to remove extra pieces.
423 static void removePopUpNotes(PathPieces &Path) {
424   for (unsigned int i = 0; i < Path.size(); ++i) {
425     auto Piece = std::move(Path.front());
426     Path.pop_front();
427     if (!isa<PathDiagnosticPopUpPiece>(*Piece))
428       Path.push_back(std::move(Piece));
429   }
430 }
431 
432 /// Returns true if the given decl has been implicitly given a body, either by
433 /// the analyzer or by the compiler proper.
434 static bool hasImplicitBody(const Decl *D) {
435   assert(D);
436   return D->isImplicit() || !D->hasBody();
437 }
438 
439 /// Recursively scan through a path and make sure that all call pieces have
440 /// valid locations.
441 static void
442 adjustCallLocations(PathPieces &Pieces,
443                     PathDiagnosticLocation *LastCallLocation = nullptr) {
444   for (const auto &I : Pieces) {
445     auto *Call = dyn_cast<PathDiagnosticCallPiece>(I.get());
446 
447     if (!Call)
448       continue;
449 
450     if (LastCallLocation) {
451       bool CallerIsImplicit = hasImplicitBody(Call->getCaller());
452       if (CallerIsImplicit || !Call->callEnter.asLocation().isValid())
453         Call->callEnter = *LastCallLocation;
454       if (CallerIsImplicit || !Call->callReturn.asLocation().isValid())
455         Call->callReturn = *LastCallLocation;
456     }
457 
458     // Recursively clean out the subclass.  Keep this call around if
459     // it contains any informative diagnostics.
460     PathDiagnosticLocation *ThisCallLocation;
461     if (Call->callEnterWithin.asLocation().isValid() &&
462         !hasImplicitBody(Call->getCallee()))
463       ThisCallLocation = &Call->callEnterWithin;
464     else
465       ThisCallLocation = &Call->callEnter;
466 
467     assert(ThisCallLocation && "Outermost call has an invalid location");
468     adjustCallLocations(Call->path, ThisCallLocation);
469   }
470 }
471 
472 /// Remove edges in and out of C++ default initializer expressions. These are
473 /// for fields that have in-class initializers, as opposed to being initialized
474 /// explicitly in a constructor or braced list.
475 static void removeEdgesToDefaultInitializers(PathPieces &Pieces) {
476   for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
477     if (auto *C = dyn_cast<PathDiagnosticCallPiece>(I->get()))
478       removeEdgesToDefaultInitializers(C->path);
479 
480     if (auto *M = dyn_cast<PathDiagnosticMacroPiece>(I->get()))
481       removeEdgesToDefaultInitializers(M->subPieces);
482 
483     if (auto *CF = dyn_cast<PathDiagnosticControlFlowPiece>(I->get())) {
484       const Stmt *Start = CF->getStartLocation().asStmt();
485       const Stmt *End = CF->getEndLocation().asStmt();
486       if (Start && isa<CXXDefaultInitExpr>(Start)) {
487         I = Pieces.erase(I);
488         continue;
489       } else if (End && isa<CXXDefaultInitExpr>(End)) {
490         PathPieces::iterator Next = std::next(I);
491         if (Next != E) {
492           if (auto *NextCF =
493                   dyn_cast<PathDiagnosticControlFlowPiece>(Next->get())) {
494             NextCF->setStartLocation(CF->getStartLocation());
495           }
496         }
497         I = Pieces.erase(I);
498         continue;
499       }
500     }
501 
502     I++;
503   }
504 }
505 
506 /// Remove all pieces with invalid locations as these cannot be serialized.
507 /// We might have pieces with invalid locations as a result of inlining Body
508 /// Farm generated functions.
509 static void removePiecesWithInvalidLocations(PathPieces &Pieces) {
510   for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
511     if (auto *C = dyn_cast<PathDiagnosticCallPiece>(I->get()))
512       removePiecesWithInvalidLocations(C->path);
513 
514     if (auto *M = dyn_cast<PathDiagnosticMacroPiece>(I->get()))
515       removePiecesWithInvalidLocations(M->subPieces);
516 
517     if (!(*I)->getLocation().isValid() ||
518         !(*I)->getLocation().asLocation().isValid()) {
519       I = Pieces.erase(I);
520       continue;
521     }
522     I++;
523   }
524 }
525 
526 PathDiagnosticLocation PathDiagnosticBuilder::ExecutionContinues(
527     const PathDiagnosticConstruct &C) const {
528   if (const Stmt *S = PathDiagnosticLocation::getNextStmt(C.getCurrentNode()))
529     return PathDiagnosticLocation(S, getSourceManager(),
530                                   C.getCurrLocationContext());
531 
532   return PathDiagnosticLocation::createDeclEnd(C.getCurrLocationContext(),
533                                                getSourceManager());
534 }
535 
536 PathDiagnosticLocation PathDiagnosticBuilder::ExecutionContinues(
537     llvm::raw_string_ostream &os, const PathDiagnosticConstruct &C) const {
538   // Slow, but probably doesn't matter.
539   if (os.str().empty())
540     os << ' ';
541 
542   const PathDiagnosticLocation &Loc = ExecutionContinues(C);
543 
544   if (Loc.asStmt())
545     os << "Execution continues on line "
546        << getSourceManager().getExpansionLineNumber(Loc.asLocation())
547        << '.';
548   else {
549     os << "Execution jumps to the end of the ";
550     const Decl *D = C.getCurrLocationContext()->getDecl();
551     if (isa<ObjCMethodDecl>(D))
552       os << "method";
553     else if (isa<FunctionDecl>(D))
554       os << "function";
555     else {
556       assert(isa<BlockDecl>(D));
557       os << "anonymous block";
558     }
559     os << '.';
560   }
561 
562   return Loc;
563 }
564 
565 static const Stmt *getEnclosingParent(const Stmt *S, const ParentMap &PM) {
566   if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
567     return PM.getParentIgnoreParens(S);
568 
569   const Stmt *Parent = PM.getParentIgnoreParens(S);
570   if (!Parent)
571     return nullptr;
572 
573   switch (Parent->getStmtClass()) {
574   case Stmt::ForStmtClass:
575   case Stmt::DoStmtClass:
576   case Stmt::WhileStmtClass:
577   case Stmt::ObjCForCollectionStmtClass:
578   case Stmt::CXXForRangeStmtClass:
579     return Parent;
580   default:
581     break;
582   }
583 
584   return nullptr;
585 }
586 
587 static PathDiagnosticLocation
588 getEnclosingStmtLocation(const Stmt *S, const LocationContext *LC,
589                          bool allowNestedContexts = false) {
590   if (!S)
591     return {};
592 
593   const SourceManager &SMgr = LC->getDecl()->getASTContext().getSourceManager();
594 
595   while (const Stmt *Parent = getEnclosingParent(S, LC->getParentMap())) {
596     switch (Parent->getStmtClass()) {
597       case Stmt::BinaryOperatorClass: {
598         const auto *B = cast<BinaryOperator>(Parent);
599         if (B->isLogicalOp())
600           return PathDiagnosticLocation(allowNestedContexts ? B : S, SMgr, LC);
601         break;
602       }
603       case Stmt::CompoundStmtClass:
604       case Stmt::StmtExprClass:
605         return PathDiagnosticLocation(S, SMgr, LC);
606       case Stmt::ChooseExprClass:
607         // Similar to '?' if we are referring to condition, just have the edge
608         // point to the entire choose expression.
609         if (allowNestedContexts || cast<ChooseExpr>(Parent)->getCond() == S)
610           return PathDiagnosticLocation(Parent, SMgr, LC);
611         else
612           return PathDiagnosticLocation(S, SMgr, LC);
613       case Stmt::BinaryConditionalOperatorClass:
614       case Stmt::ConditionalOperatorClass:
615         // For '?', if we are referring to condition, just have the edge point
616         // to the entire '?' expression.
617         if (allowNestedContexts ||
618             cast<AbstractConditionalOperator>(Parent)->getCond() == S)
619           return PathDiagnosticLocation(Parent, SMgr, LC);
620         else
621           return PathDiagnosticLocation(S, SMgr, LC);
622       case Stmt::CXXForRangeStmtClass:
623         if (cast<CXXForRangeStmt>(Parent)->getBody() == S)
624           return PathDiagnosticLocation(S, SMgr, LC);
625         break;
626       case Stmt::DoStmtClass:
627           return PathDiagnosticLocation(S, SMgr, LC);
628       case Stmt::ForStmtClass:
629         if (cast<ForStmt>(Parent)->getBody() == S)
630           return PathDiagnosticLocation(S, SMgr, LC);
631         break;
632       case Stmt::IfStmtClass:
633         if (cast<IfStmt>(Parent)->getCond() != S)
634           return PathDiagnosticLocation(S, SMgr, LC);
635         break;
636       case Stmt::ObjCForCollectionStmtClass:
637         if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
638           return PathDiagnosticLocation(S, SMgr, LC);
639         break;
640       case Stmt::WhileStmtClass:
641         if (cast<WhileStmt>(Parent)->getCond() != S)
642           return PathDiagnosticLocation(S, SMgr, LC);
643         break;
644       default:
645         break;
646     }
647 
648     S = Parent;
649   }
650 
651   assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
652 
653   return PathDiagnosticLocation(S, SMgr, LC);
654 }
655 
656 //===----------------------------------------------------------------------===//
657 // "Minimal" path diagnostic generation algorithm.
658 //===----------------------------------------------------------------------===//
659 
660 /// If the piece contains a special message, add it to all the call pieces on
661 /// the active stack. For exampler, my_malloc allocated memory, so MallocChecker
662 /// will construct an event at the call to malloc(), and add a stack hint that
663 /// an allocated memory was returned. We'll use this hint to construct a message
664 /// when returning from the call to my_malloc
665 ///
666 ///   void *my_malloc() { return malloc(sizeof(int)); }
667 ///   void fishy() {
668 ///     void *ptr = my_malloc(); // returned allocated memory
669 ///   } // leak
670 static void updateStackPiecesWithMessage(PathDiagnosticPiece &P,
671                                          const CallWithEntryStack &CallStack) {
672   if (auto *ep = dyn_cast<PathDiagnosticEventPiece>(&P)) {
673     if (ep->hasCallStackHint())
674       for (const auto &I : CallStack) {
675         PathDiagnosticCallPiece *CP = I.first;
676         const ExplodedNode *N = I.second;
677         std::string stackMsg = ep->getCallStackMessage(N);
678 
679         // The last message on the path to final bug is the most important
680         // one. Since we traverse the path backwards, do not add the message
681         // if one has been previously added.
682         if  (!CP->hasCallStackMessage())
683           CP->setCallStackMessage(stackMsg);
684       }
685   }
686 }
687 
688 static void CompactMacroExpandedPieces(PathPieces &path,
689                                        const SourceManager& SM);
690 
691 PathDiagnosticPieceRef PathDiagnosticBuilder::generateDiagForSwitchOP(
692     const PathDiagnosticConstruct &C, const CFGBlock *Dst,
693     PathDiagnosticLocation &Start) const {
694 
695   const SourceManager &SM = getSourceManager();
696   // Figure out what case arm we took.
697   std::string sbuf;
698   llvm::raw_string_ostream os(sbuf);
699   PathDiagnosticLocation End;
700 
701   if (const Stmt *S = Dst->getLabel()) {
702     End = PathDiagnosticLocation(S, SM, C.getCurrLocationContext());
703 
704     switch (S->getStmtClass()) {
705     default:
706       os << "No cases match in the switch statement. "
707         "Control jumps to line "
708         << End.asLocation().getExpansionLineNumber();
709       break;
710     case Stmt::DefaultStmtClass:
711       os << "Control jumps to the 'default' case at line "
712         << End.asLocation().getExpansionLineNumber();
713       break;
714 
715     case Stmt::CaseStmtClass: {
716       os << "Control jumps to 'case ";
717       const auto *Case = cast<CaseStmt>(S);
718       const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
719 
720       // Determine if it is an enum.
721       bool GetRawInt = true;
722 
723       if (const auto *DR = dyn_cast<DeclRefExpr>(LHS)) {
724         // FIXME: Maybe this should be an assertion.  Are there cases
725         // were it is not an EnumConstantDecl?
726         const auto *D = dyn_cast<EnumConstantDecl>(DR->getDecl());
727 
728         if (D) {
729           GetRawInt = false;
730           os << *D;
731         }
732       }
733 
734       if (GetRawInt)
735         os << LHS->EvaluateKnownConstInt(getASTContext());
736 
737       os << ":'  at line " << End.asLocation().getExpansionLineNumber();
738       break;
739     }
740     }
741   } else {
742     os << "'Default' branch taken. ";
743     End = ExecutionContinues(os, C);
744   }
745   return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
746                                                        os.str());
747 }
748 
749 PathDiagnosticPieceRef PathDiagnosticBuilder::generateDiagForGotoOP(
750     const PathDiagnosticConstruct &C, const Stmt *S,
751     PathDiagnosticLocation &Start) const {
752   std::string sbuf;
753   llvm::raw_string_ostream os(sbuf);
754   const PathDiagnosticLocation &End =
755       getEnclosingStmtLocation(S, C.getCurrLocationContext());
756   os << "Control jumps to line " << End.asLocation().getExpansionLineNumber();
757   return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str());
758 }
759 
760 PathDiagnosticPieceRef PathDiagnosticBuilder::generateDiagForBinaryOP(
761     const PathDiagnosticConstruct &C, const Stmt *T, const CFGBlock *Src,
762     const CFGBlock *Dst) const {
763 
764   const SourceManager &SM = getSourceManager();
765 
766   const auto *B = cast<BinaryOperator>(T);
767   std::string sbuf;
768   llvm::raw_string_ostream os(sbuf);
769   os << "Left side of '";
770   PathDiagnosticLocation Start, End;
771 
772   if (B->getOpcode() == BO_LAnd) {
773     os << "&&"
774       << "' is ";
775 
776     if (*(Src->succ_begin() + 1) == Dst) {
777       os << "false";
778       End = PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
779       Start =
780         PathDiagnosticLocation::createOperatorLoc(B, SM);
781     } else {
782       os << "true";
783       Start =
784           PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
785       End = ExecutionContinues(C);
786     }
787   } else {
788     assert(B->getOpcode() == BO_LOr);
789     os << "||"
790       << "' is ";
791 
792     if (*(Src->succ_begin() + 1) == Dst) {
793       os << "false";
794       Start =
795           PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
796       End = ExecutionContinues(C);
797     } else {
798       os << "true";
799       End = PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
800       Start =
801         PathDiagnosticLocation::createOperatorLoc(B, SM);
802     }
803   }
804   return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
805                                                          os.str());
806 }
807 
808 void PathDiagnosticBuilder::generateMinimalDiagForBlockEdge(
809     PathDiagnosticConstruct &C, BlockEdge BE) const {
810   const SourceManager &SM = getSourceManager();
811   const LocationContext *LC = C.getCurrLocationContext();
812   const CFGBlock *Src = BE.getSrc();
813   const CFGBlock *Dst = BE.getDst();
814   const Stmt *T = Src->getTerminatorStmt();
815   if (!T)
816     return;
817 
818   auto Start = PathDiagnosticLocation::createBegin(T, SM, LC);
819   switch (T->getStmtClass()) {
820   default:
821     break;
822 
823   case Stmt::GotoStmtClass:
824   case Stmt::IndirectGotoStmtClass: {
825     if (const Stmt *S = PathDiagnosticLocation::getNextStmt(C.getCurrentNode()))
826       C.getActivePath().push_front(generateDiagForGotoOP(C, S, Start));
827     break;
828   }
829 
830   case Stmt::SwitchStmtClass: {
831     C.getActivePath().push_front(generateDiagForSwitchOP(C, Dst, Start));
832     break;
833   }
834 
835   case Stmt::BreakStmtClass:
836   case Stmt::ContinueStmtClass: {
837     std::string sbuf;
838     llvm::raw_string_ostream os(sbuf);
839     PathDiagnosticLocation End = ExecutionContinues(os, C);
840     C.getActivePath().push_front(
841         std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str()));
842     break;
843   }
844 
845   // Determine control-flow for ternary '?'.
846   case Stmt::BinaryConditionalOperatorClass:
847   case Stmt::ConditionalOperatorClass: {
848     std::string sbuf;
849     llvm::raw_string_ostream os(sbuf);
850     os << "'?' condition is ";
851 
852     if (*(Src->succ_begin() + 1) == Dst)
853       os << "false";
854     else
855       os << "true";
856 
857     PathDiagnosticLocation End = ExecutionContinues(C);
858 
859     if (const Stmt *S = End.asStmt())
860       End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
861 
862     C.getActivePath().push_front(
863         std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str()));
864     break;
865   }
866 
867   // Determine control-flow for short-circuited '&&' and '||'.
868   case Stmt::BinaryOperatorClass: {
869     if (!C.supportsLogicalOpControlFlow())
870       break;
871 
872     C.getActivePath().push_front(generateDiagForBinaryOP(C, T, Src, Dst));
873     break;
874   }
875 
876   case Stmt::DoStmtClass:
877     if (*(Src->succ_begin()) == Dst) {
878       std::string sbuf;
879       llvm::raw_string_ostream os(sbuf);
880 
881       os << "Loop condition is true. ";
882       PathDiagnosticLocation End = ExecutionContinues(os, C);
883 
884       if (const Stmt *S = End.asStmt())
885         End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
886 
887       C.getActivePath().push_front(
888           std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
889                                                            os.str()));
890     } else {
891       PathDiagnosticLocation End = ExecutionContinues(C);
892 
893       if (const Stmt *S = End.asStmt())
894         End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
895 
896       C.getActivePath().push_front(
897           std::make_shared<PathDiagnosticControlFlowPiece>(
898               Start, End, "Loop condition is false.  Exiting loop"));
899     }
900     break;
901 
902   case Stmt::WhileStmtClass:
903   case Stmt::ForStmtClass:
904     if (*(Src->succ_begin() + 1) == Dst) {
905       std::string sbuf;
906       llvm::raw_string_ostream os(sbuf);
907 
908       os << "Loop condition is false. ";
909       PathDiagnosticLocation End = ExecutionContinues(os, C);
910       if (const Stmt *S = End.asStmt())
911         End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
912 
913       C.getActivePath().push_front(
914           std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
915                                                            os.str()));
916     } else {
917       PathDiagnosticLocation End = ExecutionContinues(C);
918       if (const Stmt *S = End.asStmt())
919         End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
920 
921       C.getActivePath().push_front(
922           std::make_shared<PathDiagnosticControlFlowPiece>(
923               Start, End, "Loop condition is true.  Entering loop body"));
924     }
925 
926     break;
927 
928   case Stmt::IfStmtClass: {
929     PathDiagnosticLocation End = ExecutionContinues(C);
930 
931     if (const Stmt *S = End.asStmt())
932       End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
933 
934     if (*(Src->succ_begin() + 1) == Dst)
935       C.getActivePath().push_front(
936           std::make_shared<PathDiagnosticControlFlowPiece>(
937               Start, End, "Taking false branch"));
938     else
939       C.getActivePath().push_front(
940           std::make_shared<PathDiagnosticControlFlowPiece>(
941               Start, End, "Taking true branch"));
942 
943     break;
944   }
945   }
946 }
947 
948 //===----------------------------------------------------------------------===//
949 // Functions for determining if a loop was executed 0 times.
950 //===----------------------------------------------------------------------===//
951 
952 static bool isLoop(const Stmt *Term) {
953   switch (Term->getStmtClass()) {
954     case Stmt::ForStmtClass:
955     case Stmt::WhileStmtClass:
956     case Stmt::ObjCForCollectionStmtClass:
957     case Stmt::CXXForRangeStmtClass:
958       return true;
959     default:
960       // Note that we intentionally do not include do..while here.
961       return false;
962   }
963 }
964 
965 static bool isJumpToFalseBranch(const BlockEdge *BE) {
966   const CFGBlock *Src = BE->getSrc();
967   assert(Src->succ_size() == 2);
968   return (*(Src->succ_begin()+1) == BE->getDst());
969 }
970 
971 static bool isContainedByStmt(const ParentMap &PM, const Stmt *S,
972                               const Stmt *SubS) {
973   while (SubS) {
974     if (SubS == S)
975       return true;
976     SubS = PM.getParent(SubS);
977   }
978   return false;
979 }
980 
981 static const Stmt *getStmtBeforeCond(const ParentMap &PM, const Stmt *Term,
982                                      const ExplodedNode *N) {
983   while (N) {
984     Optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>();
985     if (SP) {
986       const Stmt *S = SP->getStmt();
987       if (!isContainedByStmt(PM, Term, S))
988         return S;
989     }
990     N = N->getFirstPred();
991   }
992   return nullptr;
993 }
994 
995 static bool isInLoopBody(const ParentMap &PM, const Stmt *S, const Stmt *Term) {
996   const Stmt *LoopBody = nullptr;
997   switch (Term->getStmtClass()) {
998     case Stmt::CXXForRangeStmtClass: {
999       const auto *FR = cast<CXXForRangeStmt>(Term);
1000       if (isContainedByStmt(PM, FR->getInc(), S))
1001         return true;
1002       if (isContainedByStmt(PM, FR->getLoopVarStmt(), S))
1003         return true;
1004       LoopBody = FR->getBody();
1005       break;
1006     }
1007     case Stmt::ForStmtClass: {
1008       const auto *FS = cast<ForStmt>(Term);
1009       if (isContainedByStmt(PM, FS->getInc(), S))
1010         return true;
1011       LoopBody = FS->getBody();
1012       break;
1013     }
1014     case Stmt::ObjCForCollectionStmtClass: {
1015       const auto *FC = cast<ObjCForCollectionStmt>(Term);
1016       LoopBody = FC->getBody();
1017       break;
1018     }
1019     case Stmt::WhileStmtClass:
1020       LoopBody = cast<WhileStmt>(Term)->getBody();
1021       break;
1022     default:
1023       return false;
1024   }
1025   return isContainedByStmt(PM, LoopBody, S);
1026 }
1027 
1028 /// Adds a sanitized control-flow diagnostic edge to a path.
1029 static void addEdgeToPath(PathPieces &path,
1030                           PathDiagnosticLocation &PrevLoc,
1031                           PathDiagnosticLocation NewLoc) {
1032   if (!NewLoc.isValid())
1033     return;
1034 
1035   SourceLocation NewLocL = NewLoc.asLocation();
1036   if (NewLocL.isInvalid())
1037     return;
1038 
1039   if (!PrevLoc.isValid() || !PrevLoc.asLocation().isValid()) {
1040     PrevLoc = NewLoc;
1041     return;
1042   }
1043 
1044   // Ignore self-edges, which occur when there are multiple nodes at the same
1045   // statement.
1046   if (NewLoc.asStmt() && NewLoc.asStmt() == PrevLoc.asStmt())
1047     return;
1048 
1049   path.push_front(
1050       std::make_shared<PathDiagnosticControlFlowPiece>(NewLoc, PrevLoc));
1051   PrevLoc = NewLoc;
1052 }
1053 
1054 /// A customized wrapper for CFGBlock::getTerminatorCondition()
1055 /// which returns the element for ObjCForCollectionStmts.
1056 static const Stmt *getTerminatorCondition(const CFGBlock *B) {
1057   const Stmt *S = B->getTerminatorCondition();
1058   if (const auto *FS = dyn_cast_or_null<ObjCForCollectionStmt>(S))
1059     return FS->getElement();
1060   return S;
1061 }
1062 
1063 constexpr llvm::StringLiteral StrEnteringLoop = "Entering loop body";
1064 constexpr llvm::StringLiteral StrLoopBodyZero = "Loop body executed 0 times";
1065 constexpr llvm::StringLiteral StrLoopRangeEmpty =
1066     "Loop body skipped when range is empty";
1067 constexpr llvm::StringLiteral StrLoopCollectionEmpty =
1068     "Loop body skipped when collection is empty";
1069 
1070 static std::unique_ptr<FilesToLineNumsMap>
1071 findExecutedLines(const SourceManager &SM, const ExplodedNode *N);
1072 
1073 void PathDiagnosticBuilder::generatePathDiagnosticsForNode(
1074     PathDiagnosticConstruct &C, PathDiagnosticLocation &PrevLoc) const {
1075   ProgramPoint P = C.getCurrentNode()->getLocation();
1076   const SourceManager &SM = getSourceManager();
1077 
1078   // Have we encountered an entrance to a call?  It may be
1079   // the case that we have not encountered a matching
1080   // call exit before this point.  This means that the path
1081   // terminated within the call itself.
1082   if (auto CE = P.getAs<CallEnter>()) {
1083 
1084     if (C.shouldAddPathEdges()) {
1085       // Add an edge to the start of the function.
1086       const StackFrameContext *CalleeLC = CE->getCalleeContext();
1087       const Decl *D = CalleeLC->getDecl();
1088       // Add the edge only when the callee has body. We jump to the beginning
1089       // of the *declaration*, however we expect it to be followed by the
1090       // body. This isn't the case for autosynthesized property accessors in
1091       // Objective-C. No need for a similar extra check for CallExit points
1092       // because the exit edge comes from a statement (i.e. return),
1093       // not from declaration.
1094       if (D->hasBody())
1095         addEdgeToPath(C.getActivePath(), PrevLoc,
1096                       PathDiagnosticLocation::createBegin(D, SM));
1097     }
1098 
1099     // Did we visit an entire call?
1100     bool VisitedEntireCall = C.PD->isWithinCall();
1101     C.PD->popActivePath();
1102 
1103     PathDiagnosticCallPiece *Call;
1104     if (VisitedEntireCall) {
1105       Call = cast<PathDiagnosticCallPiece>(C.getActivePath().front().get());
1106     } else {
1107       // The path terminated within a nested location context, create a new
1108       // call piece to encapsulate the rest of the path pieces.
1109       const Decl *Caller = CE->getLocationContext()->getDecl();
1110       Call = PathDiagnosticCallPiece::construct(C.getActivePath(), Caller);
1111       assert(C.getActivePath().size() == 1 &&
1112              C.getActivePath().front().get() == Call);
1113 
1114       // Since we just transferred the path over to the call piece, reset the
1115       // mapping of the active path to the current location context.
1116       assert(C.isInLocCtxMap(&C.getActivePath()) &&
1117              "When we ascend to a previously unvisited call, the active path's "
1118              "address shouldn't change, but rather should be compacted into "
1119              "a single CallEvent!");
1120       C.updateLocCtxMap(&C.getActivePath(), C.getCurrLocationContext());
1121 
1122       // Record the location context mapping for the path within the call.
1123       assert(!C.isInLocCtxMap(&Call->path) &&
1124              "When we ascend to a previously unvisited call, this must be the "
1125              "first time we encounter the caller context!");
1126       C.updateLocCtxMap(&Call->path, CE->getCalleeContext());
1127     }
1128     Call->setCallee(*CE, SM);
1129 
1130     // Update the previous location in the active path.
1131     PrevLoc = Call->getLocation();
1132 
1133     if (!C.CallStack.empty()) {
1134       assert(C.CallStack.back().first == Call);
1135       C.CallStack.pop_back();
1136     }
1137     return;
1138   }
1139 
1140   assert(C.getCurrLocationContext() == C.getLocationContextForActivePath() &&
1141          "The current position in the bug path is out of sync with the "
1142          "location context associated with the active path!");
1143 
1144   // Have we encountered an exit from a function call?
1145   if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
1146 
1147     // We are descending into a call (backwards).  Construct
1148     // a new call piece to contain the path pieces for that call.
1149     auto Call = PathDiagnosticCallPiece::construct(*CE, SM);
1150     // Record the mapping from call piece to LocationContext.
1151     assert(!C.isInLocCtxMap(&Call->path) &&
1152            "We just entered a call, this must've been the first time we "
1153            "encounter its context!");
1154     C.updateLocCtxMap(&Call->path, CE->getCalleeContext());
1155 
1156     if (C.shouldAddPathEdges()) {
1157       // Add the edge to the return site.
1158       addEdgeToPath(C.getActivePath(), PrevLoc, Call->callReturn);
1159       PrevLoc.invalidate();
1160     }
1161 
1162     auto *P = Call.get();
1163     C.getActivePath().push_front(std::move(Call));
1164 
1165     // Make the contents of the call the active path for now.
1166     C.PD->pushActivePath(&P->path);
1167     C.CallStack.push_back(CallWithEntry(P, C.getCurrentNode()));
1168     return;
1169   }
1170 
1171   if (auto PS = P.getAs<PostStmt>()) {
1172     if (!C.shouldAddPathEdges())
1173       return;
1174 
1175     // Add an edge.  If this is an ObjCForCollectionStmt do
1176     // not add an edge here as it appears in the CFG both
1177     // as a terminator and as a terminator condition.
1178     if (!isa<ObjCForCollectionStmt>(PS->getStmt())) {
1179       PathDiagnosticLocation L =
1180           PathDiagnosticLocation(PS->getStmt(), SM, C.getCurrLocationContext());
1181       addEdgeToPath(C.getActivePath(), PrevLoc, L);
1182     }
1183 
1184   } else if (auto BE = P.getAs<BlockEdge>()) {
1185 
1186     if (!C.shouldAddPathEdges()) {
1187       generateMinimalDiagForBlockEdge(C, *BE);
1188       return;
1189     }
1190 
1191     // Are we jumping to the head of a loop?  Add a special diagnostic.
1192     if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
1193       PathDiagnosticLocation L(Loop, SM, C.getCurrLocationContext());
1194       const Stmt *Body = nullptr;
1195 
1196       if (const auto *FS = dyn_cast<ForStmt>(Loop))
1197         Body = FS->getBody();
1198       else if (const auto *WS = dyn_cast<WhileStmt>(Loop))
1199         Body = WS->getBody();
1200       else if (const auto *OFS = dyn_cast<ObjCForCollectionStmt>(Loop)) {
1201         Body = OFS->getBody();
1202       } else if (const auto *FRS = dyn_cast<CXXForRangeStmt>(Loop)) {
1203         Body = FRS->getBody();
1204       }
1205       // do-while statements are explicitly excluded here
1206 
1207       auto p = std::make_shared<PathDiagnosticEventPiece>(
1208           L, "Looping back to the head "
1209           "of the loop");
1210       p->setPrunable(true);
1211 
1212       addEdgeToPath(C.getActivePath(), PrevLoc, p->getLocation());
1213       C.getActivePath().push_front(std::move(p));
1214 
1215       if (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
1216         addEdgeToPath(C.getActivePath(), PrevLoc,
1217                       PathDiagnosticLocation::createEndBrace(CS, SM));
1218       }
1219     }
1220 
1221     const CFGBlock *BSrc = BE->getSrc();
1222     const ParentMap &PM = C.getParentMap();
1223 
1224     if (const Stmt *Term = BSrc->getTerminatorStmt()) {
1225       // Are we jumping past the loop body without ever executing the
1226       // loop (because the condition was false)?
1227       if (isLoop(Term)) {
1228         const Stmt *TermCond = getTerminatorCondition(BSrc);
1229         bool IsInLoopBody = isInLoopBody(
1230             PM, getStmtBeforeCond(PM, TermCond, C.getCurrentNode()), Term);
1231 
1232         StringRef str;
1233 
1234         if (isJumpToFalseBranch(&*BE)) {
1235           if (!IsInLoopBody) {
1236             if (isa<ObjCForCollectionStmt>(Term)) {
1237               str = StrLoopCollectionEmpty;
1238             } else if (isa<CXXForRangeStmt>(Term)) {
1239               str = StrLoopRangeEmpty;
1240             } else {
1241               str = StrLoopBodyZero;
1242             }
1243           }
1244         } else {
1245           str = StrEnteringLoop;
1246         }
1247 
1248         if (!str.empty()) {
1249           PathDiagnosticLocation L(TermCond ? TermCond : Term, SM,
1250                                    C.getCurrLocationContext());
1251           auto PE = std::make_shared<PathDiagnosticEventPiece>(L, str);
1252           PE->setPrunable(true);
1253           addEdgeToPath(C.getActivePath(), PrevLoc, PE->getLocation());
1254           C.getActivePath().push_front(std::move(PE));
1255         }
1256       } else if (isa<BreakStmt>(Term) || isa<ContinueStmt>(Term) ||
1257           isa<GotoStmt>(Term)) {
1258         PathDiagnosticLocation L(Term, SM, C.getCurrLocationContext());
1259         addEdgeToPath(C.getActivePath(), PrevLoc, L);
1260       }
1261     }
1262   }
1263 }
1264 
1265 static std::unique_ptr<PathDiagnostic>
1266 generateEmptyDiagnosticForReport(const BugReport *R, const SourceManager &SM) {
1267   const BugType &BT = R->getBugType();
1268   return std::make_unique<PathDiagnostic>(
1269       R->getBugType().getCheckName(), R->getDeclWithIssue(),
1270       R->getBugType().getName(), R->getDescription(),
1271       R->getShortDescription(/*UseFallback=*/false), BT.getCategory(),
1272       R->getUniqueingLocation(), R->getUniqueingDecl(),
1273       findExecutedLines(SM, R->getErrorNode()));
1274 }
1275 
1276 static const Stmt *getStmtParent(const Stmt *S, const ParentMap &PM) {
1277   if (!S)
1278     return nullptr;
1279 
1280   while (true) {
1281     S = PM.getParentIgnoreParens(S);
1282 
1283     if (!S)
1284       break;
1285 
1286     if (isa<FullExpr>(S) ||
1287         isa<CXXBindTemporaryExpr>(S) ||
1288         isa<SubstNonTypeTemplateParmExpr>(S))
1289       continue;
1290 
1291     break;
1292   }
1293 
1294   return S;
1295 }
1296 
1297 static bool isConditionForTerminator(const Stmt *S, const Stmt *Cond) {
1298   switch (S->getStmtClass()) {
1299     case Stmt::BinaryOperatorClass: {
1300       const auto *BO = cast<BinaryOperator>(S);
1301       if (!BO->isLogicalOp())
1302         return false;
1303       return BO->getLHS() == Cond || BO->getRHS() == Cond;
1304     }
1305     case Stmt::IfStmtClass:
1306       return cast<IfStmt>(S)->getCond() == Cond;
1307     case Stmt::ForStmtClass:
1308       return cast<ForStmt>(S)->getCond() == Cond;
1309     case Stmt::WhileStmtClass:
1310       return cast<WhileStmt>(S)->getCond() == Cond;
1311     case Stmt::DoStmtClass:
1312       return cast<DoStmt>(S)->getCond() == Cond;
1313     case Stmt::ChooseExprClass:
1314       return cast<ChooseExpr>(S)->getCond() == Cond;
1315     case Stmt::IndirectGotoStmtClass:
1316       return cast<IndirectGotoStmt>(S)->getTarget() == Cond;
1317     case Stmt::SwitchStmtClass:
1318       return cast<SwitchStmt>(S)->getCond() == Cond;
1319     case Stmt::BinaryConditionalOperatorClass:
1320       return cast<BinaryConditionalOperator>(S)->getCond() == Cond;
1321     case Stmt::ConditionalOperatorClass: {
1322       const auto *CO = cast<ConditionalOperator>(S);
1323       return CO->getCond() == Cond ||
1324              CO->getLHS() == Cond ||
1325              CO->getRHS() == Cond;
1326     }
1327     case Stmt::ObjCForCollectionStmtClass:
1328       return cast<ObjCForCollectionStmt>(S)->getElement() == Cond;
1329     case Stmt::CXXForRangeStmtClass: {
1330       const auto *FRS = cast<CXXForRangeStmt>(S);
1331       return FRS->getCond() == Cond || FRS->getRangeInit() == Cond;
1332     }
1333     default:
1334       return false;
1335   }
1336 }
1337 
1338 static bool isIncrementOrInitInForLoop(const Stmt *S, const Stmt *FL) {
1339   if (const auto *FS = dyn_cast<ForStmt>(FL))
1340     return FS->getInc() == S || FS->getInit() == S;
1341   if (const auto *FRS = dyn_cast<CXXForRangeStmt>(FL))
1342     return FRS->getInc() == S || FRS->getRangeStmt() == S ||
1343            FRS->getLoopVarStmt() || FRS->getRangeInit() == S;
1344   return false;
1345 }
1346 
1347 using OptimizedCallsSet = llvm::DenseSet<const PathDiagnosticCallPiece *>;
1348 
1349 /// Adds synthetic edges from top-level statements to their subexpressions.
1350 ///
1351 /// This avoids a "swoosh" effect, where an edge from a top-level statement A
1352 /// points to a sub-expression B.1 that's not at the start of B. In these cases,
1353 /// we'd like to see an edge from A to B, then another one from B to B.1.
1354 static void addContextEdges(PathPieces &pieces, const LocationContext *LC) {
1355   const ParentMap &PM = LC->getParentMap();
1356   PathPieces::iterator Prev = pieces.end();
1357   for (PathPieces::iterator I = pieces.begin(), E = Prev; I != E;
1358        Prev = I, ++I) {
1359     auto *Piece = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1360 
1361     if (!Piece)
1362       continue;
1363 
1364     PathDiagnosticLocation SrcLoc = Piece->getStartLocation();
1365     SmallVector<PathDiagnosticLocation, 4> SrcContexts;
1366 
1367     PathDiagnosticLocation NextSrcContext = SrcLoc;
1368     const Stmt *InnerStmt = nullptr;
1369     while (NextSrcContext.isValid() && NextSrcContext.asStmt() != InnerStmt) {
1370       SrcContexts.push_back(NextSrcContext);
1371       InnerStmt = NextSrcContext.asStmt();
1372       NextSrcContext = getEnclosingStmtLocation(InnerStmt, LC,
1373                                                 /*allowNested=*/true);
1374     }
1375 
1376     // Repeatedly split the edge as necessary.
1377     // This is important for nested logical expressions (||, &&, ?:) where we
1378     // want to show all the levels of context.
1379     while (true) {
1380       const Stmt *Dst = Piece->getEndLocation().getStmtOrNull();
1381 
1382       // We are looking at an edge. Is the destination within a larger
1383       // expression?
1384       PathDiagnosticLocation DstContext =
1385           getEnclosingStmtLocation(Dst, LC, /*allowNested=*/true);
1386       if (!DstContext.isValid() || DstContext.asStmt() == Dst)
1387         break;
1388 
1389       // If the source is in the same context, we're already good.
1390       if (llvm::find(SrcContexts, DstContext) != SrcContexts.end())
1391         break;
1392 
1393       // Update the subexpression node to point to the context edge.
1394       Piece->setStartLocation(DstContext);
1395 
1396       // Try to extend the previous edge if it's at the same level as the source
1397       // context.
1398       if (Prev != E) {
1399         auto *PrevPiece = dyn_cast<PathDiagnosticControlFlowPiece>(Prev->get());
1400 
1401         if (PrevPiece) {
1402           if (const Stmt *PrevSrc =
1403                   PrevPiece->getStartLocation().getStmtOrNull()) {
1404             const Stmt *PrevSrcParent = getStmtParent(PrevSrc, PM);
1405             if (PrevSrcParent ==
1406                 getStmtParent(DstContext.getStmtOrNull(), PM)) {
1407               PrevPiece->setEndLocation(DstContext);
1408               break;
1409             }
1410           }
1411         }
1412       }
1413 
1414       // Otherwise, split the current edge into a context edge and a
1415       // subexpression edge. Note that the context statement may itself have
1416       // context.
1417       auto P =
1418           std::make_shared<PathDiagnosticControlFlowPiece>(SrcLoc, DstContext);
1419       Piece = P.get();
1420       I = pieces.insert(I, std::move(P));
1421     }
1422   }
1423 }
1424 
1425 /// Move edges from a branch condition to a branch target
1426 ///        when the condition is simple.
1427 ///
1428 /// This restructures some of the work of addContextEdges.  That function
1429 /// creates edges this may destroy, but they work together to create a more
1430 /// aesthetically set of edges around branches.  After the call to
1431 /// addContextEdges, we may have (1) an edge to the branch, (2) an edge from
1432 /// the branch to the branch condition, and (3) an edge from the branch
1433 /// condition to the branch target.  We keep (1), but may wish to remove (2)
1434 /// and move the source of (3) to the branch if the branch condition is simple.
1435 static void simplifySimpleBranches(PathPieces &pieces) {
1436   for (PathPieces::iterator I = pieces.begin(), E = pieces.end(); I != E; ++I) {
1437     const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1438 
1439     if (!PieceI)
1440       continue;
1441 
1442     const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
1443     const Stmt *s1End   = PieceI->getEndLocation().getStmtOrNull();
1444 
1445     if (!s1Start || !s1End)
1446       continue;
1447 
1448     PathPieces::iterator NextI = I; ++NextI;
1449     if (NextI == E)
1450       break;
1451 
1452     PathDiagnosticControlFlowPiece *PieceNextI = nullptr;
1453 
1454     while (true) {
1455       if (NextI == E)
1456         break;
1457 
1458       const auto *EV = dyn_cast<PathDiagnosticEventPiece>(NextI->get());
1459       if (EV) {
1460         StringRef S = EV->getString();
1461         if (S == StrEnteringLoop || S == StrLoopBodyZero ||
1462             S == StrLoopCollectionEmpty || S == StrLoopRangeEmpty) {
1463           ++NextI;
1464           continue;
1465         }
1466         break;
1467       }
1468 
1469       PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
1470       break;
1471     }
1472 
1473     if (!PieceNextI)
1474       continue;
1475 
1476     const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
1477     const Stmt *s2End   = PieceNextI->getEndLocation().getStmtOrNull();
1478 
1479     if (!s2Start || !s2End || s1End != s2Start)
1480       continue;
1481 
1482     // We only perform this transformation for specific branch kinds.
1483     // We don't want to do this for do..while, for example.
1484     if (!(isa<ForStmt>(s1Start) || isa<WhileStmt>(s1Start) ||
1485           isa<IfStmt>(s1Start) || isa<ObjCForCollectionStmt>(s1Start) ||
1486           isa<CXXForRangeStmt>(s1Start)))
1487       continue;
1488 
1489     // Is s1End the branch condition?
1490     if (!isConditionForTerminator(s1Start, s1End))
1491       continue;
1492 
1493     // Perform the hoisting by eliminating (2) and changing the start
1494     // location of (3).
1495     PieceNextI->setStartLocation(PieceI->getStartLocation());
1496     I = pieces.erase(I);
1497   }
1498 }
1499 
1500 /// Returns the number of bytes in the given (character-based) SourceRange.
1501 ///
1502 /// If the locations in the range are not on the same line, returns None.
1503 ///
1504 /// Note that this does not do a precise user-visible character or column count.
1505 static Optional<size_t> getLengthOnSingleLine(const SourceManager &SM,
1506                                               SourceRange Range) {
1507   SourceRange ExpansionRange(SM.getExpansionLoc(Range.getBegin()),
1508                              SM.getExpansionRange(Range.getEnd()).getEnd());
1509 
1510   FileID FID = SM.getFileID(ExpansionRange.getBegin());
1511   if (FID != SM.getFileID(ExpansionRange.getEnd()))
1512     return None;
1513 
1514   bool Invalid;
1515   const llvm::MemoryBuffer *Buffer = SM.getBuffer(FID, &Invalid);
1516   if (Invalid)
1517     return None;
1518 
1519   unsigned BeginOffset = SM.getFileOffset(ExpansionRange.getBegin());
1520   unsigned EndOffset = SM.getFileOffset(ExpansionRange.getEnd());
1521   StringRef Snippet = Buffer->getBuffer().slice(BeginOffset, EndOffset);
1522 
1523   // We're searching the raw bytes of the buffer here, which might include
1524   // escaped newlines and such. That's okay; we're trying to decide whether the
1525   // SourceRange is covering a large or small amount of space in the user's
1526   // editor.
1527   if (Snippet.find_first_of("\r\n") != StringRef::npos)
1528     return None;
1529 
1530   // This isn't Unicode-aware, but it doesn't need to be.
1531   return Snippet.size();
1532 }
1533 
1534 /// \sa getLengthOnSingleLine(SourceManager, SourceRange)
1535 static Optional<size_t> getLengthOnSingleLine(const SourceManager &SM,
1536                                               const Stmt *S) {
1537   return getLengthOnSingleLine(SM, S->getSourceRange());
1538 }
1539 
1540 /// Eliminate two-edge cycles created by addContextEdges().
1541 ///
1542 /// Once all the context edges are in place, there are plenty of cases where
1543 /// there's a single edge from a top-level statement to a subexpression,
1544 /// followed by a single path note, and then a reverse edge to get back out to
1545 /// the top level. If the statement is simple enough, the subexpression edges
1546 /// just add noise and make it harder to understand what's going on.
1547 ///
1548 /// This function only removes edges in pairs, because removing only one edge
1549 /// might leave other edges dangling.
1550 ///
1551 /// This will not remove edges in more complicated situations:
1552 /// - if there is more than one "hop" leading to or from a subexpression.
1553 /// - if there is an inlined call between the edges instead of a single event.
1554 /// - if the whole statement is large enough that having subexpression arrows
1555 ///   might be helpful.
1556 static void removeContextCycles(PathPieces &Path, const SourceManager &SM) {
1557   for (PathPieces::iterator I = Path.begin(), E = Path.end(); I != E; ) {
1558     // Pattern match the current piece and its successor.
1559     const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1560 
1561     if (!PieceI) {
1562       ++I;
1563       continue;
1564     }
1565 
1566     const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
1567     const Stmt *s1End   = PieceI->getEndLocation().getStmtOrNull();
1568 
1569     PathPieces::iterator NextI = I; ++NextI;
1570     if (NextI == E)
1571       break;
1572 
1573     const auto *PieceNextI =
1574         dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
1575 
1576     if (!PieceNextI) {
1577       if (isa<PathDiagnosticEventPiece>(NextI->get())) {
1578         ++NextI;
1579         if (NextI == E)
1580           break;
1581         PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
1582       }
1583 
1584       if (!PieceNextI) {
1585         ++I;
1586         continue;
1587       }
1588     }
1589 
1590     const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
1591     const Stmt *s2End   = PieceNextI->getEndLocation().getStmtOrNull();
1592 
1593     if (s1Start && s2Start && s1Start == s2End && s2Start == s1End) {
1594       const size_t MAX_SHORT_LINE_LENGTH = 80;
1595       Optional<size_t> s1Length = getLengthOnSingleLine(SM, s1Start);
1596       if (s1Length && *s1Length <= MAX_SHORT_LINE_LENGTH) {
1597         Optional<size_t> s2Length = getLengthOnSingleLine(SM, s2Start);
1598         if (s2Length && *s2Length <= MAX_SHORT_LINE_LENGTH) {
1599           Path.erase(I);
1600           I = Path.erase(NextI);
1601           continue;
1602         }
1603       }
1604     }
1605 
1606     ++I;
1607   }
1608 }
1609 
1610 /// Return true if X is contained by Y.
1611 static bool lexicalContains(const ParentMap &PM, const Stmt *X, const Stmt *Y) {
1612   while (X) {
1613     if (X == Y)
1614       return true;
1615     X = PM.getParent(X);
1616   }
1617   return false;
1618 }
1619 
1620 // Remove short edges on the same line less than 3 columns in difference.
1621 static void removePunyEdges(PathPieces &path, const SourceManager &SM,
1622                             const ParentMap &PM) {
1623   bool erased = false;
1624 
1625   for (PathPieces::iterator I = path.begin(), E = path.end(); I != E;
1626        erased ? I : ++I) {
1627     erased = false;
1628 
1629     const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1630 
1631     if (!PieceI)
1632       continue;
1633 
1634     const Stmt *start = PieceI->getStartLocation().getStmtOrNull();
1635     const Stmt *end   = PieceI->getEndLocation().getStmtOrNull();
1636 
1637     if (!start || !end)
1638       continue;
1639 
1640     const Stmt *endParent = PM.getParent(end);
1641     if (!endParent)
1642       continue;
1643 
1644     if (isConditionForTerminator(end, endParent))
1645       continue;
1646 
1647     SourceLocation FirstLoc = start->getBeginLoc();
1648     SourceLocation SecondLoc = end->getBeginLoc();
1649 
1650     if (!SM.isWrittenInSameFile(FirstLoc, SecondLoc))
1651       continue;
1652     if (SM.isBeforeInTranslationUnit(SecondLoc, FirstLoc))
1653       std::swap(SecondLoc, FirstLoc);
1654 
1655     SourceRange EdgeRange(FirstLoc, SecondLoc);
1656     Optional<size_t> ByteWidth = getLengthOnSingleLine(SM, EdgeRange);
1657 
1658     // If the statements are on different lines, continue.
1659     if (!ByteWidth)
1660       continue;
1661 
1662     const size_t MAX_PUNY_EDGE_LENGTH = 2;
1663     if (*ByteWidth <= MAX_PUNY_EDGE_LENGTH) {
1664       // FIXME: There are enough /bytes/ between the endpoints of the edge, but
1665       // there might not be enough /columns/. A proper user-visible column count
1666       // is probably too expensive, though.
1667       I = path.erase(I);
1668       erased = true;
1669       continue;
1670     }
1671   }
1672 }
1673 
1674 static void removeIdenticalEvents(PathPieces &path) {
1675   for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ++I) {
1676     const auto *PieceI = dyn_cast<PathDiagnosticEventPiece>(I->get());
1677 
1678     if (!PieceI)
1679       continue;
1680 
1681     PathPieces::iterator NextI = I; ++NextI;
1682     if (NextI == E)
1683       return;
1684 
1685     const auto *PieceNextI = dyn_cast<PathDiagnosticEventPiece>(NextI->get());
1686 
1687     if (!PieceNextI)
1688       continue;
1689 
1690     // Erase the second piece if it has the same exact message text.
1691     if (PieceI->getString() == PieceNextI->getString()) {
1692       path.erase(NextI);
1693     }
1694   }
1695 }
1696 
1697 static bool optimizeEdges(const PathDiagnosticConstruct &C, PathPieces &path,
1698                           OptimizedCallsSet &OCS) {
1699   bool hasChanges = false;
1700   const LocationContext *LC = C.getLocationContextFor(&path);
1701   assert(LC);
1702   const ParentMap &PM = LC->getParentMap();
1703   const SourceManager &SM = C.getSourceManager();
1704 
1705   for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ) {
1706     // Optimize subpaths.
1707     if (auto *CallI = dyn_cast<PathDiagnosticCallPiece>(I->get())) {
1708       // Record the fact that a call has been optimized so we only do the
1709       // effort once.
1710       if (!OCS.count(CallI)) {
1711         while (optimizeEdges(C, CallI->path, OCS)) {
1712         }
1713         OCS.insert(CallI);
1714       }
1715       ++I;
1716       continue;
1717     }
1718 
1719     // Pattern match the current piece and its successor.
1720     auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1721 
1722     if (!PieceI) {
1723       ++I;
1724       continue;
1725     }
1726 
1727     const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
1728     const Stmt *s1End   = PieceI->getEndLocation().getStmtOrNull();
1729     const Stmt *level1 = getStmtParent(s1Start, PM);
1730     const Stmt *level2 = getStmtParent(s1End, PM);
1731 
1732     PathPieces::iterator NextI = I; ++NextI;
1733     if (NextI == E)
1734       break;
1735 
1736     const auto *PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
1737 
1738     if (!PieceNextI) {
1739       ++I;
1740       continue;
1741     }
1742 
1743     const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
1744     const Stmt *s2End   = PieceNextI->getEndLocation().getStmtOrNull();
1745     const Stmt *level3 = getStmtParent(s2Start, PM);
1746     const Stmt *level4 = getStmtParent(s2End, PM);
1747 
1748     // Rule I.
1749     //
1750     // If we have two consecutive control edges whose end/begin locations
1751     // are at the same level (e.g. statements or top-level expressions within
1752     // a compound statement, or siblings share a single ancestor expression),
1753     // then merge them if they have no interesting intermediate event.
1754     //
1755     // For example:
1756     //
1757     // (1.1 -> 1.2) -> (1.2 -> 1.3) becomes (1.1 -> 1.3) because the common
1758     // parent is '1'.  Here 'x.y.z' represents the hierarchy of statements.
1759     //
1760     // NOTE: this will be limited later in cases where we add barriers
1761     // to prevent this optimization.
1762     if (level1 && level1 == level2 && level1 == level3 && level1 == level4) {
1763       PieceI->setEndLocation(PieceNextI->getEndLocation());
1764       path.erase(NextI);
1765       hasChanges = true;
1766       continue;
1767     }
1768 
1769     // Rule II.
1770     //
1771     // Eliminate edges between subexpressions and parent expressions
1772     // when the subexpression is consumed.
1773     //
1774     // NOTE: this will be limited later in cases where we add barriers
1775     // to prevent this optimization.
1776     if (s1End && s1End == s2Start && level2) {
1777       bool removeEdge = false;
1778       // Remove edges into the increment or initialization of a
1779       // loop that have no interleaving event.  This means that
1780       // they aren't interesting.
1781       if (isIncrementOrInitInForLoop(s1End, level2))
1782         removeEdge = true;
1783       // Next only consider edges that are not anchored on
1784       // the condition of a terminator.  This are intermediate edges
1785       // that we might want to trim.
1786       else if (!isConditionForTerminator(level2, s1End)) {
1787         // Trim edges on expressions that are consumed by
1788         // the parent expression.
1789         if (isa<Expr>(s1End) && PM.isConsumedExpr(cast<Expr>(s1End))) {
1790           removeEdge = true;
1791         }
1792         // Trim edges where a lexical containment doesn't exist.
1793         // For example:
1794         //
1795         //  X -> Y -> Z
1796         //
1797         // If 'Z' lexically contains Y (it is an ancestor) and
1798         // 'X' does not lexically contain Y (it is a descendant OR
1799         // it has no lexical relationship at all) then trim.
1800         //
1801         // This can eliminate edges where we dive into a subexpression
1802         // and then pop back out, etc.
1803         else if (s1Start && s2End &&
1804                  lexicalContains(PM, s2Start, s2End) &&
1805                  !lexicalContains(PM, s1End, s1Start)) {
1806           removeEdge = true;
1807         }
1808         // Trim edges from a subexpression back to the top level if the
1809         // subexpression is on a different line.
1810         //
1811         // A.1 -> A -> B
1812         // becomes
1813         // A.1 -> B
1814         //
1815         // These edges just look ugly and don't usually add anything.
1816         else if (s1Start && s2End &&
1817                  lexicalContains(PM, s1Start, s1End)) {
1818           SourceRange EdgeRange(PieceI->getEndLocation().asLocation(),
1819                                 PieceI->getStartLocation().asLocation());
1820           if (!getLengthOnSingleLine(SM, EdgeRange).hasValue())
1821             removeEdge = true;
1822         }
1823       }
1824 
1825       if (removeEdge) {
1826         PieceI->setEndLocation(PieceNextI->getEndLocation());
1827         path.erase(NextI);
1828         hasChanges = true;
1829         continue;
1830       }
1831     }
1832 
1833     // Optimize edges for ObjC fast-enumeration loops.
1834     //
1835     // (X -> collection) -> (collection -> element)
1836     //
1837     // becomes:
1838     //
1839     // (X -> element)
1840     if (s1End == s2Start) {
1841       const auto *FS = dyn_cast_or_null<ObjCForCollectionStmt>(level3);
1842       if (FS && FS->getCollection()->IgnoreParens() == s2Start &&
1843           s2End == FS->getElement()) {
1844         PieceI->setEndLocation(PieceNextI->getEndLocation());
1845         path.erase(NextI);
1846         hasChanges = true;
1847         continue;
1848       }
1849     }
1850 
1851     // No changes at this index?  Move to the next one.
1852     ++I;
1853   }
1854 
1855   if (!hasChanges) {
1856     // Adjust edges into subexpressions to make them more uniform
1857     // and aesthetically pleasing.
1858     addContextEdges(path, LC);
1859     // Remove "cyclical" edges that include one or more context edges.
1860     removeContextCycles(path, SM);
1861     // Hoist edges originating from branch conditions to branches
1862     // for simple branches.
1863     simplifySimpleBranches(path);
1864     // Remove any puny edges left over after primary optimization pass.
1865     removePunyEdges(path, SM, PM);
1866     // Remove identical events.
1867     removeIdenticalEvents(path);
1868   }
1869 
1870   return hasChanges;
1871 }
1872 
1873 /// Drop the very first edge in a path, which should be a function entry edge.
1874 ///
1875 /// If the first edge is not a function entry edge (say, because the first
1876 /// statement had an invalid source location), this function does nothing.
1877 // FIXME: We should just generate invalid edges anyway and have the optimizer
1878 // deal with them.
1879 static void dropFunctionEntryEdge(const PathDiagnosticConstruct &C,
1880                                   PathPieces &Path) {
1881   const auto *FirstEdge =
1882       dyn_cast<PathDiagnosticControlFlowPiece>(Path.front().get());
1883   if (!FirstEdge)
1884     return;
1885 
1886   const Decl *D = C.getLocationContextFor(&Path)->getDecl();
1887   PathDiagnosticLocation EntryLoc =
1888       PathDiagnosticLocation::createBegin(D, C.getSourceManager());
1889   if (FirstEdge->getStartLocation() != EntryLoc)
1890     return;
1891 
1892   Path.pop_front();
1893 }
1894 
1895 /// Populate executes lines with lines containing at least one diagnostics.
1896 static void updateExecutedLinesWithDiagnosticPieces(PathDiagnostic &PD) {
1897 
1898   PathPieces path = PD.path.flatten(/*ShouldFlattenMacros=*/true);
1899   FilesToLineNumsMap &ExecutedLines = PD.getExecutedLines();
1900 
1901   for (const auto &P : path) {
1902     FullSourceLoc Loc = P->getLocation().asLocation().getExpansionLoc();
1903     FileID FID = Loc.getFileID();
1904     unsigned LineNo = Loc.getLineNumber();
1905     assert(FID.isValid());
1906     ExecutedLines[FID].insert(LineNo);
1907   }
1908 }
1909 
1910 PathDiagnosticConstruct::PathDiagnosticConstruct(
1911     const PathDiagnosticConsumer *PDC, const ExplodedNode *ErrorNode,
1912     const BugReport *R)
1913     : Consumer(PDC), CurrentNode(ErrorNode),
1914       SM(CurrentNode->getCodeDecl().getASTContext().getSourceManager()),
1915       PD(generateEmptyDiagnosticForReport(R, getSourceManager())) {
1916   LCM[&PD->getActivePath()] = ErrorNode->getLocationContext();
1917 }
1918 
1919 PathDiagnosticBuilder::PathDiagnosticBuilder(
1920     BugReporterContext BRC, std::unique_ptr<ExplodedGraph> BugPath,
1921     BugReport *r, const ExplodedNode *ErrorNode,
1922     std::unique_ptr<VisitorsDiagnosticsTy> VisitorsDiagnostics)
1923     : BugReporterContext(BRC), BugPath(std::move(BugPath)), R(r),
1924       ErrorNode(ErrorNode),
1925       VisitorsDiagnostics(std::move(VisitorsDiagnostics)) {}
1926 
1927 std::unique_ptr<PathDiagnostic>
1928 PathDiagnosticBuilder::generate(const PathDiagnosticConsumer *PDC) const {
1929   PathDiagnosticConstruct Construct(PDC, ErrorNode, R);
1930 
1931   const SourceManager &SM = getSourceManager();
1932   const BugReport *R = getBugReport();
1933   const AnalyzerOptions &Opts = getAnalyzerOptions();
1934   StringRef ErrorTag = ErrorNode->getLocation().getTag()->getTagDescription();
1935 
1936   // See whether we need to silence the checker/package.
1937   // FIXME: This will not work if the report was emitted with an incorrect tag.
1938   for (const std::string &CheckerOrPackage : Opts.SilencedCheckersAndPackages) {
1939     if (ErrorTag.startswith(CheckerOrPackage))
1940       return nullptr;
1941   }
1942 
1943   if (!PDC->shouldGenerateDiagnostics())
1944     return generateEmptyDiagnosticForReport(R, getSourceManager());
1945 
1946   // Construct the final (warning) event for the bug report.
1947   auto EndNotes = VisitorsDiagnostics->find(ErrorNode);
1948   PathDiagnosticPieceRef LastPiece;
1949   if (EndNotes != VisitorsDiagnostics->end()) {
1950     assert(!EndNotes->second.empty());
1951     LastPiece = EndNotes->second[0];
1952   } else {
1953     LastPiece = BugReporterVisitor::getDefaultEndPath(*this, ErrorNode,
1954                                                       *getBugReport());
1955   }
1956   Construct.PD->setEndOfPath(LastPiece);
1957 
1958   PathDiagnosticLocation PrevLoc = Construct.PD->getLocation();
1959   // From the error node to the root, ascend the bug path and construct the bug
1960   // report.
1961   while (Construct.ascendToPrevNode()) {
1962     generatePathDiagnosticsForNode(Construct, PrevLoc);
1963 
1964     auto VisitorNotes = VisitorsDiagnostics->find(Construct.getCurrentNode());
1965     if (VisitorNotes == VisitorsDiagnostics->end())
1966       continue;
1967 
1968     // This is a workaround due to inability to put shared PathDiagnosticPiece
1969     // into a FoldingSet.
1970     std::set<llvm::FoldingSetNodeID> DeduplicationSet;
1971 
1972     // Add pieces from custom visitors.
1973     for (const PathDiagnosticPieceRef &Note : VisitorNotes->second) {
1974       llvm::FoldingSetNodeID ID;
1975       Note->Profile(ID);
1976       if (!DeduplicationSet.insert(ID).second)
1977         continue;
1978 
1979       if (PDC->shouldAddPathEdges())
1980         addEdgeToPath(Construct.getActivePath(), PrevLoc, Note->getLocation());
1981       updateStackPiecesWithMessage(*Note, Construct.CallStack);
1982       Construct.getActivePath().push_front(Note);
1983     }
1984   }
1985 
1986   if (PDC->shouldAddPathEdges()) {
1987     // Add an edge to the start of the function.
1988     // We'll prune it out later, but it helps make diagnostics more uniform.
1989     const StackFrameContext *CalleeLC =
1990         Construct.getLocationContextForActivePath()->getStackFrame();
1991     const Decl *D = CalleeLC->getDecl();
1992     addEdgeToPath(Construct.getActivePath(), PrevLoc,
1993                   PathDiagnosticLocation::createBegin(D, SM));
1994   }
1995 
1996 
1997   // Finally, prune the diagnostic path of uninteresting stuff.
1998   if (!Construct.PD->path.empty()) {
1999     if (R->shouldPrunePath() && Opts.ShouldPrunePaths) {
2000       bool stillHasNotes =
2001           removeUnneededCalls(Construct, Construct.getMutablePieces(), R);
2002       assert(stillHasNotes);
2003       (void)stillHasNotes;
2004     }
2005 
2006     // Remove pop-up notes if needed.
2007     if (!Opts.ShouldAddPopUpNotes)
2008       removePopUpNotes(Construct.getMutablePieces());
2009 
2010     // Redirect all call pieces to have valid locations.
2011     adjustCallLocations(Construct.getMutablePieces());
2012     removePiecesWithInvalidLocations(Construct.getMutablePieces());
2013 
2014     if (PDC->shouldAddPathEdges()) {
2015 
2016       // Reduce the number of edges from a very conservative set
2017       // to an aesthetically pleasing subset that conveys the
2018       // necessary information.
2019       OptimizedCallsSet OCS;
2020       while (optimizeEdges(Construct, Construct.getMutablePieces(), OCS)) {
2021       }
2022 
2023       // Drop the very first function-entry edge. It's not really necessary
2024       // for top-level functions.
2025       dropFunctionEntryEdge(Construct, Construct.getMutablePieces());
2026     }
2027 
2028     // Remove messages that are basically the same, and edges that may not
2029     // make sense.
2030     // We have to do this after edge optimization in the Extensive mode.
2031     removeRedundantMsgs(Construct.getMutablePieces());
2032     removeEdgesToDefaultInitializers(Construct.getMutablePieces());
2033   }
2034 
2035   if (Opts.ShouldDisplayMacroExpansions)
2036     CompactMacroExpandedPieces(Construct.getMutablePieces(), SM);
2037 
2038   return std::move(Construct.PD);
2039 }
2040 
2041 //===----------------------------------------------------------------------===//
2042 // Methods for BugType and subclasses.
2043 //===----------------------------------------------------------------------===//
2044 
2045 void BugType::anchor() {}
2046 
2047 void BuiltinBug::anchor() {}
2048 
2049 //===----------------------------------------------------------------------===//
2050 // Methods for BugReport and subclasses.
2051 //===----------------------------------------------------------------------===//
2052 
2053 void BugReport::addVisitor(std::unique_ptr<BugReporterVisitor> visitor) {
2054   if (!visitor)
2055     return;
2056 
2057   llvm::FoldingSetNodeID ID;
2058   visitor->Profile(ID);
2059 
2060   void *InsertPos = nullptr;
2061   if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
2062     return;
2063   }
2064 
2065   Callbacks.push_back(std::move(visitor));
2066 }
2067 
2068 void BugReport::clearVisitors() {
2069   Callbacks.clear();
2070 }
2071 
2072 const Decl *BugReport::getDeclWithIssue() const {
2073   if (DeclWithIssue)
2074     return DeclWithIssue;
2075 
2076   const ExplodedNode *N = getErrorNode();
2077   if (!N)
2078     return nullptr;
2079 
2080   const LocationContext *LC = N->getLocationContext();
2081   return LC->getStackFrame()->getDecl();
2082 }
2083 
2084 void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
2085   hash.AddPointer(&BT);
2086   hash.AddString(Description);
2087   PathDiagnosticLocation UL = getUniqueingLocation();
2088   if (UL.isValid()) {
2089     UL.Profile(hash);
2090   } else if (Location.isValid()) {
2091     Location.Profile(hash);
2092   } else {
2093     assert(ErrorNode);
2094     hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
2095   }
2096 
2097   for (SourceRange range : Ranges) {
2098     if (!range.isValid())
2099       continue;
2100     hash.AddInteger(range.getBegin().getRawEncoding());
2101     hash.AddInteger(range.getEnd().getRawEncoding());
2102   }
2103 }
2104 
2105 template <class T>
2106 static void insertToInterestingnessMap(
2107     llvm::DenseMap<T, bugreporter::TrackingKind> &InterestingnessMap, T Val,
2108     bugreporter::TrackingKind TKind) {
2109   auto Result = InterestingnessMap.insert({Val, TKind});
2110 
2111   if (Result.second)
2112     return;
2113 
2114   // Even if this symbol/region was already marked as interesting as a
2115   // condition, if we later mark it as interesting again but with
2116   // thorough tracking, overwrite it. Entities marked with thorough
2117   // interestiness are the most important (or most interesting, if you will),
2118   // and we wouldn't like to downplay their importance.
2119 
2120   switch (TKind) {
2121     case bugreporter::TrackingKind::Thorough:
2122       Result.first->getSecond() = bugreporter::TrackingKind::Thorough;
2123       return;
2124     case bugreporter::TrackingKind::Condition:
2125       return;
2126   }
2127 
2128   llvm_unreachable(
2129       "BugReport::markInteresting currently can only handle 2 different "
2130       "tracking kinds! Please define what tracking kind should this entitiy"
2131       "have, if it was already marked as interesting with a different kind!");
2132 }
2133 
2134 void BugReport::markInteresting(SymbolRef sym,
2135                                 bugreporter::TrackingKind TKind) {
2136   if (!sym)
2137     return;
2138 
2139   insertToInterestingnessMap(InterestingSymbols, sym, TKind);
2140 
2141   if (const auto *meta = dyn_cast<SymbolMetadata>(sym))
2142     markInteresting(meta->getRegion(), TKind);
2143 }
2144 
2145 void BugReport::markInteresting(const MemRegion *R,
2146                                 bugreporter::TrackingKind TKind) {
2147   if (!R)
2148     return;
2149 
2150   R = R->getBaseRegion();
2151   insertToInterestingnessMap(InterestingRegions, R, TKind);
2152 
2153   if (const auto *SR = dyn_cast<SymbolicRegion>(R))
2154     markInteresting(SR->getSymbol(), TKind);
2155 }
2156 
2157 void BugReport::markInteresting(SVal V, bugreporter::TrackingKind TKind) {
2158   markInteresting(V.getAsRegion(), TKind);
2159   markInteresting(V.getAsSymbol(), TKind);
2160 }
2161 
2162 void BugReport::markInteresting(const LocationContext *LC) {
2163   if (!LC)
2164     return;
2165   InterestingLocationContexts.insert(LC);
2166 }
2167 
2168 Optional<bugreporter::TrackingKind>
2169 BugReport::getInterestingnessKind(SVal V) const {
2170   auto RKind = getInterestingnessKind(V.getAsRegion());
2171   auto SKind = getInterestingnessKind(V.getAsSymbol());
2172   if (!RKind)
2173     return SKind;
2174   if (!SKind)
2175     return RKind;
2176 
2177   // If either is marked with throrough tracking, return that, we wouldn't like
2178   // to downplay a note's importance by 'only' mentioning it as a condition.
2179   switch(*RKind) {
2180     case bugreporter::TrackingKind::Thorough:
2181       return RKind;
2182     case bugreporter::TrackingKind::Condition:
2183       return SKind;
2184   }
2185 
2186   llvm_unreachable(
2187       "BugReport::getInterestingnessKind currently can only handle 2 different "
2188       "tracking kinds! Please define what tracking kind should we return here "
2189       "when the kind of getAsRegion() and getAsSymbol() is different!");
2190   return None;
2191 }
2192 
2193 Optional<bugreporter::TrackingKind>
2194 BugReport::getInterestingnessKind(SymbolRef sym) const {
2195   if (!sym)
2196     return None;
2197   // We don't currently consider metadata symbols to be interesting
2198   // even if we know their region is interesting. Is that correct behavior?
2199   auto It = InterestingSymbols.find(sym);
2200   if (It == InterestingSymbols.end())
2201     return None;
2202   return It->getSecond();
2203 }
2204 
2205 Optional<bugreporter::TrackingKind>
2206 BugReport::getInterestingnessKind(const MemRegion *R) const {
2207   if (!R)
2208     return None;
2209 
2210   R = R->getBaseRegion();
2211   auto It = InterestingRegions.find(R);
2212   if (It != InterestingRegions.end())
2213     return It->getSecond();
2214 
2215   if (const auto *SR = dyn_cast<SymbolicRegion>(R))
2216     return getInterestingnessKind(SR->getSymbol());
2217   return None;
2218 }
2219 
2220 bool BugReport::isInteresting(SVal V) const {
2221   return getInterestingnessKind(V).hasValue();
2222 }
2223 
2224 bool BugReport::isInteresting(SymbolRef sym) const {
2225   return getInterestingnessKind(sym).hasValue();
2226 }
2227 
2228 bool BugReport::isInteresting(const MemRegion *R) const {
2229   return getInterestingnessKind(R).hasValue();
2230 }
2231 
2232 bool BugReport::isInteresting(const LocationContext *LC)  const {
2233   if (!LC)
2234     return false;
2235   return InterestingLocationContexts.count(LC);
2236 }
2237 
2238 const Stmt *BugReport::getStmt() const {
2239   if (!ErrorNode)
2240     return nullptr;
2241 
2242   ProgramPoint ProgP = ErrorNode->getLocation();
2243   const Stmt *S = nullptr;
2244 
2245   if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
2246     CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
2247     if (BE->getBlock() == &Exit)
2248       S = GetPreviousStmt(ErrorNode);
2249   }
2250   if (!S)
2251     S = PathDiagnosticLocation::getStmt(ErrorNode);
2252 
2253   return S;
2254 }
2255 
2256 llvm::iterator_range<BugReport::ranges_iterator> BugReport::getRanges() const {
2257   // If no custom ranges, add the range of the statement corresponding to
2258   // the error node.
2259   if (Ranges.empty()) {
2260     if (dyn_cast_or_null<Expr>(getStmt()))
2261       return llvm::make_range(&ErrorNodeRange, &ErrorNodeRange + 1);
2262     return llvm::make_range(ranges_iterator(), ranges_iterator());
2263   }
2264 
2265   // User-specified absence of range info.
2266   if (Ranges.size() == 1 && !Ranges.begin()->isValid())
2267     return llvm::make_range(ranges_iterator(), ranges_iterator());
2268 
2269   return llvm::make_range(Ranges.begin(), Ranges.end());
2270 }
2271 
2272 PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
2273   if (ErrorNode) {
2274     assert(!Location.isValid() &&
2275      "Either Location or ErrorNode should be specified but not both.");
2276     return PathDiagnosticLocation::createEndOfPath(ErrorNode, SM);
2277   }
2278 
2279   assert(Location.isValid());
2280   return Location;
2281 }
2282 
2283 //===----------------------------------------------------------------------===//
2284 // Methods for BugReporter and subclasses.
2285 //===----------------------------------------------------------------------===//
2286 
2287 const ExplodedGraph &PathSensitiveBugReporter::getGraph() const {
2288   return Eng.getGraph();
2289 }
2290 
2291 ProgramStateManager &PathSensitiveBugReporter::getStateManager() const {
2292   return Eng.getStateManager();
2293 }
2294 
2295 BugReporter::~BugReporter() {
2296   // Make sure reports are flushed.
2297   assert(StrBugTypes.empty() &&
2298          "Destroying BugReporter before diagnostics are emitted!");
2299 
2300   // Free the bug reports we are tracking.
2301   for (const auto I : EQClassesVector)
2302     delete I;
2303 }
2304 
2305 void BugReporter::FlushReports() {
2306   // We need to flush reports in deterministic order to ensure the order
2307   // of the reports is consistent between runs.
2308   for (const auto EQ : EQClassesVector)
2309     FlushReport(*EQ);
2310 
2311   // BugReporter owns and deletes only BugTypes created implicitly through
2312   // EmitBasicReport.
2313   // FIXME: There are leaks from checkers that assume that the BugTypes they
2314   // create will be destroyed by the BugReporter.
2315   llvm::DeleteContainerSeconds(StrBugTypes);
2316 }
2317 
2318 //===----------------------------------------------------------------------===//
2319 // PathDiagnostics generation.
2320 //===----------------------------------------------------------------------===//
2321 
2322 namespace {
2323 
2324 /// A wrapper around an ExplodedGraph that contains a single path from the root
2325 /// to the error node.
2326 class BugPathInfo {
2327 public:
2328   std::unique_ptr<ExplodedGraph> BugPath;
2329   BugReport *Report;
2330   const ExplodedNode *ErrorNode;
2331 };
2332 
2333 /// A wrapper around an ExplodedGraph whose leafs are all error nodes. Can
2334 /// conveniently retrieve bug paths from a single error node to the root.
2335 class BugPathGetter {
2336   std::unique_ptr<ExplodedGraph> TrimmedGraph;
2337 
2338   using PriorityMapTy = llvm::DenseMap<const ExplodedNode *, unsigned>;
2339 
2340   /// Assign each node with its distance from the root.
2341   PriorityMapTy PriorityMap;
2342 
2343   /// Since the getErrorNode() or BugReport refers to the original ExplodedGraph,
2344   /// we need to pair it to the error node of the constructed trimmed graph.
2345   using ReportNewNodePair = std::pair<BugReport *, const ExplodedNode *>;
2346   SmallVector<ReportNewNodePair, 32> ReportNodes;
2347 
2348   BugPathInfo CurrentBugPath;
2349 
2350   /// A helper class for sorting ExplodedNodes by priority.
2351   template <bool Descending>
2352   class PriorityCompare {
2353     const PriorityMapTy &PriorityMap;
2354 
2355   public:
2356     PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
2357 
2358     bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
2359       PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
2360       PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
2361       PriorityMapTy::const_iterator E = PriorityMap.end();
2362 
2363       if (LI == E)
2364         return Descending;
2365       if (RI == E)
2366         return !Descending;
2367 
2368       return Descending ? LI->second > RI->second
2369                         : LI->second < RI->second;
2370     }
2371 
2372     bool operator()(const ReportNewNodePair &LHS,
2373                     const ReportNewNodePair &RHS) const {
2374       return (*this)(LHS.second, RHS.second);
2375     }
2376   };
2377 
2378 public:
2379   BugPathGetter(const ExplodedGraph *OriginalGraph,
2380                 ArrayRef<BugReport *> &bugReports);
2381 
2382   BugPathInfo *getNextBugPath();
2383 };
2384 
2385 } // namespace
2386 
2387 BugPathGetter::BugPathGetter(const ExplodedGraph *OriginalGraph,
2388                              ArrayRef<BugReport *> &bugReports) {
2389   SmallVector<const ExplodedNode *, 32> Nodes;
2390   for (const auto I : bugReports) {
2391     assert(I->isValid() &&
2392            "We only allow BugReporterVisitors and BugReporter itself to "
2393            "invalidate reports!");
2394     Nodes.emplace_back(I->getErrorNode());
2395   }
2396 
2397   // The trimmed graph is created in the body of the constructor to ensure
2398   // that the DenseMaps have been initialized already.
2399   InterExplodedGraphMap ForwardMap;
2400   TrimmedGraph = OriginalGraph->trim(Nodes, &ForwardMap);
2401 
2402   // Find the (first) error node in the trimmed graph.  We just need to consult
2403   // the node map which maps from nodes in the original graph to nodes
2404   // in the new graph.
2405   llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes;
2406 
2407   for (BugReport *Report : bugReports) {
2408     const ExplodedNode *NewNode = ForwardMap.lookup(Report->getErrorNode());
2409     assert(NewNode &&
2410            "Failed to construct a trimmed graph that contains this error "
2411            "node!");
2412     ReportNodes.emplace_back(Report, NewNode);
2413     RemainingNodes.insert(NewNode);
2414   }
2415 
2416   assert(!RemainingNodes.empty() && "No error node found in the trimmed graph");
2417 
2418   // Perform a forward BFS to find all the shortest paths.
2419   std::queue<const ExplodedNode *> WS;
2420 
2421   assert(TrimmedGraph->num_roots() == 1);
2422   WS.push(*TrimmedGraph->roots_begin());
2423   unsigned Priority = 0;
2424 
2425   while (!WS.empty()) {
2426     const ExplodedNode *Node = WS.front();
2427     WS.pop();
2428 
2429     PriorityMapTy::iterator PriorityEntry;
2430     bool IsNew;
2431     std::tie(PriorityEntry, IsNew) = PriorityMap.insert({Node, Priority});
2432     ++Priority;
2433 
2434     if (!IsNew) {
2435       assert(PriorityEntry->second <= Priority);
2436       continue;
2437     }
2438 
2439     if (RemainingNodes.erase(Node))
2440       if (RemainingNodes.empty())
2441         break;
2442 
2443     for (const ExplodedNode *Succ : Node->succs())
2444       WS.push(Succ);
2445   }
2446 
2447   // Sort the error paths from longest to shortest.
2448   llvm::sort(ReportNodes, PriorityCompare<true>(PriorityMap));
2449 }
2450 
2451 BugPathInfo *BugPathGetter::getNextBugPath() {
2452   if (ReportNodes.empty())
2453     return nullptr;
2454 
2455   const ExplodedNode *OrigN;
2456   std::tie(CurrentBugPath.Report, OrigN) = ReportNodes.pop_back_val();
2457   assert(PriorityMap.find(OrigN) != PriorityMap.end() &&
2458          "error node not accessible from root");
2459 
2460   // Create a new graph with a single path. This is the graph that will be
2461   // returned to the caller.
2462   auto GNew = std::make_unique<ExplodedGraph>();
2463 
2464   // Now walk from the error node up the BFS path, always taking the
2465   // predeccessor with the lowest number.
2466   ExplodedNode *Succ = nullptr;
2467   while (true) {
2468     // Create the equivalent node in the new graph with the same state
2469     // and location.
2470     ExplodedNode *NewN = GNew->createUncachedNode(
2471         OrigN->getLocation(), OrigN->getState(), OrigN->isSink());
2472 
2473     // Link up the new node with the previous node.
2474     if (Succ)
2475       Succ->addPredecessor(NewN, *GNew);
2476     else
2477       CurrentBugPath.ErrorNode = NewN;
2478 
2479     Succ = NewN;
2480 
2481     // Are we at the final node?
2482     if (OrigN->pred_empty()) {
2483       GNew->addRoot(NewN);
2484       break;
2485     }
2486 
2487     // Find the next predeccessor node.  We choose the node that is marked
2488     // with the lowest BFS number.
2489     OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(),
2490                               PriorityCompare<false>(PriorityMap));
2491   }
2492 
2493   CurrentBugPath.BugPath = std::move(GNew);
2494 
2495   return &CurrentBugPath;
2496 }
2497 
2498 /// CompactMacroExpandedPieces - This function postprocesses a PathDiagnostic
2499 /// object and collapses PathDiagosticPieces that are expanded by macros.
2500 static void CompactMacroExpandedPieces(PathPieces &path,
2501                                        const SourceManager& SM) {
2502   using MacroStackTy = std::vector<
2503       std::pair<std::shared_ptr<PathDiagnosticMacroPiece>, SourceLocation>>;
2504 
2505   using PiecesTy = std::vector<PathDiagnosticPieceRef>;
2506 
2507   MacroStackTy MacroStack;
2508   PiecesTy Pieces;
2509 
2510   for (PathPieces::const_iterator I = path.begin(), E = path.end();
2511        I != E; ++I) {
2512     const auto &piece = *I;
2513 
2514     // Recursively compact calls.
2515     if (auto *call = dyn_cast<PathDiagnosticCallPiece>(&*piece)) {
2516       CompactMacroExpandedPieces(call->path, SM);
2517     }
2518 
2519     // Get the location of the PathDiagnosticPiece.
2520     const FullSourceLoc Loc = piece->getLocation().asLocation();
2521 
2522     // Determine the instantiation location, which is the location we group
2523     // related PathDiagnosticPieces.
2524     SourceLocation InstantiationLoc = Loc.isMacroID() ?
2525                                       SM.getExpansionLoc(Loc) :
2526                                       SourceLocation();
2527 
2528     if (Loc.isFileID()) {
2529       MacroStack.clear();
2530       Pieces.push_back(piece);
2531       continue;
2532     }
2533 
2534     assert(Loc.isMacroID());
2535 
2536     // Is the PathDiagnosticPiece within the same macro group?
2537     if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
2538       MacroStack.back().first->subPieces.push_back(piece);
2539       continue;
2540     }
2541 
2542     // We aren't in the same group.  Are we descending into a new macro
2543     // or are part of an old one?
2544     std::shared_ptr<PathDiagnosticMacroPiece> MacroGroup;
2545 
2546     SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
2547                                           SM.getExpansionLoc(Loc) :
2548                                           SourceLocation();
2549 
2550     // Walk the entire macro stack.
2551     while (!MacroStack.empty()) {
2552       if (InstantiationLoc == MacroStack.back().second) {
2553         MacroGroup = MacroStack.back().first;
2554         break;
2555       }
2556 
2557       if (ParentInstantiationLoc == MacroStack.back().second) {
2558         MacroGroup = MacroStack.back().first;
2559         break;
2560       }
2561 
2562       MacroStack.pop_back();
2563     }
2564 
2565     if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
2566       // Create a new macro group and add it to the stack.
2567       auto NewGroup = std::make_shared<PathDiagnosticMacroPiece>(
2568           PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
2569 
2570       if (MacroGroup)
2571         MacroGroup->subPieces.push_back(NewGroup);
2572       else {
2573         assert(InstantiationLoc.isFileID());
2574         Pieces.push_back(NewGroup);
2575       }
2576 
2577       MacroGroup = NewGroup;
2578       MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
2579     }
2580 
2581     // Finally, add the PathDiagnosticPiece to the group.
2582     MacroGroup->subPieces.push_back(piece);
2583   }
2584 
2585   // Now take the pieces and construct a new PathDiagnostic.
2586   path.clear();
2587 
2588   path.insert(path.end(), Pieces.begin(), Pieces.end());
2589 }
2590 
2591 /// Generate notes from all visitors.
2592 /// Notes associated with {@code ErrorNode} are generated using
2593 /// {@code getEndPath}, and the rest are generated with {@code VisitNode}.
2594 static std::unique_ptr<VisitorsDiagnosticsTy>
2595 generateVisitorsDiagnostics(BugReport *R, const ExplodedNode *ErrorNode,
2596                             BugReporterContext &BRC) {
2597   std::unique_ptr<VisitorsDiagnosticsTy> Notes =
2598       std::make_unique<VisitorsDiagnosticsTy>();
2599   BugReport::VisitorList visitors;
2600 
2601   // Run visitors on all nodes starting from the node *before* the last one.
2602   // The last node is reserved for notes generated with {@code getEndPath}.
2603   const ExplodedNode *NextNode = ErrorNode->getFirstPred();
2604   while (NextNode) {
2605 
2606     // At each iteration, move all visitors from report to visitor list. This is
2607     // important, because the Profile() functions of the visitors make sure that
2608     // a visitor isn't added multiple times for the same node, but it's fine
2609     // to add the a visitor with Profile() for different nodes (e.g. tracking
2610     // a region at different points of the symbolic execution).
2611     for (std::unique_ptr<BugReporterVisitor> &Visitor : R->visitors())
2612       visitors.push_back(std::move(Visitor));
2613 
2614     R->clearVisitors();
2615 
2616     const ExplodedNode *Pred = NextNode->getFirstPred();
2617     if (!Pred) {
2618       PathDiagnosticPieceRef LastPiece;
2619       for (auto &V : visitors) {
2620         V->finalizeVisitor(BRC, ErrorNode, *R);
2621 
2622         if (auto Piece = V->getEndPath(BRC, ErrorNode, *R)) {
2623           assert(!LastPiece &&
2624                  "There can only be one final piece in a diagnostic.");
2625           assert(Piece->getKind() == PathDiagnosticPiece::Kind::Event &&
2626                  "The final piece must contain a message!");
2627           LastPiece = std::move(Piece);
2628           (*Notes)[ErrorNode].push_back(LastPiece);
2629         }
2630       }
2631       break;
2632     }
2633 
2634     for (auto &V : visitors) {
2635       auto P = V->VisitNode(NextNode, BRC, *R);
2636       if (P)
2637         (*Notes)[NextNode].push_back(std::move(P));
2638     }
2639 
2640     if (!R->isValid())
2641       break;
2642 
2643     NextNode = Pred;
2644   }
2645 
2646   return Notes;
2647 }
2648 
2649 Optional<PathDiagnosticBuilder>
2650 PathDiagnosticBuilder::findValidReport(ArrayRef<BugReport *> &bugReports,
2651                                        PathSensitiveBugReporter &Reporter) {
2652 
2653   BugPathGetter BugGraph(&Reporter.getGraph(), bugReports);
2654 
2655   while (BugPathInfo *BugPath = BugGraph.getNextBugPath()) {
2656     // Find the BugReport with the original location.
2657     BugReport *R = BugPath->Report;
2658     assert(R && "No original report found for sliced graph.");
2659     assert(R->isValid() && "Report selected by trimmed graph marked invalid.");
2660     const ExplodedNode *ErrorNode = BugPath->ErrorNode;
2661 
2662     // Register refutation visitors first, if they mark the bug invalid no
2663     // further analysis is required
2664     R->addVisitor(std::make_unique<LikelyFalsePositiveSuppressionBRVisitor>());
2665 
2666     // Register additional node visitors.
2667     R->addVisitor(std::make_unique<NilReceiverBRVisitor>());
2668     R->addVisitor(std::make_unique<ConditionBRVisitor>());
2669     R->addVisitor(std::make_unique<TagVisitor>());
2670 
2671     BugReporterContext BRC(Reporter);
2672 
2673     // Run all visitors on a given graph, once.
2674     std::unique_ptr<VisitorsDiagnosticsTy> visitorNotes =
2675         generateVisitorsDiagnostics(R, ErrorNode, BRC);
2676 
2677     if (R->isValid()) {
2678       if (Reporter.getAnalyzerOptions().ShouldCrosscheckWithZ3) {
2679         // If crosscheck is enabled, remove all visitors, add the refutation
2680         // visitor and check again
2681         R->clearVisitors();
2682         R->addVisitor(std::make_unique<FalsePositiveRefutationBRVisitor>());
2683 
2684         // We don't overrite the notes inserted by other visitors because the
2685         // refutation manager does not add any new note to the path
2686         generateVisitorsDiagnostics(R, BugPath->ErrorNode, BRC);
2687       }
2688 
2689       // Check if the bug is still valid
2690       if (R->isValid())
2691         return PathDiagnosticBuilder(
2692             std::move(BRC), std::move(BugPath->BugPath), BugPath->Report,
2693             BugPath->ErrorNode, std::move(visitorNotes));
2694     }
2695   }
2696 
2697   return {};
2698 }
2699 
2700 std::unique_ptr<DiagnosticForConsumerMapTy>
2701 PathSensitiveBugReporter::generatePathDiagnostics(
2702     ArrayRef<PathDiagnosticConsumer *> consumers,
2703     ArrayRef<BugReport *> &bugReports) {
2704   assert(!bugReports.empty());
2705 
2706   auto Out = std::make_unique<DiagnosticForConsumerMapTy>();
2707 
2708   Optional<PathDiagnosticBuilder> PDB =
2709       PathDiagnosticBuilder::findValidReport(bugReports, *this);
2710 
2711   if (PDB) {
2712     for (PathDiagnosticConsumer *PC : consumers) {
2713       if (std::unique_ptr<PathDiagnostic> PD = PDB->generate(PC)) {
2714         (*Out)[PC] = std::move(PD);
2715       }
2716     }
2717   }
2718 
2719   return Out;
2720 }
2721 
2722 void BugReporter::emitReport(std::unique_ptr<BugReport> R) {
2723   if (const ExplodedNode *E = R->getErrorNode()) {
2724     // An error node must either be a sink or have a tag, otherwise
2725     // it could get reclaimed before the path diagnostic is created.
2726     assert((E->isSink() || E->getLocation().getTag()) &&
2727             "Error node must either be a sink or have a tag");
2728 
2729     const AnalysisDeclContext *DeclCtx =
2730         E->getLocationContext()->getAnalysisDeclContext();
2731     // The source of autosynthesized body can be handcrafted AST or a model
2732     // file. The locations from handcrafted ASTs have no valid source locations
2733     // and have to be discarded. Locations from model files should be preserved
2734     // for processing and reporting.
2735     if (DeclCtx->isBodyAutosynthesized() &&
2736         !DeclCtx->isBodyAutosynthesizedFromModelFile())
2737       return;
2738   }
2739 
2740   bool ValidSourceLoc = R->getLocation(getSourceManager()).isValid();
2741   assert(ValidSourceLoc);
2742   // If we mess up in a release build, we'd still prefer to just drop the bug
2743   // instead of trying to go on.
2744   if (!ValidSourceLoc)
2745     return;
2746 
2747   // Compute the bug report's hash to determine its equivalence class.
2748   llvm::FoldingSetNodeID ID;
2749   R->Profile(ID);
2750 
2751   // Lookup the equivance class.  If there isn't one, create it.
2752   void *InsertPos;
2753   BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
2754 
2755   if (!EQ) {
2756     EQ = new BugReportEquivClass(std::move(R));
2757     EQClasses.InsertNode(EQ, InsertPos);
2758     EQClassesVector.push_back(EQ);
2759   } else
2760     EQ->AddReport(std::move(R));
2761 }
2762 
2763 //===----------------------------------------------------------------------===//
2764 // Emitting reports in equivalence classes.
2765 //===----------------------------------------------------------------------===//
2766 
2767 namespace {
2768 
2769 struct FRIEC_WLItem {
2770   const ExplodedNode *N;
2771   ExplodedNode::const_succ_iterator I, E;
2772 
2773   FRIEC_WLItem(const ExplodedNode *n)
2774       : N(n), I(N->succ_begin()), E(N->succ_end()) {}
2775 };
2776 
2777 } // namespace
2778 
2779 static BugReport *
2780 FindReportInEquivalenceClass(BugReportEquivClass& EQ,
2781                              SmallVectorImpl<BugReport*> &bugReports) {
2782   BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
2783   assert(I != E);
2784   const BugType& BT = I->getBugType();
2785 
2786   // If we don't need to suppress any of the nodes because they are
2787   // post-dominated by a sink, simply add all the nodes in the equivalence class
2788   // to 'Nodes'.  Any of the reports will serve as a "representative" report.
2789   if (!BT.isSuppressOnSink()) {
2790     BugReport *R = &*I;
2791     for (auto &I : EQ) {
2792       const ExplodedNode *N = I.getErrorNode();
2793       if (N) {
2794         R = &I;
2795         bugReports.push_back(R);
2796       }
2797     }
2798     return R;
2799   }
2800 
2801   // For bug reports that should be suppressed when all paths are post-dominated
2802   // by a sink node, iterate through the reports in the equivalence class
2803   // until we find one that isn't post-dominated (if one exists).  We use a
2804   // DFS traversal of the ExplodedGraph to find a non-sink node.  We could write
2805   // this as a recursive function, but we don't want to risk blowing out the
2806   // stack for very long paths.
2807   BugReport *exampleReport = nullptr;
2808 
2809   for (; I != E; ++I) {
2810     const ExplodedNode *errorNode = I->getErrorNode();
2811 
2812     if (!errorNode)
2813       continue;
2814     if (errorNode->isSink()) {
2815       llvm_unreachable(
2816            "BugType::isSuppressSink() should not be 'true' for sink end nodes");
2817     }
2818     // No successors?  By definition this nodes isn't post-dominated by a sink.
2819     if (errorNode->succ_empty()) {
2820       bugReports.push_back(&*I);
2821       if (!exampleReport)
2822         exampleReport = &*I;
2823       continue;
2824     }
2825 
2826     // See if we are in a no-return CFG block. If so, treat this similarly
2827     // to being post-dominated by a sink. This works better when the analysis
2828     // is incomplete and we have never reached the no-return function call(s)
2829     // that we'd inevitably bump into on this path.
2830     if (const CFGBlock *ErrorB = errorNode->getCFGBlock())
2831       if (ErrorB->isInevitablySinking())
2832         continue;
2833 
2834     // At this point we know that 'N' is not a sink and it has at least one
2835     // successor.  Use a DFS worklist to find a non-sink end-of-path node.
2836     using WLItem = FRIEC_WLItem;
2837     using DFSWorkList = SmallVector<WLItem, 10>;
2838 
2839     llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
2840 
2841     DFSWorkList WL;
2842     WL.push_back(errorNode);
2843     Visited[errorNode] = 1;
2844 
2845     while (!WL.empty()) {
2846       WLItem &WI = WL.back();
2847       assert(!WI.N->succ_empty());
2848 
2849       for (; WI.I != WI.E; ++WI.I) {
2850         const ExplodedNode *Succ = *WI.I;
2851         // End-of-path node?
2852         if (Succ->succ_empty()) {
2853           // If we found an end-of-path node that is not a sink.
2854           if (!Succ->isSink()) {
2855             bugReports.push_back(&*I);
2856             if (!exampleReport)
2857               exampleReport = &*I;
2858             WL.clear();
2859             break;
2860           }
2861           // Found a sink?  Continue on to the next successor.
2862           continue;
2863         }
2864         // Mark the successor as visited.  If it hasn't been explored,
2865         // enqueue it to the DFS worklist.
2866         unsigned &mark = Visited[Succ];
2867         if (!mark) {
2868           mark = 1;
2869           WL.push_back(Succ);
2870           break;
2871         }
2872       }
2873 
2874       // The worklist may have been cleared at this point.  First
2875       // check if it is empty before checking the last item.
2876       if (!WL.empty() && &WL.back() == &WI)
2877         WL.pop_back();
2878     }
2879   }
2880 
2881   // ExampleReport will be NULL if all the nodes in the equivalence class
2882   // were post-dominated by sinks.
2883   return exampleReport;
2884 }
2885 
2886 void BugReporter::FlushReport(BugReportEquivClass& EQ) {
2887   SmallVector<BugReport*, 10> bugReports;
2888   BugReport *report = FindReportInEquivalenceClass(EQ, bugReports);
2889   if (!report)
2890     return;
2891 
2892   ArrayRef<PathDiagnosticConsumer*> Consumers = getPathDiagnosticConsumers();
2893   std::unique_ptr<DiagnosticForConsumerMapTy> Diagnostics =
2894       generateDiagnosticForConsumerMap(report, Consumers, bugReports);
2895 
2896   for (auto &P : *Diagnostics) {
2897     PathDiagnosticConsumer *Consumer = P.first;
2898     std::unique_ptr<PathDiagnostic> &PD = P.second;
2899 
2900     // If the path is empty, generate a single step path with the location
2901     // of the issue.
2902     if (PD->path.empty()) {
2903       PathDiagnosticLocation L = report->getLocation(getSourceManager());
2904       auto piece = std::make_unique<PathDiagnosticEventPiece>(
2905         L, report->getDescription());
2906       for (SourceRange Range : report->getRanges())
2907         piece->addRange(Range);
2908       PD->setEndOfPath(std::move(piece));
2909     }
2910 
2911     PathPieces &Pieces = PD->getMutablePieces();
2912     if (getAnalyzerOptions().ShouldDisplayNotesAsEvents) {
2913       // For path diagnostic consumers that don't support extra notes,
2914       // we may optionally convert those to path notes.
2915       for (auto I = report->getNotes().rbegin(),
2916            E = report->getNotes().rend(); I != E; ++I) {
2917         PathDiagnosticNotePiece *Piece = I->get();
2918         auto ConvertedPiece = std::make_shared<PathDiagnosticEventPiece>(
2919           Piece->getLocation(), Piece->getString());
2920         for (const auto &R: Piece->getRanges())
2921           ConvertedPiece->addRange(R);
2922 
2923         Pieces.push_front(std::move(ConvertedPiece));
2924       }
2925     } else {
2926       for (auto I = report->getNotes().rbegin(),
2927            E = report->getNotes().rend(); I != E; ++I)
2928         Pieces.push_front(*I);
2929     }
2930 
2931     updateExecutedLinesWithDiagnosticPieces(*PD);
2932     Consumer->HandlePathDiagnostic(std::move(PD));
2933   }
2934 }
2935 
2936 /// Insert all lines participating in the function signature \p Signature
2937 /// into \p ExecutedLines.
2938 static void populateExecutedLinesWithFunctionSignature(
2939     const Decl *Signature, const SourceManager &SM,
2940     FilesToLineNumsMap &ExecutedLines) {
2941   SourceRange SignatureSourceRange;
2942   const Stmt* Body = Signature->getBody();
2943   if (const auto FD = dyn_cast<FunctionDecl>(Signature)) {
2944     SignatureSourceRange = FD->getSourceRange();
2945   } else if (const auto OD = dyn_cast<ObjCMethodDecl>(Signature)) {
2946     SignatureSourceRange = OD->getSourceRange();
2947   } else {
2948     return;
2949   }
2950   SourceLocation Start = SignatureSourceRange.getBegin();
2951   SourceLocation End = Body ? Body->getSourceRange().getBegin()
2952     : SignatureSourceRange.getEnd();
2953   if (!Start.isValid() || !End.isValid())
2954     return;
2955   unsigned StartLine = SM.getExpansionLineNumber(Start);
2956   unsigned EndLine = SM.getExpansionLineNumber(End);
2957 
2958   FileID FID = SM.getFileID(SM.getExpansionLoc(Start));
2959   for (unsigned Line = StartLine; Line <= EndLine; Line++)
2960     ExecutedLines[FID].insert(Line);
2961 }
2962 
2963 static void populateExecutedLinesWithStmt(
2964     const Stmt *S, const SourceManager &SM,
2965     FilesToLineNumsMap &ExecutedLines) {
2966   SourceLocation Loc = S->getSourceRange().getBegin();
2967   if (!Loc.isValid())
2968     return;
2969   SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
2970   FileID FID = SM.getFileID(ExpansionLoc);
2971   unsigned LineNo = SM.getExpansionLineNumber(ExpansionLoc);
2972   ExecutedLines[FID].insert(LineNo);
2973 }
2974 
2975 /// \return all executed lines including function signatures on the path
2976 /// starting from \p N.
2977 static std::unique_ptr<FilesToLineNumsMap>
2978 findExecutedLines(const SourceManager &SM, const ExplodedNode *N) {
2979   auto ExecutedLines = std::make_unique<FilesToLineNumsMap>();
2980 
2981   while (N) {
2982     if (N->getFirstPred() == nullptr) {
2983       // First node: show signature of the entrance point.
2984       const Decl *D = N->getLocationContext()->getDecl();
2985       populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
2986     } else if (auto CE = N->getLocationAs<CallEnter>()) {
2987       // Inlined function: show signature.
2988       const Decl* D = CE->getCalleeContext()->getDecl();
2989       populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
2990     } else if (const Stmt *S = PathDiagnosticLocation::getStmt(N)) {
2991       populateExecutedLinesWithStmt(S, SM, *ExecutedLines);
2992 
2993       // Show extra context for some parent kinds.
2994       const Stmt *P = N->getParentMap().getParent(S);
2995 
2996       // The path exploration can die before the node with the associated
2997       // return statement is generated, but we do want to show the whole
2998       // return.
2999       if (const auto *RS = dyn_cast_or_null<ReturnStmt>(P)) {
3000         populateExecutedLinesWithStmt(RS, SM, *ExecutedLines);
3001         P = N->getParentMap().getParent(RS);
3002       }
3003 
3004       if (P && (isa<SwitchCase>(P) || isa<LabelStmt>(P)))
3005         populateExecutedLinesWithStmt(P, SM, *ExecutedLines);
3006     }
3007 
3008     N = N->getFirstPred();
3009   }
3010   return ExecutedLines;
3011 }
3012 
3013 std::unique_ptr<DiagnosticForConsumerMapTy>
3014 BugReporter::generateDiagnosticForConsumerMap(
3015     BugReport *report, ArrayRef<PathDiagnosticConsumer *> consumers,
3016     ArrayRef<BugReport *> bugReports) {
3017 
3018   if (!report->isPathSensitive()) {
3019     auto Out = std::make_unique<DiagnosticForConsumerMapTy>();
3020     for (auto *Consumer : consumers)
3021       (*Out)[Consumer] = generateEmptyDiagnosticForReport(report,
3022                                                           getSourceManager());
3023     return Out;
3024   }
3025 
3026   // Generate the full path sensitive diagnostic, using the generation scheme
3027   // specified by the PathDiagnosticConsumer. Note that we have to generate
3028   // path diagnostics even for consumers which do not support paths, because
3029   // the BugReporterVisitors may mark this bug as a false positive.
3030   assert(!bugReports.empty());
3031   MaxBugClassSize.updateMax(bugReports.size());
3032   std::unique_ptr<DiagnosticForConsumerMapTy> Out =
3033     generatePathDiagnostics(consumers, bugReports);
3034 
3035   if (Out->empty())
3036     return Out;
3037 
3038   MaxValidBugClassSize.updateMax(bugReports.size());
3039 
3040   // Examine the report and see if the last piece is in a header. Reset the
3041   // report location to the last piece in the main source file.
3042   const AnalyzerOptions &Opts = getAnalyzerOptions();
3043   for (auto const &P : *Out)
3044     if (Opts.ShouldReportIssuesInMainSourceFile && !Opts.AnalyzeAll)
3045       P.second->resetDiagnosticLocationToMainFile();
3046 
3047   return Out;
3048 }
3049 
3050 void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
3051                                   const CheckerBase *Checker,
3052                                   StringRef Name, StringRef Category,
3053                                   StringRef Str, PathDiagnosticLocation Loc,
3054                                   ArrayRef<SourceRange> Ranges) {
3055   EmitBasicReport(DeclWithIssue, Checker->getCheckName(), Name, Category, Str,
3056                   Loc, Ranges);
3057 }
3058 
3059 void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
3060                                   CheckName CheckName,
3061                                   StringRef name, StringRef category,
3062                                   StringRef str, PathDiagnosticLocation Loc,
3063                                   ArrayRef<SourceRange> Ranges) {
3064   // 'BT' is owned by BugReporter.
3065   BugType *BT = getBugTypeForName(CheckName, name, category);
3066   auto R = std::make_unique<BugReport>(*BT, str, Loc);
3067   R->setDeclWithIssue(DeclWithIssue);
3068   for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
3069        I != E; ++I)
3070     R->addRange(*I);
3071   emitReport(std::move(R));
3072 }
3073 
3074 BugType *BugReporter::getBugTypeForName(CheckName CheckName, StringRef name,
3075                                         StringRef category) {
3076   SmallString<136> fullDesc;
3077   llvm::raw_svector_ostream(fullDesc) << CheckName.getName() << ":" << name
3078                                       << ":" << category;
3079   BugType *&BT = StrBugTypes[fullDesc];
3080   if (!BT)
3081     BT = new BugType(CheckName, name, category);
3082   return BT;
3083 }
3084