1 //===--- PathDiagnostic.cpp - Path-Specific Diagnostic Handling -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the PathDiagnostic-related interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclCXX.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/StmtCXX.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Support/raw_ostream.h"
28 using namespace clang;
31 bool PathDiagnosticMacroPiece::containsEvent() const {
32 for (auto &P : subPieces) {
33 if (isa<PathDiagnosticEventPiece>(*P))
35 if (auto *MP = dyn_cast<PathDiagnosticMacroPiece>(P.get()))
36 if (MP->containsEvent())
42 static StringRef StripTrailingDots(StringRef s) {
43 for (StringRef::size_type i = s.size(); i != 0; --i)
45 return s.substr(0, i);
49 PathDiagnosticPiece::PathDiagnosticPiece(StringRef s,
50 Kind k, DisplayHint hint)
51 : str(StripTrailingDots(s)), kind(k), Hint(hint),
52 LastInMainSourceFile(false) {}
54 PathDiagnosticPiece::PathDiagnosticPiece(Kind k, DisplayHint hint)
55 : kind(k), Hint(hint), LastInMainSourceFile(false) {}
57 PathDiagnosticPiece::~PathDiagnosticPiece() {}
58 PathDiagnosticEventPiece::~PathDiagnosticEventPiece() {}
59 PathDiagnosticCallPiece::~PathDiagnosticCallPiece() {}
60 PathDiagnosticControlFlowPiece::~PathDiagnosticControlFlowPiece() {}
61 PathDiagnosticMacroPiece::~PathDiagnosticMacroPiece() {}
62 PathDiagnosticNotePiece::~PathDiagnosticNotePiece() {}
64 void PathPieces::flattenTo(PathPieces &Primary, PathPieces &Current,
65 bool ShouldFlattenMacros) const {
66 for (auto &Piece : *this) {
67 switch (Piece->getKind()) {
68 case PathDiagnosticPiece::Call: {
69 auto &Call = cast<PathDiagnosticCallPiece>(*Piece);
70 if (auto CallEnter = Call.getCallEnterEvent())
71 Current.push_back(std::move(CallEnter));
72 Call.path.flattenTo(Primary, Primary, ShouldFlattenMacros);
73 if (auto callExit = Call.getCallExitEvent())
74 Current.push_back(std::move(callExit));
77 case PathDiagnosticPiece::Macro: {
78 auto &Macro = cast<PathDiagnosticMacroPiece>(*Piece);
79 if (ShouldFlattenMacros) {
80 Macro.subPieces.flattenTo(Primary, Primary, ShouldFlattenMacros);
82 Current.push_back(Piece);
84 Macro.subPieces.flattenTo(Primary, NewPath, ShouldFlattenMacros);
85 // FIXME: This probably shouldn't mutate the original path piece.
86 Macro.subPieces = NewPath;
90 case PathDiagnosticPiece::Event:
91 case PathDiagnosticPiece::ControlFlow:
92 case PathDiagnosticPiece::Note:
93 Current.push_back(Piece);
99 PathDiagnostic::~PathDiagnostic() {}
101 PathDiagnostic::PathDiagnostic(StringRef CheckName, const Decl *declWithIssue,
102 StringRef bugtype, StringRef verboseDesc,
103 StringRef shortDesc, StringRef category,
104 PathDiagnosticLocation LocationToUnique,
105 const Decl *DeclToUnique)
106 : CheckName(CheckName),
107 DeclWithIssue(declWithIssue),
108 BugType(StripTrailingDots(bugtype)),
109 VerboseDesc(StripTrailingDots(verboseDesc)),
110 ShortDesc(StripTrailingDots(shortDesc)),
111 Category(StripTrailingDots(category)),
112 UniqueingLoc(LocationToUnique),
113 UniqueingDecl(DeclToUnique),
116 static PathDiagnosticCallPiece *
117 getFirstStackedCallToHeaderFile(PathDiagnosticCallPiece *CP,
118 const SourceManager &SMgr) {
119 SourceLocation CallLoc = CP->callEnter.asLocation();
121 // If the call is within a macro, don't do anything (for now).
122 if (CallLoc.isMacroID())
125 assert(SMgr.isInMainFile(CallLoc) &&
126 "The call piece should be in the main file.");
128 // Check if CP represents a path through a function outside of the main file.
129 if (!SMgr.isInMainFile(CP->callEnterWithin.asLocation()))
132 const PathPieces &Path = CP->path;
136 // Check if the last piece in the callee path is a call to a function outside
138 if (PathDiagnosticCallPiece *CPInner =
139 dyn_cast<PathDiagnosticCallPiece>(Path.back().get())) {
140 return getFirstStackedCallToHeaderFile(CPInner, SMgr);
143 // Otherwise, the last piece is in the main file.
147 void PathDiagnostic::resetDiagnosticLocationToMainFile() {
151 PathDiagnosticPiece *LastP = path.back().get();
153 const SourceManager &SMgr = LastP->getLocation().getManager();
155 // We only need to check if the report ends inside headers, if the last piece
157 if (PathDiagnosticCallPiece *CP = dyn_cast<PathDiagnosticCallPiece>(LastP)) {
158 CP = getFirstStackedCallToHeaderFile(CP, SMgr);
161 CP->setAsLastInMainSourceFile();
163 // Update the path diagnostic message.
164 const NamedDecl *ND = dyn_cast<NamedDecl>(CP->getCallee());
166 SmallString<200> buf;
167 llvm::raw_svector_ostream os(buf);
168 os << " (within a call to '" << ND->getDeclName() << "')";
169 appendToDesc(os.str());
172 // Reset the report containing declaration and location.
173 DeclWithIssue = CP->getCaller();
174 Loc = CP->getLocation();
181 void PathDiagnosticConsumer::anchor() { }
183 PathDiagnosticConsumer::~PathDiagnosticConsumer() {
184 // Delete the contents of the FoldingSet if it isn't empty already.
185 for (llvm::FoldingSet<PathDiagnostic>::iterator it =
186 Diags.begin(), et = Diags.end() ; it != et ; ++it) {
191 void PathDiagnosticConsumer::HandlePathDiagnostic(
192 std::unique_ptr<PathDiagnostic> D) {
193 if (!D || D->path.empty())
196 // We need to flatten the locations (convert Stmt* to locations) because
197 // the referenced statements may be freed by the time the diagnostics
199 D->flattenLocations();
201 // If the PathDiagnosticConsumer does not support diagnostics that
202 // cross file boundaries, prune out such diagnostics now.
203 if (!supportsCrossFileDiagnostics()) {
204 // Verify that the entire path is from the same FileID.
206 const SourceManager &SMgr = D->path.front()->getLocation().getManager();
207 SmallVector<const PathPieces *, 5> WorkList;
208 WorkList.push_back(&D->path);
209 SmallString<128> buf;
210 llvm::raw_svector_ostream warning(buf);
211 warning << "warning: Path diagnostic report is not generated. Current "
212 << "output format does not support diagnostics that cross file "
213 << "boundaries. Refer to --analyzer-output for valid output "
216 while (!WorkList.empty()) {
217 const PathPieces &path = *WorkList.pop_back_val();
219 for (PathPieces::const_iterator I = path.begin(), E = path.end(); I != E;
221 const PathDiagnosticPiece *piece = I->get();
222 FullSourceLoc L = piece->getLocation().asLocation().getExpansionLoc();
224 if (FID.isInvalid()) {
225 FID = SMgr.getFileID(L);
226 } else if (SMgr.getFileID(L) != FID) {
227 llvm::errs() << warning.str();
231 // Check the source ranges.
232 ArrayRef<SourceRange> Ranges = piece->getRanges();
233 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(),
234 E = Ranges.end(); I != E; ++I) {
235 SourceLocation L = SMgr.getExpansionLoc(I->getBegin());
236 if (!L.isFileID() || SMgr.getFileID(L) != FID) {
237 llvm::errs() << warning.str();
240 L = SMgr.getExpansionLoc(I->getEnd());
241 if (!L.isFileID() || SMgr.getFileID(L) != FID) {
242 llvm::errs() << warning.str();
247 if (const PathDiagnosticCallPiece *call =
248 dyn_cast<PathDiagnosticCallPiece>(piece)) {
249 WorkList.push_back(&call->path);
251 else if (const PathDiagnosticMacroPiece *macro =
252 dyn_cast<PathDiagnosticMacroPiece>(piece)) {
253 WorkList.push_back(¯o->subPieces);
259 return; // FIXME: Emit a warning?
262 // Profile the node to see if we already have something matching it
263 llvm::FoldingSetNodeID profile;
265 void *InsertPos = nullptr;
267 if (PathDiagnostic *orig = Diags.FindNodeOrInsertPos(profile, InsertPos)) {
268 // Keep the PathDiagnostic with the shorter path.
269 // Note, the enclosing routine is called in deterministic order, so the
270 // results will be consistent between runs (no reason to break ties if the
271 // size is the same).
272 const unsigned orig_size = orig->full_size();
273 const unsigned new_size = D->full_size();
274 if (orig_size <= new_size)
277 assert(orig != D.get());
278 Diags.RemoveNode(orig);
282 Diags.InsertNode(D.release());
285 static Optional<bool> comparePath(const PathPieces &X, const PathPieces &Y);
287 static Optional<bool>
288 compareControlFlow(const PathDiagnosticControlFlowPiece &X,
289 const PathDiagnosticControlFlowPiece &Y) {
290 FullSourceLoc XSL = X.getStartLocation().asLocation();
291 FullSourceLoc YSL = Y.getStartLocation().asLocation();
293 return XSL.isBeforeInTranslationUnitThan(YSL);
294 FullSourceLoc XEL = X.getEndLocation().asLocation();
295 FullSourceLoc YEL = Y.getEndLocation().asLocation();
297 return XEL.isBeforeInTranslationUnitThan(YEL);
301 static Optional<bool> compareMacro(const PathDiagnosticMacroPiece &X,
302 const PathDiagnosticMacroPiece &Y) {
303 return comparePath(X.subPieces, Y.subPieces);
306 static Optional<bool> compareCall(const PathDiagnosticCallPiece &X,
307 const PathDiagnosticCallPiece &Y) {
308 FullSourceLoc X_CEL = X.callEnter.asLocation();
309 FullSourceLoc Y_CEL = Y.callEnter.asLocation();
311 return X_CEL.isBeforeInTranslationUnitThan(Y_CEL);
312 FullSourceLoc X_CEWL = X.callEnterWithin.asLocation();
313 FullSourceLoc Y_CEWL = Y.callEnterWithin.asLocation();
314 if (X_CEWL != Y_CEWL)
315 return X_CEWL.isBeforeInTranslationUnitThan(Y_CEWL);
316 FullSourceLoc X_CRL = X.callReturn.asLocation();
317 FullSourceLoc Y_CRL = Y.callReturn.asLocation();
319 return X_CRL.isBeforeInTranslationUnitThan(Y_CRL);
320 return comparePath(X.path, Y.path);
323 static Optional<bool> comparePiece(const PathDiagnosticPiece &X,
324 const PathDiagnosticPiece &Y) {
325 if (X.getKind() != Y.getKind())
326 return X.getKind() < Y.getKind();
328 FullSourceLoc XL = X.getLocation().asLocation();
329 FullSourceLoc YL = Y.getLocation().asLocation();
331 return XL.isBeforeInTranslationUnitThan(YL);
333 if (X.getString() != Y.getString())
334 return X.getString() < Y.getString();
336 if (X.getRanges().size() != Y.getRanges().size())
337 return X.getRanges().size() < Y.getRanges().size();
339 const SourceManager &SM = XL.getManager();
341 for (unsigned i = 0, n = X.getRanges().size(); i < n; ++i) {
342 SourceRange XR = X.getRanges()[i];
343 SourceRange YR = Y.getRanges()[i];
345 if (XR.getBegin() != YR.getBegin())
346 return SM.isBeforeInTranslationUnit(XR.getBegin(), YR.getBegin());
347 return SM.isBeforeInTranslationUnit(XR.getEnd(), YR.getEnd());
351 switch (X.getKind()) {
352 case PathDiagnosticPiece::ControlFlow:
353 return compareControlFlow(cast<PathDiagnosticControlFlowPiece>(X),
354 cast<PathDiagnosticControlFlowPiece>(Y));
355 case PathDiagnosticPiece::Event:
356 case PathDiagnosticPiece::Note:
358 case PathDiagnosticPiece::Macro:
359 return compareMacro(cast<PathDiagnosticMacroPiece>(X),
360 cast<PathDiagnosticMacroPiece>(Y));
361 case PathDiagnosticPiece::Call:
362 return compareCall(cast<PathDiagnosticCallPiece>(X),
363 cast<PathDiagnosticCallPiece>(Y));
365 llvm_unreachable("all cases handled");
368 static Optional<bool> comparePath(const PathPieces &X, const PathPieces &Y) {
369 if (X.size() != Y.size())
370 return X.size() < Y.size();
372 PathPieces::const_iterator X_I = X.begin(), X_end = X.end();
373 PathPieces::const_iterator Y_I = Y.begin(), Y_end = Y.end();
375 for ( ; X_I != X_end && Y_I != Y_end; ++X_I, ++Y_I) {
376 Optional<bool> b = comparePiece(**X_I, **Y_I);
384 static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y) {
385 FullSourceLoc XL = X.getLocation().asLocation();
386 FullSourceLoc YL = Y.getLocation().asLocation();
388 return XL.isBeforeInTranslationUnitThan(YL);
389 if (X.getBugType() != Y.getBugType())
390 return X.getBugType() < Y.getBugType();
391 if (X.getCategory() != Y.getCategory())
392 return X.getCategory() < Y.getCategory();
393 if (X.getVerboseDescription() != Y.getVerboseDescription())
394 return X.getVerboseDescription() < Y.getVerboseDescription();
395 if (X.getShortDescription() != Y.getShortDescription())
396 return X.getShortDescription() < Y.getShortDescription();
397 if (X.getDeclWithIssue() != Y.getDeclWithIssue()) {
398 const Decl *XD = X.getDeclWithIssue();
401 const Decl *YD = Y.getDeclWithIssue();
404 SourceLocation XDL = XD->getLocation();
405 SourceLocation YDL = YD->getLocation();
407 const SourceManager &SM = XL.getManager();
408 return SM.isBeforeInTranslationUnit(XDL, YDL);
411 PathDiagnostic::meta_iterator XI = X.meta_begin(), XE = X.meta_end();
412 PathDiagnostic::meta_iterator YI = Y.meta_begin(), YE = Y.meta_end();
413 if (XE - XI != YE - YI)
414 return (XE - XI) < (YE - YI);
415 for ( ; XI != XE ; ++XI, ++YI) {
417 return (*XI) < (*YI);
419 Optional<bool> b = comparePath(X.path, Y.path);
420 assert(b.hasValue());
424 void PathDiagnosticConsumer::FlushDiagnostics(
425 PathDiagnosticConsumer::FilesMade *Files) {
431 std::vector<const PathDiagnostic *> BatchDiags;
432 for (llvm::FoldingSet<PathDiagnostic>::iterator it = Diags.begin(),
433 et = Diags.end(); it != et; ++it) {
434 const PathDiagnostic *D = &*it;
435 BatchDiags.push_back(D);
438 // Sort the diagnostics so that they are always emitted in a deterministic
440 int (*Comp)(const PathDiagnostic *const *, const PathDiagnostic *const *) =
441 [](const PathDiagnostic *const *X, const PathDiagnostic *const *Y) {
442 assert(*X != *Y && "PathDiagnostics not uniqued!");
443 if (compare(**X, **Y))
445 assert(compare(**Y, **X) && "Not a total order!");
448 array_pod_sort(BatchDiags.begin(), BatchDiags.end(), Comp);
450 FlushDiagnosticsImpl(BatchDiags, Files);
452 // Delete the flushed diagnostics.
453 for (std::vector<const PathDiagnostic *>::iterator it = BatchDiags.begin(),
454 et = BatchDiags.end(); it != et; ++it) {
455 const PathDiagnostic *D = *it;
459 // Clear out the FoldingSet.
463 PathDiagnosticConsumer::FilesMade::~FilesMade() {
464 for (PDFileEntry &Entry : Set)
465 Entry.~PDFileEntry();
468 void PathDiagnosticConsumer::FilesMade::addDiagnostic(const PathDiagnostic &PD,
469 StringRef ConsumerName,
470 StringRef FileName) {
471 llvm::FoldingSetNodeID NodeID;
474 PDFileEntry *Entry = Set.FindNodeOrInsertPos(NodeID, InsertPos);
476 Entry = Alloc.Allocate<PDFileEntry>();
477 Entry = new (Entry) PDFileEntry(NodeID);
478 Set.InsertNode(Entry, InsertPos);
481 // Allocate persistent storage for the file name.
482 char *FileName_cstr = (char*) Alloc.Allocate(FileName.size(), 1);
483 memcpy(FileName_cstr, FileName.data(), FileName.size());
485 Entry->files.push_back(std::make_pair(ConsumerName,
486 StringRef(FileName_cstr,
490 PathDiagnosticConsumer::PDFileEntry::ConsumerFiles *
491 PathDiagnosticConsumer::FilesMade::getFiles(const PathDiagnostic &PD) {
492 llvm::FoldingSetNodeID NodeID;
495 PDFileEntry *Entry = Set.FindNodeOrInsertPos(NodeID, InsertPos);
498 return &Entry->files;
501 //===----------------------------------------------------------------------===//
502 // PathDiagnosticLocation methods.
503 //===----------------------------------------------------------------------===//
505 static SourceLocation getValidSourceLocation(const Stmt* S,
506 LocationOrAnalysisDeclContext LAC,
507 bool UseEnd = false) {
508 SourceLocation L = UseEnd ? S->getLocEnd() : S->getLocStart();
509 assert(!LAC.isNull() && "A valid LocationContext or AnalysisDeclContext should "
510 "be passed to PathDiagnosticLocation upon creation.");
512 // S might be a temporary statement that does not have a location in the
513 // source code, so find an enclosing statement and use its location.
515 AnalysisDeclContext *ADC;
516 if (LAC.is<const LocationContext*>())
517 ADC = LAC.get<const LocationContext*>()->getAnalysisDeclContext();
519 ADC = LAC.get<AnalysisDeclContext*>();
521 ParentMap &PM = ADC->getParentMap();
523 const Stmt *Parent = S;
525 Parent = PM.getParent(Parent);
527 // In rare cases, we have implicit top-level expressions,
528 // such as arguments for implicit member initializers.
529 // In this case, fall back to the start of the body (even if we were
530 // asked for the statement end location).
532 const Stmt *Body = ADC->getBody();
534 L = Body->getLocStart();
536 L = ADC->getDecl()->getLocEnd();
540 L = UseEnd ? Parent->getLocEnd() : Parent->getLocStart();
541 } while (!L.isValid());
547 static PathDiagnosticLocation
548 getLocationForCaller(const StackFrameContext *SFC,
549 const LocationContext *CallerCtx,
550 const SourceManager &SM) {
551 const CFGBlock &Block = *SFC->getCallSiteBlock();
552 CFGElement Source = Block[SFC->getIndex()];
554 switch (Source.getKind()) {
555 case CFGElement::Statement:
556 return PathDiagnosticLocation(Source.castAs<CFGStmt>().getStmt(),
558 case CFGElement::Initializer: {
559 const CFGInitializer &Init = Source.castAs<CFGInitializer>();
560 return PathDiagnosticLocation(Init.getInitializer()->getInit(),
563 case CFGElement::AutomaticObjectDtor: {
564 const CFGAutomaticObjDtor &Dtor = Source.castAs<CFGAutomaticObjDtor>();
565 return PathDiagnosticLocation::createEnd(Dtor.getTriggerStmt(),
568 case CFGElement::DeleteDtor: {
569 const CFGDeleteDtor &Dtor = Source.castAs<CFGDeleteDtor>();
570 return PathDiagnosticLocation(Dtor.getDeleteExpr(), SM, CallerCtx);
572 case CFGElement::BaseDtor:
573 case CFGElement::MemberDtor: {
574 const AnalysisDeclContext *CallerInfo = CallerCtx->getAnalysisDeclContext();
575 if (const Stmt *CallerBody = CallerInfo->getBody())
576 return PathDiagnosticLocation::createEnd(CallerBody, SM, CallerCtx);
577 return PathDiagnosticLocation::create(CallerInfo->getDecl(), SM);
579 case CFGElement::TemporaryDtor:
580 case CFGElement::NewAllocator:
581 llvm_unreachable("not yet implemented!");
584 llvm_unreachable("Unknown CFGElement kind");
587 PathDiagnosticLocation
588 PathDiagnosticLocation::createBegin(const Decl *D,
589 const SourceManager &SM) {
590 return PathDiagnosticLocation(D->getLocStart(), SM, SingleLocK);
593 PathDiagnosticLocation
594 PathDiagnosticLocation::createBegin(const Stmt *S,
595 const SourceManager &SM,
596 LocationOrAnalysisDeclContext LAC) {
597 return PathDiagnosticLocation(getValidSourceLocation(S, LAC),
601 PathDiagnosticLocation
602 PathDiagnosticLocation::createEnd(const Stmt *S,
603 const SourceManager &SM,
604 LocationOrAnalysisDeclContext LAC) {
605 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S))
606 return createEndBrace(CS, SM);
607 return PathDiagnosticLocation(getValidSourceLocation(S, LAC, /*End=*/true),
611 PathDiagnosticLocation
612 PathDiagnosticLocation::createOperatorLoc(const BinaryOperator *BO,
613 const SourceManager &SM) {
614 return PathDiagnosticLocation(BO->getOperatorLoc(), SM, SingleLocK);
617 PathDiagnosticLocation
618 PathDiagnosticLocation::createConditionalColonLoc(
619 const ConditionalOperator *CO,
620 const SourceManager &SM) {
621 return PathDiagnosticLocation(CO->getColonLoc(), SM, SingleLocK);
625 PathDiagnosticLocation
626 PathDiagnosticLocation::createMemberLoc(const MemberExpr *ME,
627 const SourceManager &SM) {
628 return PathDiagnosticLocation(ME->getMemberLoc(), SM, SingleLocK);
631 PathDiagnosticLocation
632 PathDiagnosticLocation::createBeginBrace(const CompoundStmt *CS,
633 const SourceManager &SM) {
634 SourceLocation L = CS->getLBracLoc();
635 return PathDiagnosticLocation(L, SM, SingleLocK);
638 PathDiagnosticLocation
639 PathDiagnosticLocation::createEndBrace(const CompoundStmt *CS,
640 const SourceManager &SM) {
641 SourceLocation L = CS->getRBracLoc();
642 return PathDiagnosticLocation(L, SM, SingleLocK);
645 PathDiagnosticLocation
646 PathDiagnosticLocation::createDeclBegin(const LocationContext *LC,
647 const SourceManager &SM) {
648 // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
649 if (const CompoundStmt *CS =
650 dyn_cast_or_null<CompoundStmt>(LC->getDecl()->getBody()))
651 if (!CS->body_empty()) {
652 SourceLocation Loc = (*CS->body_begin())->getLocStart();
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 (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
671 const CFGBlock *BSrc = BE->getSrc();
672 S = BSrc->getTerminatorCondition();
673 } else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>()) {
675 if (P.getAs<PostStmtPurgeDeadSymbols>())
676 return PathDiagnosticLocation::createEnd(S, SMng, P.getLocationContext());
677 } else if (Optional<PostInitializer> PIP = P.getAs<PostInitializer>()) {
678 return PathDiagnosticLocation(PIP->getInitializer()->getSourceLocation(),
680 } else if (Optional<PostImplicitCall> PIE = P.getAs<PostImplicitCall>()) {
681 return PathDiagnosticLocation(PIE->getLocation(), SMng);
682 } else if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
683 return getLocationForCaller(CE->getCalleeContext(),
684 CE->getLocationContext(),
686 } else if (Optional<CallExitEnd> CEE = P.getAs<CallExitEnd>()) {
687 return getLocationForCaller(CEE->getCalleeContext(),
688 CEE->getLocationContext(),
691 llvm_unreachable("Unexpected ProgramPoint");
694 return PathDiagnosticLocation(S, SMng, P.getLocationContext());
697 static const LocationContext *
698 findTopAutosynthesizedParentContext(const LocationContext *LC) {
699 assert(LC->getAnalysisDeclContext()->isBodyAutosynthesized());
700 const LocationContext *ParentLC = LC->getParent();
701 assert(ParentLC && "We don't start analysis from autosynthesized code");
702 while (ParentLC->getAnalysisDeclContext()->isBodyAutosynthesized()) {
704 ParentLC = LC->getParent();
705 assert(ParentLC && "We don't start analysis from autosynthesized code");
710 const Stmt *PathDiagnosticLocation::getStmt(const ExplodedNode *N) {
711 // We cannot place diagnostics on autosynthesized code.
712 // Put them onto the call site through which we jumped into autosynthesized
713 // code for the first time.
714 const LocationContext *LC = N->getLocationContext();
715 if (LC->getAnalysisDeclContext()->isBodyAutosynthesized()) {
716 // It must be a stack frame because we only autosynthesize functions.
717 return cast<StackFrameContext>(findTopAutosynthesizedParentContext(LC))
720 // Otherwise, see if the node's program point directly points to a statement.
721 ProgramPoint P = N->getLocation();
722 if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
723 return SP->getStmt();
724 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>())
725 return BE->getSrc()->getTerminator();
726 if (Optional<CallEnter> CE = P.getAs<CallEnter>())
727 return CE->getCallExpr();
728 if (Optional<CallExitEnd> CEE = P.getAs<CallExitEnd>())
729 return CEE->getCalleeContext()->getCallSite();
730 if (Optional<PostInitializer> PIPP = P.getAs<PostInitializer>())
731 return PIPP->getInitializer()->getInit();
736 const Stmt *PathDiagnosticLocation::getNextStmt(const ExplodedNode *N) {
737 for (N = N->getFirstSucc(); N; N = N->getFirstSucc()) {
738 if (const Stmt *S = getStmt(N)) {
739 // Check if the statement is '?' or '&&'/'||'. These are "merges",
740 // not actual statement points.
741 switch (S->getStmtClass()) {
742 case Stmt::ChooseExprClass:
743 case Stmt::BinaryConditionalOperatorClass:
744 case Stmt::ConditionalOperatorClass:
746 case Stmt::BinaryOperatorClass: {
747 BinaryOperatorKind Op = cast<BinaryOperator>(S)->getOpcode();
748 if (Op == BO_LAnd || Op == BO_LOr)
755 // We found the statement, so return it.
763 PathDiagnosticLocation
764 PathDiagnosticLocation::createEndOfPath(const ExplodedNode *N,
765 const SourceManager &SM) {
766 assert(N && "Cannot create a location with a null node.");
767 const Stmt *S = getStmt(N);
770 // If this is an implicit call, return the implicit call point location.
771 if (Optional<PreImplicitCall> PIE = N->getLocationAs<PreImplicitCall>())
772 return PathDiagnosticLocation(PIE->getLocation(), SM);
777 ProgramPoint P = N->getLocation();
778 const LocationContext *LC = N->getLocationContext();
780 // For member expressions, return the location of the '.' or '->'.
781 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S))
782 return PathDiagnosticLocation::createMemberLoc(ME, SM);
784 // For binary operators, return the location of the operator.
785 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(S))
786 return PathDiagnosticLocation::createOperatorLoc(B, SM);
788 if (P.getAs<PostStmtPurgeDeadSymbols>())
789 return PathDiagnosticLocation::createEnd(S, SM, LC);
791 if (S->getLocStart().isValid())
792 return PathDiagnosticLocation(S, SM, LC);
793 return PathDiagnosticLocation(getValidSourceLocation(S, LC), SM);
796 return createDeclEnd(N->getLocationContext(), SM);
799 PathDiagnosticLocation PathDiagnosticLocation::createSingleLocation(
800 const PathDiagnosticLocation &PDL) {
801 FullSourceLoc L = PDL.asLocation();
802 return PathDiagnosticLocation(L, L.getManager(), SingleLocK);
806 PathDiagnosticLocation::genLocation(SourceLocation L,
807 LocationOrAnalysisDeclContext LAC) const {
809 // Note that we want a 'switch' here so that the compiler can warn us in
810 // case we add more cases.
816 // Defensive checking.
819 return FullSourceLoc(getValidSourceLocation(S, LAC),
820 const_cast<SourceManager&>(*SM));
822 // Defensive checking.
825 return FullSourceLoc(D->getLocation(), const_cast<SourceManager&>(*SM));
828 return FullSourceLoc(L, const_cast<SourceManager&>(*SM));
832 PathDiagnosticLocation::genRange(LocationOrAnalysisDeclContext LAC) const {
834 // Note that we want a 'switch' here so that the compiler can warn us in
835 // case we add more cases.
838 return PathDiagnosticRange(SourceRange(Loc,Loc), true);
842 const Stmt *S = asStmt();
843 switch (S->getStmtClass()) {
846 case Stmt::DeclStmtClass: {
847 const DeclStmt *DS = cast<DeclStmt>(S);
848 if (DS->isSingleDecl()) {
849 // Should always be the case, but we'll be defensive.
850 return SourceRange(DS->getLocStart(),
851 DS->getSingleDecl()->getLocation());
855 // FIXME: Provide better range information for different
857 case Stmt::IfStmtClass:
858 case Stmt::WhileStmtClass:
859 case Stmt::DoStmtClass:
860 case Stmt::ForStmtClass:
861 case Stmt::ChooseExprClass:
862 case Stmt::IndirectGotoStmtClass:
863 case Stmt::SwitchStmtClass:
864 case Stmt::BinaryConditionalOperatorClass:
865 case Stmt::ConditionalOperatorClass:
866 case Stmt::ObjCForCollectionStmtClass: {
867 SourceLocation L = getValidSourceLocation(S, LAC);
868 return SourceRange(L, L);
871 SourceRange R = S->getSourceRange();
877 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
878 return MD->getSourceRange();
879 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
880 if (Stmt *Body = FD->getBody())
881 return Body->getSourceRange();
884 SourceLocation L = D->getLocation();
885 return PathDiagnosticRange(SourceRange(L, L), true);
889 return SourceRange(Loc,Loc);
892 void PathDiagnosticLocation::flatten() {
898 else if (K == DeclK) {
905 //===----------------------------------------------------------------------===//
906 // Manipulation of PathDiagnosticCallPieces.
907 //===----------------------------------------------------------------------===//
909 std::shared_ptr<PathDiagnosticCallPiece>
910 PathDiagnosticCallPiece::construct(const ExplodedNode *N, const CallExitEnd &CE,
911 const SourceManager &SM) {
912 const Decl *caller = CE.getLocationContext()->getDecl();
913 PathDiagnosticLocation pos = getLocationForCaller(CE.getCalleeContext(),
914 CE.getLocationContext(),
916 return std::shared_ptr<PathDiagnosticCallPiece>(
917 new PathDiagnosticCallPiece(caller, pos));
920 PathDiagnosticCallPiece *
921 PathDiagnosticCallPiece::construct(PathPieces &path,
922 const Decl *caller) {
923 std::shared_ptr<PathDiagnosticCallPiece> C(
924 new PathDiagnosticCallPiece(path, caller));
927 path.push_front(std::move(C));
931 void PathDiagnosticCallPiece::setCallee(const CallEnter &CE,
932 const SourceManager &SM) {
933 const StackFrameContext *CalleeCtx = CE.getCalleeContext();
934 Callee = CalleeCtx->getDecl();
936 callEnterWithin = PathDiagnosticLocation::createBegin(Callee, SM);
937 callEnter = getLocationForCaller(CalleeCtx, CE.getLocationContext(), SM);
939 // Autosynthesized property accessors are special because we'd never
940 // pop back up to non-autosynthesized code until we leave them.
941 // This is not generally true for autosynthesized callees, which may call
942 // non-autosynthesized callbacks.
943 // Unless set here, the IsCalleeAnAutosynthesizedPropertyAccessor flag
944 // defaults to false.
945 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Callee))
946 IsCalleeAnAutosynthesizedPropertyAccessor = (
947 MD->isPropertyAccessor() &&
948 CalleeCtx->getAnalysisDeclContext()->isBodyAutosynthesized());
951 static inline void describeClass(raw_ostream &Out, const CXXRecordDecl *D,
952 StringRef Prefix = StringRef()) {
953 if (!D->getIdentifier())
955 Out << Prefix << '\'' << *D << '\'';
958 static bool describeCodeDecl(raw_ostream &Out, const Decl *D,
959 bool ExtendedDescription,
960 StringRef Prefix = StringRef()) {
964 if (isa<BlockDecl>(D)) {
965 if (ExtendedDescription)
966 Out << Prefix << "anonymous block";
967 return ExtendedDescription;
970 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
972 if (ExtendedDescription && !MD->isUserProvided()) {
973 if (MD->isExplicitlyDefaulted())
979 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(MD)) {
980 if (CD->isDefaultConstructor())
982 else if (CD->isCopyConstructor())
984 else if (CD->isMoveConstructor())
987 Out << "constructor";
988 describeClass(Out, MD->getParent(), " for ");
990 } else if (isa<CXXDestructorDecl>(MD)) {
991 if (!MD->isUserProvided()) {
993 describeClass(Out, MD->getParent(), " for ");
995 // Use ~Foo for explicitly-written destructors.
996 Out << "'" << *MD << "'";
999 } else if (MD->isCopyAssignmentOperator()) {
1000 Out << "copy assignment operator";
1001 describeClass(Out, MD->getParent(), " for ");
1003 } else if (MD->isMoveAssignmentOperator()) {
1004 Out << "move assignment operator";
1005 describeClass(Out, MD->getParent(), " for ");
1008 if (MD->getParent()->getIdentifier())
1009 Out << "'" << *MD->getParent() << "::" << *MD << "'";
1011 Out << "'" << *MD << "'";
1017 Out << Prefix << '\'' << cast<NamedDecl>(*D) << '\'';
1021 std::shared_ptr<PathDiagnosticEventPiece>
1022 PathDiagnosticCallPiece::getCallEnterEvent() const {
1023 // We do not produce call enters and call exits for autosynthesized property
1024 // accessors. We do generally produce them for other functions coming from
1025 // the body farm because they may call callbacks that bring us back into
1027 if (!Callee || IsCalleeAnAutosynthesizedPropertyAccessor)
1030 SmallString<256> buf;
1031 llvm::raw_svector_ostream Out(buf);
1034 describeCodeDecl(Out, Callee, /*ExtendedDescription=*/true);
1036 assert(callEnter.asLocation().isValid());
1037 return std::make_shared<PathDiagnosticEventPiece>(callEnter, Out.str());
1040 std::shared_ptr<PathDiagnosticEventPiece>
1041 PathDiagnosticCallPiece::getCallEnterWithinCallerEvent() const {
1042 if (!callEnterWithin.asLocation().isValid())
1044 if (Callee->isImplicit() || !Callee->hasBody())
1046 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee))
1047 if (MD->isDefaulted())
1050 SmallString<256> buf;
1051 llvm::raw_svector_ostream Out(buf);
1053 Out << "Entered call";
1054 describeCodeDecl(Out, Caller, /*ExtendedDescription=*/false, " from ");
1056 return std::make_shared<PathDiagnosticEventPiece>(callEnterWithin, Out.str());
1059 std::shared_ptr<PathDiagnosticEventPiece>
1060 PathDiagnosticCallPiece::getCallExitEvent() const {
1061 // We do not produce call enters and call exits for autosynthesized property
1062 // accessors. We do generally produce them for other functions coming from
1063 // the body farm because they may call callbacks that bring us back into
1065 if (NoExit || IsCalleeAnAutosynthesizedPropertyAccessor)
1068 SmallString<256> buf;
1069 llvm::raw_svector_ostream Out(buf);
1071 if (!CallStackMessage.empty()) {
1072 Out << CallStackMessage;
1074 bool DidDescribe = describeCodeDecl(Out, Callee,
1075 /*ExtendedDescription=*/false,
1078 Out << "Returning to caller";
1081 assert(callReturn.asLocation().isValid());
1082 return std::make_shared<PathDiagnosticEventPiece>(callReturn, Out.str());
1085 static void compute_path_size(const PathPieces &pieces, unsigned &size) {
1086 for (PathPieces::const_iterator it = pieces.begin(),
1087 et = pieces.end(); it != et; ++it) {
1088 const PathDiagnosticPiece *piece = it->get();
1089 if (const PathDiagnosticCallPiece *cp =
1090 dyn_cast<PathDiagnosticCallPiece>(piece)) {
1091 compute_path_size(cp->path, size);
1098 unsigned PathDiagnostic::full_size() {
1100 compute_path_size(path, size);
1104 //===----------------------------------------------------------------------===//
1105 // FoldingSet profiling methods.
1106 //===----------------------------------------------------------------------===//
1108 void PathDiagnosticLocation::Profile(llvm::FoldingSetNodeID &ID) const {
1109 ID.AddInteger(Range.getBegin().getRawEncoding());
1110 ID.AddInteger(Range.getEnd().getRawEncoding());
1111 ID.AddInteger(Loc.getRawEncoding());
1114 void PathDiagnosticPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1115 ID.AddInteger((unsigned) getKind());
1117 // FIXME: Add profiling support for code hints.
1118 ID.AddInteger((unsigned) getDisplayHint());
1119 ArrayRef<SourceRange> Ranges = getRanges();
1120 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
1122 ID.AddInteger(I->getBegin().getRawEncoding());
1123 ID.AddInteger(I->getEnd().getRawEncoding());
1127 void PathDiagnosticCallPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1128 PathDiagnosticPiece::Profile(ID);
1129 for (PathPieces::const_iterator it = path.begin(),
1130 et = path.end(); it != et; ++it) {
1135 void PathDiagnosticSpotPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1136 PathDiagnosticPiece::Profile(ID);
1140 void PathDiagnosticControlFlowPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1141 PathDiagnosticPiece::Profile(ID);
1142 for (const_iterator I = begin(), E = end(); I != E; ++I)
1146 void PathDiagnosticMacroPiece::Profile(llvm::FoldingSetNodeID &ID) const {
1147 PathDiagnosticSpotPiece::Profile(ID);
1148 for (PathPieces::const_iterator I = subPieces.begin(), E = subPieces.end();
1153 void PathDiagnosticNotePiece::Profile(llvm::FoldingSetNodeID &ID) const {
1154 PathDiagnosticSpotPiece::Profile(ID);
1157 void PathDiagnostic::Profile(llvm::FoldingSetNodeID &ID) const {
1158 ID.Add(getLocation());
1159 ID.AddString(BugType);
1160 ID.AddString(VerboseDesc);
1161 ID.AddString(Category);
1164 void PathDiagnostic::FullProfile(llvm::FoldingSetNodeID &ID) const {
1166 for (PathPieces::const_iterator I = path.begin(), E = path.end(); I != E; ++I)
1168 for (meta_iterator I = meta_begin(), E = meta_end(); I != E; ++I)
1172 StackHintGenerator::~StackHintGenerator() {}
1174 std::string StackHintGeneratorForSymbol::getMessage(const ExplodedNode *N){
1175 ProgramPoint P = N->getLocation();
1176 CallExitEnd CExit = P.castAs<CallExitEnd>();
1178 // FIXME: Use CallEvent to abstract this over all calls.
1179 const Stmt *CallSite = CExit.getCalleeContext()->getCallSite();
1180 const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite);
1185 return getMessageForSymbolNotFound();
1187 // Check if one of the parameters are set to the interesting symbol.
1188 ProgramStateRef State = N->getState();
1189 const LocationContext *LCtx = N->getLocationContext();
1190 unsigned ArgIndex = 0;
1191 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1192 E = CE->arg_end(); I != E; ++I, ++ArgIndex){
1193 SVal SV = State->getSVal(*I, LCtx);
1195 // Check if the variable corresponding to the symbol is passed by value.
1196 SymbolRef AS = SV.getAsLocSymbol();
1198 return getMessageForArg(*I, ArgIndex);
1201 // Check if the parameter is a pointer to the symbol.
1202 if (Optional<loc::MemRegionVal> Reg = SV.getAs<loc::MemRegionVal>()) {
1203 SVal PSV = State->getSVal(Reg->getRegion());
1204 SymbolRef AS = PSV.getAsLocSymbol();
1206 return getMessageForArg(*I, ArgIndex);
1211 // Check if we are returning the interesting symbol.
1212 SVal SV = State->getSVal(CE, LCtx);
1213 SymbolRef RetSym = SV.getAsLocSymbol();
1214 if (RetSym == Sym) {
1215 return getMessageForReturn(CE);
1218 return getMessageForSymbolNotFound();
1221 std::string StackHintGeneratorForSymbol::getMessageForArg(const Expr *ArgE,
1222 unsigned ArgIndex) {
1223 // Printed parameters start at 1, not 0.
1226 SmallString<200> buf;
1227 llvm::raw_svector_ostream os(buf);
1229 os << Msg << " via " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)