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 llvm::StringLiteral StrEnteringLoop = "Entering loop body";
1064 llvm::StringLiteral StrLoopBodyZero = "Loop body executed 0 times";
1065 llvm::StringLiteral StrLoopRangeEmpty = "Loop body skipped when range is empty";
1066 llvm::StringLiteral StrLoopCollectionEmpty =
1067     "Loop body skipped when collection is empty";
1068 
1069 static std::unique_ptr<FilesToLineNumsMap>
1070 findExecutedLines(const SourceManager &SM, const ExplodedNode *N);
1071 
1072 void PathDiagnosticBuilder::generatePathDiagnosticsForNode(
1073     PathDiagnosticConstruct &C, PathDiagnosticLocation &PrevLoc) const {
1074   ProgramPoint P = C.getCurrentNode()->getLocation();
1075   const SourceManager &SM = getSourceManager();
1076 
1077   // Have we encountered an entrance to a call?  It may be
1078   // the case that we have not encountered a matching
1079   // call exit before this point.  This means that the path
1080   // terminated within the call itself.
1081   if (auto CE = P.getAs<CallEnter>()) {
1082 
1083     if (C.shouldAddPathEdges()) {
1084       // Add an edge to the start of the function.
1085       const StackFrameContext *CalleeLC = CE->getCalleeContext();
1086       const Decl *D = CalleeLC->getDecl();
1087       // Add the edge only when the callee has body. We jump to the beginning
1088       // of the *declaration*, however we expect it to be followed by the
1089       // body. This isn't the case for autosynthesized property accessors in
1090       // Objective-C. No need for a similar extra check for CallExit points
1091       // because the exit edge comes from a statement (i.e. return),
1092       // not from declaration.
1093       if (D->hasBody())
1094         addEdgeToPath(C.getActivePath(), PrevLoc,
1095                       PathDiagnosticLocation::createBegin(D, SM));
1096     }
1097 
1098     // Did we visit an entire call?
1099     bool VisitedEntireCall = C.PD->isWithinCall();
1100     C.PD->popActivePath();
1101 
1102     PathDiagnosticCallPiece *Call;
1103     if (VisitedEntireCall) {
1104       Call = cast<PathDiagnosticCallPiece>(C.getActivePath().front().get());
1105     } else {
1106       // The path terminated within a nested location context, create a new
1107       // call piece to encapsulate the rest of the path pieces.
1108       const Decl *Caller = CE->getLocationContext()->getDecl();
1109       Call = PathDiagnosticCallPiece::construct(C.getActivePath(), Caller);
1110       assert(C.getActivePath().size() == 1 &&
1111              C.getActivePath().front().get() == Call);
1112 
1113       // Since we just transferred the path over to the call piece, reset the
1114       // mapping of the active path to the current location context.
1115       assert(C.isInLocCtxMap(&C.getActivePath()) &&
1116              "When we ascend to a previously unvisited call, the active path's "
1117              "address shouldn't change, but rather should be compacted into "
1118              "a single CallEvent!");
1119       C.updateLocCtxMap(&C.getActivePath(), C.getCurrLocationContext());
1120 
1121       // Record the location context mapping for the path within the call.
1122       assert(!C.isInLocCtxMap(&Call->path) &&
1123              "When we ascend to a previously unvisited call, this must be the "
1124              "first time we encounter the caller context!");
1125       C.updateLocCtxMap(&Call->path, CE->getCalleeContext());
1126     }
1127     Call->setCallee(*CE, SM);
1128 
1129     // Update the previous location in the active path.
1130     PrevLoc = Call->getLocation();
1131 
1132     if (!C.CallStack.empty()) {
1133       assert(C.CallStack.back().first == Call);
1134       C.CallStack.pop_back();
1135     }
1136     return;
1137   }
1138 
1139   assert(C.getCurrLocationContext() == C.getLocationContextForActivePath() &&
1140          "The current position in the bug path is out of sync with the "
1141          "location context associated with the active path!");
1142 
1143   // Have we encountered an exit from a function call?
1144   if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
1145 
1146     // We are descending into a call (backwards).  Construct
1147     // a new call piece to contain the path pieces for that call.
1148     auto Call = PathDiagnosticCallPiece::construct(*CE, SM);
1149     // Record the mapping from call piece to LocationContext.
1150     assert(!C.isInLocCtxMap(&Call->path) &&
1151            "We just entered a call, this must've been the first time we "
1152            "encounter its context!");
1153     C.updateLocCtxMap(&Call->path, CE->getCalleeContext());
1154 
1155     if (C.shouldAddPathEdges()) {
1156       // Add the edge to the return site.
1157       addEdgeToPath(C.getActivePath(), PrevLoc, Call->callReturn);
1158       PrevLoc.invalidate();
1159     }
1160 
1161     auto *P = Call.get();
1162     C.getActivePath().push_front(std::move(Call));
1163 
1164     // Make the contents of the call the active path for now.
1165     C.PD->pushActivePath(&P->path);
1166     C.CallStack.push_back(CallWithEntry(P, C.getCurrentNode()));
1167     return;
1168   }
1169 
1170   if (auto PS = P.getAs<PostStmt>()) {
1171     if (!C.shouldAddPathEdges())
1172       return;
1173 
1174     // Add an edge.  If this is an ObjCForCollectionStmt do
1175     // not add an edge here as it appears in the CFG both
1176     // as a terminator and as a terminator condition.
1177     if (!isa<ObjCForCollectionStmt>(PS->getStmt())) {
1178       PathDiagnosticLocation L =
1179           PathDiagnosticLocation(PS->getStmt(), SM, C.getCurrLocationContext());
1180       addEdgeToPath(C.getActivePath(), PrevLoc, L);
1181     }
1182 
1183   } else if (auto BE = P.getAs<BlockEdge>()) {
1184 
1185     if (!C.shouldAddPathEdges()) {
1186       generateMinimalDiagForBlockEdge(C, *BE);
1187       return;
1188     }
1189 
1190     // Are we jumping to the head of a loop?  Add a special diagnostic.
1191     if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
1192       PathDiagnosticLocation L(Loop, SM, C.getCurrLocationContext());
1193       const Stmt *Body = nullptr;
1194 
1195       if (const auto *FS = dyn_cast<ForStmt>(Loop))
1196         Body = FS->getBody();
1197       else if (const auto *WS = dyn_cast<WhileStmt>(Loop))
1198         Body = WS->getBody();
1199       else if (const auto *OFS = dyn_cast<ObjCForCollectionStmt>(Loop)) {
1200         Body = OFS->getBody();
1201       } else if (const auto *FRS = dyn_cast<CXXForRangeStmt>(Loop)) {
1202         Body = FRS->getBody();
1203       }
1204       // do-while statements are explicitly excluded here
1205 
1206       auto p = std::make_shared<PathDiagnosticEventPiece>(
1207           L, "Looping back to the head "
1208           "of the loop");
1209       p->setPrunable(true);
1210 
1211       addEdgeToPath(C.getActivePath(), PrevLoc, p->getLocation());
1212       C.getActivePath().push_front(std::move(p));
1213 
1214       if (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
1215         addEdgeToPath(C.getActivePath(), PrevLoc,
1216                       PathDiagnosticLocation::createEndBrace(CS, SM));
1217       }
1218     }
1219 
1220     const CFGBlock *BSrc = BE->getSrc();
1221     const ParentMap &PM = C.getParentMap();
1222 
1223     if (const Stmt *Term = BSrc->getTerminatorStmt()) {
1224       // Are we jumping past the loop body without ever executing the
1225       // loop (because the condition was false)?
1226       if (isLoop(Term)) {
1227         const Stmt *TermCond = getTerminatorCondition(BSrc);
1228         bool IsInLoopBody = isInLoopBody(
1229             PM, getStmtBeforeCond(PM, TermCond, C.getCurrentNode()), Term);
1230 
1231         StringRef str;
1232 
1233         if (isJumpToFalseBranch(&*BE)) {
1234           if (!IsInLoopBody) {
1235             if (isa<ObjCForCollectionStmt>(Term)) {
1236               str = StrLoopCollectionEmpty;
1237             } else if (isa<CXXForRangeStmt>(Term)) {
1238               str = StrLoopRangeEmpty;
1239             } else {
1240               str = StrLoopBodyZero;
1241             }
1242           }
1243         } else {
1244           str = StrEnteringLoop;
1245         }
1246 
1247         if (!str.empty()) {
1248           PathDiagnosticLocation L(TermCond ? TermCond : Term, SM,
1249                                    C.getCurrLocationContext());
1250           auto PE = std::make_shared<PathDiagnosticEventPiece>(L, str);
1251           PE->setPrunable(true);
1252           addEdgeToPath(C.getActivePath(), PrevLoc, PE->getLocation());
1253           C.getActivePath().push_front(std::move(PE));
1254         }
1255       } else if (isa<BreakStmt>(Term) || isa<ContinueStmt>(Term) ||
1256           isa<GotoStmt>(Term)) {
1257         PathDiagnosticLocation L(Term, SM, C.getCurrLocationContext());
1258         addEdgeToPath(C.getActivePath(), PrevLoc, L);
1259       }
1260     }
1261   }
1262 }
1263 
1264 static std::unique_ptr<PathDiagnostic>
1265 generateEmptyDiagnosticForReport(const BugReport *R, const SourceManager &SM) {
1266   const BugType &BT = R->getBugType();
1267   return std::make_unique<PathDiagnostic>(
1268       R->getBugType().getCheckName(), R->getDeclWithIssue(),
1269       R->getBugType().getName(), R->getDescription(),
1270       R->getShortDescription(/*UseFallback=*/false), BT.getCategory(),
1271       R->getUniqueingLocation(), R->getUniqueingDecl(),
1272       findExecutedLines(SM, R->getErrorNode()));
1273 }
1274 
1275 static const Stmt *getStmtParent(const Stmt *S, const ParentMap &PM) {
1276   if (!S)
1277     return nullptr;
1278 
1279   while (true) {
1280     S = PM.getParentIgnoreParens(S);
1281 
1282     if (!S)
1283       break;
1284 
1285     if (isa<FullExpr>(S) ||
1286         isa<CXXBindTemporaryExpr>(S) ||
1287         isa<SubstNonTypeTemplateParmExpr>(S))
1288       continue;
1289 
1290     break;
1291   }
1292 
1293   return S;
1294 }
1295 
1296 static bool isConditionForTerminator(const Stmt *S, const Stmt *Cond) {
1297   switch (S->getStmtClass()) {
1298     case Stmt::BinaryOperatorClass: {
1299       const auto *BO = cast<BinaryOperator>(S);
1300       if (!BO->isLogicalOp())
1301         return false;
1302       return BO->getLHS() == Cond || BO->getRHS() == Cond;
1303     }
1304     case Stmt::IfStmtClass:
1305       return cast<IfStmt>(S)->getCond() == Cond;
1306     case Stmt::ForStmtClass:
1307       return cast<ForStmt>(S)->getCond() == Cond;
1308     case Stmt::WhileStmtClass:
1309       return cast<WhileStmt>(S)->getCond() == Cond;
1310     case Stmt::DoStmtClass:
1311       return cast<DoStmt>(S)->getCond() == Cond;
1312     case Stmt::ChooseExprClass:
1313       return cast<ChooseExpr>(S)->getCond() == Cond;
1314     case Stmt::IndirectGotoStmtClass:
1315       return cast<IndirectGotoStmt>(S)->getTarget() == Cond;
1316     case Stmt::SwitchStmtClass:
1317       return cast<SwitchStmt>(S)->getCond() == Cond;
1318     case Stmt::BinaryConditionalOperatorClass:
1319       return cast<BinaryConditionalOperator>(S)->getCond() == Cond;
1320     case Stmt::ConditionalOperatorClass: {
1321       const auto *CO = cast<ConditionalOperator>(S);
1322       return CO->getCond() == Cond ||
1323              CO->getLHS() == Cond ||
1324              CO->getRHS() == Cond;
1325     }
1326     case Stmt::ObjCForCollectionStmtClass:
1327       return cast<ObjCForCollectionStmt>(S)->getElement() == Cond;
1328     case Stmt::CXXForRangeStmtClass: {
1329       const auto *FRS = cast<CXXForRangeStmt>(S);
1330       return FRS->getCond() == Cond || FRS->getRangeInit() == Cond;
1331     }
1332     default:
1333       return false;
1334   }
1335 }
1336 
1337 static bool isIncrementOrInitInForLoop(const Stmt *S, const Stmt *FL) {
1338   if (const auto *FS = dyn_cast<ForStmt>(FL))
1339     return FS->getInc() == S || FS->getInit() == S;
1340   if (const auto *FRS = dyn_cast<CXXForRangeStmt>(FL))
1341     return FRS->getInc() == S || FRS->getRangeStmt() == S ||
1342            FRS->getLoopVarStmt() || FRS->getRangeInit() == S;
1343   return false;
1344 }
1345 
1346 using OptimizedCallsSet = llvm::DenseSet<const PathDiagnosticCallPiece *>;
1347 
1348 /// Adds synthetic edges from top-level statements to their subexpressions.
1349 ///
1350 /// This avoids a "swoosh" effect, where an edge from a top-level statement A
1351 /// points to a sub-expression B.1 that's not at the start of B. In these cases,
1352 /// we'd like to see an edge from A to B, then another one from B to B.1.
1353 static void addContextEdges(PathPieces &pieces, const LocationContext *LC) {
1354   const ParentMap &PM = LC->getParentMap();
1355   PathPieces::iterator Prev = pieces.end();
1356   for (PathPieces::iterator I = pieces.begin(), E = Prev; I != E;
1357        Prev = I, ++I) {
1358     auto *Piece = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1359 
1360     if (!Piece)
1361       continue;
1362 
1363     PathDiagnosticLocation SrcLoc = Piece->getStartLocation();
1364     SmallVector<PathDiagnosticLocation, 4> SrcContexts;
1365 
1366     PathDiagnosticLocation NextSrcContext = SrcLoc;
1367     const Stmt *InnerStmt = nullptr;
1368     while (NextSrcContext.isValid() && NextSrcContext.asStmt() != InnerStmt) {
1369       SrcContexts.push_back(NextSrcContext);
1370       InnerStmt = NextSrcContext.asStmt();
1371       NextSrcContext = getEnclosingStmtLocation(InnerStmt, LC,
1372                                                 /*allowNested=*/true);
1373     }
1374 
1375     // Repeatedly split the edge as necessary.
1376     // This is important for nested logical expressions (||, &&, ?:) where we
1377     // want to show all the levels of context.
1378     while (true) {
1379       const Stmt *Dst = Piece->getEndLocation().getStmtOrNull();
1380 
1381       // We are looking at an edge. Is the destination within a larger
1382       // expression?
1383       PathDiagnosticLocation DstContext =
1384           getEnclosingStmtLocation(Dst, LC, /*allowNested=*/true);
1385       if (!DstContext.isValid() || DstContext.asStmt() == Dst)
1386         break;
1387 
1388       // If the source is in the same context, we're already good.
1389       if (llvm::find(SrcContexts, DstContext) != SrcContexts.end())
1390         break;
1391 
1392       // Update the subexpression node to point to the context edge.
1393       Piece->setStartLocation(DstContext);
1394 
1395       // Try to extend the previous edge if it's at the same level as the source
1396       // context.
1397       if (Prev != E) {
1398         auto *PrevPiece = dyn_cast<PathDiagnosticControlFlowPiece>(Prev->get());
1399 
1400         if (PrevPiece) {
1401           if (const Stmt *PrevSrc =
1402                   PrevPiece->getStartLocation().getStmtOrNull()) {
1403             const Stmt *PrevSrcParent = getStmtParent(PrevSrc, PM);
1404             if (PrevSrcParent ==
1405                 getStmtParent(DstContext.getStmtOrNull(), PM)) {
1406               PrevPiece->setEndLocation(DstContext);
1407               break;
1408             }
1409           }
1410         }
1411       }
1412 
1413       // Otherwise, split the current edge into a context edge and a
1414       // subexpression edge. Note that the context statement may itself have
1415       // context.
1416       auto P =
1417           std::make_shared<PathDiagnosticControlFlowPiece>(SrcLoc, DstContext);
1418       Piece = P.get();
1419       I = pieces.insert(I, std::move(P));
1420     }
1421   }
1422 }
1423 
1424 /// Move edges from a branch condition to a branch target
1425 ///        when the condition is simple.
1426 ///
1427 /// This restructures some of the work of addContextEdges.  That function
1428 /// creates edges this may destroy, but they work together to create a more
1429 /// aesthetically set of edges around branches.  After the call to
1430 /// addContextEdges, we may have (1) an edge to the branch, (2) an edge from
1431 /// the branch to the branch condition, and (3) an edge from the branch
1432 /// condition to the branch target.  We keep (1), but may wish to remove (2)
1433 /// and move the source of (3) to the branch if the branch condition is simple.
1434 static void simplifySimpleBranches(PathPieces &pieces) {
1435   for (PathPieces::iterator I = pieces.begin(), E = pieces.end(); I != E; ++I) {
1436     const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1437 
1438     if (!PieceI)
1439       continue;
1440 
1441     const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
1442     const Stmt *s1End   = PieceI->getEndLocation().getStmtOrNull();
1443 
1444     if (!s1Start || !s1End)
1445       continue;
1446 
1447     PathPieces::iterator NextI = I; ++NextI;
1448     if (NextI == E)
1449       break;
1450 
1451     PathDiagnosticControlFlowPiece *PieceNextI = nullptr;
1452 
1453     while (true) {
1454       if (NextI == E)
1455         break;
1456 
1457       const auto *EV = dyn_cast<PathDiagnosticEventPiece>(NextI->get());
1458       if (EV) {
1459         StringRef S = EV->getString();
1460         if (S == StrEnteringLoop || S == StrLoopBodyZero ||
1461             S == StrLoopCollectionEmpty || S == StrLoopRangeEmpty) {
1462           ++NextI;
1463           continue;
1464         }
1465         break;
1466       }
1467 
1468       PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
1469       break;
1470     }
1471 
1472     if (!PieceNextI)
1473       continue;
1474 
1475     const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
1476     const Stmt *s2End   = PieceNextI->getEndLocation().getStmtOrNull();
1477 
1478     if (!s2Start || !s2End || s1End != s2Start)
1479       continue;
1480 
1481     // We only perform this transformation for specific branch kinds.
1482     // We don't want to do this for do..while, for example.
1483     if (!(isa<ForStmt>(s1Start) || isa<WhileStmt>(s1Start) ||
1484           isa<IfStmt>(s1Start) || isa<ObjCForCollectionStmt>(s1Start) ||
1485           isa<CXXForRangeStmt>(s1Start)))
1486       continue;
1487 
1488     // Is s1End the branch condition?
1489     if (!isConditionForTerminator(s1Start, s1End))
1490       continue;
1491 
1492     // Perform the hoisting by eliminating (2) and changing the start
1493     // location of (3).
1494     PieceNextI->setStartLocation(PieceI->getStartLocation());
1495     I = pieces.erase(I);
1496   }
1497 }
1498 
1499 /// Returns the number of bytes in the given (character-based) SourceRange.
1500 ///
1501 /// If the locations in the range are not on the same line, returns None.
1502 ///
1503 /// Note that this does not do a precise user-visible character or column count.
1504 static Optional<size_t> getLengthOnSingleLine(const SourceManager &SM,
1505                                               SourceRange Range) {
1506   SourceRange ExpansionRange(SM.getExpansionLoc(Range.getBegin()),
1507                              SM.getExpansionRange(Range.getEnd()).getEnd());
1508 
1509   FileID FID = SM.getFileID(ExpansionRange.getBegin());
1510   if (FID != SM.getFileID(ExpansionRange.getEnd()))
1511     return None;
1512 
1513   bool Invalid;
1514   const llvm::MemoryBuffer *Buffer = SM.getBuffer(FID, &Invalid);
1515   if (Invalid)
1516     return None;
1517 
1518   unsigned BeginOffset = SM.getFileOffset(ExpansionRange.getBegin());
1519   unsigned EndOffset = SM.getFileOffset(ExpansionRange.getEnd());
1520   StringRef Snippet = Buffer->getBuffer().slice(BeginOffset, EndOffset);
1521 
1522   // We're searching the raw bytes of the buffer here, which might include
1523   // escaped newlines and such. That's okay; we're trying to decide whether the
1524   // SourceRange is covering a large or small amount of space in the user's
1525   // editor.
1526   if (Snippet.find_first_of("\r\n") != StringRef::npos)
1527     return None;
1528 
1529   // This isn't Unicode-aware, but it doesn't need to be.
1530   return Snippet.size();
1531 }
1532 
1533 /// \sa getLengthOnSingleLine(SourceManager, SourceRange)
1534 static Optional<size_t> getLengthOnSingleLine(const SourceManager &SM,
1535                                               const Stmt *S) {
1536   return getLengthOnSingleLine(SM, S->getSourceRange());
1537 }
1538 
1539 /// Eliminate two-edge cycles created by addContextEdges().
1540 ///
1541 /// Once all the context edges are in place, there are plenty of cases where
1542 /// there's a single edge from a top-level statement to a subexpression,
1543 /// followed by a single path note, and then a reverse edge to get back out to
1544 /// the top level. If the statement is simple enough, the subexpression edges
1545 /// just add noise and make it harder to understand what's going on.
1546 ///
1547 /// This function only removes edges in pairs, because removing only one edge
1548 /// might leave other edges dangling.
1549 ///
1550 /// This will not remove edges in more complicated situations:
1551 /// - if there is more than one "hop" leading to or from a subexpression.
1552 /// - if there is an inlined call between the edges instead of a single event.
1553 /// - if the whole statement is large enough that having subexpression arrows
1554 ///   might be helpful.
1555 static void removeContextCycles(PathPieces &Path, const SourceManager &SM) {
1556   for (PathPieces::iterator I = Path.begin(), E = Path.end(); I != E; ) {
1557     // Pattern match the current piece and its successor.
1558     const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1559 
1560     if (!PieceI) {
1561       ++I;
1562       continue;
1563     }
1564 
1565     const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
1566     const Stmt *s1End   = PieceI->getEndLocation().getStmtOrNull();
1567 
1568     PathPieces::iterator NextI = I; ++NextI;
1569     if (NextI == E)
1570       break;
1571 
1572     const auto *PieceNextI =
1573         dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
1574 
1575     if (!PieceNextI) {
1576       if (isa<PathDiagnosticEventPiece>(NextI->get())) {
1577         ++NextI;
1578         if (NextI == E)
1579           break;
1580         PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
1581       }
1582 
1583       if (!PieceNextI) {
1584         ++I;
1585         continue;
1586       }
1587     }
1588 
1589     const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
1590     const Stmt *s2End   = PieceNextI->getEndLocation().getStmtOrNull();
1591 
1592     if (s1Start && s2Start && s1Start == s2End && s2Start == s1End) {
1593       const size_t MAX_SHORT_LINE_LENGTH = 80;
1594       Optional<size_t> s1Length = getLengthOnSingleLine(SM, s1Start);
1595       if (s1Length && *s1Length <= MAX_SHORT_LINE_LENGTH) {
1596         Optional<size_t> s2Length = getLengthOnSingleLine(SM, s2Start);
1597         if (s2Length && *s2Length <= MAX_SHORT_LINE_LENGTH) {
1598           Path.erase(I);
1599           I = Path.erase(NextI);
1600           continue;
1601         }
1602       }
1603     }
1604 
1605     ++I;
1606   }
1607 }
1608 
1609 /// Return true if X is contained by Y.
1610 static bool lexicalContains(const ParentMap &PM, const Stmt *X, const Stmt *Y) {
1611   while (X) {
1612     if (X == Y)
1613       return true;
1614     X = PM.getParent(X);
1615   }
1616   return false;
1617 }
1618 
1619 // Remove short edges on the same line less than 3 columns in difference.
1620 static void removePunyEdges(PathPieces &path, const SourceManager &SM,
1621                             const ParentMap &PM) {
1622   bool erased = false;
1623 
1624   for (PathPieces::iterator I = path.begin(), E = path.end(); I != E;
1625        erased ? I : ++I) {
1626     erased = false;
1627 
1628     const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1629 
1630     if (!PieceI)
1631       continue;
1632 
1633     const Stmt *start = PieceI->getStartLocation().getStmtOrNull();
1634     const Stmt *end   = PieceI->getEndLocation().getStmtOrNull();
1635 
1636     if (!start || !end)
1637       continue;
1638 
1639     const Stmt *endParent = PM.getParent(end);
1640     if (!endParent)
1641       continue;
1642 
1643     if (isConditionForTerminator(end, endParent))
1644       continue;
1645 
1646     SourceLocation FirstLoc = start->getBeginLoc();
1647     SourceLocation SecondLoc = end->getBeginLoc();
1648 
1649     if (!SM.isWrittenInSameFile(FirstLoc, SecondLoc))
1650       continue;
1651     if (SM.isBeforeInTranslationUnit(SecondLoc, FirstLoc))
1652       std::swap(SecondLoc, FirstLoc);
1653 
1654     SourceRange EdgeRange(FirstLoc, SecondLoc);
1655     Optional<size_t> ByteWidth = getLengthOnSingleLine(SM, EdgeRange);
1656 
1657     // If the statements are on different lines, continue.
1658     if (!ByteWidth)
1659       continue;
1660 
1661     const size_t MAX_PUNY_EDGE_LENGTH = 2;
1662     if (*ByteWidth <= MAX_PUNY_EDGE_LENGTH) {
1663       // FIXME: There are enough /bytes/ between the endpoints of the edge, but
1664       // there might not be enough /columns/. A proper user-visible column count
1665       // is probably too expensive, though.
1666       I = path.erase(I);
1667       erased = true;
1668       continue;
1669     }
1670   }
1671 }
1672 
1673 static void removeIdenticalEvents(PathPieces &path) {
1674   for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ++I) {
1675     const auto *PieceI = dyn_cast<PathDiagnosticEventPiece>(I->get());
1676 
1677     if (!PieceI)
1678       continue;
1679 
1680     PathPieces::iterator NextI = I; ++NextI;
1681     if (NextI == E)
1682       return;
1683 
1684     const auto *PieceNextI = dyn_cast<PathDiagnosticEventPiece>(NextI->get());
1685 
1686     if (!PieceNextI)
1687       continue;
1688 
1689     // Erase the second piece if it has the same exact message text.
1690     if (PieceI->getString() == PieceNextI->getString()) {
1691       path.erase(NextI);
1692     }
1693   }
1694 }
1695 
1696 static bool optimizeEdges(const PathDiagnosticConstruct &C, PathPieces &path,
1697                           OptimizedCallsSet &OCS) {
1698   bool hasChanges = false;
1699   const LocationContext *LC = C.getLocationContextFor(&path);
1700   assert(LC);
1701   const ParentMap &PM = LC->getParentMap();
1702   const SourceManager &SM = C.getSourceManager();
1703 
1704   for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ) {
1705     // Optimize subpaths.
1706     if (auto *CallI = dyn_cast<PathDiagnosticCallPiece>(I->get())) {
1707       // Record the fact that a call has been optimized so we only do the
1708       // effort once.
1709       if (!OCS.count(CallI)) {
1710         while (optimizeEdges(C, CallI->path, OCS)) {
1711         }
1712         OCS.insert(CallI);
1713       }
1714       ++I;
1715       continue;
1716     }
1717 
1718     // Pattern match the current piece and its successor.
1719     auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
1720 
1721     if (!PieceI) {
1722       ++I;
1723       continue;
1724     }
1725 
1726     const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
1727     const Stmt *s1End   = PieceI->getEndLocation().getStmtOrNull();
1728     const Stmt *level1 = getStmtParent(s1Start, PM);
1729     const Stmt *level2 = getStmtParent(s1End, PM);
1730 
1731     PathPieces::iterator NextI = I; ++NextI;
1732     if (NextI == E)
1733       break;
1734 
1735     const auto *PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
1736 
1737     if (!PieceNextI) {
1738       ++I;
1739       continue;
1740     }
1741 
1742     const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
1743     const Stmt *s2End   = PieceNextI->getEndLocation().getStmtOrNull();
1744     const Stmt *level3 = getStmtParent(s2Start, PM);
1745     const Stmt *level4 = getStmtParent(s2End, PM);
1746 
1747     // Rule I.
1748     //
1749     // If we have two consecutive control edges whose end/begin locations
1750     // are at the same level (e.g. statements or top-level expressions within
1751     // a compound statement, or siblings share a single ancestor expression),
1752     // then merge them if they have no interesting intermediate event.
1753     //
1754     // For example:
1755     //
1756     // (1.1 -> 1.2) -> (1.2 -> 1.3) becomes (1.1 -> 1.3) because the common
1757     // parent is '1'.  Here 'x.y.z' represents the hierarchy of statements.
1758     //
1759     // NOTE: this will be limited later in cases where we add barriers
1760     // to prevent this optimization.
1761     if (level1 && level1 == level2 && level1 == level3 && level1 == level4) {
1762       PieceI->setEndLocation(PieceNextI->getEndLocation());
1763       path.erase(NextI);
1764       hasChanges = true;
1765       continue;
1766     }
1767 
1768     // Rule II.
1769     //
1770     // Eliminate edges between subexpressions and parent expressions
1771     // when the subexpression is consumed.
1772     //
1773     // NOTE: this will be limited later in cases where we add barriers
1774     // to prevent this optimization.
1775     if (s1End && s1End == s2Start && level2) {
1776       bool removeEdge = false;
1777       // Remove edges into the increment or initialization of a
1778       // loop that have no interleaving event.  This means that
1779       // they aren't interesting.
1780       if (isIncrementOrInitInForLoop(s1End, level2))
1781         removeEdge = true;
1782       // Next only consider edges that are not anchored on
1783       // the condition of a terminator.  This are intermediate edges
1784       // that we might want to trim.
1785       else if (!isConditionForTerminator(level2, s1End)) {
1786         // Trim edges on expressions that are consumed by
1787         // the parent expression.
1788         if (isa<Expr>(s1End) && PM.isConsumedExpr(cast<Expr>(s1End))) {
1789           removeEdge = true;
1790         }
1791         // Trim edges where a lexical containment doesn't exist.
1792         // For example:
1793         //
1794         //  X -> Y -> Z
1795         //
1796         // If 'Z' lexically contains Y (it is an ancestor) and
1797         // 'X' does not lexically contain Y (it is a descendant OR
1798         // it has no lexical relationship at all) then trim.
1799         //
1800         // This can eliminate edges where we dive into a subexpression
1801         // and then pop back out, etc.
1802         else if (s1Start && s2End &&
1803                  lexicalContains(PM, s2Start, s2End) &&
1804                  !lexicalContains(PM, s1End, s1Start)) {
1805           removeEdge = true;
1806         }
1807         // Trim edges from a subexpression back to the top level if the
1808         // subexpression is on a different line.
1809         //
1810         // A.1 -> A -> B
1811         // becomes
1812         // A.1 -> B
1813         //
1814         // These edges just look ugly and don't usually add anything.
1815         else if (s1Start && s2End &&
1816                  lexicalContains(PM, s1Start, s1End)) {
1817           SourceRange EdgeRange(PieceI->getEndLocation().asLocation(),
1818                                 PieceI->getStartLocation().asLocation());
1819           if (!getLengthOnSingleLine(SM, EdgeRange).hasValue())
1820             removeEdge = true;
1821         }
1822       }
1823 
1824       if (removeEdge) {
1825         PieceI->setEndLocation(PieceNextI->getEndLocation());
1826         path.erase(NextI);
1827         hasChanges = true;
1828         continue;
1829       }
1830     }
1831 
1832     // Optimize edges for ObjC fast-enumeration loops.
1833     //
1834     // (X -> collection) -> (collection -> element)
1835     //
1836     // becomes:
1837     //
1838     // (X -> element)
1839     if (s1End == s2Start) {
1840       const auto *FS = dyn_cast_or_null<ObjCForCollectionStmt>(level3);
1841       if (FS && FS->getCollection()->IgnoreParens() == s2Start &&
1842           s2End == FS->getElement()) {
1843         PieceI->setEndLocation(PieceNextI->getEndLocation());
1844         path.erase(NextI);
1845         hasChanges = true;
1846         continue;
1847       }
1848     }
1849 
1850     // No changes at this index?  Move to the next one.
1851     ++I;
1852   }
1853 
1854   if (!hasChanges) {
1855     // Adjust edges into subexpressions to make them more uniform
1856     // and aesthetically pleasing.
1857     addContextEdges(path, LC);
1858     // Remove "cyclical" edges that include one or more context edges.
1859     removeContextCycles(path, SM);
1860     // Hoist edges originating from branch conditions to branches
1861     // for simple branches.
1862     simplifySimpleBranches(path);
1863     // Remove any puny edges left over after primary optimization pass.
1864     removePunyEdges(path, SM, PM);
1865     // Remove identical events.
1866     removeIdenticalEvents(path);
1867   }
1868 
1869   return hasChanges;
1870 }
1871 
1872 /// Drop the very first edge in a path, which should be a function entry edge.
1873 ///
1874 /// If the first edge is not a function entry edge (say, because the first
1875 /// statement had an invalid source location), this function does nothing.
1876 // FIXME: We should just generate invalid edges anyway and have the optimizer
1877 // deal with them.
1878 static void dropFunctionEntryEdge(const PathDiagnosticConstruct &C,
1879                                   PathPieces &Path) {
1880   const auto *FirstEdge =
1881       dyn_cast<PathDiagnosticControlFlowPiece>(Path.front().get());
1882   if (!FirstEdge)
1883     return;
1884 
1885   const Decl *D = C.getLocationContextFor(&Path)->getDecl();
1886   PathDiagnosticLocation EntryLoc =
1887       PathDiagnosticLocation::createBegin(D, C.getSourceManager());
1888   if (FirstEdge->getStartLocation() != EntryLoc)
1889     return;
1890 
1891   Path.pop_front();
1892 }
1893 
1894 /// Populate executes lines with lines containing at least one diagnostics.
1895 static void updateExecutedLinesWithDiagnosticPieces(PathDiagnostic &PD) {
1896 
1897   PathPieces path = PD.path.flatten(/*ShouldFlattenMacros=*/true);
1898   FilesToLineNumsMap &ExecutedLines = PD.getExecutedLines();
1899 
1900   for (const auto &P : path) {
1901     FullSourceLoc Loc = P->getLocation().asLocation().getExpansionLoc();
1902     FileID FID = Loc.getFileID();
1903     unsigned LineNo = Loc.getLineNumber();
1904     assert(FID.isValid());
1905     ExecutedLines[FID].insert(LineNo);
1906   }
1907 }
1908 
1909 PathDiagnosticConstruct::PathDiagnosticConstruct(
1910     const PathDiagnosticConsumer *PDC, const ExplodedNode *ErrorNode,
1911     const BugReport *R)
1912     : Consumer(PDC), CurrentNode(ErrorNode),
1913       SM(CurrentNode->getCodeDecl().getASTContext().getSourceManager()),
1914       PD(generateEmptyDiagnosticForReport(R, getSourceManager())) {
1915   LCM[&PD->getActivePath()] = ErrorNode->getLocationContext();
1916 }
1917 
1918 PathDiagnosticBuilder::PathDiagnosticBuilder(
1919     BugReporterContext BRC, std::unique_ptr<ExplodedGraph> BugPath,
1920     BugReport *r, const ExplodedNode *ErrorNode,
1921     std::unique_ptr<VisitorsDiagnosticsTy> VisitorsDiagnostics)
1922     : BugReporterContext(BRC), BugPath(std::move(BugPath)), R(r),
1923       ErrorNode(ErrorNode),
1924       VisitorsDiagnostics(std::move(VisitorsDiagnostics)) {}
1925 
1926 std::unique_ptr<PathDiagnostic>
1927 PathDiagnosticBuilder::generate(const PathDiagnosticConsumer *PDC) const {
1928   PathDiagnosticConstruct Construct(PDC, ErrorNode, R);
1929 
1930   const SourceManager &SM = getSourceManager();
1931   const BugReport *R = getBugReport();
1932   const AnalyzerOptions &Opts = getAnalyzerOptions();
1933   StringRef ErrorTag = ErrorNode->getLocation().getTag()->getTagDescription();
1934 
1935   // See whether we need to silence the checker/package.
1936   // FIXME: This will not work if the report was emitted with an incorrect tag.
1937   for (const std::string &CheckerOrPackage : Opts.SilencedCheckersAndPackages) {
1938     if (ErrorTag.startswith(CheckerOrPackage))
1939       return nullptr;
1940   }
1941 
1942   if (!PDC->shouldGenerateDiagnostics())
1943     return generateEmptyDiagnosticForReport(R, getSourceManager());
1944 
1945   // Construct the final (warning) event for the bug report.
1946   auto EndNotes = VisitorsDiagnostics->find(ErrorNode);
1947   PathDiagnosticPieceRef LastPiece;
1948   if (EndNotes != VisitorsDiagnostics->end()) {
1949     assert(!EndNotes->second.empty());
1950     LastPiece = EndNotes->second[0];
1951   } else {
1952     LastPiece = BugReporterVisitor::getDefaultEndPath(*this, ErrorNode,
1953                                                       *getBugReport());
1954   }
1955   Construct.PD->setEndOfPath(LastPiece);
1956 
1957   PathDiagnosticLocation PrevLoc = Construct.PD->getLocation();
1958   // From the error node to the root, ascend the bug path and construct the bug
1959   // report.
1960   while (Construct.ascendToPrevNode()) {
1961     generatePathDiagnosticsForNode(Construct, PrevLoc);
1962 
1963     auto VisitorNotes = VisitorsDiagnostics->find(Construct.getCurrentNode());
1964     if (VisitorNotes == VisitorsDiagnostics->end())
1965       continue;
1966 
1967     // This is a workaround due to inability to put shared PathDiagnosticPiece
1968     // into a FoldingSet.
1969     std::set<llvm::FoldingSetNodeID> DeduplicationSet;
1970 
1971     // Add pieces from custom visitors.
1972     for (const PathDiagnosticPieceRef &Note : VisitorNotes->second) {
1973       llvm::FoldingSetNodeID ID;
1974       Note->Profile(ID);
1975       if (!DeduplicationSet.insert(ID).second)
1976         continue;
1977 
1978       if (PDC->shouldAddPathEdges())
1979         addEdgeToPath(Construct.getActivePath(), PrevLoc, Note->getLocation());
1980       updateStackPiecesWithMessage(*Note, Construct.CallStack);
1981       Construct.getActivePath().push_front(Note);
1982     }
1983   }
1984 
1985   if (PDC->shouldAddPathEdges()) {
1986     // Add an edge to the start of the function.
1987     // We'll prune it out later, but it helps make diagnostics more uniform.
1988     const StackFrameContext *CalleeLC =
1989         Construct.getLocationContextForActivePath()->getStackFrame();
1990     const Decl *D = CalleeLC->getDecl();
1991     addEdgeToPath(Construct.getActivePath(), PrevLoc,
1992                   PathDiagnosticLocation::createBegin(D, SM));
1993   }
1994 
1995 
1996   // Finally, prune the diagnostic path of uninteresting stuff.
1997   if (!Construct.PD->path.empty()) {
1998     if (R->shouldPrunePath() && Opts.ShouldPrunePaths) {
1999       bool stillHasNotes =
2000           removeUnneededCalls(Construct, Construct.getMutablePieces(), R);
2001       assert(stillHasNotes);
2002       (void)stillHasNotes;
2003     }
2004 
2005     // Remove pop-up notes if needed.
2006     if (!Opts.ShouldAddPopUpNotes)
2007       removePopUpNotes(Construct.getMutablePieces());
2008 
2009     // Redirect all call pieces to have valid locations.
2010     adjustCallLocations(Construct.getMutablePieces());
2011     removePiecesWithInvalidLocations(Construct.getMutablePieces());
2012 
2013     if (PDC->shouldAddPathEdges()) {
2014 
2015       // Reduce the number of edges from a very conservative set
2016       // to an aesthetically pleasing subset that conveys the
2017       // necessary information.
2018       OptimizedCallsSet OCS;
2019       while (optimizeEdges(Construct, Construct.getMutablePieces(), OCS)) {
2020       }
2021 
2022       // Drop the very first function-entry edge. It's not really necessary
2023       // for top-level functions.
2024       dropFunctionEntryEdge(Construct, Construct.getMutablePieces());
2025     }
2026 
2027     // Remove messages that are basically the same, and edges that may not
2028     // make sense.
2029     // We have to do this after edge optimization in the Extensive mode.
2030     removeRedundantMsgs(Construct.getMutablePieces());
2031     removeEdgesToDefaultInitializers(Construct.getMutablePieces());
2032   }
2033 
2034   if (Opts.ShouldDisplayMacroExpansions)
2035     CompactMacroExpandedPieces(Construct.getMutablePieces(), SM);
2036 
2037   return std::move(Construct.PD);
2038 }
2039 
2040 //===----------------------------------------------------------------------===//
2041 // Methods for BugType and subclasses.
2042 //===----------------------------------------------------------------------===//
2043 
2044 void BugType::anchor() {}
2045 
2046 void BuiltinBug::anchor() {}
2047 
2048 //===----------------------------------------------------------------------===//
2049 // Methods for BugReport and subclasses.
2050 //===----------------------------------------------------------------------===//
2051 
2052 void BugReport::addVisitor(std::unique_ptr<BugReporterVisitor> visitor) {
2053   if (!visitor)
2054     return;
2055 
2056   llvm::FoldingSetNodeID ID;
2057   visitor->Profile(ID);
2058 
2059   void *InsertPos = nullptr;
2060   if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
2061     return;
2062   }
2063 
2064   Callbacks.push_back(std::move(visitor));
2065 }
2066 
2067 void BugReport::clearVisitors() {
2068   Callbacks.clear();
2069 }
2070 
2071 const Decl *BugReport::getDeclWithIssue() const {
2072   if (DeclWithIssue)
2073     return DeclWithIssue;
2074 
2075   const ExplodedNode *N = getErrorNode();
2076   if (!N)
2077     return nullptr;
2078 
2079   const LocationContext *LC = N->getLocationContext();
2080   return LC->getStackFrame()->getDecl();
2081 }
2082 
2083 void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
2084   hash.AddPointer(&BT);
2085   hash.AddString(Description);
2086   PathDiagnosticLocation UL = getUniqueingLocation();
2087   if (UL.isValid()) {
2088     UL.Profile(hash);
2089   } else if (Location.isValid()) {
2090     Location.Profile(hash);
2091   } else {
2092     assert(ErrorNode);
2093     hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
2094   }
2095 
2096   for (SourceRange range : Ranges) {
2097     if (!range.isValid())
2098       continue;
2099     hash.AddInteger(range.getBegin().getRawEncoding());
2100     hash.AddInteger(range.getEnd().getRawEncoding());
2101   }
2102 }
2103 
2104 template <class T>
2105 static void insertToInterestingnessMap(
2106     llvm::DenseMap<T, bugreporter::TrackingKind> &InterestingnessMap, T Val,
2107     bugreporter::TrackingKind TKind) {
2108   auto Result = InterestingnessMap.insert({Val, TKind});
2109 
2110   if (Result.second)
2111     return;
2112 
2113   // Even if this symbol/region was already marked as interesting as a
2114   // condition, if we later mark it as interesting again but with
2115   // thorough tracking, overwrite it. Entities marked with thorough
2116   // interestiness are the most important (or most interesting, if you will),
2117   // and we wouldn't like to downplay their importance.
2118 
2119   switch (TKind) {
2120     case bugreporter::TrackingKind::Thorough:
2121       Result.first->getSecond() = bugreporter::TrackingKind::Thorough;
2122       return;
2123     case bugreporter::TrackingKind::Condition:
2124       return;
2125   }
2126 
2127   llvm_unreachable(
2128       "BugReport::markInteresting currently can only handle 2 different "
2129       "tracking kinds! Please define what tracking kind should this entitiy"
2130       "have, if it was already marked as interesting with a different kind!");
2131 }
2132 
2133 void BugReport::markInteresting(SymbolRef sym,
2134                                 bugreporter::TrackingKind TKind) {
2135   if (!sym)
2136     return;
2137 
2138   insertToInterestingnessMap(InterestingSymbols, sym, TKind);
2139 
2140   if (const auto *meta = dyn_cast<SymbolMetadata>(sym))
2141     markInteresting(meta->getRegion(), TKind);
2142 }
2143 
2144 void BugReport::markInteresting(const MemRegion *R,
2145                                 bugreporter::TrackingKind TKind) {
2146   if (!R)
2147     return;
2148 
2149   R = R->getBaseRegion();
2150   insertToInterestingnessMap(InterestingRegions, R, TKind);
2151 
2152   if (const auto *SR = dyn_cast<SymbolicRegion>(R))
2153     markInteresting(SR->getSymbol(), TKind);
2154 }
2155 
2156 void BugReport::markInteresting(SVal V, bugreporter::TrackingKind TKind) {
2157   markInteresting(V.getAsRegion(), TKind);
2158   markInteresting(V.getAsSymbol(), TKind);
2159 }
2160 
2161 void BugReport::markInteresting(const LocationContext *LC) {
2162   if (!LC)
2163     return;
2164   InterestingLocationContexts.insert(LC);
2165 }
2166 
2167 Optional<bugreporter::TrackingKind>
2168 BugReport::getInterestingnessKind(SVal V) const {
2169   auto RKind = getInterestingnessKind(V.getAsRegion());
2170   auto SKind = getInterestingnessKind(V.getAsSymbol());
2171   if (!RKind)
2172     return SKind;
2173   if (!SKind)
2174     return RKind;
2175 
2176   // If either is marked with throrough tracking, return that, we wouldn't like
2177   // to downplay a note's importance by 'only' mentioning it as a condition.
2178   switch(*RKind) {
2179     case bugreporter::TrackingKind::Thorough:
2180       return RKind;
2181     case bugreporter::TrackingKind::Condition:
2182       return SKind;
2183   }
2184 
2185   llvm_unreachable(
2186       "BugReport::getInterestingnessKind currently can only handle 2 different "
2187       "tracking kinds! Please define what tracking kind should we return here "
2188       "when the kind of getAsRegion() and getAsSymbol() is different!");
2189   return None;
2190 }
2191 
2192 Optional<bugreporter::TrackingKind>
2193 BugReport::getInterestingnessKind(SymbolRef sym) const {
2194   if (!sym)
2195     return None;
2196   // We don't currently consider metadata symbols to be interesting
2197   // even if we know their region is interesting. Is that correct behavior?
2198   auto It = InterestingSymbols.find(sym);
2199   if (It == InterestingSymbols.end())
2200     return None;
2201   return It->getSecond();
2202 }
2203 
2204 Optional<bugreporter::TrackingKind>
2205 BugReport::getInterestingnessKind(const MemRegion *R) const {
2206   if (!R)
2207     return None;
2208 
2209   R = R->getBaseRegion();
2210   auto It = InterestingRegions.find(R);
2211   if (It != InterestingRegions.end())
2212     return It->getSecond();
2213 
2214   if (const auto *SR = dyn_cast<SymbolicRegion>(R))
2215     return getInterestingnessKind(SR->getSymbol());
2216   return None;
2217 }
2218 
2219 bool BugReport::isInteresting(SVal V) const {
2220   return getInterestingnessKind(V).hasValue();
2221 }
2222 
2223 bool BugReport::isInteresting(SymbolRef sym) const {
2224   return getInterestingnessKind(sym).hasValue();
2225 }
2226 
2227 bool BugReport::isInteresting(const MemRegion *R) const {
2228   return getInterestingnessKind(R).hasValue();
2229 }
2230 
2231 bool BugReport::isInteresting(const LocationContext *LC)  const {
2232   if (!LC)
2233     return false;
2234   return InterestingLocationContexts.count(LC);
2235 }
2236 
2237 const Stmt *BugReport::getStmt() const {
2238   if (!ErrorNode)
2239     return nullptr;
2240 
2241   ProgramPoint ProgP = ErrorNode->getLocation();
2242   const Stmt *S = nullptr;
2243 
2244   if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
2245     CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
2246     if (BE->getBlock() == &Exit)
2247       S = GetPreviousStmt(ErrorNode);
2248   }
2249   if (!S)
2250     S = PathDiagnosticLocation::getStmt(ErrorNode);
2251 
2252   return S;
2253 }
2254 
2255 llvm::iterator_range<BugReport::ranges_iterator> BugReport::getRanges() const {
2256   // If no custom ranges, add the range of the statement corresponding to
2257   // the error node.
2258   if (Ranges.empty()) {
2259     if (dyn_cast_or_null<Expr>(getStmt()))
2260       return llvm::make_range(&ErrorNodeRange, &ErrorNodeRange + 1);
2261     return llvm::make_range(ranges_iterator(), ranges_iterator());
2262   }
2263 
2264   // User-specified absence of range info.
2265   if (Ranges.size() == 1 && !Ranges.begin()->isValid())
2266     return llvm::make_range(ranges_iterator(), ranges_iterator());
2267 
2268   return llvm::make_range(Ranges.begin(), Ranges.end());
2269 }
2270 
2271 PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
2272   if (ErrorNode) {
2273     assert(!Location.isValid() &&
2274      "Either Location or ErrorNode should be specified but not both.");
2275     return PathDiagnosticLocation::createEndOfPath(ErrorNode, SM);
2276   }
2277 
2278   assert(Location.isValid());
2279   return Location;
2280 }
2281 
2282 //===----------------------------------------------------------------------===//
2283 // Methods for BugReporter and subclasses.
2284 //===----------------------------------------------------------------------===//
2285 
2286 const ExplodedGraph &PathSensitiveBugReporter::getGraph() const {
2287   return Eng.getGraph();
2288 }
2289 
2290 ProgramStateManager &PathSensitiveBugReporter::getStateManager() const {
2291   return Eng.getStateManager();
2292 }
2293 
2294 BugReporter::~BugReporter() {
2295   // Make sure reports are flushed.
2296   assert(StrBugTypes.empty() &&
2297          "Destroying BugReporter before diagnostics are emitted!");
2298 
2299   // Free the bug reports we are tracking.
2300   for (const auto I : EQClassesVector)
2301     delete I;
2302 }
2303 
2304 void BugReporter::FlushReports() {
2305   // We need to flush reports in deterministic order to ensure the order
2306   // of the reports is consistent between runs.
2307   for (const auto EQ : EQClassesVector)
2308     FlushReport(*EQ);
2309 
2310   // BugReporter owns and deletes only BugTypes created implicitly through
2311   // EmitBasicReport.
2312   // FIXME: There are leaks from checkers that assume that the BugTypes they
2313   // create will be destroyed by the BugReporter.
2314   llvm::DeleteContainerSeconds(StrBugTypes);
2315 }
2316 
2317 //===----------------------------------------------------------------------===//
2318 // PathDiagnostics generation.
2319 //===----------------------------------------------------------------------===//
2320 
2321 namespace {
2322 
2323 /// A wrapper around an ExplodedGraph that contains a single path from the root
2324 /// to the error node.
2325 class BugPathInfo {
2326 public:
2327   std::unique_ptr<ExplodedGraph> BugPath;
2328   BugReport *Report;
2329   const ExplodedNode *ErrorNode;
2330 };
2331 
2332 /// A wrapper around an ExplodedGraph whose leafs are all error nodes. Can
2333 /// conveniently retrieve bug paths from a single error node to the root.
2334 class BugPathGetter {
2335   std::unique_ptr<ExplodedGraph> TrimmedGraph;
2336 
2337   using PriorityMapTy = llvm::DenseMap<const ExplodedNode *, unsigned>;
2338 
2339   /// Assign each node with its distance from the root.
2340   PriorityMapTy PriorityMap;
2341 
2342   /// Since the getErrorNode() or BugReport refers to the original ExplodedGraph,
2343   /// we need to pair it to the error node of the constructed trimmed graph.
2344   using ReportNewNodePair = std::pair<BugReport *, const ExplodedNode *>;
2345   SmallVector<ReportNewNodePair, 32> ReportNodes;
2346 
2347   BugPathInfo CurrentBugPath;
2348 
2349   /// A helper class for sorting ExplodedNodes by priority.
2350   template <bool Descending>
2351   class PriorityCompare {
2352     const PriorityMapTy &PriorityMap;
2353 
2354   public:
2355     PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
2356 
2357     bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
2358       PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
2359       PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
2360       PriorityMapTy::const_iterator E = PriorityMap.end();
2361 
2362       if (LI == E)
2363         return Descending;
2364       if (RI == E)
2365         return !Descending;
2366 
2367       return Descending ? LI->second > RI->second
2368                         : LI->second < RI->second;
2369     }
2370 
2371     bool operator()(const ReportNewNodePair &LHS,
2372                     const ReportNewNodePair &RHS) const {
2373       return (*this)(LHS.second, RHS.second);
2374     }
2375   };
2376 
2377 public:
2378   BugPathGetter(const ExplodedGraph *OriginalGraph,
2379                 ArrayRef<BugReport *> &bugReports);
2380 
2381   BugPathInfo *getNextBugPath();
2382 };
2383 
2384 } // namespace
2385 
2386 BugPathGetter::BugPathGetter(const ExplodedGraph *OriginalGraph,
2387                              ArrayRef<BugReport *> &bugReports) {
2388   SmallVector<const ExplodedNode *, 32> Nodes;
2389   for (const auto I : bugReports) {
2390     assert(I->isValid() &&
2391            "We only allow BugReporterVisitors and BugReporter itself to "
2392            "invalidate reports!");
2393     Nodes.emplace_back(I->getErrorNode());
2394   }
2395 
2396   // The trimmed graph is created in the body of the constructor to ensure
2397   // that the DenseMaps have been initialized already.
2398   InterExplodedGraphMap ForwardMap;
2399   TrimmedGraph = OriginalGraph->trim(Nodes, &ForwardMap);
2400 
2401   // Find the (first) error node in the trimmed graph.  We just need to consult
2402   // the node map which maps from nodes in the original graph to nodes
2403   // in the new graph.
2404   llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes;
2405 
2406   for (BugReport *Report : bugReports) {
2407     const ExplodedNode *NewNode = ForwardMap.lookup(Report->getErrorNode());
2408     assert(NewNode &&
2409            "Failed to construct a trimmed graph that contains this error "
2410            "node!");
2411     ReportNodes.emplace_back(Report, NewNode);
2412     RemainingNodes.insert(NewNode);
2413   }
2414 
2415   assert(!RemainingNodes.empty() && "No error node found in the trimmed graph");
2416 
2417   // Perform a forward BFS to find all the shortest paths.
2418   std::queue<const ExplodedNode *> WS;
2419 
2420   assert(TrimmedGraph->num_roots() == 1);
2421   WS.push(*TrimmedGraph->roots_begin());
2422   unsigned Priority = 0;
2423 
2424   while (!WS.empty()) {
2425     const ExplodedNode *Node = WS.front();
2426     WS.pop();
2427 
2428     PriorityMapTy::iterator PriorityEntry;
2429     bool IsNew;
2430     std::tie(PriorityEntry, IsNew) = PriorityMap.insert({Node, Priority});
2431     ++Priority;
2432 
2433     if (!IsNew) {
2434       assert(PriorityEntry->second <= Priority);
2435       continue;
2436     }
2437 
2438     if (RemainingNodes.erase(Node))
2439       if (RemainingNodes.empty())
2440         break;
2441 
2442     for (const ExplodedNode *Succ : Node->succs())
2443       WS.push(Succ);
2444   }
2445 
2446   // Sort the error paths from longest to shortest.
2447   llvm::sort(ReportNodes, PriorityCompare<true>(PriorityMap));
2448 }
2449 
2450 BugPathInfo *BugPathGetter::getNextBugPath() {
2451   if (ReportNodes.empty())
2452     return nullptr;
2453 
2454   const ExplodedNode *OrigN;
2455   std::tie(CurrentBugPath.Report, OrigN) = ReportNodes.pop_back_val();
2456   assert(PriorityMap.find(OrigN) != PriorityMap.end() &&
2457          "error node not accessible from root");
2458 
2459   // Create a new graph with a single path. This is the graph that will be
2460   // returned to the caller.
2461   auto GNew = std::make_unique<ExplodedGraph>();
2462 
2463   // Now walk from the error node up the BFS path, always taking the
2464   // predeccessor with the lowest number.
2465   ExplodedNode *Succ = nullptr;
2466   while (true) {
2467     // Create the equivalent node in the new graph with the same state
2468     // and location.
2469     ExplodedNode *NewN = GNew->createUncachedNode(
2470         OrigN->getLocation(), OrigN->getState(), OrigN->isSink());
2471 
2472     // Link up the new node with the previous node.
2473     if (Succ)
2474       Succ->addPredecessor(NewN, *GNew);
2475     else
2476       CurrentBugPath.ErrorNode = NewN;
2477 
2478     Succ = NewN;
2479 
2480     // Are we at the final node?
2481     if (OrigN->pred_empty()) {
2482       GNew->addRoot(NewN);
2483       break;
2484     }
2485 
2486     // Find the next predeccessor node.  We choose the node that is marked
2487     // with the lowest BFS number.
2488     OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(),
2489                               PriorityCompare<false>(PriorityMap));
2490   }
2491 
2492   CurrentBugPath.BugPath = std::move(GNew);
2493 
2494   return &CurrentBugPath;
2495 }
2496 
2497 /// CompactMacroExpandedPieces - This function postprocesses a PathDiagnostic
2498 /// object and collapses PathDiagosticPieces that are expanded by macros.
2499 static void CompactMacroExpandedPieces(PathPieces &path,
2500                                        const SourceManager& SM) {
2501   using MacroStackTy = std::vector<
2502       std::pair<std::shared_ptr<PathDiagnosticMacroPiece>, SourceLocation>>;
2503 
2504   using PiecesTy = std::vector<PathDiagnosticPieceRef>;
2505 
2506   MacroStackTy MacroStack;
2507   PiecesTy Pieces;
2508 
2509   for (PathPieces::const_iterator I = path.begin(), E = path.end();
2510        I != E; ++I) {
2511     const auto &piece = *I;
2512 
2513     // Recursively compact calls.
2514     if (auto *call = dyn_cast<PathDiagnosticCallPiece>(&*piece)) {
2515       CompactMacroExpandedPieces(call->path, SM);
2516     }
2517 
2518     // Get the location of the PathDiagnosticPiece.
2519     const FullSourceLoc Loc = piece->getLocation().asLocation();
2520 
2521     // Determine the instantiation location, which is the location we group
2522     // related PathDiagnosticPieces.
2523     SourceLocation InstantiationLoc = Loc.isMacroID() ?
2524                                       SM.getExpansionLoc(Loc) :
2525                                       SourceLocation();
2526 
2527     if (Loc.isFileID()) {
2528       MacroStack.clear();
2529       Pieces.push_back(piece);
2530       continue;
2531     }
2532 
2533     assert(Loc.isMacroID());
2534 
2535     // Is the PathDiagnosticPiece within the same macro group?
2536     if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
2537       MacroStack.back().first->subPieces.push_back(piece);
2538       continue;
2539     }
2540 
2541     // We aren't in the same group.  Are we descending into a new macro
2542     // or are part of an old one?
2543     std::shared_ptr<PathDiagnosticMacroPiece> MacroGroup;
2544 
2545     SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
2546                                           SM.getExpansionLoc(Loc) :
2547                                           SourceLocation();
2548 
2549     // Walk the entire macro stack.
2550     while (!MacroStack.empty()) {
2551       if (InstantiationLoc == MacroStack.back().second) {
2552         MacroGroup = MacroStack.back().first;
2553         break;
2554       }
2555 
2556       if (ParentInstantiationLoc == MacroStack.back().second) {
2557         MacroGroup = MacroStack.back().first;
2558         break;
2559       }
2560 
2561       MacroStack.pop_back();
2562     }
2563 
2564     if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
2565       // Create a new macro group and add it to the stack.
2566       auto NewGroup = std::make_shared<PathDiagnosticMacroPiece>(
2567           PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
2568 
2569       if (MacroGroup)
2570         MacroGroup->subPieces.push_back(NewGroup);
2571       else {
2572         assert(InstantiationLoc.isFileID());
2573         Pieces.push_back(NewGroup);
2574       }
2575 
2576       MacroGroup = NewGroup;
2577       MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
2578     }
2579 
2580     // Finally, add the PathDiagnosticPiece to the group.
2581     MacroGroup->subPieces.push_back(piece);
2582   }
2583 
2584   // Now take the pieces and construct a new PathDiagnostic.
2585   path.clear();
2586 
2587   path.insert(path.end(), Pieces.begin(), Pieces.end());
2588 }
2589 
2590 /// Generate notes from all visitors.
2591 /// Notes associated with {@code ErrorNode} are generated using
2592 /// {@code getEndPath}, and the rest are generated with {@code VisitNode}.
2593 static std::unique_ptr<VisitorsDiagnosticsTy>
2594 generateVisitorsDiagnostics(BugReport *R, const ExplodedNode *ErrorNode,
2595                             BugReporterContext &BRC) {
2596   std::unique_ptr<VisitorsDiagnosticsTy> Notes =
2597       std::make_unique<VisitorsDiagnosticsTy>();
2598   BugReport::VisitorList visitors;
2599 
2600   // Run visitors on all nodes starting from the node *before* the last one.
2601   // The last node is reserved for notes generated with {@code getEndPath}.
2602   const ExplodedNode *NextNode = ErrorNode->getFirstPred();
2603   while (NextNode) {
2604 
2605     // At each iteration, move all visitors from report to visitor list. This is
2606     // important, because the Profile() functions of the visitors make sure that
2607     // a visitor isn't added multiple times for the same node, but it's fine
2608     // to add the a visitor with Profile() for different nodes (e.g. tracking
2609     // a region at different points of the symbolic execution).
2610     for (std::unique_ptr<BugReporterVisitor> &Visitor : R->visitors())
2611       visitors.push_back(std::move(Visitor));
2612 
2613     R->clearVisitors();
2614 
2615     const ExplodedNode *Pred = NextNode->getFirstPred();
2616     if (!Pred) {
2617       PathDiagnosticPieceRef LastPiece;
2618       for (auto &V : visitors) {
2619         V->finalizeVisitor(BRC, ErrorNode, *R);
2620 
2621         if (auto Piece = V->getEndPath(BRC, ErrorNode, *R)) {
2622           assert(!LastPiece &&
2623                  "There can only be one final piece in a diagnostic.");
2624           assert(Piece->getKind() == PathDiagnosticPiece::Kind::Event &&
2625                  "The final piece must contain a message!");
2626           LastPiece = std::move(Piece);
2627           (*Notes)[ErrorNode].push_back(LastPiece);
2628         }
2629       }
2630       break;
2631     }
2632 
2633     for (auto &V : visitors) {
2634       auto P = V->VisitNode(NextNode, BRC, *R);
2635       if (P)
2636         (*Notes)[NextNode].push_back(std::move(P));
2637     }
2638 
2639     if (!R->isValid())
2640       break;
2641 
2642     NextNode = Pred;
2643   }
2644 
2645   return Notes;
2646 }
2647 
2648 Optional<PathDiagnosticBuilder>
2649 PathDiagnosticBuilder::findValidReport(ArrayRef<BugReport *> &bugReports,
2650                                        PathSensitiveBugReporter &Reporter) {
2651 
2652   BugPathGetter BugGraph(&Reporter.getGraph(), bugReports);
2653 
2654   while (BugPathInfo *BugPath = BugGraph.getNextBugPath()) {
2655     // Find the BugReport with the original location.
2656     BugReport *R = BugPath->Report;
2657     assert(R && "No original report found for sliced graph.");
2658     assert(R->isValid() && "Report selected by trimmed graph marked invalid.");
2659     const ExplodedNode *ErrorNode = BugPath->ErrorNode;
2660 
2661     // Register refutation visitors first, if they mark the bug invalid no
2662     // further analysis is required
2663     R->addVisitor(std::make_unique<LikelyFalsePositiveSuppressionBRVisitor>());
2664 
2665     // Register additional node visitors.
2666     R->addVisitor(std::make_unique<NilReceiverBRVisitor>());
2667     R->addVisitor(std::make_unique<ConditionBRVisitor>());
2668     R->addVisitor(std::make_unique<TagVisitor>());
2669 
2670     BugReporterContext BRC(Reporter);
2671 
2672     // Run all visitors on a given graph, once.
2673     std::unique_ptr<VisitorsDiagnosticsTy> visitorNotes =
2674         generateVisitorsDiagnostics(R, ErrorNode, BRC);
2675 
2676     if (R->isValid()) {
2677       if (Reporter.getAnalyzerOptions().ShouldCrosscheckWithZ3) {
2678         // If crosscheck is enabled, remove all visitors, add the refutation
2679         // visitor and check again
2680         R->clearVisitors();
2681         R->addVisitor(std::make_unique<FalsePositiveRefutationBRVisitor>());
2682 
2683         // We don't overrite the notes inserted by other visitors because the
2684         // refutation manager does not add any new note to the path
2685         generateVisitorsDiagnostics(R, BugPath->ErrorNode, BRC);
2686       }
2687 
2688       // Check if the bug is still valid
2689       if (R->isValid())
2690         return PathDiagnosticBuilder(
2691             std::move(BRC), std::move(BugPath->BugPath), BugPath->Report,
2692             BugPath->ErrorNode, std::move(visitorNotes));
2693     }
2694   }
2695 
2696   return {};
2697 }
2698 
2699 std::unique_ptr<DiagnosticForConsumerMapTy>
2700 PathSensitiveBugReporter::generatePathDiagnostics(
2701     ArrayRef<PathDiagnosticConsumer *> consumers,
2702     ArrayRef<BugReport *> &bugReports) {
2703   assert(!bugReports.empty());
2704 
2705   auto Out = std::make_unique<DiagnosticForConsumerMapTy>();
2706 
2707   Optional<PathDiagnosticBuilder> PDB =
2708       PathDiagnosticBuilder::findValidReport(bugReports, *this);
2709 
2710   if (PDB) {
2711     for (PathDiagnosticConsumer *PC : consumers) {
2712       if (std::unique_ptr<PathDiagnostic> PD = PDB->generate(PC)) {
2713         (*Out)[PC] = std::move(PD);
2714       }
2715     }
2716   }
2717 
2718   return Out;
2719 }
2720 
2721 void BugReporter::emitReport(std::unique_ptr<BugReport> R) {
2722   if (const ExplodedNode *E = R->getErrorNode()) {
2723     // An error node must either be a sink or have a tag, otherwise
2724     // it could get reclaimed before the path diagnostic is created.
2725     assert((E->isSink() || E->getLocation().getTag()) &&
2726             "Error node must either be a sink or have a tag");
2727 
2728     const AnalysisDeclContext *DeclCtx =
2729         E->getLocationContext()->getAnalysisDeclContext();
2730     // The source of autosynthesized body can be handcrafted AST or a model
2731     // file. The locations from handcrafted ASTs have no valid source locations
2732     // and have to be discarded. Locations from model files should be preserved
2733     // for processing and reporting.
2734     if (DeclCtx->isBodyAutosynthesized() &&
2735         !DeclCtx->isBodyAutosynthesizedFromModelFile())
2736       return;
2737   }
2738 
2739   bool ValidSourceLoc = R->getLocation(getSourceManager()).isValid();
2740   assert(ValidSourceLoc);
2741   // If we mess up in a release build, we'd still prefer to just drop the bug
2742   // instead of trying to go on.
2743   if (!ValidSourceLoc)
2744     return;
2745 
2746   // Compute the bug report's hash to determine its equivalence class.
2747   llvm::FoldingSetNodeID ID;
2748   R->Profile(ID);
2749 
2750   // Lookup the equivance class.  If there isn't one, create it.
2751   void *InsertPos;
2752   BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
2753 
2754   if (!EQ) {
2755     EQ = new BugReportEquivClass(std::move(R));
2756     EQClasses.InsertNode(EQ, InsertPos);
2757     EQClassesVector.push_back(EQ);
2758   } else
2759     EQ->AddReport(std::move(R));
2760 }
2761 
2762 //===----------------------------------------------------------------------===//
2763 // Emitting reports in equivalence classes.
2764 //===----------------------------------------------------------------------===//
2765 
2766 namespace {
2767 
2768 struct FRIEC_WLItem {
2769   const ExplodedNode *N;
2770   ExplodedNode::const_succ_iterator I, E;
2771 
2772   FRIEC_WLItem(const ExplodedNode *n)
2773       : N(n), I(N->succ_begin()), E(N->succ_end()) {}
2774 };
2775 
2776 } // namespace
2777 
2778 static BugReport *
2779 FindReportInEquivalenceClass(BugReportEquivClass& EQ,
2780                              SmallVectorImpl<BugReport*> &bugReports) {
2781   BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
2782   assert(I != E);
2783   const BugType& BT = I->getBugType();
2784 
2785   // If we don't need to suppress any of the nodes because they are
2786   // post-dominated by a sink, simply add all the nodes in the equivalence class
2787   // to 'Nodes'.  Any of the reports will serve as a "representative" report.
2788   if (!BT.isSuppressOnSink()) {
2789     BugReport *R = &*I;
2790     for (auto &I : EQ) {
2791       const ExplodedNode *N = I.getErrorNode();
2792       if (N) {
2793         R = &I;
2794         bugReports.push_back(R);
2795       }
2796     }
2797     return R;
2798   }
2799 
2800   // For bug reports that should be suppressed when all paths are post-dominated
2801   // by a sink node, iterate through the reports in the equivalence class
2802   // until we find one that isn't post-dominated (if one exists).  We use a
2803   // DFS traversal of the ExplodedGraph to find a non-sink node.  We could write
2804   // this as a recursive function, but we don't want to risk blowing out the
2805   // stack for very long paths.
2806   BugReport *exampleReport = nullptr;
2807 
2808   for (; I != E; ++I) {
2809     const ExplodedNode *errorNode = I->getErrorNode();
2810 
2811     if (!errorNode)
2812       continue;
2813     if (errorNode->isSink()) {
2814       llvm_unreachable(
2815            "BugType::isSuppressSink() should not be 'true' for sink end nodes");
2816     }
2817     // No successors?  By definition this nodes isn't post-dominated by a sink.
2818     if (errorNode->succ_empty()) {
2819       bugReports.push_back(&*I);
2820       if (!exampleReport)
2821         exampleReport = &*I;
2822       continue;
2823     }
2824 
2825     // See if we are in a no-return CFG block. If so, treat this similarly
2826     // to being post-dominated by a sink. This works better when the analysis
2827     // is incomplete and we have never reached the no-return function call(s)
2828     // that we'd inevitably bump into on this path.
2829     if (const CFGBlock *ErrorB = errorNode->getCFGBlock())
2830       if (ErrorB->isInevitablySinking())
2831         continue;
2832 
2833     // At this point we know that 'N' is not a sink and it has at least one
2834     // successor.  Use a DFS worklist to find a non-sink end-of-path node.
2835     using WLItem = FRIEC_WLItem;
2836     using DFSWorkList = SmallVector<WLItem, 10>;
2837 
2838     llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
2839 
2840     DFSWorkList WL;
2841     WL.push_back(errorNode);
2842     Visited[errorNode] = 1;
2843 
2844     while (!WL.empty()) {
2845       WLItem &WI = WL.back();
2846       assert(!WI.N->succ_empty());
2847 
2848       for (; WI.I != WI.E; ++WI.I) {
2849         const ExplodedNode *Succ = *WI.I;
2850         // End-of-path node?
2851         if (Succ->succ_empty()) {
2852           // If we found an end-of-path node that is not a sink.
2853           if (!Succ->isSink()) {
2854             bugReports.push_back(&*I);
2855             if (!exampleReport)
2856               exampleReport = &*I;
2857             WL.clear();
2858             break;
2859           }
2860           // Found a sink?  Continue on to the next successor.
2861           continue;
2862         }
2863         // Mark the successor as visited.  If it hasn't been explored,
2864         // enqueue it to the DFS worklist.
2865         unsigned &mark = Visited[Succ];
2866         if (!mark) {
2867           mark = 1;
2868           WL.push_back(Succ);
2869           break;
2870         }
2871       }
2872 
2873       // The worklist may have been cleared at this point.  First
2874       // check if it is empty before checking the last item.
2875       if (!WL.empty() && &WL.back() == &WI)
2876         WL.pop_back();
2877     }
2878   }
2879 
2880   // ExampleReport will be NULL if all the nodes in the equivalence class
2881   // were post-dominated by sinks.
2882   return exampleReport;
2883 }
2884 
2885 void BugReporter::FlushReport(BugReportEquivClass& EQ) {
2886   SmallVector<BugReport*, 10> bugReports;
2887   BugReport *report = FindReportInEquivalenceClass(EQ, bugReports);
2888   if (!report)
2889     return;
2890 
2891   ArrayRef<PathDiagnosticConsumer*> Consumers = getPathDiagnosticConsumers();
2892   std::unique_ptr<DiagnosticForConsumerMapTy> Diagnostics =
2893       generateDiagnosticForConsumerMap(report, Consumers, bugReports);
2894 
2895   for (auto &P : *Diagnostics) {
2896     PathDiagnosticConsumer *Consumer = P.first;
2897     std::unique_ptr<PathDiagnostic> &PD = P.second;
2898 
2899     // If the path is empty, generate a single step path with the location
2900     // of the issue.
2901     if (PD->path.empty()) {
2902       PathDiagnosticLocation L = report->getLocation(getSourceManager());
2903       auto piece = std::make_unique<PathDiagnosticEventPiece>(
2904         L, report->getDescription());
2905       for (SourceRange Range : report->getRanges())
2906         piece->addRange(Range);
2907       PD->setEndOfPath(std::move(piece));
2908     }
2909 
2910     PathPieces &Pieces = PD->getMutablePieces();
2911     if (getAnalyzerOptions().ShouldDisplayNotesAsEvents) {
2912       // For path diagnostic consumers that don't support extra notes,
2913       // we may optionally convert those to path notes.
2914       for (auto I = report->getNotes().rbegin(),
2915            E = report->getNotes().rend(); I != E; ++I) {
2916         PathDiagnosticNotePiece *Piece = I->get();
2917         auto ConvertedPiece = std::make_shared<PathDiagnosticEventPiece>(
2918           Piece->getLocation(), Piece->getString());
2919         for (const auto &R: Piece->getRanges())
2920           ConvertedPiece->addRange(R);
2921 
2922         Pieces.push_front(std::move(ConvertedPiece));
2923       }
2924     } else {
2925       for (auto I = report->getNotes().rbegin(),
2926            E = report->getNotes().rend(); I != E; ++I)
2927         Pieces.push_front(*I);
2928     }
2929 
2930     updateExecutedLinesWithDiagnosticPieces(*PD);
2931     Consumer->HandlePathDiagnostic(std::move(PD));
2932   }
2933 }
2934 
2935 /// Insert all lines participating in the function signature \p Signature
2936 /// into \p ExecutedLines.
2937 static void populateExecutedLinesWithFunctionSignature(
2938     const Decl *Signature, const SourceManager &SM,
2939     FilesToLineNumsMap &ExecutedLines) {
2940   SourceRange SignatureSourceRange;
2941   const Stmt* Body = Signature->getBody();
2942   if (const auto FD = dyn_cast<FunctionDecl>(Signature)) {
2943     SignatureSourceRange = FD->getSourceRange();
2944   } else if (const auto OD = dyn_cast<ObjCMethodDecl>(Signature)) {
2945     SignatureSourceRange = OD->getSourceRange();
2946   } else {
2947     return;
2948   }
2949   SourceLocation Start = SignatureSourceRange.getBegin();
2950   SourceLocation End = Body ? Body->getSourceRange().getBegin()
2951     : SignatureSourceRange.getEnd();
2952   if (!Start.isValid() || !End.isValid())
2953     return;
2954   unsigned StartLine = SM.getExpansionLineNumber(Start);
2955   unsigned EndLine = SM.getExpansionLineNumber(End);
2956 
2957   FileID FID = SM.getFileID(SM.getExpansionLoc(Start));
2958   for (unsigned Line = StartLine; Line <= EndLine; Line++)
2959     ExecutedLines[FID].insert(Line);
2960 }
2961 
2962 static void populateExecutedLinesWithStmt(
2963     const Stmt *S, const SourceManager &SM,
2964     FilesToLineNumsMap &ExecutedLines) {
2965   SourceLocation Loc = S->getSourceRange().getBegin();
2966   if (!Loc.isValid())
2967     return;
2968   SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
2969   FileID FID = SM.getFileID(ExpansionLoc);
2970   unsigned LineNo = SM.getExpansionLineNumber(ExpansionLoc);
2971   ExecutedLines[FID].insert(LineNo);
2972 }
2973 
2974 /// \return all executed lines including function signatures on the path
2975 /// starting from \p N.
2976 static std::unique_ptr<FilesToLineNumsMap>
2977 findExecutedLines(const SourceManager &SM, const ExplodedNode *N) {
2978   auto ExecutedLines = std::make_unique<FilesToLineNumsMap>();
2979 
2980   while (N) {
2981     if (N->getFirstPred() == nullptr) {
2982       // First node: show signature of the entrance point.
2983       const Decl *D = N->getLocationContext()->getDecl();
2984       populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
2985     } else if (auto CE = N->getLocationAs<CallEnter>()) {
2986       // Inlined function: show signature.
2987       const Decl* D = CE->getCalleeContext()->getDecl();
2988       populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
2989     } else if (const Stmt *S = PathDiagnosticLocation::getStmt(N)) {
2990       populateExecutedLinesWithStmt(S, SM, *ExecutedLines);
2991 
2992       // Show extra context for some parent kinds.
2993       const Stmt *P = N->getParentMap().getParent(S);
2994 
2995       // The path exploration can die before the node with the associated
2996       // return statement is generated, but we do want to show the whole
2997       // return.
2998       if (const auto *RS = dyn_cast_or_null<ReturnStmt>(P)) {
2999         populateExecutedLinesWithStmt(RS, SM, *ExecutedLines);
3000         P = N->getParentMap().getParent(RS);
3001       }
3002 
3003       if (P && (isa<SwitchCase>(P) || isa<LabelStmt>(P)))
3004         populateExecutedLinesWithStmt(P, SM, *ExecutedLines);
3005     }
3006 
3007     N = N->getFirstPred();
3008   }
3009   return ExecutedLines;
3010 }
3011 
3012 std::unique_ptr<DiagnosticForConsumerMapTy>
3013 BugReporter::generateDiagnosticForConsumerMap(
3014     BugReport *report, ArrayRef<PathDiagnosticConsumer *> consumers,
3015     ArrayRef<BugReport *> bugReports) {
3016 
3017   if (!report->isPathSensitive()) {
3018     auto Out = std::make_unique<DiagnosticForConsumerMapTy>();
3019     for (auto *Consumer : consumers)
3020       (*Out)[Consumer] = generateEmptyDiagnosticForReport(report,
3021                                                           getSourceManager());
3022     return Out;
3023   }
3024 
3025   // Generate the full path sensitive diagnostic, using the generation scheme
3026   // specified by the PathDiagnosticConsumer. Note that we have to generate
3027   // path diagnostics even for consumers which do not support paths, because
3028   // the BugReporterVisitors may mark this bug as a false positive.
3029   assert(!bugReports.empty());
3030   MaxBugClassSize.updateMax(bugReports.size());
3031   std::unique_ptr<DiagnosticForConsumerMapTy> Out =
3032     generatePathDiagnostics(consumers, bugReports);
3033 
3034   if (Out->empty())
3035     return Out;
3036 
3037   MaxValidBugClassSize.updateMax(bugReports.size());
3038 
3039   // Examine the report and see if the last piece is in a header. Reset the
3040   // report location to the last piece in the main source file.
3041   const AnalyzerOptions &Opts = getAnalyzerOptions();
3042   for (auto const &P : *Out)
3043     if (Opts.ShouldReportIssuesInMainSourceFile && !Opts.AnalyzeAll)
3044       P.second->resetDiagnosticLocationToMainFile();
3045 
3046   return Out;
3047 }
3048 
3049 void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
3050                                   const CheckerBase *Checker,
3051                                   StringRef Name, StringRef Category,
3052                                   StringRef Str, PathDiagnosticLocation Loc,
3053                                   ArrayRef<SourceRange> Ranges) {
3054   EmitBasicReport(DeclWithIssue, Checker->getCheckName(), Name, Category, Str,
3055                   Loc, Ranges);
3056 }
3057 
3058 void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
3059                                   CheckName CheckName,
3060                                   StringRef name, StringRef category,
3061                                   StringRef str, PathDiagnosticLocation Loc,
3062                                   ArrayRef<SourceRange> Ranges) {
3063   // 'BT' is owned by BugReporter.
3064   BugType *BT = getBugTypeForName(CheckName, name, category);
3065   auto R = std::make_unique<BugReport>(*BT, str, Loc);
3066   R->setDeclWithIssue(DeclWithIssue);
3067   for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
3068        I != E; ++I)
3069     R->addRange(*I);
3070   emitReport(std::move(R));
3071 }
3072 
3073 BugType *BugReporter::getBugTypeForName(CheckName CheckName, StringRef name,
3074                                         StringRef category) {
3075   SmallString<136> fullDesc;
3076   llvm::raw_svector_ostream(fullDesc) << CheckName.getName() << ":" << name
3077                                       << ":" << category;
3078   BugType *&BT = StrBugTypes[fullDesc];
3079   if (!BT)
3080     BT = new BugType(CheckName, name, category);
3081   return BT;
3082 }
3083