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::NodeResolver::anchor() {}
2053 
2054 void BugReport::addVisitor(std::unique_ptr<BugReporterVisitor> visitor) {
2055   if (!visitor)
2056     return;
2057 
2058   llvm::FoldingSetNodeID ID;
2059   visitor->Profile(ID);
2060 
2061   void *InsertPos = nullptr;
2062   if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
2063     return;
2064   }
2065 
2066   Callbacks.push_back(std::move(visitor));
2067 }
2068 
2069 void BugReport::clearVisitors() {
2070   Callbacks.clear();
2071 }
2072 
2073 const Decl *BugReport::getDeclWithIssue() const {
2074   if (DeclWithIssue)
2075     return DeclWithIssue;
2076 
2077   const ExplodedNode *N = getErrorNode();
2078   if (!N)
2079     return nullptr;
2080 
2081   const LocationContext *LC = N->getLocationContext();
2082   return LC->getStackFrame()->getDecl();
2083 }
2084 
2085 void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
2086   hash.AddPointer(&BT);
2087   hash.AddString(Description);
2088   PathDiagnosticLocation UL = getUniqueingLocation();
2089   if (UL.isValid()) {
2090     UL.Profile(hash);
2091   } else if (Location.isValid()) {
2092     Location.Profile(hash);
2093   } else {
2094     assert(ErrorNode);
2095     hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
2096   }
2097 
2098   for (SourceRange range : Ranges) {
2099     if (!range.isValid())
2100       continue;
2101     hash.AddInteger(range.getBegin().getRawEncoding());
2102     hash.AddInteger(range.getEnd().getRawEncoding());
2103   }
2104 }
2105 
2106 void BugReport::markInteresting(SymbolRef sym) {
2107   if (!sym)
2108     return;
2109 
2110   InterestingSymbols.insert(sym);
2111 
2112   if (const auto *meta = dyn_cast<SymbolMetadata>(sym))
2113     InterestingRegions.insert(meta->getRegion());
2114 }
2115 
2116 void BugReport::markInteresting(const MemRegion *R) {
2117   if (!R)
2118     return;
2119 
2120   R = R->getBaseRegion();
2121   InterestingRegions.insert(R);
2122 
2123   if (const auto *SR = dyn_cast<SymbolicRegion>(R))
2124     InterestingSymbols.insert(SR->getSymbol());
2125 }
2126 
2127 void BugReport::markInteresting(SVal V) {
2128   markInteresting(V.getAsRegion());
2129   markInteresting(V.getAsSymbol());
2130 }
2131 
2132 void BugReport::markInteresting(const LocationContext *LC) {
2133   if (!LC)
2134     return;
2135   InterestingLocationContexts.insert(LC);
2136 }
2137 
2138 bool BugReport::isInteresting(SVal V)  const {
2139   return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol());
2140 }
2141 
2142 bool BugReport::isInteresting(SymbolRef sym)  const {
2143   if (!sym)
2144     return false;
2145   // We don't currently consider metadata symbols to be interesting
2146   // even if we know their region is interesting. Is that correct behavior?
2147   return InterestingSymbols.count(sym);
2148 }
2149 
2150 bool BugReport::isInteresting(const MemRegion *R)  const {
2151   if (!R)
2152     return false;
2153   R = R->getBaseRegion();
2154   bool b = InterestingRegions.count(R);
2155   if (b)
2156     return true;
2157   if (const auto *SR = dyn_cast<SymbolicRegion>(R))
2158     return InterestingSymbols.count(SR->getSymbol());
2159   return false;
2160 }
2161 
2162 bool BugReport::isInteresting(const LocationContext *LC)  const {
2163   if (!LC)
2164     return false;
2165   return InterestingLocationContexts.count(LC);
2166 }
2167 
2168 const Stmt *BugReport::getStmt() const {
2169   if (!ErrorNode)
2170     return nullptr;
2171 
2172   ProgramPoint ProgP = ErrorNode->getLocation();
2173   const Stmt *S = nullptr;
2174 
2175   if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
2176     CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
2177     if (BE->getBlock() == &Exit)
2178       S = GetPreviousStmt(ErrorNode);
2179   }
2180   if (!S)
2181     S = PathDiagnosticLocation::getStmt(ErrorNode);
2182 
2183   return S;
2184 }
2185 
2186 llvm::iterator_range<BugReport::ranges_iterator> BugReport::getRanges() const {
2187   // If no custom ranges, add the range of the statement corresponding to
2188   // the error node.
2189   if (Ranges.empty()) {
2190     if (dyn_cast_or_null<Expr>(getStmt()))
2191       return llvm::make_range(&ErrorNodeRange, &ErrorNodeRange + 1);
2192     return llvm::make_range(ranges_iterator(), ranges_iterator());
2193   }
2194 
2195   // User-specified absence of range info.
2196   if (Ranges.size() == 1 && !Ranges.begin()->isValid())
2197     return llvm::make_range(ranges_iterator(), ranges_iterator());
2198 
2199   return llvm::make_range(Ranges.begin(), Ranges.end());
2200 }
2201 
2202 PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
2203   if (ErrorNode) {
2204     assert(!Location.isValid() &&
2205      "Either Location or ErrorNode should be specified but not both.");
2206     return PathDiagnosticLocation::createEndOfPath(ErrorNode, SM);
2207   }
2208 
2209   assert(Location.isValid());
2210   return Location;
2211 }
2212 
2213 //===----------------------------------------------------------------------===//
2214 // Methods for BugReporter and subclasses.
2215 //===----------------------------------------------------------------------===//
2216 
2217 const ExplodedGraph &PathSensitiveBugReporter::getGraph() const {
2218   return Eng.getGraph();
2219 }
2220 
2221 ProgramStateManager &PathSensitiveBugReporter::getStateManager() {
2222   return Eng.getStateManager();
2223 }
2224 
2225 ProgramStateManager &PathSensitiveBugReporter::getStateManager() const {
2226   return Eng.getStateManager();
2227 }
2228 
2229 BugReporter::~BugReporter() {
2230   // Make sure reports are flushed.
2231   assert(StrBugTypes.empty() &&
2232          "Destroying BugReporter before diagnostics are emitted!");
2233 
2234   // Free the bug reports we are tracking.
2235   for (const auto I : EQClassesVector)
2236     delete I;
2237 }
2238 
2239 void BugReporter::FlushReports() {
2240   // We need to flush reports in deterministic order to ensure the order
2241   // of the reports is consistent between runs.
2242   for (const auto EQ : EQClassesVector)
2243     FlushReport(*EQ);
2244 
2245   // BugReporter owns and deletes only BugTypes created implicitly through
2246   // EmitBasicReport.
2247   // FIXME: There are leaks from checkers that assume that the BugTypes they
2248   // create will be destroyed by the BugReporter.
2249   llvm::DeleteContainerSeconds(StrBugTypes);
2250 }
2251 
2252 //===----------------------------------------------------------------------===//
2253 // PathDiagnostics generation.
2254 //===----------------------------------------------------------------------===//
2255 
2256 namespace {
2257 
2258 /// A wrapper around an ExplodedGraph that contains a single path from the root
2259 /// to the error node, and a map that maps the nodes in this path to the ones in
2260 /// the original ExplodedGraph.
2261 class BugPathInfo {
2262 public:
2263   InterExplodedGraphMap MapToOriginNodes;
2264   std::unique_ptr<ExplodedGraph> BugPath;
2265   BugReport *Report;
2266   const ExplodedNode *ErrorNode;
2267 };
2268 
2269 /// A wrapper around an ExplodedGraph whose leafs are all error nodes. Can
2270 /// conveniently retrieve bug paths from a single error node to the root.
2271 class BugPathGetter {
2272   std::unique_ptr<ExplodedGraph> TrimmedGraph;
2273 
2274   /// Map from the trimmed graph to the original.
2275   InterExplodedGraphMap InverseMap;
2276 
2277   using PriorityMapTy = llvm::DenseMap<const ExplodedNode *, unsigned>;
2278 
2279   /// Assign each node with its distance from the root.
2280   PriorityMapTy PriorityMap;
2281 
2282   /// Since the getErrorNode() or BugReport refers to the original ExplodedGraph,
2283   /// we need to pair it to the error node of the constructed trimmed graph.
2284   using ReportNewNodePair = std::pair<BugReport *, const ExplodedNode *>;
2285   SmallVector<ReportNewNodePair, 32> ReportNodes;
2286 
2287   BugPathInfo CurrentBugPath;
2288 
2289   /// A helper class for sorting ExplodedNodes by priority.
2290   template <bool Descending>
2291   class PriorityCompare {
2292     const PriorityMapTy &PriorityMap;
2293 
2294   public:
2295     PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
2296 
2297     bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
2298       PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
2299       PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
2300       PriorityMapTy::const_iterator E = PriorityMap.end();
2301 
2302       if (LI == E)
2303         return Descending;
2304       if (RI == E)
2305         return !Descending;
2306 
2307       return Descending ? LI->second > RI->second
2308                         : LI->second < RI->second;
2309     }
2310 
2311     bool operator()(const ReportNewNodePair &LHS,
2312                     const ReportNewNodePair &RHS) const {
2313       return (*this)(LHS.second, RHS.second);
2314     }
2315   };
2316 
2317 public:
2318   BugPathGetter(const ExplodedGraph *OriginalGraph,
2319                 ArrayRef<BugReport *> &bugReports);
2320 
2321   BugPathInfo *getNextBugPath();
2322 };
2323 
2324 } // namespace
2325 
2326 BugPathGetter::BugPathGetter(const ExplodedGraph *OriginalGraph,
2327                              ArrayRef<BugReport *> &bugReports) {
2328   SmallVector<const ExplodedNode *, 32> Nodes;
2329   for (const auto I : bugReports) {
2330     assert(I->isValid() &&
2331            "We only allow BugReporterVisitors and BugReporter itself to "
2332            "invalidate reports!");
2333     Nodes.emplace_back(I->getErrorNode());
2334   }
2335 
2336   // The trimmed graph is created in the body of the constructor to ensure
2337   // that the DenseMaps have been initialized already.
2338   InterExplodedGraphMap ForwardMap;
2339   TrimmedGraph = OriginalGraph->trim(Nodes, &ForwardMap, &InverseMap);
2340 
2341   // Find the (first) error node in the trimmed graph.  We just need to consult
2342   // the node map which maps from nodes in the original graph to nodes
2343   // in the new graph.
2344   llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes;
2345 
2346   for (BugReport *Report : bugReports) {
2347     const ExplodedNode *NewNode = ForwardMap.lookup(Report->getErrorNode());
2348     assert(NewNode &&
2349            "Failed to construct a trimmed graph that contains this error "
2350            "node!");
2351     ReportNodes.emplace_back(Report, NewNode);
2352     RemainingNodes.insert(NewNode);
2353   }
2354 
2355   assert(!RemainingNodes.empty() && "No error node found in the trimmed graph");
2356 
2357   // Perform a forward BFS to find all the shortest paths.
2358   std::queue<const ExplodedNode *> WS;
2359 
2360   assert(TrimmedGraph->num_roots() == 1);
2361   WS.push(*TrimmedGraph->roots_begin());
2362   unsigned Priority = 0;
2363 
2364   while (!WS.empty()) {
2365     const ExplodedNode *Node = WS.front();
2366     WS.pop();
2367 
2368     PriorityMapTy::iterator PriorityEntry;
2369     bool IsNew;
2370     std::tie(PriorityEntry, IsNew) = PriorityMap.insert({Node, Priority});
2371     ++Priority;
2372 
2373     if (!IsNew) {
2374       assert(PriorityEntry->second <= Priority);
2375       continue;
2376     }
2377 
2378     if (RemainingNodes.erase(Node))
2379       if (RemainingNodes.empty())
2380         break;
2381 
2382     for (const ExplodedNode *Succ : Node->succs())
2383       WS.push(Succ);
2384   }
2385 
2386   // Sort the error paths from longest to shortest.
2387   llvm::sort(ReportNodes, PriorityCompare<true>(PriorityMap));
2388 }
2389 
2390 BugPathInfo *BugPathGetter::getNextBugPath() {
2391   if (ReportNodes.empty())
2392     return nullptr;
2393 
2394   const ExplodedNode *OrigN;
2395   std::tie(CurrentBugPath.Report, OrigN) = ReportNodes.pop_back_val();
2396   assert(PriorityMap.find(OrigN) != PriorityMap.end() &&
2397          "error node not accessible from root");
2398 
2399   // Create a new graph with a single path. This is the graph that will be
2400   // returned to the caller.
2401   auto GNew = std::make_unique<ExplodedGraph>();
2402   CurrentBugPath.MapToOriginNodes.clear();
2403 
2404   // Now walk from the error node up the BFS path, always taking the
2405   // predeccessor with the lowest number.
2406   ExplodedNode *Succ = nullptr;
2407   while (true) {
2408     // Create the equivalent node in the new graph with the same state
2409     // and location.
2410     ExplodedNode *NewN = GNew->createUncachedNode(
2411         OrigN->getLocation(), OrigN->getState(), OrigN->isSink());
2412 
2413     // Store the mapping to the original node.
2414     InterExplodedGraphMap::const_iterator IMitr = InverseMap.find(OrigN);
2415     assert(IMitr != InverseMap.end() && "No mapping to original node.");
2416     CurrentBugPath.MapToOriginNodes[NewN] = IMitr->second;
2417 
2418     // Link up the new node with the previous node.
2419     if (Succ)
2420       Succ->addPredecessor(NewN, *GNew);
2421     else
2422       CurrentBugPath.ErrorNode = NewN;
2423 
2424     Succ = NewN;
2425 
2426     // Are we at the final node?
2427     if (OrigN->pred_empty()) {
2428       GNew->addRoot(NewN);
2429       break;
2430     }
2431 
2432     // Find the next predeccessor node.  We choose the node that is marked
2433     // with the lowest BFS number.
2434     OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(),
2435                               PriorityCompare<false>(PriorityMap));
2436   }
2437 
2438   CurrentBugPath.BugPath = std::move(GNew);
2439 
2440   return &CurrentBugPath;
2441 }
2442 
2443 /// CompactMacroExpandedPieces - This function postprocesses a PathDiagnostic
2444 /// object and collapses PathDiagosticPieces that are expanded by macros.
2445 static void CompactMacroExpandedPieces(PathPieces &path,
2446                                        const SourceManager& SM) {
2447   using MacroStackTy = std::vector<
2448       std::pair<std::shared_ptr<PathDiagnosticMacroPiece>, SourceLocation>>;
2449 
2450   using PiecesTy = std::vector<PathDiagnosticPieceRef>;
2451 
2452   MacroStackTy MacroStack;
2453   PiecesTy Pieces;
2454 
2455   for (PathPieces::const_iterator I = path.begin(), E = path.end();
2456        I != E; ++I) {
2457     const auto &piece = *I;
2458 
2459     // Recursively compact calls.
2460     if (auto *call = dyn_cast<PathDiagnosticCallPiece>(&*piece)) {
2461       CompactMacroExpandedPieces(call->path, SM);
2462     }
2463 
2464     // Get the location of the PathDiagnosticPiece.
2465     const FullSourceLoc Loc = piece->getLocation().asLocation();
2466 
2467     // Determine the instantiation location, which is the location we group
2468     // related PathDiagnosticPieces.
2469     SourceLocation InstantiationLoc = Loc.isMacroID() ?
2470                                       SM.getExpansionLoc(Loc) :
2471                                       SourceLocation();
2472 
2473     if (Loc.isFileID()) {
2474       MacroStack.clear();
2475       Pieces.push_back(piece);
2476       continue;
2477     }
2478 
2479     assert(Loc.isMacroID());
2480 
2481     // Is the PathDiagnosticPiece within the same macro group?
2482     if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
2483       MacroStack.back().first->subPieces.push_back(piece);
2484       continue;
2485     }
2486 
2487     // We aren't in the same group.  Are we descending into a new macro
2488     // or are part of an old one?
2489     std::shared_ptr<PathDiagnosticMacroPiece> MacroGroup;
2490 
2491     SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
2492                                           SM.getExpansionLoc(Loc) :
2493                                           SourceLocation();
2494 
2495     // Walk the entire macro stack.
2496     while (!MacroStack.empty()) {
2497       if (InstantiationLoc == MacroStack.back().second) {
2498         MacroGroup = MacroStack.back().first;
2499         break;
2500       }
2501 
2502       if (ParentInstantiationLoc == MacroStack.back().second) {
2503         MacroGroup = MacroStack.back().first;
2504         break;
2505       }
2506 
2507       MacroStack.pop_back();
2508     }
2509 
2510     if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
2511       // Create a new macro group and add it to the stack.
2512       auto NewGroup = std::make_shared<PathDiagnosticMacroPiece>(
2513           PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
2514 
2515       if (MacroGroup)
2516         MacroGroup->subPieces.push_back(NewGroup);
2517       else {
2518         assert(InstantiationLoc.isFileID());
2519         Pieces.push_back(NewGroup);
2520       }
2521 
2522       MacroGroup = NewGroup;
2523       MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
2524     }
2525 
2526     // Finally, add the PathDiagnosticPiece to the group.
2527     MacroGroup->subPieces.push_back(piece);
2528   }
2529 
2530   // Now take the pieces and construct a new PathDiagnostic.
2531   path.clear();
2532 
2533   path.insert(path.end(), Pieces.begin(), Pieces.end());
2534 }
2535 
2536 /// Generate notes from all visitors.
2537 /// Notes associated with {@code ErrorNode} are generated using
2538 /// {@code getEndPath}, and the rest are generated with {@code VisitNode}.
2539 static std::unique_ptr<VisitorsDiagnosticsTy>
2540 generateVisitorsDiagnostics(BugReport *R, const ExplodedNode *ErrorNode,
2541                             BugReporterContext &BRC) {
2542   std::unique_ptr<VisitorsDiagnosticsTy> Notes =
2543       std::make_unique<VisitorsDiagnosticsTy>();
2544   BugReport::VisitorList visitors;
2545 
2546   // Run visitors on all nodes starting from the node *before* the last one.
2547   // The last node is reserved for notes generated with {@code getEndPath}.
2548   const ExplodedNode *NextNode = ErrorNode->getFirstPred();
2549   while (NextNode) {
2550 
2551     // At each iteration, move all visitors from report to visitor list. This is
2552     // important, because the Profile() functions of the visitors make sure that
2553     // a visitor isn't added multiple times for the same node, but it's fine
2554     // to add the a visitor with Profile() for different nodes (e.g. tracking
2555     // a region at different points of the symbolic execution).
2556     for (std::unique_ptr<BugReporterVisitor> &Visitor : R->visitors())
2557       visitors.push_back(std::move(Visitor));
2558 
2559     R->clearVisitors();
2560 
2561     const ExplodedNode *Pred = NextNode->getFirstPred();
2562     if (!Pred) {
2563       PathDiagnosticPieceRef LastPiece;
2564       for (auto &V : visitors) {
2565         V->finalizeVisitor(BRC, ErrorNode, *R);
2566 
2567         if (auto Piece = V->getEndPath(BRC, ErrorNode, *R)) {
2568           assert(!LastPiece &&
2569                  "There can only be one final piece in a diagnostic.");
2570           assert(Piece->getKind() == PathDiagnosticPiece::Kind::Event &&
2571                  "The final piece must contain a message!");
2572           LastPiece = std::move(Piece);
2573           (*Notes)[ErrorNode].push_back(LastPiece);
2574         }
2575       }
2576       break;
2577     }
2578 
2579     for (auto &V : visitors) {
2580       auto P = V->VisitNode(NextNode, BRC, *R);
2581       if (P)
2582         (*Notes)[NextNode].push_back(std::move(P));
2583     }
2584 
2585     if (!R->isValid())
2586       break;
2587 
2588     NextNode = Pred;
2589   }
2590 
2591   return Notes;
2592 }
2593 
2594 Optional<PathDiagnosticBuilder>
2595 PathDiagnosticBuilder::findValidReport(ArrayRef<BugReport *> &bugReports,
2596                                        PathSensitiveBugReporter &Reporter) {
2597 
2598   BugPathGetter BugGraph(&Reporter.getGraph(), bugReports);
2599 
2600   while (BugPathInfo *BugPath = BugGraph.getNextBugPath()) {
2601     // Find the BugReport with the original location.
2602     BugReport *R = BugPath->Report;
2603     assert(R && "No original report found for sliced graph.");
2604     assert(R->isValid() && "Report selected by trimmed graph marked invalid.");
2605     const ExplodedNode *ErrorNode = BugPath->ErrorNode;
2606 
2607     // Register refutation visitors first, if they mark the bug invalid no
2608     // further analysis is required
2609     R->addVisitor(std::make_unique<LikelyFalsePositiveSuppressionBRVisitor>());
2610 
2611     // Register additional node visitors.
2612     R->addVisitor(std::make_unique<NilReceiverBRVisitor>());
2613     R->addVisitor(std::make_unique<ConditionBRVisitor>());
2614     R->addVisitor(std::make_unique<TagVisitor>());
2615 
2616     BugReporterContext BRC(Reporter, BugPath->MapToOriginNodes);
2617 
2618     // Run all visitors on a given graph, once.
2619     std::unique_ptr<VisitorsDiagnosticsTy> visitorNotes =
2620         generateVisitorsDiagnostics(R, ErrorNode, BRC);
2621 
2622     if (R->isValid()) {
2623       if (Reporter.getAnalyzerOptions().ShouldCrosscheckWithZ3) {
2624         // If crosscheck is enabled, remove all visitors, add the refutation
2625         // visitor and check again
2626         R->clearVisitors();
2627         R->addVisitor(std::make_unique<FalsePositiveRefutationBRVisitor>());
2628 
2629         // We don't overrite the notes inserted by other visitors because the
2630         // refutation manager does not add any new note to the path
2631         generateVisitorsDiagnostics(R, BugPath->ErrorNode, BRC);
2632       }
2633 
2634       // Check if the bug is still valid
2635       if (R->isValid())
2636         return PathDiagnosticBuilder(
2637             std::move(BRC), std::move(BugPath->BugPath), BugPath->Report,
2638             BugPath->ErrorNode, std::move(visitorNotes));
2639     }
2640   }
2641 
2642   return {};
2643 }
2644 
2645 std::unique_ptr<DiagnosticForConsumerMapTy>
2646 PathSensitiveBugReporter::generatePathDiagnostics(
2647     ArrayRef<PathDiagnosticConsumer *> consumers,
2648     ArrayRef<BugReport *> &bugReports) {
2649   assert(!bugReports.empty());
2650 
2651   auto Out = std::make_unique<DiagnosticForConsumerMapTy>();
2652 
2653   Optional<PathDiagnosticBuilder> PDB =
2654       PathDiagnosticBuilder::findValidReport(bugReports, *this);
2655 
2656   if (PDB) {
2657     for (PathDiagnosticConsumer *PC : consumers) {
2658       if (std::unique_ptr<PathDiagnostic> PD = PDB->generate(PC)) {
2659         (*Out)[PC] = std::move(PD);
2660       }
2661     }
2662   }
2663 
2664   return Out;
2665 }
2666 
2667 void BugReporter::emitReport(std::unique_ptr<BugReport> R) {
2668   if (const ExplodedNode *E = R->getErrorNode()) {
2669     // An error node must either be a sink or have a tag, otherwise
2670     // it could get reclaimed before the path diagnostic is created.
2671     assert((E->isSink() || E->getLocation().getTag()) &&
2672             "Error node must either be a sink or have a tag");
2673 
2674     const AnalysisDeclContext *DeclCtx =
2675         E->getLocationContext()->getAnalysisDeclContext();
2676     // The source of autosynthesized body can be handcrafted AST or a model
2677     // file. The locations from handcrafted ASTs have no valid source locations
2678     // and have to be discarded. Locations from model files should be preserved
2679     // for processing and reporting.
2680     if (DeclCtx->isBodyAutosynthesized() &&
2681         !DeclCtx->isBodyAutosynthesizedFromModelFile())
2682       return;
2683   }
2684 
2685   bool ValidSourceLoc = R->getLocation(getSourceManager()).isValid();
2686   assert(ValidSourceLoc);
2687   // If we mess up in a release build, we'd still prefer to just drop the bug
2688   // instead of trying to go on.
2689   if (!ValidSourceLoc)
2690     return;
2691 
2692   // Compute the bug report's hash to determine its equivalence class.
2693   llvm::FoldingSetNodeID ID;
2694   R->Profile(ID);
2695 
2696   // Lookup the equivance class.  If there isn't one, create it.
2697   void *InsertPos;
2698   BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
2699 
2700   if (!EQ) {
2701     EQ = new BugReportEquivClass(std::move(R));
2702     EQClasses.InsertNode(EQ, InsertPos);
2703     EQClassesVector.push_back(EQ);
2704   } else
2705     EQ->AddReport(std::move(R));
2706 }
2707 
2708 //===----------------------------------------------------------------------===//
2709 // Emitting reports in equivalence classes.
2710 //===----------------------------------------------------------------------===//
2711 
2712 namespace {
2713 
2714 struct FRIEC_WLItem {
2715   const ExplodedNode *N;
2716   ExplodedNode::const_succ_iterator I, E;
2717 
2718   FRIEC_WLItem(const ExplodedNode *n)
2719       : N(n), I(N->succ_begin()), E(N->succ_end()) {}
2720 };
2721 
2722 } // namespace
2723 
2724 static BugReport *
2725 FindReportInEquivalenceClass(BugReportEquivClass& EQ,
2726                              SmallVectorImpl<BugReport*> &bugReports) {
2727   BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
2728   assert(I != E);
2729   const BugType& BT = I->getBugType();
2730 
2731   // If we don't need to suppress any of the nodes because they are
2732   // post-dominated by a sink, simply add all the nodes in the equivalence class
2733   // to 'Nodes'.  Any of the reports will serve as a "representative" report.
2734   if (!BT.isSuppressOnSink()) {
2735     BugReport *R = &*I;
2736     for (auto &I : EQ) {
2737       const ExplodedNode *N = I.getErrorNode();
2738       if (N) {
2739         R = &I;
2740         bugReports.push_back(R);
2741       }
2742     }
2743     return R;
2744   }
2745 
2746   // For bug reports that should be suppressed when all paths are post-dominated
2747   // by a sink node, iterate through the reports in the equivalence class
2748   // until we find one that isn't post-dominated (if one exists).  We use a
2749   // DFS traversal of the ExplodedGraph to find a non-sink node.  We could write
2750   // this as a recursive function, but we don't want to risk blowing out the
2751   // stack for very long paths.
2752   BugReport *exampleReport = nullptr;
2753 
2754   for (; I != E; ++I) {
2755     const ExplodedNode *errorNode = I->getErrorNode();
2756 
2757     if (!errorNode)
2758       continue;
2759     if (errorNode->isSink()) {
2760       llvm_unreachable(
2761            "BugType::isSuppressSink() should not be 'true' for sink end nodes");
2762     }
2763     // No successors?  By definition this nodes isn't post-dominated by a sink.
2764     if (errorNode->succ_empty()) {
2765       bugReports.push_back(&*I);
2766       if (!exampleReport)
2767         exampleReport = &*I;
2768       continue;
2769     }
2770 
2771     // See if we are in a no-return CFG block. If so, treat this similarly
2772     // to being post-dominated by a sink. This works better when the analysis
2773     // is incomplete and we have never reached the no-return function call(s)
2774     // that we'd inevitably bump into on this path.
2775     if (const CFGBlock *ErrorB = errorNode->getCFGBlock())
2776       if (ErrorB->isInevitablySinking())
2777         continue;
2778 
2779     // At this point we know that 'N' is not a sink and it has at least one
2780     // successor.  Use a DFS worklist to find a non-sink end-of-path node.
2781     using WLItem = FRIEC_WLItem;
2782     using DFSWorkList = SmallVector<WLItem, 10>;
2783 
2784     llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
2785 
2786     DFSWorkList WL;
2787     WL.push_back(errorNode);
2788     Visited[errorNode] = 1;
2789 
2790     while (!WL.empty()) {
2791       WLItem &WI = WL.back();
2792       assert(!WI.N->succ_empty());
2793 
2794       for (; WI.I != WI.E; ++WI.I) {
2795         const ExplodedNode *Succ = *WI.I;
2796         // End-of-path node?
2797         if (Succ->succ_empty()) {
2798           // If we found an end-of-path node that is not a sink.
2799           if (!Succ->isSink()) {
2800             bugReports.push_back(&*I);
2801             if (!exampleReport)
2802               exampleReport = &*I;
2803             WL.clear();
2804             break;
2805           }
2806           // Found a sink?  Continue on to the next successor.
2807           continue;
2808         }
2809         // Mark the successor as visited.  If it hasn't been explored,
2810         // enqueue it to the DFS worklist.
2811         unsigned &mark = Visited[Succ];
2812         if (!mark) {
2813           mark = 1;
2814           WL.push_back(Succ);
2815           break;
2816         }
2817       }
2818 
2819       // The worklist may have been cleared at this point.  First
2820       // check if it is empty before checking the last item.
2821       if (!WL.empty() && &WL.back() == &WI)
2822         WL.pop_back();
2823     }
2824   }
2825 
2826   // ExampleReport will be NULL if all the nodes in the equivalence class
2827   // were post-dominated by sinks.
2828   return exampleReport;
2829 }
2830 
2831 void BugReporter::FlushReport(BugReportEquivClass& EQ) {
2832   SmallVector<BugReport*, 10> bugReports;
2833   BugReport *report = FindReportInEquivalenceClass(EQ, bugReports);
2834   if (!report)
2835     return;
2836 
2837   ArrayRef<PathDiagnosticConsumer*> Consumers = getPathDiagnosticConsumers();
2838   std::unique_ptr<DiagnosticForConsumerMapTy> Diagnostics =
2839       generateDiagnosticForConsumerMap(report, Consumers, bugReports);
2840 
2841   for (auto &P : *Diagnostics) {
2842     PathDiagnosticConsumer *Consumer = P.first;
2843     std::unique_ptr<PathDiagnostic> &PD = P.second;
2844 
2845     // If the path is empty, generate a single step path with the location
2846     // of the issue.
2847     if (PD->path.empty()) {
2848       PathDiagnosticLocation L = report->getLocation(getSourceManager());
2849       auto piece = std::make_unique<PathDiagnosticEventPiece>(
2850         L, report->getDescription());
2851       for (SourceRange Range : report->getRanges())
2852         piece->addRange(Range);
2853       PD->setEndOfPath(std::move(piece));
2854     }
2855 
2856     PathPieces &Pieces = PD->getMutablePieces();
2857     if (getAnalyzerOptions().ShouldDisplayNotesAsEvents) {
2858       // For path diagnostic consumers that don't support extra notes,
2859       // we may optionally convert those to path notes.
2860       for (auto I = report->getNotes().rbegin(),
2861            E = report->getNotes().rend(); I != E; ++I) {
2862         PathDiagnosticNotePiece *Piece = I->get();
2863         auto ConvertedPiece = std::make_shared<PathDiagnosticEventPiece>(
2864           Piece->getLocation(), Piece->getString());
2865         for (const auto &R: Piece->getRanges())
2866           ConvertedPiece->addRange(R);
2867 
2868         Pieces.push_front(std::move(ConvertedPiece));
2869       }
2870     } else {
2871       for (auto I = report->getNotes().rbegin(),
2872            E = report->getNotes().rend(); I != E; ++I)
2873         Pieces.push_front(*I);
2874     }
2875 
2876     updateExecutedLinesWithDiagnosticPieces(*PD);
2877     Consumer->HandlePathDiagnostic(std::move(PD));
2878   }
2879 }
2880 
2881 /// Insert all lines participating in the function signature \p Signature
2882 /// into \p ExecutedLines.
2883 static void populateExecutedLinesWithFunctionSignature(
2884     const Decl *Signature, const SourceManager &SM,
2885     FilesToLineNumsMap &ExecutedLines) {
2886   SourceRange SignatureSourceRange;
2887   const Stmt* Body = Signature->getBody();
2888   if (const auto FD = dyn_cast<FunctionDecl>(Signature)) {
2889     SignatureSourceRange = FD->getSourceRange();
2890   } else if (const auto OD = dyn_cast<ObjCMethodDecl>(Signature)) {
2891     SignatureSourceRange = OD->getSourceRange();
2892   } else {
2893     return;
2894   }
2895   SourceLocation Start = SignatureSourceRange.getBegin();
2896   SourceLocation End = Body ? Body->getSourceRange().getBegin()
2897     : SignatureSourceRange.getEnd();
2898   if (!Start.isValid() || !End.isValid())
2899     return;
2900   unsigned StartLine = SM.getExpansionLineNumber(Start);
2901   unsigned EndLine = SM.getExpansionLineNumber(End);
2902 
2903   FileID FID = SM.getFileID(SM.getExpansionLoc(Start));
2904   for (unsigned Line = StartLine; Line <= EndLine; Line++)
2905     ExecutedLines[FID].insert(Line);
2906 }
2907 
2908 static void populateExecutedLinesWithStmt(
2909     const Stmt *S, const SourceManager &SM,
2910     FilesToLineNumsMap &ExecutedLines) {
2911   SourceLocation Loc = S->getSourceRange().getBegin();
2912   if (!Loc.isValid())
2913     return;
2914   SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
2915   FileID FID = SM.getFileID(ExpansionLoc);
2916   unsigned LineNo = SM.getExpansionLineNumber(ExpansionLoc);
2917   ExecutedLines[FID].insert(LineNo);
2918 }
2919 
2920 /// \return all executed lines including function signatures on the path
2921 /// starting from \p N.
2922 static std::unique_ptr<FilesToLineNumsMap>
2923 findExecutedLines(const SourceManager &SM, const ExplodedNode *N) {
2924   auto ExecutedLines = std::make_unique<FilesToLineNumsMap>();
2925 
2926   while (N) {
2927     if (N->getFirstPred() == nullptr) {
2928       // First node: show signature of the entrance point.
2929       const Decl *D = N->getLocationContext()->getDecl();
2930       populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
2931     } else if (auto CE = N->getLocationAs<CallEnter>()) {
2932       // Inlined function: show signature.
2933       const Decl* D = CE->getCalleeContext()->getDecl();
2934       populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
2935     } else if (const Stmt *S = PathDiagnosticLocation::getStmt(N)) {
2936       populateExecutedLinesWithStmt(S, SM, *ExecutedLines);
2937 
2938       // Show extra context for some parent kinds.
2939       const Stmt *P = N->getParentMap().getParent(S);
2940 
2941       // The path exploration can die before the node with the associated
2942       // return statement is generated, but we do want to show the whole
2943       // return.
2944       if (const auto *RS = dyn_cast_or_null<ReturnStmt>(P)) {
2945         populateExecutedLinesWithStmt(RS, SM, *ExecutedLines);
2946         P = N->getParentMap().getParent(RS);
2947       }
2948 
2949       if (P && (isa<SwitchCase>(P) || isa<LabelStmt>(P)))
2950         populateExecutedLinesWithStmt(P, SM, *ExecutedLines);
2951     }
2952 
2953     N = N->getFirstPred();
2954   }
2955   return ExecutedLines;
2956 }
2957 
2958 std::unique_ptr<DiagnosticForConsumerMapTy>
2959 BugReporter::generateDiagnosticForConsumerMap(
2960     BugReport *report, ArrayRef<PathDiagnosticConsumer *> consumers,
2961     ArrayRef<BugReport *> bugReports) {
2962 
2963   if (!report->isPathSensitive()) {
2964     auto Out = std::make_unique<DiagnosticForConsumerMapTy>();
2965     for (auto *Consumer : consumers)
2966       (*Out)[Consumer] = generateEmptyDiagnosticForReport(report,
2967                                                           getSourceManager());
2968     return Out;
2969   }
2970 
2971   // Generate the full path sensitive diagnostic, using the generation scheme
2972   // specified by the PathDiagnosticConsumer. Note that we have to generate
2973   // path diagnostics even for consumers which do not support paths, because
2974   // the BugReporterVisitors may mark this bug as a false positive.
2975   assert(!bugReports.empty());
2976   MaxBugClassSize.updateMax(bugReports.size());
2977   std::unique_ptr<DiagnosticForConsumerMapTy> Out =
2978     generatePathDiagnostics(consumers, bugReports);
2979 
2980   if (Out->empty())
2981     return Out;
2982 
2983   MaxValidBugClassSize.updateMax(bugReports.size());
2984 
2985   // Examine the report and see if the last piece is in a header. Reset the
2986   // report location to the last piece in the main source file.
2987   const AnalyzerOptions &Opts = getAnalyzerOptions();
2988   for (auto const &P : *Out)
2989     if (Opts.ShouldReportIssuesInMainSourceFile && !Opts.AnalyzeAll)
2990       P.second->resetDiagnosticLocationToMainFile();
2991 
2992   return Out;
2993 }
2994 
2995 void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
2996                                   const CheckerBase *Checker,
2997                                   StringRef Name, StringRef Category,
2998                                   StringRef Str, PathDiagnosticLocation Loc,
2999                                   ArrayRef<SourceRange> Ranges) {
3000   EmitBasicReport(DeclWithIssue, Checker->getCheckName(), Name, Category, Str,
3001                   Loc, Ranges);
3002 }
3003 
3004 void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
3005                                   CheckName CheckName,
3006                                   StringRef name, StringRef category,
3007                                   StringRef str, PathDiagnosticLocation Loc,
3008                                   ArrayRef<SourceRange> Ranges) {
3009   // 'BT' is owned by BugReporter.
3010   BugType *BT = getBugTypeForName(CheckName, name, category);
3011   auto R = std::make_unique<BugReport>(*BT, str, Loc);
3012   R->setDeclWithIssue(DeclWithIssue);
3013   for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
3014        I != E; ++I)
3015     R->addRange(*I);
3016   emitReport(std::move(R));
3017 }
3018 
3019 BugType *BugReporter::getBugTypeForName(CheckName CheckName, StringRef name,
3020                                         StringRef category) {
3021   SmallString<136> fullDesc;
3022   llvm::raw_svector_ostream(fullDesc) << CheckName.getName() << ":" << name
3023                                       << ":" << category;
3024   BugType *&BT = StrBugTypes[fullDesc];
3025   if (!BT)
3026     BT = new BugType(CheckName, name, category);
3027   return BT;
3028 }
3029