1 // BugReporter.cpp - Generate PathDiagnostics for Bugs ------------*- 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 BugReporter, a utility class for generating
13 //===----------------------------------------------------------------------===//
15 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
16 #include "clang/AST/ASTContext.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/AST/StmtObjC.h"
23 #include "clang/Analysis/CFG.h"
24 #include "clang/Analysis/ProgramPoint.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
27 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/IntrusiveRefCntPtr.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/raw_ostream.h"
38 using namespace clang;
41 #define DEBUG_TYPE "BugReporter"
43 STATISTIC(MaxBugClassSize,
44 "The maximum number of bug reports in the same equivalence class");
45 STATISTIC(MaxValidBugClassSize,
46 "The maximum number of bug reports in the same equivalence class "
47 "where at least one report is valid (not suppressed)");
49 BugReporterVisitor::~BugReporterVisitor() {}
51 void BugReporterContext::anchor() {}
53 //===----------------------------------------------------------------------===//
54 // Helper routines for walking the ExplodedGraph and fetching statements.
55 //===----------------------------------------------------------------------===//
57 static const Stmt *GetPreviousStmt(const ExplodedNode *N) {
58 for (N = N->getFirstPred(); N; N = N->getFirstPred())
59 if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
65 static inline const Stmt*
66 GetCurrentOrPreviousStmt(const ExplodedNode *N) {
67 if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
70 return GetPreviousStmt(N);
73 //===----------------------------------------------------------------------===//
74 // Diagnostic cleanup.
75 //===----------------------------------------------------------------------===//
77 static PathDiagnosticEventPiece *
78 eventsDescribeSameCondition(PathDiagnosticEventPiece *X,
79 PathDiagnosticEventPiece *Y) {
80 // Prefer diagnostics that come from ConditionBRVisitor over
81 // those that came from TrackConstraintBRVisitor.
82 const void *tagPreferred = ConditionBRVisitor::getTag();
83 const void *tagLesser = TrackConstraintBRVisitor::getTag();
85 if (X->getLocation() != Y->getLocation())
88 if (X->getTag() == tagPreferred && Y->getTag() == tagLesser)
91 if (Y->getTag() == tagPreferred && X->getTag() == tagLesser)
97 /// An optimization pass over PathPieces that removes redundant diagnostics
98 /// generated by both ConditionBRVisitor and TrackConstraintBRVisitor. Both
99 /// BugReporterVisitors use different methods to generate diagnostics, with
100 /// one capable of emitting diagnostics in some cases but not in others. This
101 /// can lead to redundant diagnostic pieces at the same point in a path.
102 static void removeRedundantMsgs(PathPieces &path) {
103 unsigned N = path.size();
106 // NOTE: this loop intentionally is not using an iterator. Instead, we
107 // are streaming the path and modifying it in place. This is done by
108 // grabbing the front, processing it, and if we decide to keep it append
109 // it to the end of the path. The entire path is processed in this way.
110 for (unsigned i = 0; i < N; ++i) {
111 IntrusiveRefCntPtr<PathDiagnosticPiece> piece(path.front());
114 switch (piece->getKind()) {
115 case clang::ento::PathDiagnosticPiece::Call:
116 removeRedundantMsgs(cast<PathDiagnosticCallPiece>(piece)->path);
118 case clang::ento::PathDiagnosticPiece::Macro:
119 removeRedundantMsgs(cast<PathDiagnosticMacroPiece>(piece)->subPieces);
121 case clang::ento::PathDiagnosticPiece::ControlFlow:
123 case clang::ento::PathDiagnosticPiece::Event: {
127 if (PathDiagnosticEventPiece *nextEvent =
128 dyn_cast<PathDiagnosticEventPiece>(path.front().get())) {
129 PathDiagnosticEventPiece *event =
130 cast<PathDiagnosticEventPiece>(piece);
131 // Check to see if we should keep one of the two pieces. If we
132 // come up with a preference, record which piece to keep, and consume
133 // another piece from the path.
134 if (PathDiagnosticEventPiece *pieceToKeep =
135 eventsDescribeSameCondition(event, nextEvent)) {
144 path.push_back(piece);
148 /// A map from PathDiagnosticPiece to the LocationContext of the inlined
149 /// function call it represents.
150 typedef llvm::DenseMap<const PathPieces *, const LocationContext *>
153 /// Recursively scan through a path and prune out calls and macros pieces
154 /// that aren't needed. Return true if afterwards the path contains
155 /// "interesting stuff" which means it shouldn't be pruned from the parent path.
156 static bool removeUnneededCalls(PathPieces &pieces, BugReport *R,
157 LocationContextMap &LCM) {
158 bool containsSomethingInteresting = false;
159 const unsigned N = pieces.size();
161 for (unsigned i = 0 ; i < N ; ++i) {
162 // Remove the front piece from the path. If it is still something we
163 // want to keep once we are done, we will push it back on the end.
164 IntrusiveRefCntPtr<PathDiagnosticPiece> piece(pieces.front());
167 switch (piece->getKind()) {
168 case PathDiagnosticPiece::Call: {
169 PathDiagnosticCallPiece *call = cast<PathDiagnosticCallPiece>(piece);
170 // Check if the location context is interesting.
171 assert(LCM.count(&call->path));
172 if (R->isInteresting(LCM[&call->path])) {
173 containsSomethingInteresting = true;
177 if (!removeUnneededCalls(call->path, R, LCM))
180 containsSomethingInteresting = true;
183 case PathDiagnosticPiece::Macro: {
184 PathDiagnosticMacroPiece *macro = cast<PathDiagnosticMacroPiece>(piece);
185 if (!removeUnneededCalls(macro->subPieces, R, LCM))
187 containsSomethingInteresting = true;
190 case PathDiagnosticPiece::Event: {
191 PathDiagnosticEventPiece *event = cast<PathDiagnosticEventPiece>(piece);
193 // We never throw away an event, but we do throw it away wholesale
194 // as part of a path if we throw the entire path away.
195 containsSomethingInteresting |= !event->isPrunable();
198 case PathDiagnosticPiece::ControlFlow:
202 pieces.push_back(piece);
205 return containsSomethingInteresting;
208 /// Returns true if the given decl has been implicitly given a body, either by
209 /// the analyzer or by the compiler proper.
210 static bool hasImplicitBody(const Decl *D) {
212 return D->isImplicit() || !D->hasBody();
215 /// Recursively scan through a path and make sure that all call pieces have
218 adjustCallLocations(PathPieces &Pieces,
219 PathDiagnosticLocation *LastCallLocation = nullptr) {
220 for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E; ++I) {
221 PathDiagnosticCallPiece *Call = dyn_cast<PathDiagnosticCallPiece>(*I);
224 assert((*I)->getLocation().asLocation().isValid());
228 if (LastCallLocation) {
229 bool CallerIsImplicit = hasImplicitBody(Call->getCaller());
230 if (CallerIsImplicit || !Call->callEnter.asLocation().isValid())
231 Call->callEnter = *LastCallLocation;
232 if (CallerIsImplicit || !Call->callReturn.asLocation().isValid())
233 Call->callReturn = *LastCallLocation;
236 // Recursively clean out the subclass. Keep this call around if
237 // it contains any informative diagnostics.
238 PathDiagnosticLocation *ThisCallLocation;
239 if (Call->callEnterWithin.asLocation().isValid() &&
240 !hasImplicitBody(Call->getCallee()))
241 ThisCallLocation = &Call->callEnterWithin;
243 ThisCallLocation = &Call->callEnter;
245 assert(ThisCallLocation && "Outermost call has an invalid location");
246 adjustCallLocations(Call->path, ThisCallLocation);
250 /// Remove edges in and out of C++ default initializer expressions. These are
251 /// for fields that have in-class initializers, as opposed to being initialized
252 /// explicitly in a constructor or braced list.
253 static void removeEdgesToDefaultInitializers(PathPieces &Pieces) {
254 for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
255 if (PathDiagnosticCallPiece *C = dyn_cast<PathDiagnosticCallPiece>(*I))
256 removeEdgesToDefaultInitializers(C->path);
258 if (PathDiagnosticMacroPiece *M = dyn_cast<PathDiagnosticMacroPiece>(*I))
259 removeEdgesToDefaultInitializers(M->subPieces);
261 if (PathDiagnosticControlFlowPiece *CF =
262 dyn_cast<PathDiagnosticControlFlowPiece>(*I)) {
263 const Stmt *Start = CF->getStartLocation().asStmt();
264 const Stmt *End = CF->getEndLocation().asStmt();
265 if (Start && isa<CXXDefaultInitExpr>(Start)) {
268 } else if (End && isa<CXXDefaultInitExpr>(End)) {
269 PathPieces::iterator Next = std::next(I);
271 if (PathDiagnosticControlFlowPiece *NextCF =
272 dyn_cast<PathDiagnosticControlFlowPiece>(*Next)) {
273 NextCF->setStartLocation(CF->getStartLocation());
285 /// Remove all pieces with invalid locations as these cannot be serialized.
286 /// We might have pieces with invalid locations as a result of inlining Body
287 /// Farm generated functions.
288 static void removePiecesWithInvalidLocations(PathPieces &Pieces) {
289 for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
290 if (PathDiagnosticCallPiece *C = dyn_cast<PathDiagnosticCallPiece>(*I))
291 removePiecesWithInvalidLocations(C->path);
293 if (PathDiagnosticMacroPiece *M = dyn_cast<PathDiagnosticMacroPiece>(*I))
294 removePiecesWithInvalidLocations(M->subPieces);
296 if (!(*I)->getLocation().isValid() ||
297 !(*I)->getLocation().asLocation().isValid()) {
305 //===----------------------------------------------------------------------===//
306 // PathDiagnosticBuilder and its associated routines and helper objects.
307 //===----------------------------------------------------------------------===//
310 class NodeMapClosure : public BugReport::NodeResolver {
311 InterExplodedGraphMap &M;
313 NodeMapClosure(InterExplodedGraphMap &m) : M(m) {}
315 const ExplodedNode *getOriginalNode(const ExplodedNode *N) override {
320 class PathDiagnosticBuilder : public BugReporterContext {
322 PathDiagnosticConsumer *PDC;
325 const LocationContext *LC;
327 PathDiagnosticBuilder(GRBugReporter &br,
328 BugReport *r, InterExplodedGraphMap &Backmap,
329 PathDiagnosticConsumer *pdc)
330 : BugReporterContext(br),
331 R(r), PDC(pdc), NMC(Backmap), LC(r->getErrorNode()->getLocationContext())
334 PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N);
336 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os,
337 const ExplodedNode *N);
339 BugReport *getBugReport() { return R; }
341 Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); }
343 ParentMap& getParentMap() { return LC->getParentMap(); }
345 const Stmt *getParent(const Stmt *S) {
346 return getParentMap().getParent(S);
349 NodeMapClosure& getNodeResolver() override { return NMC; }
351 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
353 PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const {
354 return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Extensive;
357 bool supportsLogicalOpControlFlow() const {
358 return PDC ? PDC->supportsLogicalOpControlFlow() : true;
361 } // end anonymous namespace
363 PathDiagnosticLocation
364 PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) {
365 if (const Stmt *S = PathDiagnosticLocation::getNextStmt(N))
366 return PathDiagnosticLocation(S, getSourceManager(), LC);
368 return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(),
372 PathDiagnosticLocation
373 PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os,
374 const ExplodedNode *N) {
376 // Slow, but probably doesn't matter.
377 if (os.str().empty())
380 const PathDiagnosticLocation &Loc = ExecutionContinues(N);
383 os << "Execution continues on line "
384 << getSourceManager().getExpansionLineNumber(Loc.asLocation())
387 os << "Execution jumps to the end of the ";
388 const Decl *D = N->getLocationContext()->getDecl();
389 if (isa<ObjCMethodDecl>(D))
391 else if (isa<FunctionDecl>(D))
394 assert(isa<BlockDecl>(D));
395 os << "anonymous block";
403 static const Stmt *getEnclosingParent(const Stmt *S, const ParentMap &PM) {
404 if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
405 return PM.getParentIgnoreParens(S);
407 const Stmt *Parent = PM.getParentIgnoreParens(S);
411 switch (Parent->getStmtClass()) {
412 case Stmt::ForStmtClass:
413 case Stmt::DoStmtClass:
414 case Stmt::WhileStmtClass:
415 case Stmt::ObjCForCollectionStmtClass:
416 case Stmt::CXXForRangeStmtClass:
425 static PathDiagnosticLocation
426 getEnclosingStmtLocation(const Stmt *S, SourceManager &SMgr, const ParentMap &P,
427 const LocationContext *LC, bool allowNestedContexts) {
429 return PathDiagnosticLocation();
431 while (const Stmt *Parent = getEnclosingParent(S, P)) {
432 switch (Parent->getStmtClass()) {
433 case Stmt::BinaryOperatorClass: {
434 const BinaryOperator *B = cast<BinaryOperator>(Parent);
435 if (B->isLogicalOp())
436 return PathDiagnosticLocation(allowNestedContexts ? B : S, SMgr, LC);
439 case Stmt::CompoundStmtClass:
440 case Stmt::StmtExprClass:
441 return PathDiagnosticLocation(S, SMgr, LC);
442 case Stmt::ChooseExprClass:
443 // Similar to '?' if we are referring to condition, just have the edge
444 // point to the entire choose expression.
445 if (allowNestedContexts || cast<ChooseExpr>(Parent)->getCond() == S)
446 return PathDiagnosticLocation(Parent, SMgr, LC);
448 return PathDiagnosticLocation(S, SMgr, LC);
449 case Stmt::BinaryConditionalOperatorClass:
450 case Stmt::ConditionalOperatorClass:
451 // For '?', if we are referring to condition, just have the edge point
452 // to the entire '?' expression.
453 if (allowNestedContexts ||
454 cast<AbstractConditionalOperator>(Parent)->getCond() == S)
455 return PathDiagnosticLocation(Parent, SMgr, LC);
457 return PathDiagnosticLocation(S, SMgr, LC);
458 case Stmt::CXXForRangeStmtClass:
459 if (cast<CXXForRangeStmt>(Parent)->getBody() == S)
460 return PathDiagnosticLocation(S, SMgr, LC);
462 case Stmt::DoStmtClass:
463 return PathDiagnosticLocation(S, SMgr, LC);
464 case Stmt::ForStmtClass:
465 if (cast<ForStmt>(Parent)->getBody() == S)
466 return PathDiagnosticLocation(S, SMgr, LC);
468 case Stmt::IfStmtClass:
469 if (cast<IfStmt>(Parent)->getCond() != S)
470 return PathDiagnosticLocation(S, SMgr, LC);
472 case Stmt::ObjCForCollectionStmtClass:
473 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
474 return PathDiagnosticLocation(S, SMgr, LC);
476 case Stmt::WhileStmtClass:
477 if (cast<WhileStmt>(Parent)->getCond() != S)
478 return PathDiagnosticLocation(S, SMgr, LC);
487 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
489 return PathDiagnosticLocation(S, SMgr, LC);
492 PathDiagnosticLocation
493 PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
494 assert(S && "Null Stmt passed to getEnclosingStmtLocation");
495 return ::getEnclosingStmtLocation(S, getSourceManager(), getParentMap(), LC,
496 /*allowNestedContexts=*/false);
499 //===----------------------------------------------------------------------===//
500 // "Visitors only" path diagnostic generation algorithm.
501 //===----------------------------------------------------------------------===//
502 static bool GenerateVisitorsOnlyPathDiagnostic(
503 PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
504 ArrayRef<std::unique_ptr<BugReporterVisitor>> visitors) {
505 // All path generation skips the very first node (the error node).
506 // This is because there is special handling for the end-of-path note.
507 N = N->getFirstPred();
511 BugReport *R = PDB.getBugReport();
512 while (const ExplodedNode *Pred = N->getFirstPred()) {
513 for (auto &V : visitors) {
514 // Visit all the node pairs, but throw the path pieces away.
515 PathDiagnosticPiece *Piece = V->VisitNode(N, Pred, PDB, *R);
525 //===----------------------------------------------------------------------===//
526 // "Minimal" path diagnostic generation algorithm.
527 //===----------------------------------------------------------------------===//
528 typedef std::pair<PathDiagnosticCallPiece*, const ExplodedNode*> StackDiagPair;
529 typedef SmallVector<StackDiagPair, 6> StackDiagVector;
531 static void updateStackPiecesWithMessage(PathDiagnosticPiece *P,
532 StackDiagVector &CallStack) {
533 // If the piece contains a special message, add it to all the call
534 // pieces on the active stack.
535 if (PathDiagnosticEventPiece *ep =
536 dyn_cast<PathDiagnosticEventPiece>(P)) {
538 if (ep->hasCallStackHint())
539 for (StackDiagVector::iterator I = CallStack.begin(),
540 E = CallStack.end(); I != E; ++I) {
541 PathDiagnosticCallPiece *CP = I->first;
542 const ExplodedNode *N = I->second;
543 std::string stackMsg = ep->getCallStackMessage(N);
545 // The last message on the path to final bug is the most important
546 // one. Since we traverse the path backwards, do not add the message
547 // if one has been previously added.
548 if (!CP->hasCallStackMessage())
549 CP->setCallStackMessage(stackMsg);
554 static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM);
556 static bool GenerateMinimalPathDiagnostic(
557 PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
558 LocationContextMap &LCM,
559 ArrayRef<std::unique_ptr<BugReporterVisitor>> visitors) {
561 SourceManager& SMgr = PDB.getSourceManager();
562 const LocationContext *LC = PDB.LC;
563 const ExplodedNode *NextNode = N->pred_empty()
564 ? nullptr : *(N->pred_begin());
566 StackDiagVector CallStack;
570 PDB.LC = N->getLocationContext();
571 NextNode = N->getFirstPred();
573 ProgramPoint P = N->getLocation();
576 if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
577 PathDiagnosticCallPiece *C =
578 PathDiagnosticCallPiece::construct(N, *CE, SMgr);
579 // Record the mapping from call piece to LocationContext.
580 LCM[&C->path] = CE->getCalleeContext();
581 PD.getActivePath().push_front(C);
582 PD.pushActivePath(&C->path);
583 CallStack.push_back(StackDiagPair(C, N));
587 if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
588 // Flush all locations, and pop the active path.
589 bool VisitedEntireCall = PD.isWithinCall();
592 // Either we just added a bunch of stuff to the top-level path, or
593 // we have a previous CallExitEnd. If the former, it means that the
594 // path terminated within a function call. We must then take the
595 // current contents of the active path and place it within
596 // a new PathDiagnosticCallPiece.
597 PathDiagnosticCallPiece *C;
598 if (VisitedEntireCall) {
599 C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
601 const Decl *Caller = CE->getLocationContext()->getDecl();
602 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
603 // Record the mapping from call piece to LocationContext.
604 LCM[&C->path] = CE->getCalleeContext();
607 C->setCallee(*CE, SMgr);
608 if (!CallStack.empty()) {
609 assert(CallStack.back().first == C);
610 CallStack.pop_back();
615 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
616 const CFGBlock *Src = BE->getSrc();
617 const CFGBlock *Dst = BE->getDst();
618 const Stmt *T = Src->getTerminator();
623 PathDiagnosticLocation Start =
624 PathDiagnosticLocation::createBegin(T, SMgr,
625 N->getLocationContext());
627 switch (T->getStmtClass()) {
631 case Stmt::GotoStmtClass:
632 case Stmt::IndirectGotoStmtClass: {
633 const Stmt *S = PathDiagnosticLocation::getNextStmt(N);
639 llvm::raw_string_ostream os(sbuf);
640 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
642 os << "Control jumps to line "
643 << End.asLocation().getExpansionLineNumber();
644 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
645 Start, End, os.str()));
649 case Stmt::SwitchStmtClass: {
650 // Figure out what case arm we took.
652 llvm::raw_string_ostream os(sbuf);
654 if (const Stmt *S = Dst->getLabel()) {
655 PathDiagnosticLocation End(S, SMgr, LC);
657 switch (S->getStmtClass()) {
659 os << "No cases match in the switch statement. "
660 "Control jumps to line "
661 << End.asLocation().getExpansionLineNumber();
663 case Stmt::DefaultStmtClass:
664 os << "Control jumps to the 'default' case at line "
665 << End.asLocation().getExpansionLineNumber();
668 case Stmt::CaseStmtClass: {
669 os << "Control jumps to 'case ";
670 const CaseStmt *Case = cast<CaseStmt>(S);
671 const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
673 // Determine if it is an enum.
674 bool GetRawInt = true;
676 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
677 // FIXME: Maybe this should be an assertion. Are there cases
678 // were it is not an EnumConstantDecl?
679 const EnumConstantDecl *D =
680 dyn_cast<EnumConstantDecl>(DR->getDecl());
689 os << LHS->EvaluateKnownConstInt(PDB.getASTContext());
692 << End.asLocation().getExpansionLineNumber();
696 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
697 Start, End, os.str()));
700 os << "'Default' branch taken. ";
701 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
702 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
703 Start, End, os.str()));
709 case Stmt::BreakStmtClass:
710 case Stmt::ContinueStmtClass: {
712 llvm::raw_string_ostream os(sbuf);
713 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
714 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
715 Start, End, os.str()));
719 // Determine control-flow for ternary '?'.
720 case Stmt::BinaryConditionalOperatorClass:
721 case Stmt::ConditionalOperatorClass: {
723 llvm::raw_string_ostream os(sbuf);
724 os << "'?' condition is ";
726 if (*(Src->succ_begin()+1) == Dst)
731 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
733 if (const Stmt *S = End.asStmt())
734 End = PDB.getEnclosingStmtLocation(S);
736 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
737 Start, End, os.str()));
741 // Determine control-flow for short-circuited '&&' and '||'.
742 case Stmt::BinaryOperatorClass: {
743 if (!PDB.supportsLogicalOpControlFlow())
746 const BinaryOperator *B = cast<BinaryOperator>(T);
748 llvm::raw_string_ostream os(sbuf);
749 os << "Left side of '";
751 if (B->getOpcode() == BO_LAnd) {
752 os << "&&" << "' is ";
754 if (*(Src->succ_begin()+1) == Dst) {
756 PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
757 PathDiagnosticLocation Start =
758 PathDiagnosticLocation::createOperatorLoc(B, SMgr);
759 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
760 Start, End, os.str()));
764 PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
765 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
766 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
767 Start, End, os.str()));
771 assert(B->getOpcode() == BO_LOr);
772 os << "||" << "' is ";
774 if (*(Src->succ_begin()+1) == Dst) {
776 PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
777 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
778 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
779 Start, End, os.str()));
783 PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
784 PathDiagnosticLocation Start =
785 PathDiagnosticLocation::createOperatorLoc(B, SMgr);
786 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
787 Start, End, os.str()));
794 case Stmt::DoStmtClass: {
795 if (*(Src->succ_begin()) == Dst) {
797 llvm::raw_string_ostream os(sbuf);
799 os << "Loop condition is true. ";
800 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
802 if (const Stmt *S = End.asStmt())
803 End = PDB.getEnclosingStmtLocation(S);
805 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
806 Start, End, os.str()));
809 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
811 if (const Stmt *S = End.asStmt())
812 End = PDB.getEnclosingStmtLocation(S);
814 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
815 Start, End, "Loop condition is false. Exiting loop"));
821 case Stmt::WhileStmtClass:
822 case Stmt::ForStmtClass: {
823 if (*(Src->succ_begin()+1) == Dst) {
825 llvm::raw_string_ostream os(sbuf);
827 os << "Loop condition is false. ";
828 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
829 if (const Stmt *S = End.asStmt())
830 End = PDB.getEnclosingStmtLocation(S);
832 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
833 Start, End, os.str()));
836 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
837 if (const Stmt *S = End.asStmt())
838 End = PDB.getEnclosingStmtLocation(S);
840 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
841 Start, End, "Loop condition is true. Entering loop body"));
847 case Stmt::IfStmtClass: {
848 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
850 if (const Stmt *S = End.asStmt())
851 End = PDB.getEnclosingStmtLocation(S);
853 if (*(Src->succ_begin()+1) == Dst)
854 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
855 Start, End, "Taking false branch"));
857 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
858 Start, End, "Taking true branch"));
867 // Add diagnostic pieces from custom visitors.
868 BugReport *R = PDB.getBugReport();
869 for (auto &V : visitors) {
870 if (PathDiagnosticPiece *p = V->VisitNode(N, NextNode, PDB, *R)) {
871 PD.getActivePath().push_front(p);
872 updateStackPiecesWithMessage(p, CallStack);
878 if (!PDB.getBugReport()->isValid())
881 // After constructing the full PathDiagnostic, do a pass over it to compact
882 // PathDiagnosticPieces that occur within a macro.
883 CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager());
887 //===----------------------------------------------------------------------===//
888 // "Extensive" PathDiagnostic generation.
889 //===----------------------------------------------------------------------===//
891 static bool IsControlFlowExpr(const Stmt *S) {
892 const Expr *E = dyn_cast<Expr>(S);
897 E = E->IgnoreParenCasts();
899 if (isa<AbstractConditionalOperator>(E))
902 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
903 if (B->isLogicalOp())
910 class ContextLocation : public PathDiagnosticLocation {
913 ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
914 : PathDiagnosticLocation(L), IsDead(isdead) {}
916 void markDead() { IsDead = true; }
917 bool isDead() const { return IsDead; }
920 static PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
921 const LocationContext *LC,
922 bool firstCharOnly = false) {
923 if (const Stmt *S = L.asStmt()) {
924 const Stmt *Original = S;
926 // Adjust the location for some expressions that are best referenced
927 // by one of their subexpressions.
928 switch (S->getStmtClass()) {
931 case Stmt::ParenExprClass:
932 case Stmt::GenericSelectionExprClass:
933 S = cast<Expr>(S)->IgnoreParens();
934 firstCharOnly = true;
936 case Stmt::BinaryConditionalOperatorClass:
937 case Stmt::ConditionalOperatorClass:
938 S = cast<AbstractConditionalOperator>(S)->getCond();
939 firstCharOnly = true;
941 case Stmt::ChooseExprClass:
942 S = cast<ChooseExpr>(S)->getCond();
943 firstCharOnly = true;
945 case Stmt::BinaryOperatorClass:
946 S = cast<BinaryOperator>(S)->getLHS();
947 firstCharOnly = true;
955 L = PathDiagnosticLocation(S, L.getManager(), LC);
959 L = PathDiagnosticLocation::createSingleLocation(L);
965 std::vector<ContextLocation> CLocs;
966 typedef std::vector<ContextLocation>::iterator iterator;
968 PathDiagnosticBuilder &PDB;
969 PathDiagnosticLocation PrevLoc;
971 bool IsConsumedExpr(const PathDiagnosticLocation &L);
973 bool containsLocation(const PathDiagnosticLocation &Container,
974 const PathDiagnosticLocation &Containee);
976 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
981 if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
982 // For contexts, we only one the first character as the range.
983 rawAddEdge(cleanUpLocation(CLocs.back(), PDB.LC, true));
989 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
992 // If the PathDiagnostic already has pieces, add the enclosing statement
993 // of the first piece as a context as well.
994 if (!PD.path.empty()) {
995 PrevLoc = (*PD.path.begin())->getLocation();
997 if (const Stmt *S = PrevLoc.asStmt())
998 addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1003 while (!CLocs.empty()) popLocation();
1005 // Finally, add an initial edge from the start location of the first
1006 // statement (if it doesn't already exist).
1007 PathDiagnosticLocation L = PathDiagnosticLocation::createDeclBegin(
1009 PDB.getSourceManager());
1014 void flushLocations() {
1015 while (!CLocs.empty())
1017 PrevLoc = PathDiagnosticLocation();
1020 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false,
1021 bool IsPostJump = false);
1023 void rawAddEdge(PathDiagnosticLocation NewLoc);
1025 void addContext(const Stmt *S);
1026 void addContext(const PathDiagnosticLocation &L);
1027 void addExtendedContext(const Stmt *S);
1029 } // end anonymous namespace
1032 PathDiagnosticLocation
1033 EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
1034 if (const Stmt *S = L.asStmt()) {
1035 if (IsControlFlowExpr(S))
1038 return PDB.getEnclosingStmtLocation(S);
1044 bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
1045 const PathDiagnosticLocation &Containee) {
1047 if (Container == Containee)
1050 if (Container.asDecl())
1053 if (const Stmt *S = Containee.asStmt())
1054 if (const Stmt *ContainerS = Container.asStmt()) {
1056 if (S == ContainerS)
1058 S = PDB.getParent(S);
1063 // Less accurate: compare using source ranges.
1064 SourceRange ContainerR = Container.asRange();
1065 SourceRange ContaineeR = Containee.asRange();
1067 SourceManager &SM = PDB.getSourceManager();
1068 SourceLocation ContainerRBeg = SM.getExpansionLoc(ContainerR.getBegin());
1069 SourceLocation ContainerREnd = SM.getExpansionLoc(ContainerR.getEnd());
1070 SourceLocation ContaineeRBeg = SM.getExpansionLoc(ContaineeR.getBegin());
1071 SourceLocation ContaineeREnd = SM.getExpansionLoc(ContaineeR.getEnd());
1073 unsigned ContainerBegLine = SM.getExpansionLineNumber(ContainerRBeg);
1074 unsigned ContainerEndLine = SM.getExpansionLineNumber(ContainerREnd);
1075 unsigned ContaineeBegLine = SM.getExpansionLineNumber(ContaineeRBeg);
1076 unsigned ContaineeEndLine = SM.getExpansionLineNumber(ContaineeREnd);
1078 assert(ContainerBegLine <= ContainerEndLine);
1079 assert(ContaineeBegLine <= ContaineeEndLine);
1081 return (ContainerBegLine <= ContaineeBegLine &&
1082 ContainerEndLine >= ContaineeEndLine &&
1083 (ContainerBegLine != ContaineeBegLine ||
1084 SM.getExpansionColumnNumber(ContainerRBeg) <=
1085 SM.getExpansionColumnNumber(ContaineeRBeg)) &&
1086 (ContainerEndLine != ContaineeEndLine ||
1087 SM.getExpansionColumnNumber(ContainerREnd) >=
1088 SM.getExpansionColumnNumber(ContaineeREnd)));
1091 void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
1092 if (!PrevLoc.isValid()) {
1097 const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc, PDB.LC);
1098 const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc, PDB.LC);
1100 if (PrevLocClean.asLocation().isInvalid()) {
1105 if (NewLocClean.asLocation() == PrevLocClean.asLocation())
1108 // FIXME: Ignore intra-macro edges for now.
1109 if (NewLocClean.asLocation().getExpansionLoc() ==
1110 PrevLocClean.asLocation().getExpansionLoc())
1113 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
1117 void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd,
1120 if (!alwaysAdd && NewLoc.asLocation().isMacroID())
1123 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
1125 while (!CLocs.empty()) {
1126 ContextLocation &TopContextLoc = CLocs.back();
1128 // Is the top location context the same as the one for the new location?
1129 if (TopContextLoc == CLoc) {
1131 if (IsConsumedExpr(TopContextLoc))
1132 TopContextLoc.markDead();
1138 TopContextLoc.markDead();
1142 if (containsLocation(TopContextLoc, CLoc)) {
1146 if (IsConsumedExpr(CLoc)) {
1147 CLocs.push_back(ContextLocation(CLoc, /*IsDead=*/true));
1152 CLocs.push_back(ContextLocation(CLoc, /*IsDead=*/IsPostJump));
1156 // Context does not contain the location. Flush it.
1160 // If we reach here, there is no enclosing context. Just add the edge.
1164 bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
1165 if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
1166 return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
1171 void EdgeBuilder::addExtendedContext(const Stmt *S) {
1175 const Stmt *Parent = PDB.getParent(S);
1177 if (isa<CompoundStmt>(Parent))
1178 Parent = PDB.getParent(Parent);
1184 switch (Parent->getStmtClass()) {
1185 case Stmt::DoStmtClass:
1186 case Stmt::ObjCAtSynchronizedStmtClass:
1196 void EdgeBuilder::addContext(const Stmt *S) {
1200 PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.LC);
1204 void EdgeBuilder::addContext(const PathDiagnosticLocation &L) {
1205 while (!CLocs.empty()) {
1206 const PathDiagnosticLocation &TopContextLoc = CLocs.back();
1208 // Is the top location context the same as the one for the new location?
1209 if (TopContextLoc == L)
1212 if (containsLocation(TopContextLoc, L)) {
1217 // Context does not contain the location. Flush it.
1224 // Cone-of-influence: support the reverse propagation of "interesting" symbols
1225 // and values by tracing interesting calculations backwards through evaluated
1226 // expressions along a path. This is probably overly complicated, but the idea
1227 // is that if an expression computed an "interesting" value, the child
1228 // expressions are are also likely to be "interesting" as well (which then
1229 // propagates to the values they in turn compute). This reverse propagation
1230 // is needed to track interesting correlations across function call boundaries,
1231 // where formal arguments bind to actual arguments, etc. This is also needed
1232 // because the constraint solver sometimes simplifies certain symbolic values
1233 // into constants when appropriate, and this complicates reasoning about
1234 // interesting values.
1235 typedef llvm::DenseSet<const Expr *> InterestingExprs;
1237 static void reversePropagateIntererstingSymbols(BugReport &R,
1238 InterestingExprs &IE,
1239 const ProgramState *State,
1241 const LocationContext *LCtx) {
1242 SVal V = State->getSVal(Ex, LCtx);
1243 if (!(R.isInteresting(V) || IE.count(Ex)))
1246 switch (Ex->getStmtClass()) {
1248 if (!isa<CastExpr>(Ex))
1251 case Stmt::BinaryOperatorClass:
1252 case Stmt::UnaryOperatorClass: {
1253 for (Stmt::const_child_iterator CI = Ex->child_begin(),
1254 CE = Ex->child_end();
1256 if (const Expr *child = dyn_cast_or_null<Expr>(*CI)) {
1258 SVal ChildV = State->getSVal(child, LCtx);
1259 R.markInteresting(ChildV);
1266 R.markInteresting(V);
1269 static void reversePropagateInterestingSymbols(BugReport &R,
1270 InterestingExprs &IE,
1271 const ProgramState *State,
1272 const LocationContext *CalleeCtx,
1273 const LocationContext *CallerCtx)
1275 // FIXME: Handle non-CallExpr-based CallEvents.
1276 const StackFrameContext *Callee = CalleeCtx->getCurrentStackFrame();
1277 const Stmt *CallSite = Callee->getCallSite();
1278 if (const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite)) {
1279 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeCtx->getDecl())) {
1280 FunctionDecl::param_const_iterator PI = FD->param_begin(),
1281 PE = FD->param_end();
1282 CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end();
1283 for (; AI != AE && PI != PE; ++AI, ++PI) {
1284 if (const Expr *ArgE = *AI) {
1285 if (const ParmVarDecl *PD = *PI) {
1286 Loc LV = State->getLValue(PD, CalleeCtx);
1287 if (R.isInteresting(LV) || R.isInteresting(State->getRawSVal(LV)))
1296 //===----------------------------------------------------------------------===//
1297 // Functions for determining if a loop was executed 0 times.
1298 //===----------------------------------------------------------------------===//
1300 static bool isLoop(const Stmt *Term) {
1301 switch (Term->getStmtClass()) {
1302 case Stmt::ForStmtClass:
1303 case Stmt::WhileStmtClass:
1304 case Stmt::ObjCForCollectionStmtClass:
1305 case Stmt::CXXForRangeStmtClass:
1308 // Note that we intentionally do not include do..while here.
1313 static bool isJumpToFalseBranch(const BlockEdge *BE) {
1314 const CFGBlock *Src = BE->getSrc();
1315 assert(Src->succ_size() == 2);
1316 return (*(Src->succ_begin()+1) == BE->getDst());
1319 /// Return true if the terminator is a loop and the destination is the
1321 static bool isLoopJumpPastBody(const Stmt *Term, const BlockEdge *BE) {
1325 // Did we take the false branch?
1326 return isJumpToFalseBranch(BE);
1329 static bool isContainedByStmt(ParentMap &PM, const Stmt *S, const Stmt *SubS) {
1333 SubS = PM.getParent(SubS);
1338 static const Stmt *getStmtBeforeCond(ParentMap &PM, const Stmt *Term,
1339 const ExplodedNode *N) {
1341 Optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>();
1343 const Stmt *S = SP->getStmt();
1344 if (!isContainedByStmt(PM, Term, S))
1347 N = N->getFirstPred();
1352 static bool isInLoopBody(ParentMap &PM, const Stmt *S, const Stmt *Term) {
1353 const Stmt *LoopBody = nullptr;
1354 switch (Term->getStmtClass()) {
1355 case Stmt::CXXForRangeStmtClass: {
1356 const CXXForRangeStmt *FR = cast<CXXForRangeStmt>(Term);
1357 if (isContainedByStmt(PM, FR->getInc(), S))
1359 if (isContainedByStmt(PM, FR->getLoopVarStmt(), S))
1361 LoopBody = FR->getBody();
1364 case Stmt::ForStmtClass: {
1365 const ForStmt *FS = cast<ForStmt>(Term);
1366 if (isContainedByStmt(PM, FS->getInc(), S))
1368 LoopBody = FS->getBody();
1371 case Stmt::ObjCForCollectionStmtClass: {
1372 const ObjCForCollectionStmt *FC = cast<ObjCForCollectionStmt>(Term);
1373 LoopBody = FC->getBody();
1376 case Stmt::WhileStmtClass:
1377 LoopBody = cast<WhileStmt>(Term)->getBody();
1382 return isContainedByStmt(PM, LoopBody, S);
1385 //===----------------------------------------------------------------------===//
1386 // Top-level logic for generating extensive path diagnostics.
1387 //===----------------------------------------------------------------------===//
1389 static bool GenerateExtensivePathDiagnostic(
1390 PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
1391 LocationContextMap &LCM,
1392 ArrayRef<std::unique_ptr<BugReporterVisitor>> visitors) {
1393 EdgeBuilder EB(PD, PDB);
1394 const SourceManager& SM = PDB.getSourceManager();
1395 StackDiagVector CallStack;
1396 InterestingExprs IE;
1398 const ExplodedNode *NextNode = N->pred_empty() ? nullptr : *(N->pred_begin());
1401 NextNode = N->getFirstPred();
1402 ProgramPoint P = N->getLocation();
1405 if (Optional<PostStmt> PS = P.getAs<PostStmt>()) {
1406 if (const Expr *Ex = PS->getStmtAs<Expr>())
1407 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1408 N->getState().get(), Ex,
1409 N->getLocationContext());
1412 if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
1413 const Stmt *S = CE->getCalleeContext()->getCallSite();
1414 if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) {
1415 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1416 N->getState().get(), Ex,
1417 N->getLocationContext());
1420 PathDiagnosticCallPiece *C =
1421 PathDiagnosticCallPiece::construct(N, *CE, SM);
1422 LCM[&C->path] = CE->getCalleeContext();
1424 EB.addEdge(C->callReturn, /*AlwaysAdd=*/true, /*IsPostJump=*/true);
1425 EB.flushLocations();
1427 PD.getActivePath().push_front(C);
1428 PD.pushActivePath(&C->path);
1429 CallStack.push_back(StackDiagPair(C, N));
1433 // Pop the call hierarchy if we are done walking the contents
1434 // of a function call.
1435 if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
1436 // Add an edge to the start of the function.
1437 const Decl *D = CE->getCalleeContext()->getDecl();
1438 PathDiagnosticLocation pos =
1439 PathDiagnosticLocation::createBegin(D, SM);
1442 // Flush all locations, and pop the active path.
1443 bool VisitedEntireCall = PD.isWithinCall();
1444 EB.flushLocations();
1446 PDB.LC = N->getLocationContext();
1448 // Either we just added a bunch of stuff to the top-level path, or
1449 // we have a previous CallExitEnd. If the former, it means that the
1450 // path terminated within a function call. We must then take the
1451 // current contents of the active path and place it within
1452 // a new PathDiagnosticCallPiece.
1453 PathDiagnosticCallPiece *C;
1454 if (VisitedEntireCall) {
1455 C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
1457 const Decl *Caller = CE->getLocationContext()->getDecl();
1458 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
1459 LCM[&C->path] = CE->getCalleeContext();
1462 C->setCallee(*CE, SM);
1463 EB.addContext(C->getLocation());
1465 if (!CallStack.empty()) {
1466 assert(CallStack.back().first == C);
1467 CallStack.pop_back();
1472 // Note that is important that we update the LocationContext
1473 // after looking at CallExits. CallExit basically adds an
1474 // edge in the *caller*, so we don't want to update the LocationContext
1476 PDB.LC = N->getLocationContext();
1479 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
1480 // Does this represent entering a call? If so, look at propagating
1481 // interesting symbols across call boundaries.
1483 const LocationContext *CallerCtx = NextNode->getLocationContext();
1484 const LocationContext *CalleeCtx = PDB.LC;
1485 if (CallerCtx != CalleeCtx) {
1486 reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
1487 N->getState().get(),
1488 CalleeCtx, CallerCtx);
1492 // Are we jumping to the head of a loop? Add a special diagnostic.
1493 if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
1494 PathDiagnosticLocation L(Loop, SM, PDB.LC);
1495 const CompoundStmt *CS = nullptr;
1497 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1498 CS = dyn_cast<CompoundStmt>(FS->getBody());
1499 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1500 CS = dyn_cast<CompoundStmt>(WS->getBody());
1502 PathDiagnosticEventPiece *p =
1503 new PathDiagnosticEventPiece(L,
1504 "Looping back to the head of the loop");
1505 p->setPrunable(true);
1507 EB.addEdge(p->getLocation(), true);
1508 PD.getActivePath().push_front(p);
1511 PathDiagnosticLocation BL =
1512 PathDiagnosticLocation::createEndBrace(CS, SM);
1517 const CFGBlock *BSrc = BE->getSrc();
1518 ParentMap &PM = PDB.getParentMap();
1520 if (const Stmt *Term = BSrc->getTerminator()) {
1521 // Are we jumping past the loop body without ever executing the
1522 // loop (because the condition was false)?
1523 if (isLoopJumpPastBody(Term, &*BE) &&
1525 getStmtBeforeCond(PM,
1526 BSrc->getTerminatorCondition(),
1529 PathDiagnosticLocation L(Term, SM, PDB.LC);
1530 PathDiagnosticEventPiece *PE =
1531 new PathDiagnosticEventPiece(L, "Loop body executed 0 times");
1532 PE->setPrunable(true);
1534 EB.addEdge(PE->getLocation(), true);
1535 PD.getActivePath().push_front(PE);
1538 // In any case, add the terminator as the current statement
1539 // context for control edges.
1540 EB.addContext(Term);
1546 if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) {
1547 Optional<CFGElement> First = BE->getFirstElement();
1548 if (Optional<CFGStmt> S = First ? First->getAs<CFGStmt>() : None) {
1549 const Stmt *stmt = S->getStmt();
1550 if (IsControlFlowExpr(stmt)) {
1551 // Add the proper context for '&&', '||', and '?'.
1552 EB.addContext(stmt);
1555 EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt());
1567 // Add pieces from custom visitors.
1568 BugReport *R = PDB.getBugReport();
1569 for (auto &V : visitors) {
1570 if (PathDiagnosticPiece *p = V->VisitNode(N, NextNode, PDB, *R)) {
1571 const PathDiagnosticLocation &Loc = p->getLocation();
1572 EB.addEdge(Loc, true);
1573 PD.getActivePath().push_front(p);
1574 updateStackPiecesWithMessage(p, CallStack);
1576 if (const Stmt *S = Loc.asStmt())
1577 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1582 return PDB.getBugReport()->isValid();
1585 /// \brief Adds a sanitized control-flow diagnostic edge to a path.
1586 static void addEdgeToPath(PathPieces &path,
1587 PathDiagnosticLocation &PrevLoc,
1588 PathDiagnosticLocation NewLoc,
1589 const LocationContext *LC) {
1590 if (!NewLoc.isValid())
1593 SourceLocation NewLocL = NewLoc.asLocation();
1594 if (NewLocL.isInvalid())
1597 if (!PrevLoc.isValid() || !PrevLoc.asLocation().isValid()) {
1602 // Ignore self-edges, which occur when there are multiple nodes at the same
1604 if (NewLoc.asStmt() && NewLoc.asStmt() == PrevLoc.asStmt())
1607 path.push_front(new PathDiagnosticControlFlowPiece(NewLoc,
1612 /// A customized wrapper for CFGBlock::getTerminatorCondition()
1613 /// which returns the element for ObjCForCollectionStmts.
1614 static const Stmt *getTerminatorCondition(const CFGBlock *B) {
1615 const Stmt *S = B->getTerminatorCondition();
1616 if (const ObjCForCollectionStmt *FS =
1617 dyn_cast_or_null<ObjCForCollectionStmt>(S))
1618 return FS->getElement();
1622 static const char StrEnteringLoop[] = "Entering loop body";
1623 static const char StrLoopBodyZero[] = "Loop body executed 0 times";
1624 static const char StrLoopRangeEmpty[] =
1625 "Loop body skipped when range is empty";
1626 static const char StrLoopCollectionEmpty[] =
1627 "Loop body skipped when collection is empty";
1629 static bool GenerateAlternateExtensivePathDiagnostic(
1630 PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
1631 LocationContextMap &LCM,
1632 ArrayRef<std::unique_ptr<BugReporterVisitor>> visitors) {
1634 BugReport *report = PDB.getBugReport();
1635 const SourceManager& SM = PDB.getSourceManager();
1636 StackDiagVector CallStack;
1637 InterestingExprs IE;
1639 PathDiagnosticLocation PrevLoc = PD.getLocation();
1641 const ExplodedNode *NextNode = N->getFirstPred();
1644 NextNode = N->getFirstPred();
1645 ProgramPoint P = N->getLocation();
1648 // Have we encountered an entrance to a call? It may be
1649 // the case that we have not encountered a matching
1650 // call exit before this point. This means that the path
1651 // terminated within the call itself.
1652 if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
1653 // Add an edge to the start of the function.
1654 const StackFrameContext *CalleeLC = CE->getCalleeContext();
1655 const Decl *D = CalleeLC->getDecl();
1656 addEdgeToPath(PD.getActivePath(), PrevLoc,
1657 PathDiagnosticLocation::createBegin(D, SM),
1660 // Did we visit an entire call?
1661 bool VisitedEntireCall = PD.isWithinCall();
1664 PathDiagnosticCallPiece *C;
1665 if (VisitedEntireCall) {
1666 PathDiagnosticPiece *P = PD.getActivePath().front().get();
1667 C = cast<PathDiagnosticCallPiece>(P);
1669 const Decl *Caller = CE->getLocationContext()->getDecl();
1670 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
1672 // Since we just transferred the path over to the call piece,
1673 // reset the mapping from active to location context.
1674 assert(PD.getActivePath().size() == 1 &&
1675 PD.getActivePath().front() == C);
1676 LCM[&PD.getActivePath()] = nullptr;
1678 // Record the location context mapping for the path within
1680 assert(LCM[&C->path] == nullptr ||
1681 LCM[&C->path] == CE->getCalleeContext());
1682 LCM[&C->path] = CE->getCalleeContext();
1684 // If this is the first item in the active path, record
1685 // the new mapping from active path to location context.
1686 const LocationContext *&NewLC = LCM[&PD.getActivePath()];
1688 NewLC = N->getLocationContext();
1692 C->setCallee(*CE, SM);
1694 // Update the previous location in the active path.
1695 PrevLoc = C->getLocation();
1697 if (!CallStack.empty()) {
1698 assert(CallStack.back().first == C);
1699 CallStack.pop_back();
1704 // Query the location context here and the previous location
1705 // as processing CallEnter may change the active path.
1706 PDB.LC = N->getLocationContext();
1708 // Record the mapping from the active path to the location
1710 assert(!LCM[&PD.getActivePath()] ||
1711 LCM[&PD.getActivePath()] == PDB.LC);
1712 LCM[&PD.getActivePath()] = PDB.LC;
1714 // Have we encountered an exit from a function call?
1715 if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
1716 const Stmt *S = CE->getCalleeContext()->getCallSite();
1717 // Propagate the interesting symbols accordingly.
1718 if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) {
1719 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1720 N->getState().get(), Ex,
1721 N->getLocationContext());
1724 // We are descending into a call (backwards). Construct
1725 // a new call piece to contain the path pieces for that call.
1726 PathDiagnosticCallPiece *C =
1727 PathDiagnosticCallPiece::construct(N, *CE, SM);
1729 // Record the location context for this call piece.
1730 LCM[&C->path] = CE->getCalleeContext();
1732 // Add the edge to the return site.
1733 addEdgeToPath(PD.getActivePath(), PrevLoc, C->callReturn, PDB.LC);
1734 PD.getActivePath().push_front(C);
1735 PrevLoc.invalidate();
1737 // Make the contents of the call the active path for now.
1738 PD.pushActivePath(&C->path);
1739 CallStack.push_back(StackDiagPair(C, N));
1743 if (Optional<PostStmt> PS = P.getAs<PostStmt>()) {
1744 // For expressions, make sure we propagate the
1745 // interesting symbols correctly.
1746 if (const Expr *Ex = PS->getStmtAs<Expr>())
1747 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1748 N->getState().get(), Ex,
1749 N->getLocationContext());
1751 // Add an edge. If this is an ObjCForCollectionStmt do
1752 // not add an edge here as it appears in the CFG both
1753 // as a terminator and as a terminator condition.
1754 if (!isa<ObjCForCollectionStmt>(PS->getStmt())) {
1755 PathDiagnosticLocation L =
1756 PathDiagnosticLocation(PS->getStmt(), SM, PDB.LC);
1757 addEdgeToPath(PD.getActivePath(), PrevLoc, L, PDB.LC);
1763 if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
1764 // Does this represent entering a call? If so, look at propagating
1765 // interesting symbols across call boundaries.
1767 const LocationContext *CallerCtx = NextNode->getLocationContext();
1768 const LocationContext *CalleeCtx = PDB.LC;
1769 if (CallerCtx != CalleeCtx) {
1770 reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
1771 N->getState().get(),
1772 CalleeCtx, CallerCtx);
1776 // Are we jumping to the head of a loop? Add a special diagnostic.
1777 if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
1778 PathDiagnosticLocation L(Loop, SM, PDB.LC);
1779 const Stmt *Body = nullptr;
1781 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1782 Body = FS->getBody();
1783 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1784 Body = WS->getBody();
1785 else if (const ObjCForCollectionStmt *OFS =
1786 dyn_cast<ObjCForCollectionStmt>(Loop)) {
1787 Body = OFS->getBody();
1788 } else if (const CXXForRangeStmt *FRS =
1789 dyn_cast<CXXForRangeStmt>(Loop)) {
1790 Body = FRS->getBody();
1792 // do-while statements are explicitly excluded here
1794 PathDiagnosticEventPiece *p =
1795 new PathDiagnosticEventPiece(L, "Looping back to the head "
1797 p->setPrunable(true);
1799 addEdgeToPath(PD.getActivePath(), PrevLoc, p->getLocation(), PDB.LC);
1800 PD.getActivePath().push_front(p);
1802 if (const CompoundStmt *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
1803 addEdgeToPath(PD.getActivePath(), PrevLoc,
1804 PathDiagnosticLocation::createEndBrace(CS, SM),
1809 const CFGBlock *BSrc = BE->getSrc();
1810 ParentMap &PM = PDB.getParentMap();
1812 if (const Stmt *Term = BSrc->getTerminator()) {
1813 // Are we jumping past the loop body without ever executing the
1814 // loop (because the condition was false)?
1816 const Stmt *TermCond = getTerminatorCondition(BSrc);
1818 isInLoopBody(PM, getStmtBeforeCond(PM, TermCond, N), Term);
1820 const char *str = nullptr;
1822 if (isJumpToFalseBranch(&*BE)) {
1823 if (!IsInLoopBody) {
1824 if (isa<ObjCForCollectionStmt>(Term)) {
1825 str = StrLoopCollectionEmpty;
1826 } else if (isa<CXXForRangeStmt>(Term)) {
1827 str = StrLoopRangeEmpty;
1829 str = StrLoopBodyZero;
1833 str = StrEnteringLoop;
1837 PathDiagnosticLocation L(TermCond ? TermCond : Term, SM, PDB.LC);
1838 PathDiagnosticEventPiece *PE =
1839 new PathDiagnosticEventPiece(L, str);
1840 PE->setPrunable(true);
1841 addEdgeToPath(PD.getActivePath(), PrevLoc,
1842 PE->getLocation(), PDB.LC);
1843 PD.getActivePath().push_front(PE);
1845 } else if (isa<BreakStmt>(Term) || isa<ContinueStmt>(Term) ||
1846 isa<GotoStmt>(Term)) {
1847 PathDiagnosticLocation L(Term, SM, PDB.LC);
1848 addEdgeToPath(PD.getActivePath(), PrevLoc, L, PDB.LC);
1858 // Add pieces from custom visitors.
1859 for (auto &V : visitors) {
1860 if (PathDiagnosticPiece *p = V->VisitNode(N, NextNode, PDB, *report)) {
1861 addEdgeToPath(PD.getActivePath(), PrevLoc, p->getLocation(), PDB.LC);
1862 PD.getActivePath().push_front(p);
1863 updateStackPiecesWithMessage(p, CallStack);
1868 // Add an edge to the start of the function.
1869 // We'll prune it out later, but it helps make diagnostics more uniform.
1870 const StackFrameContext *CalleeLC = PDB.LC->getCurrentStackFrame();
1871 const Decl *D = CalleeLC->getDecl();
1872 addEdgeToPath(PD.getActivePath(), PrevLoc,
1873 PathDiagnosticLocation::createBegin(D, SM),
1876 return report->isValid();
1879 static const Stmt *getLocStmt(PathDiagnosticLocation L) {
1885 static const Stmt *getStmtParent(const Stmt *S, const ParentMap &PM) {
1890 S = PM.getParentIgnoreParens(S);
1895 if (isa<ExprWithCleanups>(S) ||
1896 isa<CXXBindTemporaryExpr>(S) ||
1897 isa<SubstNonTypeTemplateParmExpr>(S))
1906 static bool isConditionForTerminator(const Stmt *S, const Stmt *Cond) {
1907 switch (S->getStmtClass()) {
1908 case Stmt::BinaryOperatorClass: {
1909 const BinaryOperator *BO = cast<BinaryOperator>(S);
1910 if (!BO->isLogicalOp())
1912 return BO->getLHS() == Cond || BO->getRHS() == Cond;
1914 case Stmt::IfStmtClass:
1915 return cast<IfStmt>(S)->getCond() == Cond;
1916 case Stmt::ForStmtClass:
1917 return cast<ForStmt>(S)->getCond() == Cond;
1918 case Stmt::WhileStmtClass:
1919 return cast<WhileStmt>(S)->getCond() == Cond;
1920 case Stmt::DoStmtClass:
1921 return cast<DoStmt>(S)->getCond() == Cond;
1922 case Stmt::ChooseExprClass:
1923 return cast<ChooseExpr>(S)->getCond() == Cond;
1924 case Stmt::IndirectGotoStmtClass:
1925 return cast<IndirectGotoStmt>(S)->getTarget() == Cond;
1926 case Stmt::SwitchStmtClass:
1927 return cast<SwitchStmt>(S)->getCond() == Cond;
1928 case Stmt::BinaryConditionalOperatorClass:
1929 return cast<BinaryConditionalOperator>(S)->getCond() == Cond;
1930 case Stmt::ConditionalOperatorClass: {
1931 const ConditionalOperator *CO = cast<ConditionalOperator>(S);
1932 return CO->getCond() == Cond ||
1933 CO->getLHS() == Cond ||
1934 CO->getRHS() == Cond;
1936 case Stmt::ObjCForCollectionStmtClass:
1937 return cast<ObjCForCollectionStmt>(S)->getElement() == Cond;
1938 case Stmt::CXXForRangeStmtClass: {
1939 const CXXForRangeStmt *FRS = cast<CXXForRangeStmt>(S);
1940 return FRS->getCond() == Cond || FRS->getRangeInit() == Cond;
1947 static bool isIncrementOrInitInForLoop(const Stmt *S, const Stmt *FL) {
1948 if (const ForStmt *FS = dyn_cast<ForStmt>(FL))
1949 return FS->getInc() == S || FS->getInit() == S;
1950 if (const CXXForRangeStmt *FRS = dyn_cast<CXXForRangeStmt>(FL))
1951 return FRS->getInc() == S || FRS->getRangeStmt() == S ||
1952 FRS->getLoopVarStmt() || FRS->getRangeInit() == S;
1956 typedef llvm::DenseSet<const PathDiagnosticCallPiece *>
1959 /// Adds synthetic edges from top-level statements to their subexpressions.
1961 /// This avoids a "swoosh" effect, where an edge from a top-level statement A
1962 /// points to a sub-expression B.1 that's not at the start of B. In these cases,
1963 /// we'd like to see an edge from A to B, then another one from B to B.1.
1964 static void addContextEdges(PathPieces &pieces, SourceManager &SM,
1965 const ParentMap &PM, const LocationContext *LCtx) {
1966 PathPieces::iterator Prev = pieces.end();
1967 for (PathPieces::iterator I = pieces.begin(), E = Prev; I != E;
1969 PathDiagnosticControlFlowPiece *Piece =
1970 dyn_cast<PathDiagnosticControlFlowPiece>(*I);
1975 PathDiagnosticLocation SrcLoc = Piece->getStartLocation();
1976 SmallVector<PathDiagnosticLocation, 4> SrcContexts;
1978 PathDiagnosticLocation NextSrcContext = SrcLoc;
1979 const Stmt *InnerStmt = nullptr;
1980 while (NextSrcContext.isValid() && NextSrcContext.asStmt() != InnerStmt) {
1981 SrcContexts.push_back(NextSrcContext);
1982 InnerStmt = NextSrcContext.asStmt();
1983 NextSrcContext = getEnclosingStmtLocation(InnerStmt, SM, PM, LCtx,
1984 /*allowNested=*/true);
1987 // Repeatedly split the edge as necessary.
1988 // This is important for nested logical expressions (||, &&, ?:) where we
1989 // want to show all the levels of context.
1991 const Stmt *Dst = getLocStmt(Piece->getEndLocation());
1993 // We are looking at an edge. Is the destination within a larger
1995 PathDiagnosticLocation DstContext =
1996 getEnclosingStmtLocation(Dst, SM, PM, LCtx, /*allowNested=*/true);
1997 if (!DstContext.isValid() || DstContext.asStmt() == Dst)
2000 // If the source is in the same context, we're already good.
2001 if (std::find(SrcContexts.begin(), SrcContexts.end(), DstContext) !=
2005 // Update the subexpression node to point to the context edge.
2006 Piece->setStartLocation(DstContext);
2008 // Try to extend the previous edge if it's at the same level as the source
2011 PathDiagnosticControlFlowPiece *PrevPiece =
2012 dyn_cast<PathDiagnosticControlFlowPiece>(*Prev);
2015 if (const Stmt *PrevSrc = getLocStmt(PrevPiece->getStartLocation())) {
2016 const Stmt *PrevSrcParent = getStmtParent(PrevSrc, PM);
2017 if (PrevSrcParent == getStmtParent(getLocStmt(DstContext), PM)) {
2018 PrevPiece->setEndLocation(DstContext);
2025 // Otherwise, split the current edge into a context edge and a
2026 // subexpression edge. Note that the context statement may itself have
2028 Piece = new PathDiagnosticControlFlowPiece(SrcLoc, DstContext);
2029 I = pieces.insert(I, Piece);
2034 /// \brief Move edges from a branch condition to a branch target
2035 /// when the condition is simple.
2037 /// This restructures some of the work of addContextEdges. That function
2038 /// creates edges this may destroy, but they work together to create a more
2039 /// aesthetically set of edges around branches. After the call to
2040 /// addContextEdges, we may have (1) an edge to the branch, (2) an edge from
2041 /// the branch to the branch condition, and (3) an edge from the branch
2042 /// condition to the branch target. We keep (1), but may wish to remove (2)
2043 /// and move the source of (3) to the branch if the branch condition is simple.
2045 static void simplifySimpleBranches(PathPieces &pieces) {
2046 for (PathPieces::iterator I = pieces.begin(), E = pieces.end(); I != E; ++I) {
2048 PathDiagnosticControlFlowPiece *PieceI =
2049 dyn_cast<PathDiagnosticControlFlowPiece>(*I);
2054 const Stmt *s1Start = getLocStmt(PieceI->getStartLocation());
2055 const Stmt *s1End = getLocStmt(PieceI->getEndLocation());
2057 if (!s1Start || !s1End)
2060 PathPieces::iterator NextI = I; ++NextI;
2064 PathDiagnosticControlFlowPiece *PieceNextI = nullptr;
2070 PathDiagnosticEventPiece *EV = dyn_cast<PathDiagnosticEventPiece>(*NextI);
2072 StringRef S = EV->getString();
2073 if (S == StrEnteringLoop || S == StrLoopBodyZero ||
2074 S == StrLoopCollectionEmpty || S == StrLoopRangeEmpty) {
2081 PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(*NextI);
2088 const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation());
2089 const Stmt *s2End = getLocStmt(PieceNextI->getEndLocation());
2091 if (!s2Start || !s2End || s1End != s2Start)
2094 // We only perform this transformation for specific branch kinds.
2095 // We don't want to do this for do..while, for example.
2096 if (!(isa<ForStmt>(s1Start) || isa<WhileStmt>(s1Start) ||
2097 isa<IfStmt>(s1Start) || isa<ObjCForCollectionStmt>(s1Start) ||
2098 isa<CXXForRangeStmt>(s1Start)))
2101 // Is s1End the branch condition?
2102 if (!isConditionForTerminator(s1Start, s1End))
2105 // Perform the hoisting by eliminating (2) and changing the start
2107 PieceNextI->setStartLocation(PieceI->getStartLocation());
2108 I = pieces.erase(I);
2112 /// Returns the number of bytes in the given (character-based) SourceRange.
2114 /// If the locations in the range are not on the same line, returns None.
2116 /// Note that this does not do a precise user-visible character or column count.
2117 static Optional<size_t> getLengthOnSingleLine(SourceManager &SM,
2118 SourceRange Range) {
2119 SourceRange ExpansionRange(SM.getExpansionLoc(Range.getBegin()),
2120 SM.getExpansionRange(Range.getEnd()).second);
2122 FileID FID = SM.getFileID(ExpansionRange.getBegin());
2123 if (FID != SM.getFileID(ExpansionRange.getEnd()))
2127 const llvm::MemoryBuffer *Buffer = SM.getBuffer(FID, &Invalid);
2131 unsigned BeginOffset = SM.getFileOffset(ExpansionRange.getBegin());
2132 unsigned EndOffset = SM.getFileOffset(ExpansionRange.getEnd());
2133 StringRef Snippet = Buffer->getBuffer().slice(BeginOffset, EndOffset);
2135 // We're searching the raw bytes of the buffer here, which might include
2136 // escaped newlines and such. That's okay; we're trying to decide whether the
2137 // SourceRange is covering a large or small amount of space in the user's
2139 if (Snippet.find_first_of("\r\n") != StringRef::npos)
2142 // This isn't Unicode-aware, but it doesn't need to be.
2143 return Snippet.size();
2146 /// \sa getLengthOnSingleLine(SourceManager, SourceRange)
2147 static Optional<size_t> getLengthOnSingleLine(SourceManager &SM,
2149 return getLengthOnSingleLine(SM, S->getSourceRange());
2152 /// Eliminate two-edge cycles created by addContextEdges().
2154 /// Once all the context edges are in place, there are plenty of cases where
2155 /// there's a single edge from a top-level statement to a subexpression,
2156 /// followed by a single path note, and then a reverse edge to get back out to
2157 /// the top level. If the statement is simple enough, the subexpression edges
2158 /// just add noise and make it harder to understand what's going on.
2160 /// This function only removes edges in pairs, because removing only one edge
2161 /// might leave other edges dangling.
2163 /// This will not remove edges in more complicated situations:
2164 /// - if there is more than one "hop" leading to or from a subexpression.
2165 /// - if there is an inlined call between the edges instead of a single event.
2166 /// - if the whole statement is large enough that having subexpression arrows
2167 /// might be helpful.
2168 static void removeContextCycles(PathPieces &Path, SourceManager &SM,
2170 for (PathPieces::iterator I = Path.begin(), E = Path.end(); I != E; ) {
2171 // Pattern match the current piece and its successor.
2172 PathDiagnosticControlFlowPiece *PieceI =
2173 dyn_cast<PathDiagnosticControlFlowPiece>(*I);
2180 const Stmt *s1Start = getLocStmt(PieceI->getStartLocation());
2181 const Stmt *s1End = getLocStmt(PieceI->getEndLocation());
2183 PathPieces::iterator NextI = I; ++NextI;
2187 PathDiagnosticControlFlowPiece *PieceNextI =
2188 dyn_cast<PathDiagnosticControlFlowPiece>(*NextI);
2191 if (isa<PathDiagnosticEventPiece>(*NextI)) {
2195 PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(*NextI);
2204 const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation());
2205 const Stmt *s2End = getLocStmt(PieceNextI->getEndLocation());
2207 if (s1Start && s2Start && s1Start == s2End && s2Start == s1End) {
2208 const size_t MAX_SHORT_LINE_LENGTH = 80;
2209 Optional<size_t> s1Length = getLengthOnSingleLine(SM, s1Start);
2210 if (s1Length && *s1Length <= MAX_SHORT_LINE_LENGTH) {
2211 Optional<size_t> s2Length = getLengthOnSingleLine(SM, s2Start);
2212 if (s2Length && *s2Length <= MAX_SHORT_LINE_LENGTH) {
2214 I = Path.erase(NextI);
2224 /// \brief Return true if X is contained by Y.
2225 static bool lexicalContains(ParentMap &PM,
2231 X = PM.getParent(X);
2236 // Remove short edges on the same line less than 3 columns in difference.
2237 static void removePunyEdges(PathPieces &path,
2241 bool erased = false;
2243 for (PathPieces::iterator I = path.begin(), E = path.end(); I != E;
2248 PathDiagnosticControlFlowPiece *PieceI =
2249 dyn_cast<PathDiagnosticControlFlowPiece>(*I);
2254 const Stmt *start = getLocStmt(PieceI->getStartLocation());
2255 const Stmt *end = getLocStmt(PieceI->getEndLocation());
2260 const Stmt *endParent = PM.getParent(end);
2264 if (isConditionForTerminator(end, endParent))
2267 SourceLocation FirstLoc = start->getLocStart();
2268 SourceLocation SecondLoc = end->getLocStart();
2270 if (!SM.isWrittenInSameFile(FirstLoc, SecondLoc))
2272 if (SM.isBeforeInTranslationUnit(SecondLoc, FirstLoc))
2273 std::swap(SecondLoc, FirstLoc);
2275 SourceRange EdgeRange(FirstLoc, SecondLoc);
2276 Optional<size_t> ByteWidth = getLengthOnSingleLine(SM, EdgeRange);
2278 // If the statements are on different lines, continue.
2282 const size_t MAX_PUNY_EDGE_LENGTH = 2;
2283 if (*ByteWidth <= MAX_PUNY_EDGE_LENGTH) {
2284 // FIXME: There are enough /bytes/ between the endpoints of the edge, but
2285 // there might not be enough /columns/. A proper user-visible column count
2286 // is probably too expensive, though.
2294 static void removeIdenticalEvents(PathPieces &path) {
2295 for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ++I) {
2296 PathDiagnosticEventPiece *PieceI =
2297 dyn_cast<PathDiagnosticEventPiece>(*I);
2302 PathPieces::iterator NextI = I; ++NextI;
2306 PathDiagnosticEventPiece *PieceNextI =
2307 dyn_cast<PathDiagnosticEventPiece>(*NextI);
2312 // Erase the second piece if it has the same exact message text.
2313 if (PieceI->getString() == PieceNextI->getString()) {
2319 static bool optimizeEdges(PathPieces &path, SourceManager &SM,
2320 OptimizedCallsSet &OCS,
2321 LocationContextMap &LCM) {
2322 bool hasChanges = false;
2323 const LocationContext *LC = LCM[&path];
2325 ParentMap &PM = LC->getParentMap();
2327 for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ) {
2328 // Optimize subpaths.
2329 if (PathDiagnosticCallPiece *CallI = dyn_cast<PathDiagnosticCallPiece>(*I)){
2330 // Record the fact that a call has been optimized so we only do the
2332 if (!OCS.count(CallI)) {
2333 while (optimizeEdges(CallI->path, SM, OCS, LCM)) {}
2340 // Pattern match the current piece and its successor.
2341 PathDiagnosticControlFlowPiece *PieceI =
2342 dyn_cast<PathDiagnosticControlFlowPiece>(*I);
2349 const Stmt *s1Start = getLocStmt(PieceI->getStartLocation());
2350 const Stmt *s1End = getLocStmt(PieceI->getEndLocation());
2351 const Stmt *level1 = getStmtParent(s1Start, PM);
2352 const Stmt *level2 = getStmtParent(s1End, PM);
2354 PathPieces::iterator NextI = I; ++NextI;
2358 PathDiagnosticControlFlowPiece *PieceNextI =
2359 dyn_cast<PathDiagnosticControlFlowPiece>(*NextI);
2366 const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation());
2367 const Stmt *s2End = getLocStmt(PieceNextI->getEndLocation());
2368 const Stmt *level3 = getStmtParent(s2Start, PM);
2369 const Stmt *level4 = getStmtParent(s2End, PM);
2373 // If we have two consecutive control edges whose end/begin locations
2374 // are at the same level (e.g. statements or top-level expressions within
2375 // a compound statement, or siblings share a single ancestor expression),
2376 // then merge them if they have no interesting intermediate event.
2380 // (1.1 -> 1.2) -> (1.2 -> 1.3) becomes (1.1 -> 1.3) because the common
2381 // parent is '1'. Here 'x.y.z' represents the hierarchy of statements.
2383 // NOTE: this will be limited later in cases where we add barriers
2384 // to prevent this optimization.
2386 if (level1 && level1 == level2 && level1 == level3 && level1 == level4) {
2387 PieceI->setEndLocation(PieceNextI->getEndLocation());
2395 // Eliminate edges between subexpressions and parent expressions
2396 // when the subexpression is consumed.
2398 // NOTE: this will be limited later in cases where we add barriers
2399 // to prevent this optimization.
2401 if (s1End && s1End == s2Start && level2) {
2402 bool removeEdge = false;
2403 // Remove edges into the increment or initialization of a
2404 // loop that have no interleaving event. This means that
2405 // they aren't interesting.
2406 if (isIncrementOrInitInForLoop(s1End, level2))
2408 // Next only consider edges that are not anchored on
2409 // the condition of a terminator. This are intermediate edges
2410 // that we might want to trim.
2411 else if (!isConditionForTerminator(level2, s1End)) {
2412 // Trim edges on expressions that are consumed by
2413 // the parent expression.
2414 if (isa<Expr>(s1End) && PM.isConsumedExpr(cast<Expr>(s1End))) {
2417 // Trim edges where a lexical containment doesn't exist.
2422 // If 'Z' lexically contains Y (it is an ancestor) and
2423 // 'X' does not lexically contain Y (it is a descendant OR
2424 // it has no lexical relationship at all) then trim.
2426 // This can eliminate edges where we dive into a subexpression
2427 // and then pop back out, etc.
2428 else if (s1Start && s2End &&
2429 lexicalContains(PM, s2Start, s2End) &&
2430 !lexicalContains(PM, s1End, s1Start)) {
2433 // Trim edges from a subexpression back to the top level if the
2434 // subexpression is on a different line.
2440 // These edges just look ugly and don't usually add anything.
2441 else if (s1Start && s2End &&
2442 lexicalContains(PM, s1Start, s1End)) {
2443 SourceRange EdgeRange(PieceI->getEndLocation().asLocation(),
2444 PieceI->getStartLocation().asLocation());
2445 if (!getLengthOnSingleLine(SM, EdgeRange).hasValue())
2451 PieceI->setEndLocation(PieceNextI->getEndLocation());
2458 // Optimize edges for ObjC fast-enumeration loops.
2460 // (X -> collection) -> (collection -> element)
2465 if (s1End == s2Start) {
2466 const ObjCForCollectionStmt *FS =
2467 dyn_cast_or_null<ObjCForCollectionStmt>(level3);
2468 if (FS && FS->getCollection()->IgnoreParens() == s2Start &&
2469 s2End == FS->getElement()) {
2470 PieceI->setEndLocation(PieceNextI->getEndLocation());
2477 // No changes at this index? Move to the next one.
2482 // Adjust edges into subexpressions to make them more uniform
2483 // and aesthetically pleasing.
2484 addContextEdges(path, SM, PM, LC);
2485 // Remove "cyclical" edges that include one or more context edges.
2486 removeContextCycles(path, SM, PM);
2487 // Hoist edges originating from branch conditions to branches
2488 // for simple branches.
2489 simplifySimpleBranches(path);
2490 // Remove any puny edges left over after primary optimization pass.
2491 removePunyEdges(path, SM, PM);
2492 // Remove identical events.
2493 removeIdenticalEvents(path);
2499 /// Drop the very first edge in a path, which should be a function entry edge.
2501 /// If the first edge is not a function entry edge (say, because the first
2502 /// statement had an invalid source location), this function does nothing.
2503 // FIXME: We should just generate invalid edges anyway and have the optimizer
2505 static void dropFunctionEntryEdge(PathPieces &Path,
2506 LocationContextMap &LCM,
2507 SourceManager &SM) {
2508 const PathDiagnosticControlFlowPiece *FirstEdge =
2509 dyn_cast<PathDiagnosticControlFlowPiece>(Path.front());
2513 const Decl *D = LCM[&Path]->getDecl();
2514 PathDiagnosticLocation EntryLoc = PathDiagnosticLocation::createBegin(D, SM);
2515 if (FirstEdge->getStartLocation() != EntryLoc)
2522 //===----------------------------------------------------------------------===//
2523 // Methods for BugType and subclasses.
2524 //===----------------------------------------------------------------------===//
2525 void BugType::anchor() { }
2527 void BugType::FlushReports(BugReporter &BR) {}
2529 void BuiltinBug::anchor() {}
2531 //===----------------------------------------------------------------------===//
2532 // Methods for BugReport and subclasses.
2533 //===----------------------------------------------------------------------===//
2535 void BugReport::NodeResolver::anchor() {}
2537 void BugReport::addVisitor(std::unique_ptr<BugReporterVisitor> visitor) {
2541 llvm::FoldingSetNodeID ID;
2542 visitor->Profile(ID);
2545 if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos))
2548 CallbacksSet.InsertNode(visitor.get(), InsertPos);
2549 Callbacks.push_back(std::move(visitor));
2550 ++ConfigurationChangeToken;
2553 BugReport::~BugReport() {
2554 while (!interestingSymbols.empty()) {
2555 popInterestingSymbolsAndRegions();
2559 const Decl *BugReport::getDeclWithIssue() const {
2561 return DeclWithIssue;
2563 const ExplodedNode *N = getErrorNode();
2567 const LocationContext *LC = N->getLocationContext();
2568 return LC->getCurrentStackFrame()->getDecl();
2571 void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
2572 hash.AddPointer(&BT);
2573 hash.AddString(Description);
2574 PathDiagnosticLocation UL = getUniqueingLocation();
2577 } else if (Location.isValid()) {
2578 Location.Profile(hash);
2581 hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
2584 for (SmallVectorImpl<SourceRange>::const_iterator I =
2585 Ranges.begin(), E = Ranges.end(); I != E; ++I) {
2586 const SourceRange range = *I;
2587 if (!range.isValid())
2589 hash.AddInteger(range.getBegin().getRawEncoding());
2590 hash.AddInteger(range.getEnd().getRawEncoding());
2594 void BugReport::markInteresting(SymbolRef sym) {
2598 // If the symbol wasn't already in our set, note a configuration change.
2599 if (getInterestingSymbols().insert(sym).second)
2600 ++ConfigurationChangeToken;
2602 if (const SymbolMetadata *meta = dyn_cast<SymbolMetadata>(sym))
2603 getInterestingRegions().insert(meta->getRegion());
2606 void BugReport::markInteresting(const MemRegion *R) {
2610 // If the base region wasn't already in our set, note a configuration change.
2611 R = R->getBaseRegion();
2612 if (getInterestingRegions().insert(R).second)
2613 ++ConfigurationChangeToken;
2615 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
2616 getInterestingSymbols().insert(SR->getSymbol());
2619 void BugReport::markInteresting(SVal V) {
2620 markInteresting(V.getAsRegion());
2621 markInteresting(V.getAsSymbol());
2624 void BugReport::markInteresting(const LocationContext *LC) {
2627 InterestingLocationContexts.insert(LC);
2630 bool BugReport::isInteresting(SVal V) {
2631 return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol());
2634 bool BugReport::isInteresting(SymbolRef sym) {
2637 // We don't currently consider metadata symbols to be interesting
2638 // even if we know their region is interesting. Is that correct behavior?
2639 return getInterestingSymbols().count(sym);
2642 bool BugReport::isInteresting(const MemRegion *R) {
2645 R = R->getBaseRegion();
2646 bool b = getInterestingRegions().count(R);
2649 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
2650 return getInterestingSymbols().count(SR->getSymbol());
2654 bool BugReport::isInteresting(const LocationContext *LC) {
2657 return InterestingLocationContexts.count(LC);
2660 void BugReport::lazyInitializeInterestingSets() {
2661 if (interestingSymbols.empty()) {
2662 interestingSymbols.push_back(new Symbols());
2663 interestingRegions.push_back(new Regions());
2667 BugReport::Symbols &BugReport::getInterestingSymbols() {
2668 lazyInitializeInterestingSets();
2669 return *interestingSymbols.back();
2672 BugReport::Regions &BugReport::getInterestingRegions() {
2673 lazyInitializeInterestingSets();
2674 return *interestingRegions.back();
2677 void BugReport::pushInterestingSymbolsAndRegions() {
2678 interestingSymbols.push_back(new Symbols(getInterestingSymbols()));
2679 interestingRegions.push_back(new Regions(getInterestingRegions()));
2682 void BugReport::popInterestingSymbolsAndRegions() {
2683 delete interestingSymbols.pop_back_val();
2684 delete interestingRegions.pop_back_val();
2687 const Stmt *BugReport::getStmt() const {
2691 ProgramPoint ProgP = ErrorNode->getLocation();
2692 const Stmt *S = nullptr;
2694 if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
2695 CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
2696 if (BE->getBlock() == &Exit)
2697 S = GetPreviousStmt(ErrorNode);
2700 S = PathDiagnosticLocation::getStmt(ErrorNode);
2705 std::pair<BugReport::ranges_iterator, BugReport::ranges_iterator>
2706 BugReport::getRanges() {
2707 // If no custom ranges, add the range of the statement corresponding to
2709 if (Ranges.empty()) {
2710 if (const Expr *E = dyn_cast_or_null<Expr>(getStmt()))
2711 addRange(E->getSourceRange());
2713 return std::make_pair(ranges_iterator(), ranges_iterator());
2716 // User-specified absence of range info.
2717 if (Ranges.size() == 1 && !Ranges.begin()->isValid())
2718 return std::make_pair(ranges_iterator(), ranges_iterator());
2720 return std::make_pair(Ranges.begin(), Ranges.end());
2723 PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
2725 assert(!Location.isValid() &&
2726 "Either Location or ErrorNode should be specified but not both.");
2727 return PathDiagnosticLocation::createEndOfPath(ErrorNode, SM);
2730 assert(Location.isValid());
2734 //===----------------------------------------------------------------------===//
2735 // Methods for BugReporter and subclasses.
2736 //===----------------------------------------------------------------------===//
2738 BugReportEquivClass::~BugReportEquivClass() { }
2739 GRBugReporter::~GRBugReporter() { }
2740 BugReporterData::~BugReporterData() {}
2742 ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
2744 ProgramStateManager&
2745 GRBugReporter::getStateManager() { return Eng.getStateManager(); }
2747 BugReporter::~BugReporter() {
2750 // Free the bug reports we are tracking.
2751 typedef std::vector<BugReportEquivClass *> ContTy;
2752 for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end();
2758 void BugReporter::FlushReports() {
2759 if (BugTypes.isEmpty())
2762 // First flush the warnings for each BugType. This may end up creating new
2763 // warnings and new BugTypes.
2764 // FIXME: Only NSErrorChecker needs BugType's FlushReports.
2765 // Turn NSErrorChecker into a proper checker and remove this.
2766 SmallVector<const BugType*, 16> bugTypes;
2767 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
2768 bugTypes.push_back(*I);
2769 for (SmallVectorImpl<const BugType *>::iterator
2770 I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I)
2771 const_cast<BugType*>(*I)->FlushReports(*this);
2773 // We need to flush reports in deterministic order to ensure the order
2774 // of the reports is consistent between runs.
2775 typedef std::vector<BugReportEquivClass *> ContVecTy;
2776 for (ContVecTy::iterator EI=EQClassesVector.begin(), EE=EQClassesVector.end();
2778 BugReportEquivClass& EQ = **EI;
2782 // BugReporter owns and deletes only BugTypes created implicitly through
2784 // FIXME: There are leaks from checkers that assume that the BugTypes they
2785 // create will be destroyed by the BugReporter.
2786 llvm::DeleteContainerSeconds(StrBugTypes);
2788 // Remove all references to the BugType objects.
2789 BugTypes = F.getEmptySet();
2792 //===----------------------------------------------------------------------===//
2793 // PathDiagnostics generation.
2794 //===----------------------------------------------------------------------===//
2797 /// A wrapper around a report graph, which contains only a single path, and its
2801 InterExplodedGraphMap BackMap;
2802 std::unique_ptr<ExplodedGraph> Graph;
2803 const ExplodedNode *ErrorNode;
2807 /// A wrapper around a trimmed graph and its node maps.
2808 class TrimmedGraph {
2809 InterExplodedGraphMap InverseMap;
2811 typedef llvm::DenseMap<const ExplodedNode *, unsigned> PriorityMapTy;
2812 PriorityMapTy PriorityMap;
2814 typedef std::pair<const ExplodedNode *, size_t> NodeIndexPair;
2815 SmallVector<NodeIndexPair, 32> ReportNodes;
2817 std::unique_ptr<ExplodedGraph> G;
2819 /// A helper class for sorting ExplodedNodes by priority.
2820 template <bool Descending>
2821 class PriorityCompare {
2822 const PriorityMapTy &PriorityMap;
2825 PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
2827 bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
2828 PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
2829 PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
2830 PriorityMapTy::const_iterator E = PriorityMap.end();
2837 return Descending ? LI->second > RI->second
2838 : LI->second < RI->second;
2841 bool operator()(const NodeIndexPair &LHS, const NodeIndexPair &RHS) const {
2842 return (*this)(LHS.first, RHS.first);
2847 TrimmedGraph(const ExplodedGraph *OriginalGraph,
2848 ArrayRef<const ExplodedNode *> Nodes);
2850 bool popNextReportGraph(ReportGraph &GraphWrapper);
2854 TrimmedGraph::TrimmedGraph(const ExplodedGraph *OriginalGraph,
2855 ArrayRef<const ExplodedNode *> Nodes) {
2856 // The trimmed graph is created in the body of the constructor to ensure
2857 // that the DenseMaps have been initialized already.
2858 InterExplodedGraphMap ForwardMap;
2859 G = OriginalGraph->trim(Nodes, &ForwardMap, &InverseMap);
2861 // Find the (first) error node in the trimmed graph. We just need to consult
2862 // the node map which maps from nodes in the original graph to nodes
2863 // in the new graph.
2864 llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes;
2866 for (unsigned i = 0, count = Nodes.size(); i < count; ++i) {
2867 if (const ExplodedNode *NewNode = ForwardMap.lookup(Nodes[i])) {
2868 ReportNodes.push_back(std::make_pair(NewNode, i));
2869 RemainingNodes.insert(NewNode);
2873 assert(!RemainingNodes.empty() && "No error node found in the trimmed graph");
2875 // Perform a forward BFS to find all the shortest paths.
2876 std::queue<const ExplodedNode *> WS;
2878 assert(G->num_roots() == 1);
2879 WS.push(*G->roots_begin());
2880 unsigned Priority = 0;
2882 while (!WS.empty()) {
2883 const ExplodedNode *Node = WS.front();
2886 PriorityMapTy::iterator PriorityEntry;
2888 std::tie(PriorityEntry, IsNew) =
2889 PriorityMap.insert(std::make_pair(Node, Priority));
2893 assert(PriorityEntry->second <= Priority);
2897 if (RemainingNodes.erase(Node))
2898 if (RemainingNodes.empty())
2901 for (ExplodedNode::const_pred_iterator I = Node->succ_begin(),
2902 E = Node->succ_end();
2907 // Sort the error paths from longest to shortest.
2908 std::sort(ReportNodes.begin(), ReportNodes.end(),
2909 PriorityCompare<true>(PriorityMap));
2912 bool TrimmedGraph::popNextReportGraph(ReportGraph &GraphWrapper) {
2913 if (ReportNodes.empty())
2916 const ExplodedNode *OrigN;
2917 std::tie(OrigN, GraphWrapper.Index) = ReportNodes.pop_back_val();
2918 assert(PriorityMap.find(OrigN) != PriorityMap.end() &&
2919 "error node not accessible from root");
2921 // Create a new graph with a single path. This is the graph
2922 // that will be returned to the caller.
2923 auto GNew = llvm::make_unique<ExplodedGraph>();
2924 GraphWrapper.BackMap.clear();
2926 // Now walk from the error node up the BFS path, always taking the
2927 // predeccessor with the lowest number.
2928 ExplodedNode *Succ = nullptr;
2930 // Create the equivalent node in the new graph with the same state
2932 ExplodedNode *NewN = GNew->getNode(OrigN->getLocation(), OrigN->getState(),
2935 // Store the mapping to the original node.
2936 InterExplodedGraphMap::const_iterator IMitr = InverseMap.find(OrigN);
2937 assert(IMitr != InverseMap.end() && "No mapping to original node.");
2938 GraphWrapper.BackMap[NewN] = IMitr->second;
2940 // Link up the new node with the previous node.
2942 Succ->addPredecessor(NewN, *GNew);
2944 GraphWrapper.ErrorNode = NewN;
2948 // Are we at the final node?
2949 if (OrigN->pred_empty()) {
2950 GNew->addRoot(NewN);
2954 // Find the next predeccessor node. We choose the node that is marked
2955 // with the lowest BFS number.
2956 OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(),
2957 PriorityCompare<false>(PriorityMap));
2960 GraphWrapper.Graph = std::move(GNew);
2966 /// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
2967 /// and collapses PathDiagosticPieces that are expanded by macros.
2968 static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM) {
2969 typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiece>,
2970 SourceLocation> > MacroStackTy;
2972 typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> >
2975 MacroStackTy MacroStack;
2978 for (PathPieces::const_iterator I = path.begin(), E = path.end();
2981 PathDiagnosticPiece *piece = I->get();
2983 // Recursively compact calls.
2984 if (PathDiagnosticCallPiece *call=dyn_cast<PathDiagnosticCallPiece>(piece)){
2985 CompactPathDiagnostic(call->path, SM);
2988 // Get the location of the PathDiagnosticPiece.
2989 const FullSourceLoc Loc = piece->getLocation().asLocation();
2991 // Determine the instantiation location, which is the location we group
2992 // related PathDiagnosticPieces.
2993 SourceLocation InstantiationLoc = Loc.isMacroID() ?
2994 SM.getExpansionLoc(Loc) :
2997 if (Loc.isFileID()) {
2999 Pieces.push_back(piece);
3003 assert(Loc.isMacroID());
3005 // Is the PathDiagnosticPiece within the same macro group?
3006 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
3007 MacroStack.back().first->subPieces.push_back(piece);
3011 // We aren't in the same group. Are we descending into a new macro
3012 // or are part of an old one?
3013 IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup;
3015 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
3016 SM.getExpansionLoc(Loc) :
3019 // Walk the entire macro stack.
3020 while (!MacroStack.empty()) {
3021 if (InstantiationLoc == MacroStack.back().second) {
3022 MacroGroup = MacroStack.back().first;
3026 if (ParentInstantiationLoc == MacroStack.back().second) {
3027 MacroGroup = MacroStack.back().first;
3031 MacroStack.pop_back();
3034 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
3035 // Create a new macro group and add it to the stack.
3036 PathDiagnosticMacroPiece *NewGroup =
3037 new PathDiagnosticMacroPiece(
3038 PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
3041 MacroGroup->subPieces.push_back(NewGroup);
3043 assert(InstantiationLoc.isFileID());
3044 Pieces.push_back(NewGroup);
3047 MacroGroup = NewGroup;
3048 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
3051 // Finally, add the PathDiagnosticPiece to the group.
3052 MacroGroup->subPieces.push_back(piece);
3055 // Now take the pieces and construct a new PathDiagnostic.
3058 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I)
3062 bool GRBugReporter::generatePathDiagnostic(PathDiagnostic& PD,
3063 PathDiagnosticConsumer &PC,
3064 ArrayRef<BugReport *> &bugReports) {
3065 assert(!bugReports.empty());
3067 bool HasValid = false;
3068 bool HasInvalid = false;
3069 SmallVector<const ExplodedNode *, 32> errorNodes;
3070 for (ArrayRef<BugReport*>::iterator I = bugReports.begin(),
3071 E = bugReports.end(); I != E; ++I) {
3072 if ((*I)->isValid()) {
3074 errorNodes.push_back((*I)->getErrorNode());
3076 // Keep the errorNodes list in sync with the bugReports list.
3078 errorNodes.push_back(nullptr);
3082 // If all the reports have been marked invalid by a previous path generation,
3087 typedef PathDiagnosticConsumer::PathGenerationScheme PathGenerationScheme;
3088 PathGenerationScheme ActiveScheme = PC.getGenerationScheme();
3090 if (ActiveScheme == PathDiagnosticConsumer::Extensive) {
3091 AnalyzerOptions &options = getAnalyzerOptions();
3092 if (options.getBooleanOption("path-diagnostics-alternate", true)) {
3093 ActiveScheme = PathDiagnosticConsumer::AlternateExtensive;
3097 TrimmedGraph TrimG(&getGraph(), errorNodes);
3098 ReportGraph ErrorGraph;
3100 while (TrimG.popNextReportGraph(ErrorGraph)) {
3101 // Find the BugReport with the original location.
3102 assert(ErrorGraph.Index < bugReports.size());
3103 BugReport *R = bugReports[ErrorGraph.Index];
3104 assert(R && "No original report found for sliced graph.");
3105 assert(R->isValid() && "Report selected by trimmed graph marked invalid.");
3107 // Start building the path diagnostic...
3108 PathDiagnosticBuilder PDB(*this, R, ErrorGraph.BackMap, &PC);
3109 const ExplodedNode *N = ErrorGraph.ErrorNode;
3111 // Register additional node visitors.
3112 R->addVisitor(llvm::make_unique<NilReceiverBRVisitor>());
3113 R->addVisitor(llvm::make_unique<ConditionBRVisitor>());
3114 R->addVisitor(llvm::make_unique<LikelyFalsePositiveSuppressionBRVisitor>());
3116 BugReport::VisitorList visitors;
3117 unsigned origReportConfigToken, finalReportConfigToken;
3118 LocationContextMap LCM;
3120 // While generating diagnostics, it's possible the visitors will decide
3121 // new symbols and regions are interesting, or add other visitors based on
3122 // the information they find. If they do, we need to regenerate the path
3123 // based on our new report configuration.
3125 // Get a clean copy of all the visitors.
3126 for (BugReport::visitor_iterator I = R->visitor_begin(),
3127 E = R->visitor_end(); I != E; ++I)
3128 visitors.push_back((*I)->clone());
3130 // Clear out the active path from any previous work.
3132 origReportConfigToken = R->getConfigurationChangeToken();
3134 // Generate the very last diagnostic piece - the piece is visible before
3135 // the trace is expanded.
3136 std::unique_ptr<PathDiagnosticPiece> LastPiece;
3137 for (BugReport::visitor_iterator I = visitors.begin(), E = visitors.end();
3139 if (std::unique_ptr<PathDiagnosticPiece> Piece =
3140 (*I)->getEndPath(PDB, N, *R)) {
3141 assert (!LastPiece &&
3142 "There can only be one final piece in a diagnostic.");
3143 LastPiece = std::move(Piece);
3147 if (ActiveScheme != PathDiagnosticConsumer::None) {
3149 LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R);
3151 PD.setEndOfPath(std::move(LastPiece));
3154 // Make sure we get a clean location context map so we don't
3155 // hold onto old mappings.
3158 switch (ActiveScheme) {
3159 case PathDiagnosticConsumer::AlternateExtensive:
3160 GenerateAlternateExtensivePathDiagnostic(PD, PDB, N, LCM, visitors);
3162 case PathDiagnosticConsumer::Extensive:
3163 GenerateExtensivePathDiagnostic(PD, PDB, N, LCM, visitors);
3165 case PathDiagnosticConsumer::Minimal:
3166 GenerateMinimalPathDiagnostic(PD, PDB, N, LCM, visitors);
3168 case PathDiagnosticConsumer::None:
3169 GenerateVisitorsOnlyPathDiagnostic(PD, PDB, N, visitors);
3173 // Clean up the visitors we used.
3176 // Did anything change while generating this path?
3177 finalReportConfigToken = R->getConfigurationChangeToken();
3178 } while (finalReportConfigToken != origReportConfigToken);
3183 // Finally, prune the diagnostic path of uninteresting stuff.
3184 if (!PD.path.empty()) {
3185 if (R->shouldPrunePath() && getAnalyzerOptions().shouldPrunePaths()) {
3186 bool stillHasNotes = removeUnneededCalls(PD.getMutablePieces(), R, LCM);
3187 assert(stillHasNotes);
3188 (void)stillHasNotes;
3191 // Redirect all call pieces to have valid locations.
3192 adjustCallLocations(PD.getMutablePieces());
3193 removePiecesWithInvalidLocations(PD.getMutablePieces());
3195 if (ActiveScheme == PathDiagnosticConsumer::AlternateExtensive) {
3196 SourceManager &SM = getSourceManager();
3198 // Reduce the number of edges from a very conservative set
3199 // to an aesthetically pleasing subset that conveys the
3200 // necessary information.
3201 OptimizedCallsSet OCS;
3202 while (optimizeEdges(PD.getMutablePieces(), SM, OCS, LCM)) {}
3204 // Drop the very first function-entry edge. It's not really necessary
3205 // for top-level functions.
3206 dropFunctionEntryEdge(PD.getMutablePieces(), LCM, SM);
3209 // Remove messages that are basically the same, and edges that may not
3211 // We have to do this after edge optimization in the Extensive mode.
3212 removeRedundantMsgs(PD.getMutablePieces());
3213 removeEdgesToDefaultInitializers(PD.getMutablePieces());
3216 // We found a report and didn't suppress it.
3220 // We suppressed all the reports in this equivalence class.
3221 assert(!HasInvalid && "Inconsistent suppression");
3226 void BugReporter::Register(BugType *BT) {
3227 BugTypes = F.add(BugTypes, BT);
3230 void BugReporter::emitReport(BugReport* R) {
3231 // To guarantee memory release.
3232 std::unique_ptr<BugReport> UniqueR(R);
3234 if (const ExplodedNode *E = R->getErrorNode()) {
3235 const AnalysisDeclContext *DeclCtx =
3236 E->getLocationContext()->getAnalysisDeclContext();
3237 // The source of autosynthesized body can be handcrafted AST or a model
3238 // file. The locations from handcrafted ASTs have no valid source locations
3239 // and have to be discarded. Locations from model files should be preserved
3240 // for processing and reporting.
3241 if (DeclCtx->isBodyAutosynthesized() &&
3242 !DeclCtx->isBodyAutosynthesizedFromModelFile())
3246 bool ValidSourceLoc = R->getLocation(getSourceManager()).isValid();
3247 assert(ValidSourceLoc);
3248 // If we mess up in a release build, we'd still prefer to just drop the bug
3249 // instead of trying to go on.
3250 if (!ValidSourceLoc)
3253 // Compute the bug report's hash to determine its equivalence class.
3254 llvm::FoldingSetNodeID ID;
3257 // Lookup the equivance class. If there isn't one, create it.
3258 BugType& BT = R->getBugType();
3261 BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
3264 EQ = new BugReportEquivClass(std::move(UniqueR));
3265 EQClasses.InsertNode(EQ, InsertPos);
3266 EQClassesVector.push_back(EQ);
3268 EQ->AddReport(std::move(UniqueR));
3272 //===----------------------------------------------------------------------===//
3273 // Emitting reports in equivalence classes.
3274 //===----------------------------------------------------------------------===//
3277 struct FRIEC_WLItem {
3278 const ExplodedNode *N;
3279 ExplodedNode::const_succ_iterator I, E;
3281 FRIEC_WLItem(const ExplodedNode *n)
3282 : N(n), I(N->succ_begin()), E(N->succ_end()) {}
3287 FindReportInEquivalenceClass(BugReportEquivClass& EQ,
3288 SmallVectorImpl<BugReport*> &bugReports) {
3290 BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
3292 BugType& BT = I->getBugType();
3294 // If we don't need to suppress any of the nodes because they are
3295 // post-dominated by a sink, simply add all the nodes in the equivalence class
3296 // to 'Nodes'. Any of the reports will serve as a "representative" report.
3297 if (!BT.isSuppressOnSink()) {
3299 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
3300 const ExplodedNode *N = I->getErrorNode();
3303 bugReports.push_back(R);
3309 // For bug reports that should be suppressed when all paths are post-dominated
3310 // by a sink node, iterate through the reports in the equivalence class
3311 // until we find one that isn't post-dominated (if one exists). We use a
3312 // DFS traversal of the ExplodedGraph to find a non-sink node. We could write
3313 // this as a recursive function, but we don't want to risk blowing out the
3314 // stack for very long paths.
3315 BugReport *exampleReport = nullptr;
3317 for (; I != E; ++I) {
3318 const ExplodedNode *errorNode = I->getErrorNode();
3322 if (errorNode->isSink()) {
3324 "BugType::isSuppressSink() should not be 'true' for sink end nodes");
3326 // No successors? By definition this nodes isn't post-dominated by a sink.
3327 if (errorNode->succ_empty()) {
3328 bugReports.push_back(I);
3334 // At this point we know that 'N' is not a sink and it has at least one
3335 // successor. Use a DFS worklist to find a non-sink end-of-path node.
3336 typedef FRIEC_WLItem WLItem;
3337 typedef SmallVector<WLItem, 10> DFSWorkList;
3338 llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
3341 WL.push_back(errorNode);
3342 Visited[errorNode] = 1;
3344 while (!WL.empty()) {
3345 WLItem &WI = WL.back();
3346 assert(!WI.N->succ_empty());
3348 for (; WI.I != WI.E; ++WI.I) {
3349 const ExplodedNode *Succ = *WI.I;
3350 // End-of-path node?
3351 if (Succ->succ_empty()) {
3352 // If we found an end-of-path node that is not a sink.
3353 if (!Succ->isSink()) {
3354 bugReports.push_back(I);
3360 // Found a sink? Continue on to the next successor.
3363 // Mark the successor as visited. If it hasn't been explored,
3364 // enqueue it to the DFS worklist.
3365 unsigned &mark = Visited[Succ];
3373 // The worklist may have been cleared at this point. First
3374 // check if it is empty before checking the last item.
3375 if (!WL.empty() && &WL.back() == &WI)
3380 // ExampleReport will be NULL if all the nodes in the equivalence class
3381 // were post-dominated by sinks.
3382 return exampleReport;
3385 void BugReporter::FlushReport(BugReportEquivClass& EQ) {
3386 SmallVector<BugReport*, 10> bugReports;
3387 BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports);
3388 if (exampleReport) {
3389 for (PathDiagnosticConsumer *PDC : getPathDiagnosticConsumers()) {
3390 FlushReport(exampleReport, *PDC, bugReports);
3395 void BugReporter::FlushReport(BugReport *exampleReport,
3396 PathDiagnosticConsumer &PD,
3397 ArrayRef<BugReport*> bugReports) {
3399 // FIXME: Make sure we use the 'R' for the path that was actually used.
3400 // Probably doesn't make a difference in practice.
3401 BugType& BT = exampleReport->getBugType();
3403 std::unique_ptr<PathDiagnostic> D(new PathDiagnostic(
3404 exampleReport->getBugType().getCheckName(),
3405 exampleReport->getDeclWithIssue(), exampleReport->getBugType().getName(),
3406 exampleReport->getDescription(),
3407 exampleReport->getShortDescription(/*Fallback=*/false), BT.getCategory(),
3408 exampleReport->getUniqueingLocation(),
3409 exampleReport->getUniqueingDecl()));
3411 MaxBugClassSize = std::max(bugReports.size(),
3412 static_cast<size_t>(MaxBugClassSize));
3414 // Generate the full path diagnostic, using the generation scheme
3415 // specified by the PathDiagnosticConsumer. Note that we have to generate
3416 // path diagnostics even for consumers which do not support paths, because
3417 // the BugReporterVisitors may mark this bug as a false positive.
3418 if (!bugReports.empty())
3419 if (!generatePathDiagnostic(*D.get(), PD, bugReports))
3422 MaxValidBugClassSize = std::max(bugReports.size(),
3423 static_cast<size_t>(MaxValidBugClassSize));
3425 // Examine the report and see if the last piece is in a header. Reset the
3426 // report location to the last piece in the main source file.
3427 AnalyzerOptions& Opts = getAnalyzerOptions();
3428 if (Opts.shouldReportIssuesInMainSourceFile() && !Opts.AnalyzeAll)
3429 D->resetDiagnosticLocationToMainFile();
3431 // If the path is empty, generate a single step path with the location
3433 if (D->path.empty()) {
3434 PathDiagnosticLocation L = exampleReport->getLocation(getSourceManager());
3435 auto piece = llvm::make_unique<PathDiagnosticEventPiece>(
3436 L, exampleReport->getDescription());
3437 BugReport::ranges_iterator Beg, End;
3438 std::tie(Beg, End) = exampleReport->getRanges();
3439 for ( ; Beg != End; ++Beg)
3440 piece->addRange(*Beg);
3441 D->setEndOfPath(std::move(piece));
3444 // Get the meta data.
3445 const BugReport::ExtraTextList &Meta = exampleReport->getExtraText();
3446 for (BugReport::ExtraTextList::const_iterator i = Meta.begin(),
3447 e = Meta.end(); i != e; ++i) {
3451 PD.HandlePathDiagnostic(std::move(D));
3454 void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
3455 const CheckerBase *Checker,
3456 StringRef Name, StringRef Category,
3457 StringRef Str, PathDiagnosticLocation Loc,
3458 ArrayRef<SourceRange> Ranges) {
3459 EmitBasicReport(DeclWithIssue, Checker->getCheckName(), Name, Category, Str,
3462 void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
3463 CheckName CheckName,
3464 StringRef name, StringRef category,
3465 StringRef str, PathDiagnosticLocation Loc,
3466 ArrayRef<SourceRange> Ranges) {
3468 // 'BT' is owned by BugReporter.
3469 BugType *BT = getBugTypeForName(CheckName, name, category);
3470 BugReport *R = new BugReport(*BT, str, Loc);
3471 R->setDeclWithIssue(DeclWithIssue);
3472 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
3478 BugType *BugReporter::getBugTypeForName(CheckName CheckName, StringRef name,
3479 StringRef category) {
3480 SmallString<136> fullDesc;
3481 llvm::raw_svector_ostream(fullDesc) << CheckName.getName() << ":" << name
3483 BugType *&BT = StrBugTypes[fullDesc];
3485 BT = new BugType(CheckName, name, category);
3489 LLVM_DUMP_METHOD void PathPieces::dump() const {
3491 for (PathPieces::const_iterator I = begin(), E = end(); I != E; ++I) {
3492 llvm::errs() << "[" << index++ << "] ";
3494 llvm::errs() << "\n";
3498 void PathDiagnosticCallPiece::dump() const {
3499 llvm::errs() << "CALL\n--------------\n";
3501 if (const Stmt *SLoc = getLocStmt(getLocation()))
3503 else if (const NamedDecl *ND = dyn_cast<NamedDecl>(getCallee()))
3504 llvm::errs() << *ND << "\n";
3506 getLocation().dump();
3509 void PathDiagnosticEventPiece::dump() const {
3510 llvm::errs() << "EVENT\n--------------\n";
3511 llvm::errs() << getString() << "\n";
3512 llvm::errs() << " ---- at ----\n";
3513 getLocation().dump();
3516 void PathDiagnosticControlFlowPiece::dump() const {
3517 llvm::errs() << "CONTROL\n--------------\n";
3518 getStartLocation().dump();
3519 llvm::errs() << " ---- to ----\n";
3520 getEndLocation().dump();
3523 void PathDiagnosticMacroPiece::dump() const {
3524 llvm::errs() << "MACRO\n--------------\n";
3525 // FIXME: Print which macro is being invoked.
3528 void PathDiagnosticLocation::dump() const {
3530 llvm::errs() << "<INVALID>\n";
3536 // FIXME: actually print the range.
3537 llvm::errs() << "<range>\n";
3540 asLocation().dump();
3541 llvm::errs() << "\n";
3547 llvm::errs() << "<NULL STMT>\n";
3550 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
3551 llvm::errs() << *ND << "\n";
3552 else if (isa<BlockDecl>(D))
3553 // FIXME: Make this nicer.
3554 llvm::errs() << "<block>\n";
3556 llvm::errs() << "<unknown decl>\n";
3558 llvm::errs() << "<NULL DECL>\n";