1 //===- PathDiagnostic.cpp - Path-Specific Diagnostic Handling -------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the PathDiagnostic-related interfaces.
11 //===----------------------------------------------------------------------===//
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/OperationKinds.h"
22 #include "clang/AST/ParentMap.h"
23 #include "clang/AST/PrettyPrinter.h"
24 #include "clang/AST/Stmt.h"
25 #include "clang/AST/Type.h"
26 #include "clang/Analysis/AnalysisDeclContext.h"
27 #include "clang/Analysis/CFG.h"
28 #include "clang/Analysis/ProgramPoint.h"
29 #include "clang/Basic/FileManager.h"
30 #include "clang/Basic/LLVM.h"
31 #include "clang/Basic/SourceLocation.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "llvm/ADT/ArrayRef.h"
34 #include "llvm/ADT/FoldingSet.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/StringRef.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/raw_ostream.h"
50 using namespace clang
;
53 static StringRef
StripTrailingDots(StringRef s
) {
54 for (StringRef::size_type i
= s
.size(); i
!= 0; --i
)
56 return s
.substr(0, i
);
60 PathDiagnosticPiece::PathDiagnosticPiece(StringRef s
,
61 Kind k
, DisplayHint hint
)
62 : str(StripTrailingDots(s
)), kind(k
), Hint(hint
) {}
64 PathDiagnosticPiece::PathDiagnosticPiece(Kind k
, DisplayHint hint
)
65 : kind(k
), Hint(hint
) {}
67 PathDiagnosticPiece::~PathDiagnosticPiece() = default;
69 PathDiagnosticEventPiece::~PathDiagnosticEventPiece() = default;
71 PathDiagnosticCallPiece::~PathDiagnosticCallPiece() = default;
73 PathDiagnosticControlFlowPiece::~PathDiagnosticControlFlowPiece() = default;
75 PathDiagnosticMacroPiece::~PathDiagnosticMacroPiece() = default;
77 PathDiagnosticNotePiece::~PathDiagnosticNotePiece() = default;
79 PathDiagnosticPopUpPiece::~PathDiagnosticPopUpPiece() = default;
81 void PathPieces::flattenTo(PathPieces
&Primary
, PathPieces
&Current
,
82 bool ShouldFlattenMacros
) const {
83 for (auto &Piece
: *this) {
84 switch (Piece
->getKind()) {
85 case PathDiagnosticPiece::Call
: {
86 auto &Call
= cast
<PathDiagnosticCallPiece
>(*Piece
);
87 if (auto CallEnter
= Call
.getCallEnterEvent())
88 Current
.push_back(std::move(CallEnter
));
89 Call
.path
.flattenTo(Primary
, Primary
, ShouldFlattenMacros
);
90 if (auto callExit
= Call
.getCallExitEvent())
91 Current
.push_back(std::move(callExit
));
94 case PathDiagnosticPiece::Macro
: {
95 auto &Macro
= cast
<PathDiagnosticMacroPiece
>(*Piece
);
96 if (ShouldFlattenMacros
) {
97 Macro
.subPieces
.flattenTo(Primary
, Primary
, ShouldFlattenMacros
);
99 Current
.push_back(Piece
);
101 Macro
.subPieces
.flattenTo(Primary
, NewPath
, ShouldFlattenMacros
);
102 // FIXME: This probably shouldn't mutate the original path piece.
103 Macro
.subPieces
= NewPath
;
107 case PathDiagnosticPiece::Event
:
108 case PathDiagnosticPiece::ControlFlow
:
109 case PathDiagnosticPiece::Note
:
110 case PathDiagnosticPiece::PopUp
:
111 Current
.push_back(Piece
);
117 PathDiagnostic::~PathDiagnostic() = default;
119 PathDiagnostic::PathDiagnostic(
120 StringRef CheckerName
, const Decl
*declWithIssue
, StringRef bugtype
,
121 StringRef verboseDesc
, StringRef shortDesc
, StringRef category
,
122 PathDiagnosticLocation LocationToUnique
, const Decl
*DeclToUnique
,
123 std::unique_ptr
<FilesToLineNumsMap
> ExecutedLines
)
124 : CheckerName(CheckerName
), DeclWithIssue(declWithIssue
),
125 BugType(StripTrailingDots(bugtype
)),
126 VerboseDesc(StripTrailingDots(verboseDesc
)),
127 ShortDesc(StripTrailingDots(shortDesc
)),
128 Category(StripTrailingDots(category
)), UniqueingLoc(LocationToUnique
),
129 UniqueingDecl(DeclToUnique
), ExecutedLines(std::move(ExecutedLines
)),
132 void PathDiagnosticConsumer::anchor() {}
134 PathDiagnosticConsumer::~PathDiagnosticConsumer() {
135 // Delete the contents of the FoldingSet if it isn't empty already.
136 for (auto &Diag
: Diags
)
140 void PathDiagnosticConsumer::HandlePathDiagnostic(
141 std::unique_ptr
<PathDiagnostic
> D
) {
142 if (!D
|| D
->path
.empty())
145 // We need to flatten the locations (convert Stmt* to locations) because
146 // the referenced statements may be freed by the time the diagnostics
148 D
->flattenLocations();
150 // If the PathDiagnosticConsumer does not support diagnostics that
151 // cross file boundaries, prune out such diagnostics now.
152 if (!supportsCrossFileDiagnostics()) {
153 // Verify that the entire path is from the same FileID.
155 const SourceManager
&SMgr
= D
->path
.front()->getLocation().getManager();
156 SmallVector
<const PathPieces
*, 5> WorkList
;
157 WorkList
.push_back(&D
->path
);
158 SmallString
<128> buf
;
159 llvm::raw_svector_ostream
warning(buf
);
160 warning
<< "warning: Path diagnostic report is not generated. Current "
161 << "output format does not support diagnostics that cross file "
162 << "boundaries. Refer to --analyzer-output for valid output "
165 while (!WorkList
.empty()) {
166 const PathPieces
&path
= *WorkList
.pop_back_val();
168 for (const auto &I
: path
) {
169 const PathDiagnosticPiece
*piece
= I
.get();
170 FullSourceLoc L
= piece
->getLocation().asLocation().getExpansionLoc();
172 if (FID
.isInvalid()) {
173 FID
= SMgr
.getFileID(L
);
174 } else if (SMgr
.getFileID(L
) != FID
) {
175 llvm::errs() << warning
.str();
179 // Check the source ranges.
180 ArrayRef
<SourceRange
> Ranges
= piece
->getRanges();
181 for (const auto &I
: Ranges
) {
182 SourceLocation L
= SMgr
.getExpansionLoc(I
.getBegin());
183 if (!L
.isFileID() || SMgr
.getFileID(L
) != FID
) {
184 llvm::errs() << warning
.str();
187 L
= SMgr
.getExpansionLoc(I
.getEnd());
188 if (!L
.isFileID() || SMgr
.getFileID(L
) != FID
) {
189 llvm::errs() << warning
.str();
194 if (const auto *call
= dyn_cast
<PathDiagnosticCallPiece
>(piece
))
195 WorkList
.push_back(&call
->path
);
196 else if (const auto *macro
= dyn_cast
<PathDiagnosticMacroPiece
>(piece
))
197 WorkList
.push_back(¯o
->subPieces
);
202 return; // FIXME: Emit a warning?
205 // Profile the node to see if we already have something matching it
206 llvm::FoldingSetNodeID profile
;
208 void *InsertPos
= nullptr;
210 if (PathDiagnostic
*orig
= Diags
.FindNodeOrInsertPos(profile
, InsertPos
)) {
211 // Keep the PathDiagnostic with the shorter path.
212 // Note, the enclosing routine is called in deterministic order, so the
213 // results will be consistent between runs (no reason to break ties if the
214 // size is the same).
215 const unsigned orig_size
= orig
->full_size();
216 const unsigned new_size
= D
->full_size();
217 if (orig_size
<= new_size
)
220 assert(orig
!= D
.get());
221 Diags
.RemoveNode(orig
);
225 Diags
.InsertNode(D
.release());
228 static std::optional
<bool> comparePath(const PathPieces
&X
,
229 const PathPieces
&Y
);
231 static std::optional
<bool>
232 compareControlFlow(const PathDiagnosticControlFlowPiece
&X
,
233 const PathDiagnosticControlFlowPiece
&Y
) {
234 FullSourceLoc XSL
= X
.getStartLocation().asLocation();
235 FullSourceLoc YSL
= Y
.getStartLocation().asLocation();
237 return XSL
.isBeforeInTranslationUnitThan(YSL
);
238 FullSourceLoc XEL
= X
.getEndLocation().asLocation();
239 FullSourceLoc YEL
= Y
.getEndLocation().asLocation();
241 return XEL
.isBeforeInTranslationUnitThan(YEL
);
245 static std::optional
<bool> compareMacro(const PathDiagnosticMacroPiece
&X
,
246 const PathDiagnosticMacroPiece
&Y
) {
247 return comparePath(X
.subPieces
, Y
.subPieces
);
250 static std::optional
<bool> compareCall(const PathDiagnosticCallPiece
&X
,
251 const PathDiagnosticCallPiece
&Y
) {
252 FullSourceLoc X_CEL
= X
.callEnter
.asLocation();
253 FullSourceLoc Y_CEL
= Y
.callEnter
.asLocation();
255 return X_CEL
.isBeforeInTranslationUnitThan(Y_CEL
);
256 FullSourceLoc X_CEWL
= X
.callEnterWithin
.asLocation();
257 FullSourceLoc Y_CEWL
= Y
.callEnterWithin
.asLocation();
258 if (X_CEWL
!= Y_CEWL
)
259 return X_CEWL
.isBeforeInTranslationUnitThan(Y_CEWL
);
260 FullSourceLoc X_CRL
= X
.callReturn
.asLocation();
261 FullSourceLoc Y_CRL
= Y
.callReturn
.asLocation();
263 return X_CRL
.isBeforeInTranslationUnitThan(Y_CRL
);
264 return comparePath(X
.path
, Y
.path
);
267 static std::optional
<bool> comparePiece(const PathDiagnosticPiece
&X
,
268 const PathDiagnosticPiece
&Y
) {
269 if (X
.getKind() != Y
.getKind())
270 return X
.getKind() < Y
.getKind();
272 FullSourceLoc XL
= X
.getLocation().asLocation();
273 FullSourceLoc YL
= Y
.getLocation().asLocation();
275 return XL
.isBeforeInTranslationUnitThan(YL
);
277 if (X
.getString() != Y
.getString())
278 return X
.getString() < Y
.getString();
280 if (X
.getRanges().size() != Y
.getRanges().size())
281 return X
.getRanges().size() < Y
.getRanges().size();
283 const SourceManager
&SM
= XL
.getManager();
285 for (unsigned i
= 0, n
= X
.getRanges().size(); i
< n
; ++i
) {
286 SourceRange XR
= X
.getRanges()[i
];
287 SourceRange YR
= Y
.getRanges()[i
];
289 if (XR
.getBegin() != YR
.getBegin())
290 return SM
.isBeforeInTranslationUnit(XR
.getBegin(), YR
.getBegin());
291 return SM
.isBeforeInTranslationUnit(XR
.getEnd(), YR
.getEnd());
295 switch (X
.getKind()) {
296 case PathDiagnosticPiece::ControlFlow
:
297 return compareControlFlow(cast
<PathDiagnosticControlFlowPiece
>(X
),
298 cast
<PathDiagnosticControlFlowPiece
>(Y
));
299 case PathDiagnosticPiece::Macro
:
300 return compareMacro(cast
<PathDiagnosticMacroPiece
>(X
),
301 cast
<PathDiagnosticMacroPiece
>(Y
));
302 case PathDiagnosticPiece::Call
:
303 return compareCall(cast
<PathDiagnosticCallPiece
>(X
),
304 cast
<PathDiagnosticCallPiece
>(Y
));
305 case PathDiagnosticPiece::Event
:
306 case PathDiagnosticPiece::Note
:
307 case PathDiagnosticPiece::PopUp
:
310 llvm_unreachable("all cases handled");
313 static std::optional
<bool> comparePath(const PathPieces
&X
,
314 const PathPieces
&Y
) {
315 if (X
.size() != Y
.size())
316 return X
.size() < Y
.size();
318 PathPieces::const_iterator X_I
= X
.begin(), X_end
= X
.end();
319 PathPieces::const_iterator Y_I
= Y
.begin(), Y_end
= Y
.end();
321 for (; X_I
!= X_end
&& Y_I
!= Y_end
; ++X_I
, ++Y_I
)
322 if (std::optional
<bool> b
= comparePiece(**X_I
, **Y_I
))
328 static bool compareCrossTUSourceLocs(FullSourceLoc XL
, FullSourceLoc YL
) {
329 if (XL
.isInvalid() && YL
.isValid())
331 if (XL
.isValid() && YL
.isInvalid())
333 std::pair
<FileID
, unsigned> XOffs
= XL
.getDecomposedLoc();
334 std::pair
<FileID
, unsigned> YOffs
= YL
.getDecomposedLoc();
335 const SourceManager
&SM
= XL
.getManager();
336 std::pair
<bool, bool> InSameTU
= SM
.isInTheSameTranslationUnit(XOffs
, YOffs
);
338 return XL
.isBeforeInTranslationUnitThan(YL
);
339 OptionalFileEntryRef XFE
=
340 SM
.getFileEntryRefForID(XL
.getSpellingLoc().getFileID());
341 OptionalFileEntryRef YFE
=
342 SM
.getFileEntryRefForID(YL
.getSpellingLoc().getFileID());
345 int NameCmp
= XFE
->getName().compare(YFE
->getName());
348 // Last resort: Compare raw file IDs that are possibly expansions.
349 return XL
.getFileID() < YL
.getFileID();
352 static bool compare(const PathDiagnostic
&X
, const PathDiagnostic
&Y
) {
353 FullSourceLoc XL
= X
.getLocation().asLocation();
354 FullSourceLoc YL
= Y
.getLocation().asLocation();
356 return compareCrossTUSourceLocs(XL
, YL
);
357 FullSourceLoc XUL
= X
.getUniqueingLoc().asLocation();
358 FullSourceLoc YUL
= Y
.getUniqueingLoc().asLocation();
360 return compareCrossTUSourceLocs(XUL
, YUL
);
361 if (X
.getBugType() != Y
.getBugType())
362 return X
.getBugType() < Y
.getBugType();
363 if (X
.getCategory() != Y
.getCategory())
364 return X
.getCategory() < Y
.getCategory();
365 if (X
.getVerboseDescription() != Y
.getVerboseDescription())
366 return X
.getVerboseDescription() < Y
.getVerboseDescription();
367 if (X
.getShortDescription() != Y
.getShortDescription())
368 return X
.getShortDescription() < Y
.getShortDescription();
369 auto CompareDecls
= [&XL
](const Decl
*D1
,
370 const Decl
*D2
) -> std::optional
<bool> {
377 SourceLocation D1L
= D1
->getLocation();
378 SourceLocation D2L
= D2
->getLocation();
380 const SourceManager
&SM
= XL
.getManager();
381 return compareCrossTUSourceLocs(FullSourceLoc(D1L
, SM
),
382 FullSourceLoc(D2L
, SM
));
386 if (auto Result
= CompareDecls(X
.getDeclWithIssue(), Y
.getDeclWithIssue()))
389 if (auto Result
= CompareDecls(X
.getUniqueingDecl(), Y
.getUniqueingDecl()))
392 PathDiagnostic::meta_iterator XI
= X
.meta_begin(), XE
= X
.meta_end();
393 PathDiagnostic::meta_iterator YI
= Y
.meta_begin(), YE
= Y
.meta_end();
394 if (XE
- XI
!= YE
- YI
)
395 return (XE
- XI
) < (YE
- YI
);
396 for ( ; XI
!= XE
; ++XI
, ++YI
) {
398 return (*XI
) < (*YI
);
400 return *comparePath(X
.path
, Y
.path
);
403 void PathDiagnosticConsumer::FlushDiagnostics(
404 PathDiagnosticConsumer::FilesMade
*Files
) {
410 std::vector
<const PathDiagnostic
*> BatchDiags
;
411 for (const auto &D
: Diags
)
412 BatchDiags
.push_back(&D
);
414 // Sort the diagnostics so that they are always emitted in a deterministic
416 int (*Comp
)(const PathDiagnostic
*const *, const PathDiagnostic
*const *) =
417 [](const PathDiagnostic
*const *X
, const PathDiagnostic
*const *Y
) {
418 assert(*X
!= *Y
&& "PathDiagnostics not uniqued!");
419 if (compare(**X
, **Y
))
421 assert(compare(**Y
, **X
) && "Not a total order!");
424 array_pod_sort(BatchDiags
.begin(), BatchDiags
.end(), Comp
);
426 FlushDiagnosticsImpl(BatchDiags
, Files
);
428 // Delete the flushed diagnostics.
429 for (const auto D
: BatchDiags
)
432 // Clear out the FoldingSet.
436 PathDiagnosticConsumer::FilesMade::~FilesMade() {
437 for (auto It
= Set
.begin(); It
!= Set
.end();)
438 (It
++)->~PDFileEntry();
441 void PathDiagnosticConsumer::FilesMade::addDiagnostic(const PathDiagnostic
&PD
,
442 StringRef ConsumerName
,
443 StringRef FileName
) {
444 llvm::FoldingSetNodeID NodeID
;
447 PDFileEntry
*Entry
= Set
.FindNodeOrInsertPos(NodeID
, InsertPos
);
449 Entry
= Alloc
.Allocate
<PDFileEntry
>();
450 Entry
= new (Entry
) PDFileEntry(NodeID
);
451 Set
.InsertNode(Entry
, InsertPos
);
454 // Allocate persistent storage for the file name.
455 char *FileName_cstr
= (char*) Alloc
.Allocate(FileName
.size(), 1);
456 memcpy(FileName_cstr
, FileName
.data(), FileName
.size());
458 Entry
->files
.push_back(std::make_pair(ConsumerName
,
459 StringRef(FileName_cstr
,
463 PathDiagnosticConsumer::PDFileEntry::ConsumerFiles
*
464 PathDiagnosticConsumer::FilesMade::getFiles(const PathDiagnostic
&PD
) {
465 llvm::FoldingSetNodeID NodeID
;
468 PDFileEntry
*Entry
= Set
.FindNodeOrInsertPos(NodeID
, InsertPos
);
471 return &Entry
->files
;
474 //===----------------------------------------------------------------------===//
475 // PathDiagnosticLocation methods.
476 //===----------------------------------------------------------------------===//
478 SourceLocation
PathDiagnosticLocation::getValidSourceLocation(
479 const Stmt
*S
, LocationOrAnalysisDeclContext LAC
, bool UseEndOfStatement
) {
480 SourceLocation L
= UseEndOfStatement
? S
->getEndLoc() : S
->getBeginLoc();
481 assert(!LAC
.isNull() &&
482 "A valid LocationContext or AnalysisDeclContext should be passed to "
483 "PathDiagnosticLocation upon creation.");
485 // S might be a temporary statement that does not have a location in the
486 // source code, so find an enclosing statement and use its location.
488 AnalysisDeclContext
*ADC
;
489 if (LAC
.is
<const LocationContext
*>())
490 ADC
= LAC
.get
<const LocationContext
*>()->getAnalysisDeclContext();
492 ADC
= LAC
.get
<AnalysisDeclContext
*>();
494 ParentMap
&PM
= ADC
->getParentMap();
496 const Stmt
*Parent
= S
;
498 Parent
= PM
.getParent(Parent
);
500 // In rare cases, we have implicit top-level expressions,
501 // such as arguments for implicit member initializers.
502 // In this case, fall back to the start of the body (even if we were
503 // asked for the statement end location).
505 const Stmt
*Body
= ADC
->getBody();
507 L
= Body
->getBeginLoc();
509 L
= ADC
->getDecl()->getEndLoc();
513 L
= UseEndOfStatement
? Parent
->getEndLoc() : Parent
->getBeginLoc();
514 } while (!L
.isValid());
517 // FIXME: Ironically, this assert actually fails in some cases.
518 //assert(L.isValid());
522 static PathDiagnosticLocation
523 getLocationForCaller(const StackFrameContext
*SFC
,
524 const LocationContext
*CallerCtx
,
525 const SourceManager
&SM
) {
526 const CFGBlock
&Block
= *SFC
->getCallSiteBlock();
527 CFGElement Source
= Block
[SFC
->getIndex()];
529 switch (Source
.getKind()) {
530 case CFGElement::Statement
:
531 case CFGElement::Constructor
:
532 case CFGElement::CXXRecordTypedCall
:
533 return PathDiagnosticLocation(Source
.castAs
<CFGStmt
>().getStmt(),
535 case CFGElement::Initializer
: {
536 const CFGInitializer
&Init
= Source
.castAs
<CFGInitializer
>();
537 return PathDiagnosticLocation(Init
.getInitializer()->getInit(),
540 case CFGElement::AutomaticObjectDtor
: {
541 const CFGAutomaticObjDtor
&Dtor
= Source
.castAs
<CFGAutomaticObjDtor
>();
542 return PathDiagnosticLocation::createEnd(Dtor
.getTriggerStmt(),
545 case CFGElement::DeleteDtor
: {
546 const CFGDeleteDtor
&Dtor
= Source
.castAs
<CFGDeleteDtor
>();
547 return PathDiagnosticLocation(Dtor
.getDeleteExpr(), SM
, CallerCtx
);
549 case CFGElement::BaseDtor
:
550 case CFGElement::MemberDtor
: {
551 const AnalysisDeclContext
*CallerInfo
= CallerCtx
->getAnalysisDeclContext();
552 if (const Stmt
*CallerBody
= CallerInfo
->getBody())
553 return PathDiagnosticLocation::createEnd(CallerBody
, SM
, CallerCtx
);
554 return PathDiagnosticLocation::create(CallerInfo
->getDecl(), SM
);
556 case CFGElement::NewAllocator
: {
557 const CFGNewAllocator
&Alloc
= Source
.castAs
<CFGNewAllocator
>();
558 return PathDiagnosticLocation(Alloc
.getAllocatorExpr(), SM
, CallerCtx
);
560 case CFGElement::TemporaryDtor
: {
561 // Temporary destructors are for temporaries. They die immediately at around
562 // the location of CXXBindTemporaryExpr. If they are lifetime-extended,
563 // they'd be dealt with via an AutomaticObjectDtor instead.
564 const auto &Dtor
= Source
.castAs
<CFGTemporaryDtor
>();
565 return PathDiagnosticLocation::createEnd(Dtor
.getBindTemporaryExpr(), SM
,
568 case CFGElement::ScopeBegin
:
569 case CFGElement::ScopeEnd
:
570 case CFGElement::CleanupFunction
:
571 llvm_unreachable("not yet implemented!");
572 case CFGElement::LifetimeEnds
:
573 case CFGElement::LoopExit
:
574 llvm_unreachable("CFGElement kind should not be on callsite!");
577 llvm_unreachable("Unknown CFGElement kind");
580 PathDiagnosticLocation
581 PathDiagnosticLocation::createBegin(const Decl
*D
,
582 const SourceManager
&SM
) {
583 return PathDiagnosticLocation(D
->getBeginLoc(), SM
, SingleLocK
);
586 PathDiagnosticLocation
587 PathDiagnosticLocation::createBegin(const Stmt
*S
,
588 const SourceManager
&SM
,
589 LocationOrAnalysisDeclContext LAC
) {
590 assert(S
&& "Statement cannot be null");
591 return PathDiagnosticLocation(getValidSourceLocation(S
, LAC
),
595 PathDiagnosticLocation
596 PathDiagnosticLocation::createEnd(const Stmt
*S
,
597 const SourceManager
&SM
,
598 LocationOrAnalysisDeclContext LAC
) {
599 if (const auto *CS
= dyn_cast
<CompoundStmt
>(S
))
600 return createEndBrace(CS
, SM
);
601 return PathDiagnosticLocation(getValidSourceLocation(S
, LAC
, /*End=*/true),
605 PathDiagnosticLocation
606 PathDiagnosticLocation::createOperatorLoc(const BinaryOperator
*BO
,
607 const SourceManager
&SM
) {
608 return PathDiagnosticLocation(BO
->getOperatorLoc(), SM
, SingleLocK
);
611 PathDiagnosticLocation
612 PathDiagnosticLocation::createConditionalColonLoc(
613 const ConditionalOperator
*CO
,
614 const SourceManager
&SM
) {
615 return PathDiagnosticLocation(CO
->getColonLoc(), SM
, SingleLocK
);
618 PathDiagnosticLocation
619 PathDiagnosticLocation::createMemberLoc(const MemberExpr
*ME
,
620 const SourceManager
&SM
) {
622 assert(ME
->getMemberLoc().isValid() || ME
->getBeginLoc().isValid());
624 // In some cases, getMemberLoc isn't valid -- in this case we'll return with
625 // some other related valid SourceLocation.
626 if (ME
->getMemberLoc().isValid())
627 return PathDiagnosticLocation(ME
->getMemberLoc(), SM
, SingleLocK
);
629 return PathDiagnosticLocation(ME
->getBeginLoc(), SM
, SingleLocK
);
632 PathDiagnosticLocation
633 PathDiagnosticLocation::createBeginBrace(const CompoundStmt
*CS
,
634 const SourceManager
&SM
) {
635 SourceLocation L
= CS
->getLBracLoc();
636 return PathDiagnosticLocation(L
, SM
, SingleLocK
);
639 PathDiagnosticLocation
640 PathDiagnosticLocation::createEndBrace(const CompoundStmt
*CS
,
641 const SourceManager
&SM
) {
642 SourceLocation L
= CS
->getRBracLoc();
643 return PathDiagnosticLocation(L
, SM
, SingleLocK
);
646 PathDiagnosticLocation
647 PathDiagnosticLocation::createDeclBegin(const LocationContext
*LC
,
648 const SourceManager
&SM
) {
649 // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
650 if (const auto *CS
= dyn_cast_or_null
<CompoundStmt
>(LC
->getDecl()->getBody()))
651 if (!CS
->body_empty()) {
652 SourceLocation Loc
= (*CS
->body_begin())->getBeginLoc();
653 return PathDiagnosticLocation(Loc
, SM
, SingleLocK
);
656 return PathDiagnosticLocation();
659 PathDiagnosticLocation
660 PathDiagnosticLocation::createDeclEnd(const LocationContext
*LC
,
661 const SourceManager
&SM
) {
662 SourceLocation L
= LC
->getDecl()->getBodyRBrace();
663 return PathDiagnosticLocation(L
, SM
, SingleLocK
);
666 PathDiagnosticLocation
667 PathDiagnosticLocation::create(const ProgramPoint
& P
,
668 const SourceManager
&SMng
) {
669 const Stmt
* S
= nullptr;
670 if (std::optional
<BlockEdge
> BE
= P
.getAs
<BlockEdge
>()) {
671 const CFGBlock
*BSrc
= BE
->getSrc();
672 if (BSrc
->getTerminator().isVirtualBaseBranch()) {
673 // TODO: VirtualBaseBranches should also appear for destructors.
674 // In this case we should put the diagnostic at the end of decl.
675 return PathDiagnosticLocation::createBegin(
676 P
.getLocationContext()->getDecl(), SMng
);
679 S
= BSrc
->getTerminatorCondition();
681 // If the BlockEdge has no terminator condition statement but its
682 // source is the entry of the CFG (e.g. a checker crated the branch at
683 // the beginning of a function), use the function's declaration instead.
684 assert(BSrc
== &BSrc
->getParent()->getEntry() && "CFGBlock has no "
685 "TerminatorCondition and is not the enrty block of the CFG");
686 return PathDiagnosticLocation::createBegin(
687 P
.getLocationContext()->getDecl(), SMng
);
690 } else if (std::optional
<StmtPoint
> SP
= P
.getAs
<StmtPoint
>()) {
692 if (P
.getAs
<PostStmtPurgeDeadSymbols
>())
693 return PathDiagnosticLocation::createEnd(S
, SMng
, P
.getLocationContext());
694 } else if (std::optional
<PostInitializer
> PIP
= P
.getAs
<PostInitializer
>()) {
695 return PathDiagnosticLocation(PIP
->getInitializer()->getSourceLocation(),
697 } else if (std::optional
<PreImplicitCall
> PIC
= P
.getAs
<PreImplicitCall
>()) {
698 return PathDiagnosticLocation(PIC
->getLocation(), SMng
);
699 } else if (std::optional
<PostImplicitCall
> PIE
=
700 P
.getAs
<PostImplicitCall
>()) {
701 return PathDiagnosticLocation(PIE
->getLocation(), SMng
);
702 } else if (std::optional
<CallEnter
> CE
= P
.getAs
<CallEnter
>()) {
703 return getLocationForCaller(CE
->getCalleeContext(),
704 CE
->getLocationContext(),
706 } else if (std::optional
<CallExitEnd
> CEE
= P
.getAs
<CallExitEnd
>()) {
707 return getLocationForCaller(CEE
->getCalleeContext(),
708 CEE
->getLocationContext(),
710 } else if (auto CEB
= P
.getAs
<CallExitBegin
>()) {
711 if (const ReturnStmt
*RS
= CEB
->getReturnStmt())
712 return PathDiagnosticLocation::createBegin(RS
, SMng
,
713 CEB
->getLocationContext());
714 return PathDiagnosticLocation(
715 CEB
->getLocationContext()->getDecl()->getSourceRange().getEnd(), SMng
);
716 } else if (std::optional
<BlockEntrance
> BE
= P
.getAs
<BlockEntrance
>()) {
717 if (std::optional
<CFGElement
> BlockFront
= BE
->getFirstElement()) {
718 if (auto StmtElt
= BlockFront
->getAs
<CFGStmt
>()) {
719 return PathDiagnosticLocation(StmtElt
->getStmt()->getBeginLoc(), SMng
);
720 } else if (auto NewAllocElt
= BlockFront
->getAs
<CFGNewAllocator
>()) {
721 return PathDiagnosticLocation(
722 NewAllocElt
->getAllocatorExpr()->getBeginLoc(), SMng
);
724 llvm_unreachable("Unexpected CFG element at front of block");
727 return PathDiagnosticLocation(
728 BE
->getBlock()->getTerminatorStmt()->getBeginLoc(), SMng
);
729 } else if (std::optional
<FunctionExitPoint
> FE
=
730 P
.getAs
<FunctionExitPoint
>()) {
731 return PathDiagnosticLocation(FE
->getStmt(), SMng
,
732 FE
->getLocationContext());
734 llvm_unreachable("Unexpected ProgramPoint");
737 return PathDiagnosticLocation(S
, SMng
, P
.getLocationContext());
740 PathDiagnosticLocation
PathDiagnosticLocation::createSingleLocation(
741 const PathDiagnosticLocation
&PDL
) {
742 FullSourceLoc L
= PDL
.asLocation();
743 return PathDiagnosticLocation(L
, L
.getManager(), SingleLocK
);
747 PathDiagnosticLocation::genLocation(SourceLocation L
,
748 LocationOrAnalysisDeclContext LAC
) const {
750 // Note that we want a 'switch' here so that the compiler can warn us in
751 // case we add more cases.
757 // Defensive checking.
760 return FullSourceLoc(getValidSourceLocation(S
, LAC
),
761 const_cast<SourceManager
&>(*SM
));
763 // Defensive checking.
766 return FullSourceLoc(D
->getLocation(), const_cast<SourceManager
&>(*SM
));
769 return FullSourceLoc(L
, const_cast<SourceManager
&>(*SM
));
773 PathDiagnosticLocation::genRange(LocationOrAnalysisDeclContext LAC
) const {
775 // Note that we want a 'switch' here so that the compiler can warn us in
776 // case we add more cases.
779 return PathDiagnosticRange(SourceRange(Loc
,Loc
), true);
783 const Stmt
*S
= asStmt();
784 switch (S
->getStmtClass()) {
787 case Stmt::DeclStmtClass
: {
788 const auto *DS
= cast
<DeclStmt
>(S
);
789 if (DS
->isSingleDecl()) {
790 // Should always be the case, but we'll be defensive.
791 return SourceRange(DS
->getBeginLoc(),
792 DS
->getSingleDecl()->getLocation());
796 // FIXME: Provide better range information for different
798 case Stmt::IfStmtClass
:
799 case Stmt::WhileStmtClass
:
800 case Stmt::DoStmtClass
:
801 case Stmt::ForStmtClass
:
802 case Stmt::ChooseExprClass
:
803 case Stmt::IndirectGotoStmtClass
:
804 case Stmt::SwitchStmtClass
:
805 case Stmt::BinaryConditionalOperatorClass
:
806 case Stmt::ConditionalOperatorClass
:
807 case Stmt::ObjCForCollectionStmtClass
: {
808 SourceLocation L
= getValidSourceLocation(S
, LAC
);
809 return SourceRange(L
, L
);
812 SourceRange R
= S
->getSourceRange();
818 if (const auto *MD
= dyn_cast
<ObjCMethodDecl
>(D
))
819 return MD
->getSourceRange();
820 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
821 if (Stmt
*Body
= FD
->getBody())
822 return Body
->getSourceRange();
825 SourceLocation L
= D
->getLocation();
826 return PathDiagnosticRange(SourceRange(L
, L
), true);
830 return SourceRange(Loc
, Loc
);
833 void PathDiagnosticLocation::flatten() {
839 else if (K
== DeclK
) {
846 //===----------------------------------------------------------------------===//
847 // Manipulation of PathDiagnosticCallPieces.
848 //===----------------------------------------------------------------------===//
850 std::shared_ptr
<PathDiagnosticCallPiece
>
851 PathDiagnosticCallPiece::construct(const CallExitEnd
&CE
,
852 const SourceManager
&SM
) {
853 const Decl
*caller
= CE
.getLocationContext()->getDecl();
854 PathDiagnosticLocation pos
= getLocationForCaller(CE
.getCalleeContext(),
855 CE
.getLocationContext(),
857 return std::shared_ptr
<PathDiagnosticCallPiece
>(
858 new PathDiagnosticCallPiece(caller
, pos
));
861 PathDiagnosticCallPiece
*
862 PathDiagnosticCallPiece::construct(PathPieces
&path
,
863 const Decl
*caller
) {
864 std::shared_ptr
<PathDiagnosticCallPiece
> C(
865 new PathDiagnosticCallPiece(path
, caller
));
868 path
.push_front(std::move(C
));
872 void PathDiagnosticCallPiece::setCallee(const CallEnter
&CE
,
873 const SourceManager
&SM
) {
874 const StackFrameContext
*CalleeCtx
= CE
.getCalleeContext();
875 Callee
= CalleeCtx
->getDecl();
877 callEnterWithin
= PathDiagnosticLocation::createBegin(Callee
, SM
);
878 callEnter
= getLocationForCaller(CalleeCtx
, CE
.getLocationContext(), SM
);
880 // Autosynthesized property accessors are special because we'd never
881 // pop back up to non-autosynthesized code until we leave them.
882 // This is not generally true for autosynthesized callees, which may call
883 // non-autosynthesized callbacks.
884 // Unless set here, the IsCalleeAnAutosynthesizedPropertyAccessor flag
885 // defaults to false.
886 if (const auto *MD
= dyn_cast
<ObjCMethodDecl
>(Callee
))
887 IsCalleeAnAutosynthesizedPropertyAccessor
= (
888 MD
->isPropertyAccessor() &&
889 CalleeCtx
->getAnalysisDeclContext()->isBodyAutosynthesized());
892 static void describeTemplateParameters(raw_ostream
&Out
,
893 const ArrayRef
<TemplateArgument
> TAList
,
894 const LangOptions
&LO
,
895 StringRef Prefix
= StringRef(),
896 StringRef Postfix
= StringRef());
898 static void describeTemplateParameter(raw_ostream
&Out
,
899 const TemplateArgument
&TArg
,
900 const LangOptions
&LO
) {
902 if (TArg
.getKind() == TemplateArgument::ArgKind::Pack
) {
903 describeTemplateParameters(Out
, TArg
.getPackAsArray(), LO
);
905 TArg
.print(PrintingPolicy(LO
), Out
, /*IncludeType*/ true);
909 static void describeTemplateParameters(raw_ostream
&Out
,
910 const ArrayRef
<TemplateArgument
> TAList
,
911 const LangOptions
&LO
,
912 StringRef Prefix
, StringRef Postfix
) {
917 for (int I
= 0, Last
= TAList
.size() - 1; I
!= Last
; ++I
) {
918 describeTemplateParameter(Out
, TAList
[I
], LO
);
921 describeTemplateParameter(Out
, TAList
[TAList
.size() - 1], LO
);
925 static void describeClass(raw_ostream
&Out
, const CXXRecordDecl
*D
,
926 StringRef Prefix
= StringRef()) {
927 if (!D
->getIdentifier())
929 Out
<< Prefix
<< '\'' << *D
;
930 if (const auto T
= dyn_cast
<ClassTemplateSpecializationDecl
>(D
))
931 describeTemplateParameters(Out
, T
->getTemplateArgs().asArray(),
932 D
->getLangOpts(), "<", ">");
937 static bool describeCodeDecl(raw_ostream
&Out
, const Decl
*D
,
938 bool ExtendedDescription
,
939 StringRef Prefix
= StringRef()) {
943 if (isa
<BlockDecl
>(D
)) {
944 if (ExtendedDescription
)
945 Out
<< Prefix
<< "anonymous block";
946 return ExtendedDescription
;
949 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(D
)) {
951 if (ExtendedDescription
&& !MD
->isUserProvided()) {
952 if (MD
->isExplicitlyDefaulted())
958 if (const auto *CD
= dyn_cast
<CXXConstructorDecl
>(MD
)) {
959 if (CD
->isDefaultConstructor())
961 else if (CD
->isCopyConstructor())
963 else if (CD
->isMoveConstructor())
966 Out
<< "constructor";
967 describeClass(Out
, MD
->getParent(), " for ");
968 } else if (isa
<CXXDestructorDecl
>(MD
)) {
969 if (!MD
->isUserProvided()) {
971 describeClass(Out
, MD
->getParent(), " for ");
973 // Use ~Foo for explicitly-written destructors.
974 Out
<< "'" << *MD
<< "'";
976 } else if (MD
->isCopyAssignmentOperator()) {
977 Out
<< "copy assignment operator";
978 describeClass(Out
, MD
->getParent(), " for ");
979 } else if (MD
->isMoveAssignmentOperator()) {
980 Out
<< "move assignment operator";
981 describeClass(Out
, MD
->getParent(), " for ");
983 if (MD
->getParent()->getIdentifier())
984 Out
<< "'" << *MD
->getParent() << "::" << *MD
<< "'";
986 Out
<< "'" << *MD
<< "'";
992 Out
<< Prefix
<< '\'' << cast
<NamedDecl
>(*D
);
994 // Adding template parameters.
995 if (const auto FD
= dyn_cast
<FunctionDecl
>(D
))
996 if (const TemplateArgumentList
*TAList
=
997 FD
->getTemplateSpecializationArgs())
998 describeTemplateParameters(Out
, TAList
->asArray(), FD
->getLangOpts(), "<",
1005 std::shared_ptr
<PathDiagnosticEventPiece
>
1006 PathDiagnosticCallPiece::getCallEnterEvent() const {
1007 // We do not produce call enters and call exits for autosynthesized property
1008 // accessors. We do generally produce them for other functions coming from
1009 // the body farm because they may call callbacks that bring us back into
1011 if (!Callee
|| IsCalleeAnAutosynthesizedPropertyAccessor
)
1014 SmallString
<256> buf
;
1015 llvm::raw_svector_ostream
Out(buf
);
1018 describeCodeDecl(Out
, Callee
, /*ExtendedDescription=*/true);
1020 assert(callEnter
.asLocation().isValid());
1021 return std::make_shared
<PathDiagnosticEventPiece
>(callEnter
, Out
.str());
1024 std::shared_ptr
<PathDiagnosticEventPiece
>
1025 PathDiagnosticCallPiece::getCallEnterWithinCallerEvent() const {
1026 if (!callEnterWithin
.asLocation().isValid())
1028 if (Callee
->isImplicit() || !Callee
->hasBody())
1030 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(Callee
))
1031 if (MD
->isDefaulted())
1034 SmallString
<256> buf
;
1035 llvm::raw_svector_ostream
Out(buf
);
1037 Out
<< "Entered call";
1038 describeCodeDecl(Out
, Caller
, /*ExtendedDescription=*/false, " from ");
1040 return std::make_shared
<PathDiagnosticEventPiece
>(callEnterWithin
, Out
.str());
1043 std::shared_ptr
<PathDiagnosticEventPiece
>
1044 PathDiagnosticCallPiece::getCallExitEvent() const {
1045 // We do not produce call enters and call exits for autosynthesized property
1046 // accessors. We do generally produce them for other functions coming from
1047 // the body farm because they may call callbacks that bring us back into
1049 if (NoExit
|| IsCalleeAnAutosynthesizedPropertyAccessor
)
1052 SmallString
<256> buf
;
1053 llvm::raw_svector_ostream
Out(buf
);
1055 if (!CallStackMessage
.empty()) {
1056 Out
<< CallStackMessage
;
1058 bool DidDescribe
= describeCodeDecl(Out
, Callee
,
1059 /*ExtendedDescription=*/false,
1062 Out
<< "Returning to caller";
1065 assert(callReturn
.asLocation().isValid());
1066 return std::make_shared
<PathDiagnosticEventPiece
>(callReturn
, Out
.str());
1069 static void compute_path_size(const PathPieces
&pieces
, unsigned &size
) {
1070 for (const auto &I
: pieces
) {
1071 const PathDiagnosticPiece
*piece
= I
.get();
1072 if (const auto *cp
= dyn_cast
<PathDiagnosticCallPiece
>(piece
))
1073 compute_path_size(cp
->path
, size
);
1079 unsigned PathDiagnostic::full_size() {
1081 compute_path_size(path
, size
);
1085 //===----------------------------------------------------------------------===//
1086 // FoldingSet profiling methods.
1087 //===----------------------------------------------------------------------===//
1089 void PathDiagnosticLocation::Profile(llvm::FoldingSetNodeID
&ID
) const {
1090 ID
.Add(Range
.getBegin());
1091 ID
.Add(Range
.getEnd());
1092 ID
.Add(static_cast<const SourceLocation
&>(Loc
));
1095 void PathDiagnosticPiece::Profile(llvm::FoldingSetNodeID
&ID
) const {
1096 ID
.AddInteger((unsigned) getKind());
1098 // FIXME: Add profiling support for code hints.
1099 ID
.AddInteger((unsigned) getDisplayHint());
1100 ArrayRef
<SourceRange
> Ranges
= getRanges();
1101 for (const auto &I
: Ranges
) {
1102 ID
.Add(I
.getBegin());
1107 void PathDiagnosticCallPiece::Profile(llvm::FoldingSetNodeID
&ID
) const {
1108 PathDiagnosticPiece::Profile(ID
);
1109 for (const auto &I
: path
)
1113 void PathDiagnosticSpotPiece::Profile(llvm::FoldingSetNodeID
&ID
) const {
1114 PathDiagnosticPiece::Profile(ID
);
1118 void PathDiagnosticControlFlowPiece::Profile(llvm::FoldingSetNodeID
&ID
) const {
1119 PathDiagnosticPiece::Profile(ID
);
1120 for (const auto &I
: *this)
1124 void PathDiagnosticMacroPiece::Profile(llvm::FoldingSetNodeID
&ID
) const {
1125 PathDiagnosticSpotPiece::Profile(ID
);
1126 for (const auto &I
: subPieces
)
1130 void PathDiagnosticNotePiece::Profile(llvm::FoldingSetNodeID
&ID
) const {
1131 PathDiagnosticSpotPiece::Profile(ID
);
1134 void PathDiagnosticPopUpPiece::Profile(llvm::FoldingSetNodeID
&ID
) const {
1135 PathDiagnosticSpotPiece::Profile(ID
);
1138 void PathDiagnostic::Profile(llvm::FoldingSetNodeID
&ID
) const {
1139 ID
.Add(getLocation());
1140 ID
.Add(getUniqueingLoc());
1141 ID
.AddString(BugType
);
1142 ID
.AddString(VerboseDesc
);
1143 ID
.AddString(Category
);
1146 void PathDiagnostic::FullProfile(llvm::FoldingSetNodeID
&ID
) const {
1148 for (const auto &I
: path
)
1150 for (meta_iterator I
= meta_begin(), E
= meta_end(); I
!= E
; ++I
)
1154 LLVM_DUMP_METHOD
void PathPieces::dump() const {
1156 for (PathPieces::const_iterator I
= begin(), E
= end(); I
!= E
; ++I
) {
1157 llvm::errs() << "[" << index
++ << "] ";
1159 llvm::errs() << "\n";
1163 LLVM_DUMP_METHOD
void PathDiagnosticCallPiece::dump() const {
1164 llvm::errs() << "CALL\n--------------\n";
1166 if (const Stmt
*SLoc
= getLocation().getStmtOrNull())
1168 else if (const auto *ND
= dyn_cast_or_null
<NamedDecl
>(getCallee()))
1169 llvm::errs() << *ND
<< "\n";
1171 getLocation().dump();
1174 LLVM_DUMP_METHOD
void PathDiagnosticEventPiece::dump() const {
1175 llvm::errs() << "EVENT\n--------------\n";
1176 llvm::errs() << getString() << "\n";
1177 llvm::errs() << " ---- at ----\n";
1178 getLocation().dump();
1181 LLVM_DUMP_METHOD
void PathDiagnosticControlFlowPiece::dump() const {
1182 llvm::errs() << "CONTROL\n--------------\n";
1183 getStartLocation().dump();
1184 llvm::errs() << " ---- to ----\n";
1185 getEndLocation().dump();
1188 LLVM_DUMP_METHOD
void PathDiagnosticMacroPiece::dump() const {
1189 llvm::errs() << "MACRO\n--------------\n";
1190 // FIXME: Print which macro is being invoked.
1193 LLVM_DUMP_METHOD
void PathDiagnosticNotePiece::dump() const {
1194 llvm::errs() << "NOTE\n--------------\n";
1195 llvm::errs() << getString() << "\n";
1196 llvm::errs() << " ---- at ----\n";
1197 getLocation().dump();
1200 LLVM_DUMP_METHOD
void PathDiagnosticPopUpPiece::dump() const {
1201 llvm::errs() << "POP-UP\n--------------\n";
1202 llvm::errs() << getString() << "\n";
1203 llvm::errs() << " ---- at ----\n";
1204 getLocation().dump();
1207 LLVM_DUMP_METHOD
void PathDiagnosticLocation::dump() const {
1209 llvm::errs() << "<INVALID>\n";
1215 // FIXME: actually print the range.
1216 llvm::errs() << "<range>\n";
1219 asLocation().dump();
1220 llvm::errs() << "\n";
1226 llvm::errs() << "<NULL STMT>\n";
1229 if (const auto *ND
= dyn_cast_or_null
<NamedDecl
>(D
))
1230 llvm::errs() << *ND
<< "\n";
1231 else if (isa
<BlockDecl
>(D
))
1232 // FIXME: Make this nicer.
1233 llvm::errs() << "<block>\n";
1235 llvm::errs() << "<unknown decl>\n";
1237 llvm::errs() << "<NULL DECL>\n";