1//===- PathDiagnostic.cpp - Path-Specific Diagnostic Handling -------------===//
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 the PathDiagnostic-related interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Analysis/PathDiagnostic.h"
14#include "clang/AST/Decl.h"
15#include "clang/AST/DeclBase.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ParentMap.h"
22#include "clang/AST/PrettyPrinter.h"
23#include "clang/AST/Stmt.h"
24#include "clang/AST/Type.h"
25#include "clang/Analysis/AnalysisDeclContext.h"
26#include "clang/Analysis/CFG.h"
27#include "clang/Analysis/IssueHash.h"
28#include "clang/Analysis/ProgramPoint.h"
29#include "clang/Basic/LLVM.h"
30#include "clang/Basic/SourceLocation.h"
31#include "clang/Basic/SourceManager.h"
32#include "llvm/ADT/ArrayRef.h"
33#include "llvm/ADT/FoldingSet.h"
34#include "llvm/ADT/STLExtras.h"
35#include "llvm/ADT/StringExtras.h"
36#include "llvm/ADT/StringRef.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/raw_ostream.h"
39#include <cassert>
40#include <cstring>
41#include <memory>
42#include <optional>
43#include <utility>
44#include <vector>
45
46using namespace clang;
47using namespace ento;
48
49static StringRef StripTrailingDots(StringRef s) { return s.rtrim(Char: '.'); }
50
51PathDiagnosticPiece::PathDiagnosticPiece(StringRef s,
52 Kind k, DisplayHint hint)
53 : str(StripTrailingDots(s)), kind(k), Hint(hint) {}
54
55PathDiagnosticPiece::PathDiagnosticPiece(Kind k, DisplayHint hint)
56 : kind(k), Hint(hint) {}
57
58PathDiagnosticPiece::~PathDiagnosticPiece() = default;
59
60PathDiagnosticEventPiece::~PathDiagnosticEventPiece() = default;
61
62PathDiagnosticCallPiece::~PathDiagnosticCallPiece() = default;
63
64PathDiagnosticControlFlowPiece::~PathDiagnosticControlFlowPiece() = default;
65
66PathDiagnosticMacroPiece::~PathDiagnosticMacroPiece() = default;
67
68PathDiagnosticNotePiece::~PathDiagnosticNotePiece() = default;
69
70PathDiagnosticPopUpPiece::~PathDiagnosticPopUpPiece() = default;
71
72void PathPieces::flattenTo(PathPieces &Primary, PathPieces &Current,
73 bool ShouldFlattenMacros) const {
74 for (auto &Piece : *this) {
75 switch (Piece->getKind()) {
76 case PathDiagnosticPiece::Call: {
77 auto &Call = cast<PathDiagnosticCallPiece>(Val&: *Piece);
78 if (auto CallEnter = Call.getCallEnterEvent())
79 Current.push_back(x: std::move(CallEnter));
80 Call.path.flattenTo(Primary, Current&: Primary, ShouldFlattenMacros);
81 if (auto callExit = Call.getCallExitEvent())
82 Current.push_back(x: std::move(callExit));
83 break;
84 }
85 case PathDiagnosticPiece::Macro: {
86 auto &Macro = cast<PathDiagnosticMacroPiece>(Val&: *Piece);
87 if (ShouldFlattenMacros) {
88 Macro.subPieces.flattenTo(Primary, Current&: Primary, ShouldFlattenMacros);
89 } else {
90 Current.push_back(x: Piece);
91 PathPieces NewPath;
92 Macro.subPieces.flattenTo(Primary, Current&: NewPath, ShouldFlattenMacros);
93 // FIXME: This probably shouldn't mutate the original path piece.
94 Macro.subPieces = NewPath;
95 }
96 break;
97 }
98 case PathDiagnosticPiece::Event:
99 case PathDiagnosticPiece::ControlFlow:
100 case PathDiagnosticPiece::Note:
101 case PathDiagnosticPiece::PopUp:
102 Current.push_back(x: Piece);
103 break;
104 }
105 }
106}
107
108PathDiagnostic::~PathDiagnostic() = default;
109
110PathDiagnostic::PathDiagnostic(
111 StringRef CheckerName, const Decl *declWithIssue, StringRef bugtype,
112 StringRef verboseDesc, StringRef shortDesc, StringRef category,
113 PathDiagnosticLocation LocationToUnique, const Decl *DeclToUnique,
114 const Decl *AnalysisEntryPoint,
115 std::unique_ptr<FilesToLineNumsMap> ExecutedLines)
116 : CheckerName(CheckerName), DeclWithIssue(declWithIssue),
117 BugType(StripTrailingDots(s: bugtype)),
118 VerboseDesc(StripTrailingDots(s: verboseDesc)),
119 ShortDesc(StripTrailingDots(s: shortDesc)),
120 Category(StripTrailingDots(s: category)), UniqueingLoc(LocationToUnique),
121 UniqueingDecl(DeclToUnique), AnalysisEntryPoint(AnalysisEntryPoint),
122 ExecutedLines(std::move(ExecutedLines)), path(pathImpl) {
123 assert(AnalysisEntryPoint);
124}
125
126void PathDiagnosticConsumer::anchor() {}
127
128PathDiagnosticConsumer::~PathDiagnosticConsumer() {
129 // Delete the contents of the FoldingSet if it isn't empty already.
130 for (auto &Diag : Diags)
131 delete &Diag;
132}
133
134void PathDiagnosticConsumer::HandlePathDiagnostic(
135 std::unique_ptr<PathDiagnostic> D) {
136 if (!D || D->path.empty())
137 return;
138
139 // We need to flatten the locations (convert Stmt* to locations) because
140 // the referenced statements may be freed by the time the diagnostics
141 // are emitted.
142 D->flattenLocations();
143
144 // If the PathDiagnosticConsumer does not support diagnostics that
145 // cross file boundaries, prune out such diagnostics now.
146 if (!supportsCrossFileDiagnostics()) {
147 // Verify that the entire path is from the same FileID.
148 FileID FID;
149 const SourceManager &SMgr = D->path.front()->getLocation().getManager();
150 SmallVector<const PathPieces *, 5> WorkList;
151 WorkList.push_back(Elt: &D->path);
152 SmallString<128> buf;
153 llvm::raw_svector_ostream warning(buf);
154 warning << "warning: Path diagnostic report is not generated. Current "
155 << "output format does not support diagnostics that cross file "
156 << "boundaries. Refer to --analyzer-output for valid output "
157 << "formats\n";
158
159 while (!WorkList.empty()) {
160 const PathPieces &path = *WorkList.pop_back_val();
161
162 for (const auto &I : path) {
163 const PathDiagnosticPiece *piece = I.get();
164 FullSourceLoc L = piece->getLocation().asLocation().getExpansionLoc();
165
166 if (FID.isInvalid()) {
167 FID = SMgr.getFileID(SpellingLoc: L);
168 } else if (SMgr.getFileID(SpellingLoc: L) != FID) {
169 llvm::errs() << warning.str();
170 return;
171 }
172
173 // Check the source ranges.
174 ArrayRef<SourceRange> Ranges = piece->getRanges();
175 for (const auto &I : Ranges) {
176 SourceLocation L = SMgr.getExpansionLoc(Loc: I.getBegin());
177 if (!L.isFileID() || SMgr.getFileID(SpellingLoc: L) != FID) {
178 llvm::errs() << warning.str();
179 return;
180 }
181 L = SMgr.getExpansionLoc(Loc: I.getEnd());
182 if (!L.isFileID() || SMgr.getFileID(SpellingLoc: L) != FID) {
183 llvm::errs() << warning.str();
184 return;
185 }
186 }
187
188 if (const auto *call = dyn_cast<PathDiagnosticCallPiece>(Val: piece))
189 WorkList.push_back(Elt: &call->path);
190 else if (const auto *macro = dyn_cast<PathDiagnosticMacroPiece>(Val: piece))
191 WorkList.push_back(Elt: &macro->subPieces);
192 }
193 }
194
195 if (FID.isInvalid())
196 return; // FIXME: Emit a warning?
197 }
198
199 // Profile the node to see if we already have something matching it
200 llvm::FoldingSetNodeID profile;
201 D->Profile(ID&: profile);
202 void *InsertPos = nullptr;
203
204 if (PathDiagnostic *orig = Diags.FindNodeOrInsertPos(ID: profile, InsertPos)) {
205 // Keep the PathDiagnostic with the shorter path.
206 // Note, the enclosing routine is called in deterministic order, so the
207 // results will be consistent between runs (no reason to break ties if the
208 // size is the same).
209 const unsigned orig_size = orig->full_size();
210 const unsigned new_size = D->full_size();
211 if (orig_size <= new_size)
212 return;
213
214 assert(orig != D.get());
215 Diags.RemoveNode(N: orig);
216 delete orig;
217 }
218
219 Diags.InsertNode(N: D.release());
220}
221
222static std::optional<bool> comparePath(const PathPieces &X,
223 const PathPieces &Y);
224
225static std::optional<bool>
226compareControlFlow(const PathDiagnosticControlFlowPiece &X,
227 const PathDiagnosticControlFlowPiece &Y) {
228 FullSourceLoc XSL = X.getStartLocation().asLocation();
229 FullSourceLoc YSL = Y.getStartLocation().asLocation();
230 if (XSL != YSL)
231 return XSL.isBeforeInTranslationUnitThan(Loc: YSL);
232 FullSourceLoc XEL = X.getEndLocation().asLocation();
233 FullSourceLoc YEL = Y.getEndLocation().asLocation();
234 if (XEL != YEL)
235 return XEL.isBeforeInTranslationUnitThan(Loc: YEL);
236 return std::nullopt;
237}
238
239static std::optional<bool> compareMacro(const PathDiagnosticMacroPiece &X,
240 const PathDiagnosticMacroPiece &Y) {
241 return comparePath(X: X.subPieces, Y: Y.subPieces);
242}
243
244static std::optional<bool> compareCall(const PathDiagnosticCallPiece &X,
245 const PathDiagnosticCallPiece &Y) {
246 FullSourceLoc X_CEL = X.callEnter.asLocation();
247 FullSourceLoc Y_CEL = Y.callEnter.asLocation();
248 if (X_CEL != Y_CEL)
249 return X_CEL.isBeforeInTranslationUnitThan(Loc: Y_CEL);
250 FullSourceLoc X_CEWL = X.callEnterWithin.asLocation();
251 FullSourceLoc Y_CEWL = Y.callEnterWithin.asLocation();
252 if (X_CEWL != Y_CEWL)
253 return X_CEWL.isBeforeInTranslationUnitThan(Loc: Y_CEWL);
254 FullSourceLoc X_CRL = X.callReturn.asLocation();
255 FullSourceLoc Y_CRL = Y.callReturn.asLocation();
256 if (X_CRL != Y_CRL)
257 return X_CRL.isBeforeInTranslationUnitThan(Loc: Y_CRL);
258 return comparePath(X: X.path, Y: Y.path);
259}
260
261static std::optional<bool> comparePiece(const PathDiagnosticPiece &X,
262 const PathDiagnosticPiece &Y) {
263 if (X.getKind() != Y.getKind())
264 return X.getKind() < Y.getKind();
265
266 FullSourceLoc XL = X.getLocation().asLocation();
267 FullSourceLoc YL = Y.getLocation().asLocation();
268 if (XL != YL)
269 return XL.isBeforeInTranslationUnitThan(Loc: YL);
270
271 if (X.getString() != Y.getString())
272 return X.getString() < Y.getString();
273
274 if (X.getRanges().size() != Y.getRanges().size())
275 return X.getRanges().size() < Y.getRanges().size();
276
277 const SourceManager &SM = XL.getManager();
278
279 for (unsigned i = 0, n = X.getRanges().size(); i < n; ++i) {
280 SourceRange XR = X.getRanges()[i];
281 SourceRange YR = Y.getRanges()[i];
282 if (XR != YR) {
283 if (XR.getBegin() != YR.getBegin())
284 return SM.isBeforeInTranslationUnit(LHS: XR.getBegin(), RHS: YR.getBegin());
285 return SM.isBeforeInTranslationUnit(LHS: XR.getEnd(), RHS: YR.getEnd());
286 }
287 }
288
289 switch (X.getKind()) {
290 case PathDiagnosticPiece::ControlFlow:
291 return compareControlFlow(X: cast<PathDiagnosticControlFlowPiece>(Val: X),
292 Y: cast<PathDiagnosticControlFlowPiece>(Val: Y));
293 case PathDiagnosticPiece::Macro:
294 return compareMacro(X: cast<PathDiagnosticMacroPiece>(Val: X),
295 Y: cast<PathDiagnosticMacroPiece>(Val: Y));
296 case PathDiagnosticPiece::Call:
297 return compareCall(X: cast<PathDiagnosticCallPiece>(Val: X),
298 Y: cast<PathDiagnosticCallPiece>(Val: Y));
299 case PathDiagnosticPiece::Event:
300 case PathDiagnosticPiece::Note:
301 case PathDiagnosticPiece::PopUp:
302 return std::nullopt;
303 }
304 llvm_unreachable("all cases handled");
305}
306
307static std::optional<bool> comparePath(const PathPieces &X,
308 const PathPieces &Y) {
309 if (X.size() != Y.size())
310 return X.size() < Y.size();
311
312 PathPieces::const_iterator X_I = X.begin(), X_end = X.end();
313 PathPieces::const_iterator Y_I = Y.begin(), Y_end = Y.end();
314
315 for (; X_I != X_end && Y_I != Y_end; ++X_I, ++Y_I)
316 if (std::optional<bool> b = comparePiece(X: **X_I, Y: **Y_I))
317 return *b;
318
319 return std::nullopt;
320}
321
322static bool compareCrossTUSourceLocs(FullSourceLoc XL, FullSourceLoc YL) {
323 if (XL.isInvalid() && YL.isValid())
324 return true;
325 if (XL.isValid() && YL.isInvalid())
326 return false;
327 FileIDAndOffset XOffs = XL.getDecomposedLoc();
328 FileIDAndOffset YOffs = YL.getDecomposedLoc();
329 const SourceManager &SM = XL.getManager();
330 std::pair<bool, bool> InSameTU = SM.isInTheSameTranslationUnit(LOffs&: XOffs, ROffs&: YOffs);
331 if (InSameTU.first)
332 return XL.isBeforeInTranslationUnitThan(Loc: YL);
333 OptionalFileEntryRef XFE =
334 SM.getFileEntryRefForID(FID: XL.getSpellingLoc().getFileID());
335 OptionalFileEntryRef YFE =
336 SM.getFileEntryRefForID(FID: YL.getSpellingLoc().getFileID());
337 if (!XFE || !YFE)
338 return XFE && !YFE;
339 int NameCmp = XFE->getName().compare(RHS: YFE->getName());
340 if (NameCmp != 0)
341 return NameCmp < 0;
342 // Last resort: Compare raw file IDs that are possibly expansions.
343 return XL.getFileID() < YL.getFileID();
344}
345
346static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y) {
347 FullSourceLoc XL = X.getLocation().asLocation();
348 FullSourceLoc YL = Y.getLocation().asLocation();
349 if (XL != YL)
350 return compareCrossTUSourceLocs(XL, YL);
351 FullSourceLoc XUL = X.getUniqueingLoc().asLocation();
352 FullSourceLoc YUL = Y.getUniqueingLoc().asLocation();
353 if (XUL != YUL)
354 return compareCrossTUSourceLocs(XL: XUL, YL: YUL);
355 if (X.getBugType() != Y.getBugType())
356 return X.getBugType() < Y.getBugType();
357 if (X.getCategory() != Y.getCategory())
358 return X.getCategory() < Y.getCategory();
359 if (X.getVerboseDescription() != Y.getVerboseDescription())
360 return X.getVerboseDescription() < Y.getVerboseDescription();
361 if (X.getShortDescription() != Y.getShortDescription())
362 return X.getShortDescription() < Y.getShortDescription();
363 auto CompareDecls = [&XL](const Decl *D1,
364 const Decl *D2) -> std::optional<bool> {
365 if (D1 == D2)
366 return std::nullopt;
367 if (!D1)
368 return true;
369 if (!D2)
370 return false;
371 SourceLocation D1L = D1->getLocation();
372 SourceLocation D2L = D2->getLocation();
373 if (D1L != D2L) {
374 const SourceManager &SM = XL.getManager();
375 return compareCrossTUSourceLocs(XL: FullSourceLoc(D1L, SM),
376 YL: FullSourceLoc(D2L, SM));
377 }
378 return std::nullopt;
379 };
380 if (auto Result = CompareDecls(X.getDeclWithIssue(), Y.getDeclWithIssue()))
381 return *Result;
382 if (XUL.isValid()) {
383 if (auto Result = CompareDecls(X.getUniqueingDecl(), Y.getUniqueingDecl()))
384 return *Result;
385 }
386 PathDiagnostic::meta_iterator XI = X.meta_begin(), XE = X.meta_end();
387 PathDiagnostic::meta_iterator YI = Y.meta_begin(), YE = Y.meta_end();
388 if (XE - XI != YE - YI)
389 return (XE - XI) < (YE - YI);
390 for ( ; XI != XE ; ++XI, ++YI) {
391 if (*XI != *YI)
392 return (*XI) < (*YI);
393 }
394 return *comparePath(X: X.path, Y: Y.path);
395}
396
397void PathDiagnosticConsumer::FlushDiagnostics(
398 PathDiagnosticConsumer::FilesMade *Files) {
399 if (flushed)
400 return;
401
402 flushed = true;
403
404 std::vector<const PathDiagnostic *> BatchDiags;
405 for (const auto &D : Diags)
406 BatchDiags.push_back(x: &D);
407
408 // Sort the diagnostics so that they are always emitted in a deterministic
409 // order.
410 int (*Comp)(const PathDiagnostic *const *, const PathDiagnostic *const *) =
411 [](const PathDiagnostic *const *X, const PathDiagnostic *const *Y) {
412 assert(*X != *Y && "PathDiagnostics not uniqued!");
413 if (compare(X: **X, Y: **Y))
414 return -1;
415 assert(compare(**Y, **X) && "Not a total order!");
416 return 1;
417 };
418 array_pod_sort(Start: BatchDiags.begin(), End: BatchDiags.end(), Compare: Comp);
419
420 FlushDiagnosticsImpl(Diags&: BatchDiags, filesMade: Files);
421
422 // Delete the flushed diagnostics.
423 for (const auto D : BatchDiags)
424 delete D;
425
426 // Clear out the FoldingSet.
427 Diags.clear();
428}
429
430PathDiagnosticConsumer::FilesMade::~FilesMade() {
431 for (auto It = Set.begin(); It != Set.end();)
432 (It++)->~PDFileEntry();
433}
434
435void PathDiagnosticConsumer::FilesMade::addDiagnostic(const PathDiagnostic &PD,
436 StringRef ConsumerName,
437 StringRef FileName) {
438 llvm::FoldingSetNodeID NodeID;
439 NodeID.Add(x: PD);
440 void *InsertPos;
441 PDFileEntry *Entry = Set.FindNodeOrInsertPos(ID: NodeID, InsertPos);
442 if (!Entry) {
443 Entry = Alloc.Allocate<PDFileEntry>();
444 Entry = new (Entry) PDFileEntry(NodeID);
445 Set.InsertNode(N: Entry, InsertPos);
446 }
447
448 // Allocate persistent storage for the file name.
449 char *FileName_cstr = (char*) Alloc.Allocate(Size: FileName.size(), Alignment: 1);
450 memcpy(dest: FileName_cstr, src: FileName.data(), n: FileName.size());
451
452 Entry->files.push_back(x: std::make_pair(x&: ConsumerName,
453 y: StringRef(FileName_cstr,
454 FileName.size())));
455}
456
457PathDiagnosticConsumer::PDFileEntry::ConsumerFiles *
458PathDiagnosticConsumer::FilesMade::getFiles(const PathDiagnostic &PD) {
459 llvm::FoldingSetNodeID NodeID;
460 NodeID.Add(x: PD);
461 void *InsertPos;
462 PDFileEntry *Entry = Set.FindNodeOrInsertPos(ID: NodeID, InsertPos);
463 if (!Entry)
464 return nullptr;
465 return &Entry->files;
466}
467
468//===----------------------------------------------------------------------===//
469// PathDiagnosticLocation methods.
470//===----------------------------------------------------------------------===//
471
472SourceLocation PathDiagnosticLocation::getValidSourceLocation(
473 const Stmt *S, StackFrameOrAnalysisDeclContext SFAC,
474 bool UseEndOfStatement) {
475 SourceLocation L = UseEndOfStatement ? S->getEndLoc() : S->getBeginLoc();
476 assert(!SFAC.isNull() &&
477 "A valid StackFrame or AnalysisDeclContext should be passed to "
478 "PathDiagnosticLocation upon creation.");
479
480 // S might be a temporary statement that does not have a location in the
481 // source code, so find an enclosing statement and use its location.
482 if (!L.isValid()) {
483 AnalysisDeclContext *ADC;
484 if (auto *SF = dyn_cast<const StackFrame *>(Val&: SFAC))
485 ADC = SF->getAnalysisDeclContext();
486 else
487 ADC = cast<AnalysisDeclContext *>(Val&: SFAC);
488
489 ParentMap &PM = ADC->getParentMap();
490
491 const Stmt *Parent = S;
492 do {
493 Parent = PM.getParent(S: Parent);
494
495 // In rare cases, we have implicit top-level expressions,
496 // such as arguments for implicit member initializers.
497 // In this case, fall back to the start of the body (even if we were
498 // asked for the statement end location).
499 if (!Parent) {
500 const Stmt *Body = ADC->getBody();
501 if (Body)
502 L = Body->getBeginLoc();
503 else
504 L = ADC->getDecl()->getEndLoc();
505 break;
506 }
507
508 L = UseEndOfStatement ? Parent->getEndLoc() : Parent->getBeginLoc();
509 } while (!L.isValid());
510 }
511
512 // FIXME: Ironically, this assert actually fails in some cases.
513 //assert(L.isValid());
514 return L;
515}
516
517static PathDiagnosticLocation getLocationForCaller(const StackFrame *SF,
518 const StackFrame *CallerSF,
519 const SourceManager &SM) {
520 const CFGBlock &Block = *SF->getCallSiteBlock();
521 CFGElement Source = Block[SF->getIndex()];
522
523 switch (Source.getKind()) {
524 case CFGElement::Statement:
525 case CFGElement::Constructor:
526 case CFGElement::CXXRecordTypedCall:
527 return PathDiagnosticLocation(Source.castAs<CFGStmt>().getStmt(), SM,
528 CallerSF);
529 case CFGElement::Initializer: {
530 const CFGInitializer &Init = Source.castAs<CFGInitializer>();
531 return PathDiagnosticLocation(Init.getInitializer()->getInit(), SM,
532 CallerSF);
533 }
534 case CFGElement::AutomaticObjectDtor: {
535 const CFGAutomaticObjDtor &Dtor = Source.castAs<CFGAutomaticObjDtor>();
536 return PathDiagnosticLocation::createEnd(S: Dtor.getTriggerStmt(), SM,
537 SFAC: CallerSF);
538 }
539 case CFGElement::DeleteDtor: {
540 const CFGDeleteDtor &Dtor = Source.castAs<CFGDeleteDtor>();
541 return PathDiagnosticLocation(Dtor.getDeleteExpr(), SM, CallerSF);
542 }
543 case CFGElement::BaseDtor:
544 case CFGElement::MemberDtor: {
545 const AnalysisDeclContext *CallerInfo = CallerSF->getAnalysisDeclContext();
546 if (const Stmt *CallerBody = CallerInfo->getBody())
547 return PathDiagnosticLocation::createEnd(S: CallerBody, SM, SFAC: CallerSF);
548 return PathDiagnosticLocation::create(D: CallerInfo->getDecl(), SM);
549 }
550 case CFGElement::NewAllocator: {
551 const CFGNewAllocator &Alloc = Source.castAs<CFGNewAllocator>();
552 return PathDiagnosticLocation(Alloc.getAllocatorExpr(), SM, CallerSF);
553 }
554 case CFGElement::TemporaryDtor: {
555 // Temporary destructors are for temporaries. They die immediately at around
556 // the location of CXXBindTemporaryExpr. If they are lifetime-extended,
557 // they'd be dealt with via an AutomaticObjectDtor instead.
558 const auto &Dtor = Source.castAs<CFGTemporaryDtor>();
559 return PathDiagnosticLocation::createEnd(S: Dtor.getBindTemporaryExpr(), SM,
560 SFAC: CallerSF);
561 }
562 case CFGElement::ScopeBegin:
563 case CFGElement::ScopeEnd:
564 case CFGElement::CleanupFunction:
565 llvm_unreachable("not yet implemented!");
566 case CFGElement::LifetimeEnds:
567 case CFGElement::FullExprCleanup:
568 case CFGElement::LoopExit:
569 llvm_unreachable("CFGElement kind should not be on callsite!");
570 }
571
572 llvm_unreachable("Unknown CFGElement kind");
573}
574
575PathDiagnosticLocation
576PathDiagnosticLocation::createBegin(const Decl *D,
577 const SourceManager &SM) {
578 return PathDiagnosticLocation(D->getBeginLoc(), SM, SingleLocK);
579}
580
581PathDiagnosticLocation
582PathDiagnosticLocation::createBegin(const Stmt *S, const SourceManager &SM,
583 StackFrameOrAnalysisDeclContext SFAC) {
584 assert(S && "Statement cannot be null");
585 return PathDiagnosticLocation(getValidSourceLocation(S, SFAC), SM,
586 SingleLocK);
587}
588
589PathDiagnosticLocation
590PathDiagnosticLocation::createEnd(const Stmt *S, const SourceManager &SM,
591 StackFrameOrAnalysisDeclContext SFAC) {
592 if (const auto *CS = dyn_cast<CompoundStmt>(Val: S))
593 return createEndBrace(CS, SM);
594 return PathDiagnosticLocation(getValidSourceLocation(S, SFAC, /*End=*/UseEndOfStatement: true),
595 SM, SingleLocK);
596}
597
598PathDiagnosticLocation
599PathDiagnosticLocation::createOperatorLoc(const BinaryOperator *BO,
600 const SourceManager &SM) {
601 return PathDiagnosticLocation(BO->getOperatorLoc(), SM, SingleLocK);
602}
603
604PathDiagnosticLocation
605PathDiagnosticLocation::createConditionalColonLoc(
606 const ConditionalOperator *CO,
607 const SourceManager &SM) {
608 return PathDiagnosticLocation(CO->getColonLoc(), SM, SingleLocK);
609}
610
611PathDiagnosticLocation
612PathDiagnosticLocation::createMemberLoc(const MemberExpr *ME,
613 const SourceManager &SM) {
614
615 assert(ME->getMemberLoc().isValid() || ME->getBeginLoc().isValid());
616
617 // In some cases, getMemberLoc isn't valid -- in this case we'll return with
618 // some other related valid SourceLocation.
619 if (ME->getMemberLoc().isValid())
620 return PathDiagnosticLocation(ME->getMemberLoc(), SM, SingleLocK);
621
622 return PathDiagnosticLocation(ME->getBeginLoc(), SM, SingleLocK);
623}
624
625PathDiagnosticLocation
626PathDiagnosticLocation::createBeginBrace(const CompoundStmt *CS,
627 const SourceManager &SM) {
628 SourceLocation L = CS->getLBracLoc();
629 return PathDiagnosticLocation(L, SM, SingleLocK);
630}
631
632PathDiagnosticLocation
633PathDiagnosticLocation::createEndBrace(const CompoundStmt *CS,
634 const SourceManager &SM) {
635 SourceLocation L = CS->getRBracLoc();
636 return PathDiagnosticLocation(L, SM, SingleLocK);
637}
638
639PathDiagnosticLocation
640PathDiagnosticLocation::createDeclBegin(const StackFrame *SF,
641 const SourceManager &SM) {
642 // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
643 if (const auto *CS = dyn_cast_or_null<CompoundStmt>(Val: SF->getDecl()->getBody()))
644 if (!CS->body_empty()) {
645 SourceLocation Loc = (*CS->body_begin())->getBeginLoc();
646 return PathDiagnosticLocation(Loc, SM, SingleLocK);
647 }
648
649 return PathDiagnosticLocation();
650}
651
652PathDiagnosticLocation
653PathDiagnosticLocation::createDeclEnd(const StackFrame *SF,
654 const SourceManager &SM) {
655 SourceLocation L = SF->getDecl()->getBodyRBrace();
656 return PathDiagnosticLocation(L, SM, SingleLocK);
657}
658
659PathDiagnosticLocation
660PathDiagnosticLocation::create(const ProgramPoint& P,
661 const SourceManager &SMng) {
662 const Stmt* S = nullptr;
663 if (std::optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
664 const CFGBlock *BSrc = BE->getSrc();
665 if (BSrc->getTerminator().isVirtualBaseBranch()) {
666 // TODO: VirtualBaseBranches should also appear for destructors.
667 // In this case we should put the diagnostic at the end of decl.
668 return PathDiagnosticLocation::createBegin(D: P.getStackFrame()->getDecl(),
669 SM: SMng);
670
671 } else {
672 S = BSrc->getTerminatorCondition();
673 if (!S) {
674 // If the BlockEdge has no terminator condition statement but its
675 // source is the entry of the CFG (e.g. a checker crated the branch at
676 // the beginning of a function), use the function's declaration instead.
677 assert(BSrc == &BSrc->getParent()->getEntry() && "CFGBlock has no "
678 "TerminatorCondition and is not the enrty block of the CFG");
679 return PathDiagnosticLocation::createBegin(D: P.getStackFrame()->getDecl(),
680 SM: SMng);
681 }
682 }
683 } else if (std::optional<StmtPoint> SP = P.getAs<StmtPoint>()) {
684 S = SP->getStmt();
685 if (P.getAs<PostStmtPurgeDeadSymbols>())
686 return PathDiagnosticLocation::createEnd(S, SM: SMng, SFAC: P.getStackFrame());
687 } else if (std::optional<PostInitializer> PIP = P.getAs<PostInitializer>()) {
688 return PathDiagnosticLocation(PIP->getInitializer()->getSourceLocation(),
689 SMng);
690 } else if (std::optional<PreImplicitCall> PIC = P.getAs<PreImplicitCall>()) {
691 return PathDiagnosticLocation(PIC->getLocation(), SMng);
692 } else if (std::optional<PostImplicitCall> PIE =
693 P.getAs<PostImplicitCall>()) {
694 return PathDiagnosticLocation(PIE->getLocation(), SMng);
695 } else if (std::optional<CallEnter> CE = P.getAs<CallEnter>()) {
696 return getLocationForCaller(SF: CE->getCalleeStackFrame(), CallerSF: CE->getStackFrame(),
697 SM: SMng);
698 } else if (std::optional<CallExitEnd> CEE = P.getAs<CallExitEnd>()) {
699 return getLocationForCaller(SF: CEE->getCalleeStackFrame(),
700 CallerSF: CEE->getStackFrame(), SM: SMng);
701 } else if (auto CEB = P.getAs<CallExitBegin>()) {
702 if (const ReturnStmt *RS = CEB->getReturnStmt())
703 return PathDiagnosticLocation::createBegin(S: RS, SM: SMng,
704 SFAC: CEB->getStackFrame());
705 return PathDiagnosticLocation(
706 CEB->getStackFrame()->getDecl()->getSourceRange().getEnd(), SMng);
707 } else if (std::optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) {
708 if (std::optional<CFGElement> BlockFront = BE->getFirstElement()) {
709 if (auto StmtElt = BlockFront->getAs<CFGStmt>()) {
710 return PathDiagnosticLocation(StmtElt->getStmt()->getBeginLoc(), SMng);
711 } else if (auto NewAllocElt = BlockFront->getAs<CFGNewAllocator>()) {
712 return PathDiagnosticLocation(
713 NewAllocElt->getAllocatorExpr()->getBeginLoc(), SMng);
714 }
715 llvm_unreachable("Unexpected CFG element at front of block");
716 }
717
718 return PathDiagnosticLocation(
719 BE->getBlock()->getTerminatorStmt()->getBeginLoc(), SMng);
720 } else if (std::optional<FunctionExitPoint> FE =
721 P.getAs<FunctionExitPoint>()) {
722 return PathDiagnosticLocation(FE->getStmt(), SMng, FE->getStackFrame());
723 } else if (std::optional<LifetimeEnd> LE = P.getAs<LifetimeEnd>()) {
724 return PathDiagnosticLocation::createEnd(S: LE->getTriggerStmt(), SM: SMng,
725 SFAC: LE->getStackFrame());
726 } else {
727 llvm_unreachable("Unexpected ProgramPoint");
728 }
729
730 return PathDiagnosticLocation(S, SMng, P.getStackFrame());
731}
732
733PathDiagnosticLocation PathDiagnosticLocation::createSingleLocation(
734 const PathDiagnosticLocation &PDL) {
735 FullSourceLoc L = PDL.asLocation();
736 return PathDiagnosticLocation(L, L.getManager(), SingleLocK);
737}
738
739FullSourceLoc PathDiagnosticLocation::genLocation(
740 SourceLocation L, StackFrameOrAnalysisDeclContext SFAC) const {
741 assert(isValid());
742 // Note that we want a 'switch' here so that the compiler can warn us in
743 // case we add more cases.
744 switch (K) {
745 case SingleLocK:
746 case RangeK:
747 break;
748 case StmtK:
749 // Defensive checking.
750 if (!S)
751 break;
752 return FullSourceLoc(getValidSourceLocation(S, SFAC),
753 const_cast<SourceManager &>(*SM));
754 case DeclK:
755 // Defensive checking.
756 if (!D)
757 break;
758 return FullSourceLoc(D->getLocation(), const_cast<SourceManager&>(*SM));
759 }
760
761 return FullSourceLoc(L, const_cast<SourceManager&>(*SM));
762}
763
764PathDiagnosticRange
765PathDiagnosticLocation::genRange(StackFrameOrAnalysisDeclContext SFAC) const {
766 assert(isValid());
767 // Note that we want a 'switch' here so that the compiler can warn us in
768 // case we add more cases.
769 switch (K) {
770 case SingleLocK:
771 return PathDiagnosticRange(SourceRange(Loc,Loc), true);
772 case RangeK:
773 break;
774 case StmtK: {
775 const Stmt *S = asStmt();
776 switch (S->getStmtClass()) {
777 default:
778 break;
779 case Stmt::DeclStmtClass: {
780 const auto *DS = cast<DeclStmt>(Val: S);
781 if (DS->isSingleDecl()) {
782 // Should always be the case, but we'll be defensive.
783 return SourceRange(DS->getBeginLoc(),
784 DS->getSingleDecl()->getLocation());
785 }
786 break;
787 }
788 // FIXME: Provide better range information for different
789 // terminators.
790 case Stmt::IfStmtClass:
791 case Stmt::WhileStmtClass:
792 case Stmt::DoStmtClass:
793 case Stmt::ForStmtClass:
794 case Stmt::ChooseExprClass:
795 case Stmt::IndirectGotoStmtClass:
796 case Stmt::SwitchStmtClass:
797 case Stmt::BinaryConditionalOperatorClass:
798 case Stmt::ConditionalOperatorClass:
799 case Stmt::ObjCForCollectionStmtClass: {
800 SourceLocation L = getValidSourceLocation(S, SFAC);
801 return SourceRange(L, L);
802 }
803 }
804 SourceRange R = S->getSourceRange();
805 if (R.isValid())
806 return R;
807 break;
808 }
809 case DeclK:
810 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
811 return MD->getSourceRange();
812 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
813 if (Stmt *Body = FD->getBody())
814 return Body->getSourceRange();
815 }
816 else {
817 SourceLocation L = D->getLocation();
818 return PathDiagnosticRange(SourceRange(L, L), true);
819 }
820 }
821
822 return SourceRange(Loc, Loc);
823}
824
825void PathDiagnosticLocation::flatten() {
826 if (K == StmtK) {
827 K = RangeK;
828 S = nullptr;
829 D = nullptr;
830 }
831 else if (K == DeclK) {
832 K = SingleLocK;
833 S = nullptr;
834 D = nullptr;
835 }
836}
837
838//===----------------------------------------------------------------------===//
839// Manipulation of PathDiagnosticCallPieces.
840//===----------------------------------------------------------------------===//
841
842std::shared_ptr<PathDiagnosticCallPiece>
843PathDiagnosticCallPiece::construct(const CallExitEnd &CE,
844 const SourceManager &SM) {
845 const Decl *caller = CE.getStackFrame()->getDecl();
846 PathDiagnosticLocation pos =
847 getLocationForCaller(SF: CE.getCalleeStackFrame(), CallerSF: CE.getStackFrame(), SM);
848 return std::shared_ptr<PathDiagnosticCallPiece>(
849 new PathDiagnosticCallPiece(caller, pos));
850}
851
852PathDiagnosticCallPiece *
853PathDiagnosticCallPiece::construct(PathPieces &path,
854 const Decl *caller) {
855 std::shared_ptr<PathDiagnosticCallPiece> C(
856 new PathDiagnosticCallPiece(path, caller));
857 path.clear();
858 auto *R = C.get();
859 path.push_front(x: std::move(C));
860 return R;
861}
862
863void PathDiagnosticCallPiece::setCallee(const CallEnter &CE,
864 const SourceManager &SM) {
865 const StackFrame *CalleeSF = CE.getCalleeStackFrame();
866 Callee = CalleeSF->getDecl();
867
868 callEnterWithin = PathDiagnosticLocation::createBegin(D: Callee, SM);
869 callEnter = getLocationForCaller(SF: CalleeSF, CallerSF: CE.getStackFrame(), SM);
870
871 // Autosynthesized property accessors are special because we'd never
872 // pop back up to non-autosynthesized code until we leave them.
873 // This is not generally true for autosynthesized callees, which may call
874 // non-autosynthesized callbacks.
875 // Unless set here, the IsCalleeAnAutosynthesizedPropertyAccessor flag
876 // defaults to false.
877 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: Callee))
878 IsCalleeAnAutosynthesizedPropertyAccessor =
879 (MD->isPropertyAccessor() &&
880 CalleeSF->getAnalysisDeclContext()->isBodyAutosynthesized());
881}
882
883static void describeTemplateParameters(raw_ostream &Out,
884 const ArrayRef<TemplateArgument> TAList,
885 const LangOptions &LO,
886 StringRef Prefix = StringRef(),
887 StringRef Postfix = StringRef());
888
889static void describeTemplateParameter(raw_ostream &Out,
890 const TemplateArgument &TArg,
891 const LangOptions &LO) {
892
893 if (TArg.getKind() == TemplateArgument::ArgKind::Pack) {
894 describeTemplateParameters(Out, TAList: TArg.getPackAsArray(), LO);
895 } else {
896 TArg.print(Policy: PrintingPolicy(LO), Out, /*IncludeType*/ true);
897 }
898}
899
900static void describeTemplateParameters(raw_ostream &Out,
901 const ArrayRef<TemplateArgument> TAList,
902 const LangOptions &LO,
903 StringRef Prefix, StringRef Postfix) {
904 if (TAList.empty())
905 return;
906
907 Out << Prefix;
908 for (int I = 0, Last = TAList.size() - 1; I != Last; ++I) {
909 describeTemplateParameter(Out, TArg: TAList[I], LO);
910 Out << ", ";
911 }
912 describeTemplateParameter(Out, TArg: TAList[TAList.size() - 1], LO);
913 Out << Postfix;
914}
915
916static void describeClass(raw_ostream &Out, const CXXRecordDecl *D,
917 StringRef Prefix = StringRef()) {
918 if (!D->getIdentifier())
919 return;
920 Out << Prefix << '\'' << *D;
921 if (const auto T = dyn_cast<ClassTemplateSpecializationDecl>(Val: D))
922 describeTemplateParameters(Out, TAList: T->getTemplateArgs().asArray(),
923 LO: D->getLangOpts(), Prefix: "<", Postfix: ">");
924
925 Out << '\'';
926}
927
928static bool describeCodeDecl(raw_ostream &Out, const Decl *D,
929 bool ExtendedDescription,
930 StringRef Prefix = StringRef()) {
931 if (!D)
932 return false;
933
934 if (isa<BlockDecl>(Val: D)) {
935 if (ExtendedDescription)
936 Out << Prefix << "anonymous block";
937 return ExtendedDescription;
938 }
939
940 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
941 Out << Prefix;
942 if (ExtendedDescription && !MD->isUserProvided()) {
943 if (MD->isExplicitlyDefaulted())
944 Out << "defaulted ";
945 else
946 Out << "implicit ";
947 }
948
949 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD)) {
950 if (CD->isDefaultConstructor())
951 Out << "default ";
952 else if (CD->isCopyConstructor())
953 Out << "copy ";
954 else if (CD->isMoveConstructor())
955 Out << "move ";
956
957 Out << "constructor";
958 describeClass(Out, D: MD->getParent(), Prefix: " for ");
959 } else if (isa<CXXDestructorDecl>(Val: MD)) {
960 if (!MD->isUserProvided()) {
961 Out << "destructor";
962 describeClass(Out, D: MD->getParent(), Prefix: " for ");
963 } else {
964 // Use ~Foo for explicitly-written destructors.
965 Out << "'" << *MD << "'";
966 }
967 } else if (MD->isCopyAssignmentOperator()) {
968 Out << "copy assignment operator";
969 describeClass(Out, D: MD->getParent(), Prefix: " for ");
970 } else if (MD->isMoveAssignmentOperator()) {
971 Out << "move assignment operator";
972 describeClass(Out, D: MD->getParent(), Prefix: " for ");
973 } else {
974 if (MD->getParent()->getIdentifier())
975 Out << "'" << *MD->getParent() << "::" << *MD << "'";
976 else
977 Out << "'" << *MD << "'";
978 }
979
980 return true;
981 }
982
983 Out << Prefix << '\'' << cast<NamedDecl>(Val: *D);
984
985 // Adding template parameters.
986 if (const auto FD = dyn_cast<FunctionDecl>(Val: D))
987 if (const TemplateArgumentList *TAList =
988 FD->getTemplateSpecializationArgs())
989 describeTemplateParameters(Out, TAList: TAList->asArray(), LO: FD->getLangOpts(), Prefix: "<",
990 Postfix: ">");
991
992 Out << '\'';
993 return true;
994}
995
996std::shared_ptr<PathDiagnosticEventPiece>
997PathDiagnosticCallPiece::getCallEnterEvent() const {
998 // We do not produce call enters and call exits for autosynthesized property
999 // accessors. We do generally produce them for other functions coming from
1000 // the body farm because they may call callbacks that bring us back into
1001 // visible code.
1002 if (!Callee || IsCalleeAnAutosynthesizedPropertyAccessor)
1003 return nullptr;
1004
1005 SmallString<256> buf;
1006 llvm::raw_svector_ostream Out(buf);
1007
1008 Out << "Calling ";
1009 describeCodeDecl(Out, D: Callee, /*ExtendedDescription=*/true);
1010
1011 assert(callEnter.asLocation().isValid());
1012 return std::make_shared<PathDiagnosticEventPiece>(args: callEnter, args: Out.str());
1013}
1014
1015std::shared_ptr<PathDiagnosticEventPiece>
1016PathDiagnosticCallPiece::getCallEnterWithinCallerEvent() const {
1017 if (!callEnterWithin.asLocation().isValid())
1018 return nullptr;
1019 if (Callee->isImplicit() || !Callee->hasBody())
1020 return nullptr;
1021 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: Callee))
1022 if (MD->isDefaulted())
1023 return nullptr;
1024
1025 SmallString<256> buf;
1026 llvm::raw_svector_ostream Out(buf);
1027
1028 Out << "Entered call";
1029 describeCodeDecl(Out, D: Caller, /*ExtendedDescription=*/false, Prefix: " from ");
1030
1031 return std::make_shared<PathDiagnosticEventPiece>(args: callEnterWithin, args: Out.str());
1032}
1033
1034std::shared_ptr<PathDiagnosticEventPiece>
1035PathDiagnosticCallPiece::getCallExitEvent() const {
1036 // We do not produce call enters and call exits for autosynthesized property
1037 // accessors. We do generally produce them for other functions coming from
1038 // the body farm because they may call callbacks that bring us back into
1039 // visible code.
1040 if (NoExit || IsCalleeAnAutosynthesizedPropertyAccessor)
1041 return nullptr;
1042
1043 SmallString<256> buf;
1044 llvm::raw_svector_ostream Out(buf);
1045
1046 if (!CallStackMessage.empty()) {
1047 Out << CallStackMessage;
1048 } else {
1049 bool DidDescribe = describeCodeDecl(Out, D: Callee,
1050 /*ExtendedDescription=*/false,
1051 Prefix: "Returning from ");
1052 if (!DidDescribe)
1053 Out << "Returning to caller";
1054 }
1055
1056 assert(callReturn.asLocation().isValid());
1057 return std::make_shared<PathDiagnosticEventPiece>(args: callReturn, args: Out.str());
1058}
1059
1060static void compute_path_size(const PathPieces &pieces, unsigned &size) {
1061 for (const auto &I : pieces) {
1062 const PathDiagnosticPiece *piece = I.get();
1063 if (const auto *cp = dyn_cast<PathDiagnosticCallPiece>(Val: piece))
1064 compute_path_size(pieces: cp->path, size);
1065 else
1066 ++size;
1067 }
1068}
1069
1070unsigned PathDiagnostic::full_size() {
1071 unsigned size = 0;
1072 compute_path_size(pieces: path, size);
1073 return size;
1074}
1075
1076SmallString<32>
1077PathDiagnostic::getIssueHash(const SourceManager &SrcMgr,
1078 const LangOptions &LangOpts) const {
1079 PathDiagnosticLocation UPDLoc = getUniqueingLoc();
1080 FullSourceLoc FullLoc(
1081 SrcMgr.getExpansionLoc(Loc: UPDLoc.isValid() ? UPDLoc.asLocation()
1082 : getLocation().asLocation()),
1083 SrcMgr);
1084
1085 return clang::getIssueHash(IssueLoc: FullLoc, CheckerName: getCheckerName(), WarningMessage: getBugType(),
1086 IssueDecl: getDeclWithIssue(), LangOpts);
1087}
1088
1089//===----------------------------------------------------------------------===//
1090// FoldingSet profiling methods.
1091//===----------------------------------------------------------------------===//
1092
1093void PathDiagnosticLocation::Profile(llvm::FoldingSetNodeID &ID) const {
1094 ID.Add(x: Range.getBegin());
1095 ID.Add(x: Range.getEnd());
1096 ID.Add(x: static_cast<const SourceLocation &>(Loc));
1097}
1098
1099void PathDiagnosticPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1100 ID.AddInteger(I: (unsigned) getKind());
1101 ID.AddString(String: str);
1102 // FIXME: Add profiling support for code hints.
1103 ID.AddInteger(I: (unsigned) getDisplayHint());
1104 ArrayRef<SourceRange> Ranges = getRanges();
1105 for (const auto &I : Ranges) {
1106 ID.Add(x: I.getBegin());
1107 ID.Add(x: I.getEnd());
1108 }
1109}
1110
1111void PathDiagnosticCallPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1112 PathDiagnosticPiece::Profile(ID);
1113 for (const auto &I : path)
1114 ID.Add(x: *I);
1115}
1116
1117void PathDiagnosticSpotPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1118 PathDiagnosticPiece::Profile(ID);
1119 ID.Add(x: Pos);
1120}
1121
1122void PathDiagnosticControlFlowPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1123 PathDiagnosticPiece::Profile(ID);
1124 for (const auto &I : *this)
1125 ID.Add(x: I);
1126}
1127
1128void PathDiagnosticMacroPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1129 PathDiagnosticSpotPiece::Profile(ID);
1130 for (const auto &I : subPieces)
1131 ID.Add(x: *I);
1132}
1133
1134void PathDiagnosticNotePiece::Profile(llvm::FoldingSetNodeID &ID) const {
1135 PathDiagnosticSpotPiece::Profile(ID);
1136}
1137
1138void PathDiagnosticPopUpPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1139 PathDiagnosticSpotPiece::Profile(ID);
1140}
1141
1142void PathDiagnostic::Profile(llvm::FoldingSetNodeID &ID) const {
1143 ID.Add(x: getLocation());
1144 ID.Add(x: getUniqueingLoc());
1145 ID.AddString(String: BugType);
1146 ID.AddString(String: VerboseDesc);
1147 ID.AddString(String: Category);
1148}
1149
1150void PathDiagnostic::FullProfile(llvm::FoldingSetNodeID &ID) const {
1151 Profile(ID);
1152 for (const auto &I : path)
1153 ID.Add(x: *I);
1154 for (meta_iterator I = meta_begin(), E = meta_end(); I != E; ++I)
1155 ID.AddString(String: *I);
1156}
1157
1158LLVM_DUMP_METHOD void PathPieces::dump() const {
1159 unsigned index = 0;
1160 for (const PathDiagnosticPieceRef &Piece : *this) {
1161 llvm::errs() << "[" << index++ << "] ";
1162 Piece->dump();
1163 llvm::errs() << "\n";
1164 }
1165}
1166
1167LLVM_DUMP_METHOD void PathDiagnosticCallPiece::dump() const {
1168 llvm::errs() << "CALL\n--------------\n";
1169
1170 if (const Stmt *SLoc = getLocation().getStmtOrNull())
1171 SLoc->dump();
1172 else if (const auto *ND = dyn_cast_or_null<NamedDecl>(Val: getCallee()))
1173 llvm::errs() << *ND << "\n";
1174 else
1175 getLocation().dump();
1176}
1177
1178LLVM_DUMP_METHOD void PathDiagnosticEventPiece::dump() const {
1179 llvm::errs() << "EVENT\n--------------\n";
1180 llvm::errs() << getString() << "\n";
1181 llvm::errs() << " ---- at ----\n";
1182 getLocation().dump();
1183}
1184
1185LLVM_DUMP_METHOD void PathDiagnosticControlFlowPiece::dump() const {
1186 llvm::errs() << "CONTROL\n--------------\n";
1187 getStartLocation().dump();
1188 llvm::errs() << " ---- to ----\n";
1189 getEndLocation().dump();
1190}
1191
1192LLVM_DUMP_METHOD void PathDiagnosticMacroPiece::dump() const {
1193 llvm::errs() << "MACRO\n--------------\n";
1194 // FIXME: Print which macro is being invoked.
1195}
1196
1197LLVM_DUMP_METHOD void PathDiagnosticNotePiece::dump() const {
1198 llvm::errs() << "NOTE\n--------------\n";
1199 llvm::errs() << getString() << "\n";
1200 llvm::errs() << " ---- at ----\n";
1201 getLocation().dump();
1202}
1203
1204LLVM_DUMP_METHOD void PathDiagnosticPopUpPiece::dump() const {
1205 llvm::errs() << "POP-UP\n--------------\n";
1206 llvm::errs() << getString() << "\n";
1207 llvm::errs() << " ---- at ----\n";
1208 getLocation().dump();
1209}
1210
1211LLVM_DUMP_METHOD void PathDiagnosticLocation::dump() const {
1212 if (!isValid()) {
1213 llvm::errs() << "<INVALID>\n";
1214 return;
1215 }
1216
1217 switch (K) {
1218 case RangeK:
1219 // FIXME: actually print the range.
1220 llvm::errs() << "<range>\n";
1221 break;
1222 case SingleLocK:
1223 asLocation().dump();
1224 llvm::errs() << "\n";
1225 break;
1226 case StmtK:
1227 if (S)
1228 S->dump();
1229 else
1230 llvm::errs() << "<NULL STMT>\n";
1231 break;
1232 case DeclK:
1233 if (const auto *ND = dyn_cast_or_null<NamedDecl>(Val: D))
1234 llvm::errs() << *ND << "\n";
1235 else if (isa<BlockDecl>(Val: D))
1236 // FIXME: Make this nicer.
1237 llvm::errs() << "<block>\n";
1238 else if (D)
1239 llvm::errs() << "<unknown decl>\n";
1240 else
1241 llvm::errs() << "<NULL DECL>\n";
1242 break;
1243 }
1244}
1245